packages feed

waterfall-cad-0.9.0.0: src/Waterfall/BoundingBox/AxisAligned.hs

module Waterfall.BoundingBox.AxisAligned
( HasAxisAlignedBoundingBox ()
, axisAlignedBoundingBox
, aabbToSolid
) where
import Waterfall.Internal.Solid(Solid, acquireSolid)
import Waterfall.Internal.Finalizers (unsafeFromAcquire, acquireForeignPtr)
import Waterfall.Internal.FromOpenCascade (gpPntToV3)
import Waterfall.Solid (box, volume)
import Waterfall.Transforms (translate)
import Linear (V3 (..), (^-^))
import qualified OpenCascade.Bnd.Box as Bnd.Box
import qualified OpenCascade.BRepBndLib as BRepBndLib
import Control.Monad.IO.Class (liftIO)
import Data.Acquire (Acquire)
import Foreign (Ptr)
import qualified OpenCascade.TopoDS as TopoDS
import Waterfall.Internal.Path (Path (..))
import Waterfall.Internal.Path.Common (RawPath(..))
import OpenCascade.Inheritance (upcast)
import Waterfall.Internal.ToOpenCascade (v3ToVertex)
import Control.Monad (forM_)

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

instance HasAxisAlignedBoundingBox Solid where
    _isEmpty s = volume s == 0
    _getShapes = fmap pure . acquireSolid

instance HasAxisAlignedBoundingBox Path where
    _isEmpty (Path EmptyRawPath) = True
    _isEmpty _ = False

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

-- | Return the smallest Axis Aligned Bounding Box (AABB) that contains the `Solid` or `Path`.
-- 
-- If computable, the AABB is returned in the form @(lo, hi)@,
-- where @lo@ is the vertex of the box with the lowest individual values,
-- and @hi@ is the vertex with the highest values.
axisAlignedBoundingBox :: HasAxisAlignedBoundingBox a => a -> Maybe (V3 Double, V3 Double)
axisAlignedBoundingBox s =  
    if _isEmpty s
        then Nothing 
        else Just . unsafeFromAcquire $ do
            shapes <- _getShapes s
            theBox <- Bnd.Box.new
            liftIO $ forM_ shapes $ \shape -> BRepBndLib.addOptimal shape theBox False False
            p1 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMin theBox
            p2 <- liftIO . gpPntToV3 =<< Bnd.Box.cornerMax theBox
            return (p1, p2)

-- | A cuboid, specified by two diagonal vertices.
--  
-- This can be used to make a solid from the output of `axisAlignedBoundingBox` 
aabbToSolid :: (V3 Double, V3 Double) -- ^ if this argument input is @(lo, hi)@, one vertex of the cuboid is placed at @lo@, the opposite vertex is at @hi@
    -> Solid
aabbToSolid (lo, hi) = translate lo $ box (hi ^-^ lo)