module Tile
    ( tToRender
    , makeTileFromPoly
    ) where
import Data.Tile
import Geometry

tToRender :: Tile -> [(Point3,Point3)]
tToRender t = polyToTris $ zip ps3 coords3
  where
    ps = _tilePoly t
    coords = map (calcTexCoord (_tileZero t) (_tileX t)) ps
    ps3 = map (addToV2 0) ps
    coords3 = map (addToV2 (_tileZ t)) coords

addToV2 :: a -> V2 a -> V3 a
addToV2 z (V2 x y) = V3 x y z

calcTexCoord
    :: Point2   -- ^ tile (0,0)
    -> Point2   -- ^ tile (1,0)
    -> Point2   -- ^ world point
    -> Point2
calcTexCoord c p x = V2 (0.02 * dotV (p -.- c) xdir) (0.02 * dotV (p -.- c) ydir)
  where
    xdir = x -.- c
    ydir = vNormal xdir

makeTileFromPoly :: [Point2] -> Float -> Tile
makeTileFromPoly poly z = Tile
    { _tilePoly = poly
    , _tileZero = c
    , _tileX  = c +.+ normalizeV ((poly !! 1) -.- c)
    , _tileZ = z
    }
  where
    c = head poly
