never executed always true always false
1 {-# LANGUAGE BangPatterns #-}
2 {-|
3 2D transformation matrices capable of translating, scaling,
4 rotating, and skewing.
5 -}
6 module Reanimate.Transform
7 ( identity
8 , transformPoint
9 , mkMatrix
10 , toTransformation
11 ) where
12
13 -- XXX: Use Linear.Matrix instead of Data.Matrix to drop the 'matrix' dependency.
14 import Data.List
15 import Data.Matrix (Matrix)
16 import qualified Data.Matrix as M
17 import Data.Maybe
18 import Graphics.SvgTree
19 import Linear.V2
20
21 -- | Identity matrix.
22 --
23 -- @transformPoints identity x = x@
24 identity :: Matrix Coord
25 identity = M.identity 3
26
27 fromList :: [Coord] -> Matrix Coord
28 fromList [a,b,c,d,e,f] = M.fromList 3 3 [a,c,e,b,d,f,0,0,1]
29 fromList _ = error "Reanimate.Transform.fromList: bad input"
30
31 -- | Apply a transformation matrix to a 2D point.
32 transformPoint :: Matrix Coord -> RPoint -> RPoint
33 transformPoint m (V2 x y) = V2 (a*x +c*y + e) (b*x + d*y +f)
34 where
35 !a = M.unsafeGet 1 1 m
36 !c = M.unsafeGet 1 2 m
37 !e = M.unsafeGet 1 3 m
38 !b = M.unsafeGet 2 1 m
39 !d = M.unsafeGet 2 2 m
40 !f = M.unsafeGet 2 3 m
41 -- (a:c:e:b:d:f:_) = M.toList m
42
43 -- | Convert multiple SVG transformations into a single transformation matrix.
44 mkMatrix :: Maybe [Transformation] -> Matrix Coord
45 mkMatrix Nothing = identity
46 mkMatrix (Just ts) = foldl' (*) identity (map transformationMatrix ts)
47
48 -- | Convert an SVG transformation into a transformation matrix.
49 transformationMatrix :: Transformation -> Matrix Coord
50 transformationMatrix transformation =
51 case transformation of
52 TransformMatrix a b c d e f -> fromList [a,b,c,d,e,f]
53 Translate x y -> translate x y
54 Scale sx mbSy -> fromList [sx,0,0,fromMaybe sx mbSy,0,0]
55 Rotate a Nothing -> rotate a
56 Rotate a (Just (x,y)) -> translate x y * rotate a * translate (-x) (-y)
57 SkewX a -> fromList [1,0,tan (a*pi/180),1,0,0]
58 SkewY a -> fromList [1,tan (a*pi/180),0,1,0,0]
59 TransformUnknown -> identity
60 where
61 translate x y = fromList [1,0,0,1,x,y]
62 rotate a = fromList [cos r,sin r,-sin r,cos r,0,0]
63 where r = a * pi / 180
64
65 -- | Convert a transformation matrix back into an SVG transformation.
66 toTransformation :: Matrix Coord -> Transformation
67 toTransformation m = TransformMatrix a b c d e f
68 where
69 [a,c,e,b,d,f,_,_,_] = M.toList m