Debian Codegraph @

src/Diagrams/TwoD/Points.hs

raw symbols SCIP
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 -- | Find the convex hull of a list of points using Andrew's monotone chain
26 -- algorithm O(n log n).
27 --
28 -- Returns clockwise list of points starting from the left-most point.
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 -- | Find the convex hull of a set of points already sorted in the x direction.
35 -- The first list of the tuple is the upper hull going clockwise from
36 -- left-most to right-most point. The second is the lower hull from
37 -- right-most to left-most in the anti-clockwise direction.
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