| 1 |
{-# LANGUAGE ConstraintKinds #-} |
| 2 |
----------------------------------------------------------------------------- |
| 3 |
-- | |
| 4 |
-- Module : Diagrams.TwoD.Points |
| 5 |
-- Copyright : (c) 2014 diagrams-lib team (see LICENSE) |
| 6 |
-- License : BSD-style (see LICENSE) |
| 7 |
-- Maintainer : [email protected] |
| 8 |
-- |
| 9 |
-- Special functions for points in R2. |
| 10 |
-- |
| 11 |
----------------------------------------------------------------------------- |
| 12 |
|
| 13 |
{-# LANGUAGE TypeFamilies #-} |
| 14 |
|
| 15 |
module Diagrams.TwoD.Points where |
| 16 |
|
| 17 |
import Data.List |
| 18 |
|
| 19 |
import Diagrams.Core |
| 20 |
import Diagrams.TwoD.Vector |
| 21 |
import Diagrams.TwoD.Types (P2) |
| 22 |
|
| 23 |
import Linear.Affine |
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
convexHull2D :: OrderedField n => [P2 n] -> [P2 n] |
| 30 |
convexHull2D ps = init upper ++ reverse (tail lower) |
| 31 |
where |
| 32 |
(upper, lower) = sortedConvexHull (sort ps) |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 37 |
|
| 38 |
sortedConvexHull :: OrderedField n => [P2 n] -> ([P2 n], [P2 n]) |
| 39 |
sortedConvexHull ps = (chain True ps, chain False ps) |
| 40 |
where |
| 41 |
chain upper (p1_:p2_:rest_) = |
| 42 |
case go (p2_ .-. p1_) p2_ rest_ of |
| 43 |
Right l -> p1_:l |
| 44 |
Left l -> chain upper (p1_:l) |
| 45 |
where |
| 46 |
test = if upper then (>0) else (<0) |
| 47 |
-- find the convex hull by comparing the angles of the vectors with |
| 48 |
-- the cross product and backtracking if necessary |
| 49 |
go dir p1 l@(p2:rest) |
| 50 |
-- backtrack if the direction is outward |
| 51 |
| test $ dir `cross2` dir' = Left l |
| 52 |
| otherwise = |
| 53 |
case go dir' p2 rest of |
| 54 |
Left m -> go dir p1 m |
| 55 |
Right m -> Right (p1:m) |
| 56 |
where |
| 57 |
dir' = p2 .-. p1 |
| 58 |
go _ p1 p = Right (p1:p) |
| 59 |
|
| 60 |
chain _ l = l |