module Game.LambdaHack.Vector
( Vector, toVector, shift, shiftBounded, moves, movesWidth
, euclidDistSq, diagonal, neg, towards, displacement, displacePath
) where
import Data.Binary
import Game.LambdaHack.PointXY
import Game.LambdaHack.VectorXY
import Game.LambdaHack.Area
import Game.LambdaHack.Point
import Game.LambdaHack.Utils.Assert
newtype Vector = Vector Int
deriving (Show, Eq)
instance Binary Vector where
put (Vector dir) = put dir
get = fmap Vector get
toVector :: X -> VectorXY -> Vector
toVector lxsize (VectorXY (x, y)) =
Vector $ x + y * lxsize
toDir :: X -> VectorXY -> Vector
toDir lxsize v@(VectorXY (x, y)) =
assert (lxsize >= 3 && chessDistXY v == 1 `blame` (lxsize, v)) $
Vector $ x + y * lxsize
fromDir :: X -> Vector -> VectorXY
fromDir lxsize (Vector dir) =
assert (lxsize >= 3 && chessDistXY res == 1 &&
fst len1 + snd len1 * lxsize == dir
`blame` (lxsize, dir, res)) $
res
where
(x, y) = (dir `mod` lxsize, dir `div` lxsize)
len1 = if x > 1
then (x lxsize, y + 1)
else (x, y)
res = VectorXY len1
shift :: Point -> Vector -> Point
shift loc (Vector dir) = loc + dir
shiftBounded :: X -> Area -> Point -> Vector -> Point
shiftBounded lxsize area loc dir =
let res = shift loc dir
in if inside lxsize res area then res else loc
moves :: X -> [Vector]
moves lxsize = map (toDir lxsize) movesXY
movesWidth :: [X -> Vector]
movesWidth = map (flip toDir) movesXY
euclidDistSq :: X -> Vector -> Vector -> Int
euclidDistSq lxsize dir0 dir1
| VectorXY (x0, y0) <- fromDir lxsize dir0
, VectorXY (x1, y1) <- fromDir lxsize dir1 =
euclidDistSqXY $ VectorXY (y1 y0, x1 x0)
diagonal :: X -> Vector -> Bool
diagonal lxsize dir | VectorXY (x, y) <- fromDir lxsize dir =
x * y /= 0
neg :: Vector -> Vector
neg (Vector dir) = Vector (dir)
normalize :: X -> VectorXY -> Vector
normalize lxsize (VectorXY (dx, dy)) =
assert (dx /= 0 || dy /= 0 `blame` (dx, dy)) $
let angle :: Double
angle = atan (fromIntegral dy / fromIntegral dx) / (pi / 2)
dxy | angle <= 0.75 = (0, 1)
| angle <= 0.25 = (1, 1)
| angle <= 0.25 = (1, 0)
| angle <= 0.75 = (1, 1)
| angle <= 1.25 = (0, 1)
| otherwise = assert `failure` (lxsize, dx, dy, angle)
in if dx >= 0
then toDir lxsize $ VectorXY dxy
else neg (toDir lxsize $ VectorXY dxy)
towards :: X -> Point -> Point -> Vector
towards lxsize loc0 loc1 =
assert (loc0 /= loc1 `blame` (loc0, loc1)) $
let v = displacementXYZ lxsize loc0 loc1
in normalize lxsize v
displacement :: Point -> Point -> Vector
displacement loc1 loc2 = Vector $ loc2 loc1
displacePath :: [Point] -> [Vector]
displacePath [] = []
displacePath lp1@(_ : lp2) =
map (uncurry displacement) $ zip lp1 lp2