Debian Codegraph @

src/Diagrams/TwoD/Polygons.hs

raw symbols SCIP
1 {-# LANGUAGE ConstraintKinds #-}
2 {-# LANGUAGE DeriveFunctor #-}
3 {-# LANGUAGE FlexibleContexts #-}
4 {-# LANGUAGE ScopedTypeVariables #-}
5 {-# LANGUAGE TemplateHaskell #-}
6 {-# LANGUAGE TypeFamilies #-}
7 {-# LANGUAGE ViewPatterns #-}
8
9 -----------------------------------------------------------------------------
10 -- |
11 -- Module : Diagrams.TwoD.Polygons
12 -- Copyright : (c) 2011 diagrams-lib team (see LICENSE)
13 -- License : BSD-style (see LICENSE)
14 -- Maintainer : [email protected]
15 --
16 -- This module defines a general API for creating various types of
17 -- polygons.
18 --
19 -----------------------------------------------------------------------------
20
21 module Diagrams.TwoD.Polygons(
22 -- * Polygons
23 PolyType(..)
24 , PolyOrientation(..)
25 , PolygonOpts(..), polyType, polyOrient, polyCenter
26
27 , polygon
28 , polyTrail
29
30 -- ** Generating polygon vertices
31
32 , polyPolarTrail
33 , polySidesTrail
34 , polyRegularTrail
35
36 , orient
37
38 -- * Star polygons
39 , StarOpts(..)
40 , star
41
42 -- ** Function graphs
43 -- $graphs
44 , GraphPart(..)
45 , orbits, mkGraph
46
47 ) where
48
49 import Control.Lens (Lens', generateSignatures, lensRules,
50 makeLensesWith, view, (.~), (^.))
51 import Control.Monad (forM, liftM)
52 import Control.Monad.ST (ST, runST)
53 import Data.Array.ST (STUArray, newArray, readArray,
54 writeArray)
55 import Data.Default
56 import Data.List (maximumBy, minimumBy)
57 import Data.Maybe (catMaybes)
58 import Data.Ord (comparing)
59
60 import Diagrams.Angle
61 import Diagrams.Core
62 import Diagrams.Located
63 import Diagrams.Path
64 import Diagrams.Points (centroid)
65 import Diagrams.Trail
66 import Diagrams.TrailLike
67 import Diagrams.TwoD.Types
68 import Diagrams.TwoD.Vector (leftTurn, unitX, unitY, unit_Y)
69 import Diagrams.Util (tau, ( # ))
70
71 import Linear.Affine
72 import Linear.Metric
73 import Linear.Vector
74
75 -- | Method used to determine the vertices of a polygon.
76 data PolyType n = PolyPolar [Angle n] [n]
77 -- ^ A \"polar\" polygon.
78 --
79 -- * The first argument is a list of /central/
80 -- /angles/ from each vertex to the next.
81 --
82 -- * The second argument is a list of /radii/ from
83 -- the origin to each successive vertex.
84 --
85 -- To construct an /n/-gon, use a list of /n-1/
86 -- angles and /n/ radii. Extra angles or radii
87 -- are ignored.
88 --
89 -- Cyclic polygons (with all vertices lying on a
90 -- circle) can be constructed using a second
91 -- argument of @(repeat r)@.
92
93 | PolySides [Angle n] [n]
94 -- ^ A polygon determined by the distance between
95 -- successive vertices and the external angles formed
96 -- by each three successive vertices. In other
97 -- words, a polygon specified by \"turtle
98 -- graphics\": go straight ahead x1 units; turn by
99 -- external angle a1; go straight ahead x2 units; turn by
100 -- external angle a2; etc. The polygon will be centered
101 -- at the /centroid/ of its vertices.
102 --
103 -- * The first argument is a list of /vertex/
104 -- /angles/, giving the external angle at each vertex
105 -- from the previous vertex to the next. The
106 -- first angle in the list is the external angle at
107 -- the /second/ vertex; the first edge always starts
108 -- out heading in the positive y direction from
109 -- the first vertex.
110 --
111 -- * The second argument is a list of distances
112 -- between successive vertices.
113 --
114 -- To construct an /n/-gon, use a list of /n-2/
115 -- angles and /n-1/ edge lengths. Extra angles or
116 -- lengths are ignored.
117
118 | PolyRegular Int n
119 -- ^ A regular polygon with the given number of
120 -- sides (first argument) and the given radius
121 -- (second argument).
122
123 -- | Determine how a polygon should be oriented.
124 data PolyOrientation n = NoOrient -- ^ No special orientation; the first
125 -- vertex will be at (1,0).
126 | OrientH -- ^ Orient /horizontally/, so the
127 -- bottommost edge is parallel to
128 -- the x-axis.
129 -- This is the default.
130 | OrientV -- ^ Orient /vertically/, so the
131 -- leftmost edge is parallel to the
132 -- y-axis.
133 | OrientTo (V2 n) -- ^ Orient so some edge is
134 -- /facing/ /in/ /the/ /direction/
135 -- /of/, that is, perpendicular
136 -- to, the given vector.
137 deriving (Eq, Ord, Show, Read)
138
139 -- | Options for specifying a polygon.
140 data PolygonOpts n = PolygonOpts
141 { _polyType :: PolyType n
142 , _polyOrient :: PolyOrientation n
143 , _polyCenter :: Point V2 n
144 }
145
146 makeLensesWith (generateSignatures .~ False $ lensRules) ''PolygonOpts
147
148 -- | Specification for the polygon's vertices.
149 polyType :: Lens' (PolygonOpts n) (PolyType n)
150
151 -- | Should a rotation be applied to the polygon in order to orient it in a
152 -- particular way?
153 polyOrient :: Lens' (PolygonOpts n) (PolyOrientation n)
154
155 -- | Should a translation be applied to the polygon in order to place the center
156 -- at a particular location?
157 polyCenter :: Lens' (PolygonOpts n) (Point V2 n)
158
159 -- | The default polygon is a regular pentagon of radius 1, centered
160 -- at the origin, aligned to the x-axis.
161 instance Num n => Default (PolygonOpts n) where
162 def = PolygonOpts (PolyRegular 5 1) OrientH origin
163
164 -- | Generate a polygon. See 'PolygonOpts' for more information.
165 polyTrail :: OrderedField n => PolygonOpts n -> Located (Trail V2 n)
166 polyTrail po = transform ori tr
167 where
168 tr = case po^.polyType of
169 PolyPolar ans szs -> polyPolarTrail ans szs
170 PolySides ans szs -> polySidesTrail ans szs
171 PolyRegular n r -> polyRegularTrail n r
172 ori = case po^.polyOrient of
173 OrientH -> orient unit_Y tr
174 OrientV -> orient unitX tr
175 OrientTo v -> orient v tr
176 NoOrient -> mempty
177
178 -- | Generate the polygon described by the given options.
179 polygon :: (InSpace V2 n t, TrailLike t) => PolygonOpts n -> t
180 polygon = trailLike . polyTrail
181
182 -- | Generate the located trail of a polygon specified by polar data
183 -- (central angles and radii). See 'PolyPolar'.
184 polyPolarTrail :: OrderedField n => [Angle n] -> [n] -> Located (Trail V2 n)
185 polyPolarTrail [] _ = emptyTrail `at` origin
186 polyPolarTrail _ [] = emptyTrail `at` origin
187 polyPolarTrail ans (r:rs) = tr `at` p1
188 where
189 p1 = p2 (1,0) # scale r
190 tr = closeTrail . trailFromVertices $
191 zipWith
192 (\a l -> rotate a . scale l $ p2 (1,0))
193 (scanl (^+^) zero ans)
194 (r:rs)
195
196 -- | Generate the vertices of a polygon specified by side length and
197 -- angles, and a starting point for the trail such that the origin
198 -- is at the centroid of the vertices. See 'PolySides'.
199 polySidesTrail :: OrderedField n => [Angle n] -> [n] -> Located (Trail V2 n)
200 polySidesTrail ans ls = tr `at` (centroid ps # scale (-1))
201 where
202 ans' = scanl (^+^) zero ans
203 offsets = zipWith rotate ans' (map (unitY ^*) ls)
204 ps = scanl (.+^) origin offsets
205 tr = closeTrail . trailFromOffsets $ offsets
206
207 -- | Generate the vertices of a regular polygon. See 'PolyRegular'.
208 polyRegularTrail :: OrderedField n => Int -> n -> Located (Trail V2 n)
209 polyRegularTrail n r = polyPolarTrail
210 (replicate (n - 1) $ fullTurn ^/ fromIntegral n)
211 (repeat r)
212
213 -- | Generate a transformation to orient a trail. @orient v t@
214 -- generates the smallest rotation such that one of the segments
215 -- adjacent to the vertex furthest in the direction of @v@ is
216 -- perpendicular to @v@.
217 orient :: OrderedField n => V2 n -> Located (Trail V2 n) -> Transformation V2 n
218 orient v = orientPoints v . trailVertices
219
220 orientPoints :: OrderedField n => V2 n -> [Point V2 n] -> Transformation V2 n
221 orientPoints _ [] = mempty
222 orientPoints _ [_] = mempty
223 orientPoints v xs = rotation a
224 where
225 (n1,x,n2) = maximumBy (comparing (distAlong v . sndOf3))
226 (zip3 (tail (cycle xs)) xs (last xs : init xs))
227 distAlong w ((.-. origin) -> p) = signum (w `dot` p) * norm (project w p)
228 sndOf3 (_,b,_) = b
229 -- a :: Angle (Scalar v)
230 a = minimumBy (comparing $ abs . view rad)
231 . map (angleFromNormal . (.-. x)) $ [n1,n2]
232 v' = signorm v
233 -- angleFromNormal :: v -> Angle (Scalar v)
234 angleFromNormal o
235 | leftTurn o' v' = phi
236 | otherwise = negated phi
237 where
238 o' = signorm o
239 theta = acos (v' `dot` o')
240 -- phi :: Angle (Scalar v)
241 phi
242 | theta <= tau/4 = tau/4 - theta @@ rad
243 | otherwise = theta - tau/4 @@ rad
244
245 ------------------------------------------------------------
246 -- Function graphs
247 ------------------------------------------------------------
248
249 -- $graphs
250 -- These functions are used to implement 'star', but are exported on
251 -- the offchance that someone else finds them useful.
252
253 -- | Pieces of a function graph can either be cycles or \"hairs\".
254 data GraphPart a = Cycle [a]
255 | Hair [a]
256 deriving (Show, Functor)
257
258 -- | @orbits f n@ computes the graph of @f@ on the integers mod @n@.
259 orbits :: (Int -> Int) -> Int -> [GraphPart Int]
260 orbits f n = runST genOrbits
261 where
262 f_n i = f i `mod` n
263
264 genOrbits :: ST s [GraphPart Int]
265 genOrbits = newArray (0,n-1) False >>= genOrbits'
266
267 genOrbits' :: STUArray s Int Bool -> ST s [GraphPart Int]
268 genOrbits' marks = liftM (concat . catMaybes) (forM [0 .. n-1] (genPart marks))
269
270 genPart :: STUArray s Int Bool -> Int -> ST s (Maybe [GraphPart Int])
271 genPart marks i = do
272 tr <- markRho i marks
273 case tr of
274 [] -> return Nothing
275 _ -> return . Just . splitParts $ tr
276
277 markRho :: Int -> STUArray s Int Bool -> ST s [Int]
278 markRho i marks = do
279 isMarked <- readArray marks i
280 if isMarked
281 then return []
282 else writeArray marks i True >>
283 liftM (i:) (markRho (f_n i) marks)
284
285 splitParts :: [Int] -> [GraphPart Int]
286 splitParts tr = hair ++ cyc
287 where hair | not (null tl) = [Hair $ tl ++ [f_n (last tl)]]
288 | otherwise = []
289 cyc | not (null body) = [Cycle body]
290 | otherwise = []
291 l = last tr
292 (tl, body) = span (/= f_n l) tr
293
294 -- | Generate a function graph from the given function and labels.
295 mkGraph :: (Int -> Int) -> [a] -> [GraphPart a]
296 mkGraph f xs = (map . fmap) (xs!!) $ orbits f (length xs)
297
298 ------------------------------------------------------------
299 -- Star polygons
300 ------------------------------------------------------------
301
302 -- | Options for creating \"star\" polygons, where the edges connect
303 -- possibly non-adjacent vertices.
304 data StarOpts = StarFun (Int -> Int)
305 -- ^ Specify the order in which the vertices should be
306 -- connected by a function that maps each vertex
307 -- index to the index of the vertex that should come
308 -- next. Indexing of vertices begins at 0.
309
310 | StarSkip Int
311 -- ^ Specify a star polygon by a \"skip\". A skip of
312 -- 1 indicates a normal polygon, where edges go
313 -- between successive vertices. A skip of 2 means
314 -- that edges will connect every second vertex,
315 -- skipping one in between. Generally, a skip of
316 -- /n/ means that edges will connect every /n/th
317 -- vertex.
318
319 -- | Create a generalized /star/ /polygon/. The 'StarOpts' are used
320 -- to determine in which order the given vertices should be
321 -- connected. The intention is that the second argument of type
322 -- @[Point v]@ could be generated by a call to 'polygon', 'regPoly', or
323 -- the like, since a list of vertices is 'TrailLike'. But of course
324 -- the list can be generated any way you like. A @'Path' 'v'@ is
325 -- returned (instead of any 'TrailLike') because the resulting path
326 -- may have more than one component, for example if the vertices are
327 -- to be connected in several disjoint cycles.
328 star :: OrderedField n => StarOpts -> [Point V2 n] -> Path V2 n
329 star sOpts vs = graphToPath $ mkGraph f vs
330 where f = case sOpts of
331 StarFun g -> g
332 StarSkip k -> (+k)
333 graphToPath = mconcat . map partToPath
334
335 partToPath (Cycle ps) = pathFromLocTrail
336 . mapLoc closeTrail
337 . fromVertices
338 $ ps
339
340 partToPath (Hair ps) = fromVertices ps