module Graphics.Formats.Collada.Transformations where
import Graphics.Formats.Collada.ColladaTypes
type V = (Float,Float,Float)
-- |extrude a 2d polygon to 3d, the same points are added again with extrusion direction v
extrude :: V -> Geometry -> Geometry
extrude v (Geometry name prims (Vertices vname ps _)) = Geometry name
                                                         (map addIndices prims)
                                                         (Vertices vname (concat (map addPoints lines))
                                                                         (concat (map (\x -> [x,x,x,x]) ns)) )
  where
  addIndices (LP (LinePrimitive points normals tex color)) = PL (LinePrimitive (p points) (p points) tex color)
  lines = cycleNeighbours ps
  addPoints points = points ++ ( map (add v) (reverse points) )
  add (x0,y0,z0) (x1,y1,z1) = (x0+x1, y0+y1, z0+z1)
  ns = map (normals v) lines
  normals (vx0,vy0,vz0) [(vx1,vy1,vz1),(vx2,vy2,vz2)] = crosspr (vx1-vx0,vy1-vy0,vz1-vz0)
                                                                (vx1-vx2,vy1-vy2,vz1-vz2)
  crosspr (v0,v1,v2) (w0,w1,w2) = (v1*w2-v2*w1, v2*w0-v0*w2, v0*w1-v1*w0)
  p points = concat $ map (map (\x -> [x*4, x*4+1, x*4+2, x*4+3])) points

-- |return a list containing lists of every element with its neighbour
-- i.e. [e1,e2,e3] -> [ [e1,e2], [e2,e3], [e3, e1] ]
cycleNeighbours :: [a] -> [[a]]
cycleNeighbours [] = []
cycleNeighbours xs = cycleN (head xs) xs

cycleN :: a -> [a] -> [[a]]
cycleN f (x:y:xs) = [x,y] : (cycleN f (y:xs))
cycleN f e = [[head e, f ]] -- if the upper doesn't match close cycle