packages feed

waterfall-cad-0.9.0.0: src/Waterfall/TwoD/BoundingBox/Oriented.hs

{-# LANGUAGE InstanceSigs #-}
module Waterfall.TwoD.BoundingBox.Oriented
( HasOrientedBoundingBox2D ()
, OrientedBoundingBox2D
, obb2DCenter
, obb2DSideX
, obb2DSideY
, orientedBoundingBox2D
, obbToShape
) where

import Linear (V2 (..), normalize, (^*), _xy, norm, unangle, quadrance, zero)
import Waterfall.TwoD.Shape (Shape, centeredSquare, area)
import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquire)
import Waterfall.Internal.FromOpenCascade (gpXYZToV3)
import Foreign.Ptr (Ptr)
import qualified OpenCascade.Bnd.OBB as OBB
import OpenCascade.Bnd.OBB (OBB)
import OpenCascade.GP.Types (XYZ)
import qualified OpenCascade.BRepBndLib as BRepBndLib
import OpenCascade.Inheritance (upcast)
import Data.Acquire (Acquire)
import Control.Monad.IO.Class (liftIO)
import Control.Monad ((<=<), forM_)
import Foreign.ForeignPtr (ForeignPtr)
import Control.DeepSeq (NFData (rnf), rwhnf)
import qualified OpenCascade.TopoDS as TopoDS
import Waterfall.Internal.Path.Common (RawPath(..))
import Waterfall.Internal.ToOpenCascade (v3ToVertex)
import Waterfall.TwoD.Internal.Path2D (Path2D (..))
import Waterfall.Diagram (Diagram (getDiagramFills), getDiagramLines)
import Waterfall.TwoD.Internal.Shape (acquireShape)
import Data.Monoid (Ap(..))
import Data.Functor.Compose (Compose(..))
import Control.Lens ((^.))
import Data.Function ((&))
import Waterfall.TwoD.Transforms (scale2D, rotate2D, Transformable2D (translate2D))
import Data.List (sortOn)
import Data.Ord (Down(..))

-- | Class for things that have a Bounding Box
-- 
-- Has instances for `Shape`, `Path2D` and `Diagram`
class HasOrientedBoundingBox2D a where
    _isEmpty :: a -> Bool
    _getShapes :: a -> Acquire [Ptr TopoDS.Shape]

instance HasOrientedBoundingBox2D Shape where
    _isEmpty s = area s == 0
    _getShapes = fmap pure . acquireShape

instance HasOrientedBoundingBox2D Path2D where
    _isEmpty (Path2D EmptyRawPath) = True
    _isEmpty _ = False

    _getShapes (Path2D (ComplexRawPath p)) = fmap (pure . upcast) . acquireForeignPtr $ p
    _getShapes (Path2D (SinglePointRawPath p)) = fmap (pure . upcast) . v3ToVertex $ p
    _getShapes (Path2D EmptyRawPath) = pure []

instance HasOrientedBoundingBox2D Diagram where
    _isEmpty diagram = 
        all (all _isEmpty) (getDiagramLines diagram)
        && all (_isEmpty . snd) (getDiagramFills diagram)

    _getShapes diagram = 
            getAp 
                ((foldMap (Ap . _getShapes) . Compose) (getDiagramLines diagram)
                <> (foldMap (Ap . _getShapes) . Compose) (getDiagramFills diagram)
                )


-- | An OrientedBoundingBox may be a tighter fit than an axis aligned bounding box would be
-- 
newtype OrientedBoundingBox2D = OrientedBoundingBox2D { rawOBB :: ForeignPtr OBB }

instance NFData OrientedBoundingBox2D where 
    rnf (OrientedBoundingBox2D obb) = rwhnf obb

-- | Compute an `OrientedBoundingBox2D` for a `Shape`, `Path2D` or Diagram
orientedBoundingBox2D :: HasOrientedBoundingBox2D a => a -> Maybe OrientedBoundingBox2D
orientedBoundingBox2D s = 
    if _isEmpty s
        then Nothing 
        else Just . OrientedBoundingBox2D . unsafeFromAcquirePtr $ do
            obb <- OBB.new
            shapes <- _getShapes s
            liftIO $ forM_ shapes $ \shape -> BRepBndLib.addOBB shape obb False True True
            return obb

queryOBB :: (Ptr OBB -> Acquire (V2 Double)) -> OrientedBoundingBox2D -> V2 Double
queryOBB f = unsafeFromAcquire . ( f <=< acquireForeignPtr . rawOBB)

-- | The center point of an `OrientedBoundingBox2D`
obb2DCenter :: OrientedBoundingBox2D -> V2 Double
obb2DCenter = queryOBB (fmap (^. _xy) . liftIO . gpXYZToV3 <=< OBB.center)

getSide :: (Ptr OBB -> Acquire (Ptr XYZ)) -> (Ptr OBB -> IO Double) -> OrientedBoundingBox2D -> V2 Double
getSide fxyz fLength = queryOBB $ \obb -> do
    side <- fmap (^. _xy) . liftIO . gpXYZToV3 =<< fxyz obb
    len <- liftIO $ fLength obb
    return $ normalize side ^* len

obb2DSides :: OrientedBoundingBox2D -> (V2 Double, V2 Double)
obb2DSides obb = 
    let x =  getSide OBB.xDirection OBB.xHSize obb
        y =  getSide OBB.yDirection OBB.yHSize obb
        z =  getSide OBB.zDirection OBB.zHSize obb
    in case sortOn (Down . quadrance) [x, y, z] of 
        (a : b : _)  -> (a, b)
        _ -> (zero, zero)

-- | The longer side of the oriented bounding box.
--
-- This is measured from the center to one edge.
-- So the length of this vector is /half/ of the side length of the bounding box.
obb2DSideX :: OrientedBoundingBox2D -> V2 Double 
obb2DSideX = fst . obb2DSides 

-- | The shorter side of the oriented bounding box.
--
-- This is measured from the center to one edge.
-- So the length of this vector is /half/ of the side length of the bounding box.
obb2DSideY :: OrientedBoundingBox2D -> V2 Double 
obb2DSideY = snd . obb2DSides
    
-- | Reify an `OrientedBoundingBox2D` as a `Shape`
obbToShape :: OrientedBoundingBox2D -> Shape
obbToShape obb =
    let box = V2 (norm $ obb2DSideX obb) (norm $ obb2DSideY obb) ^* 2
        theta = unangle (obb2DSideX obb)
    in centeredSquare
        & scale2D box
        & rotate2D theta 
        & translate2D (obb2DCenter obb)