packages feed

waterfall-cad-0.9.0.0: src/Waterfall/TwoD/Internal/Shape.hs

{-# OPTIONS_HADDOCK not-home #-}
{-# LANGUAGE FlexibleContexts #-}
module Waterfall.TwoD.Internal.Shape
( Shape (..)
, acquireShape
, shapeFromAcquire
, union2D
, difference2D
, intersection2D
, unions2D
, intersections2D
, emptyShape
) where

import qualified OpenCascade.TopoDS as TopoDS
import Foreign.Ptr
import Data.Acquire (Acquire)
import Algebra.Lattice
import Waterfall.Internal.Finalizers (acquireForeignPtr, unsafeFromAcquirePtr, unsafeFromAcquire)
import qualified OpenCascade.BRepAlgoAPI.Fuse as Fuse
import qualified OpenCascade.BRepAlgoAPI.Cut as Cut
import qualified OpenCascade.BRepAlgoAPI.Common as Common
import OpenCascade.BRepBuilderAPI (MakeShape)
import qualified OpenCascade.BRepBuilderAPI.MakeShape as MakeShape
import qualified OpenCascade.BOPAlgo.Operation as BOPAlgo.Operation
import qualified OpenCascade.BOPAlgo.BOP as BOPAlgo.BOP
import qualified OpenCascade.BOPAlgo.Builder as BOPAlgo.Builder
import qualified OpenCascade.ShapeUpgrade.UnifySameDomain as UnifySameDomain
import OpenCascade.Inheritance (SubTypeOf, upcast)
import Control.Monad.IO.Class (liftIO)
import Data.Foldable (traverse_)
import Foreign.ForeignPtr (ForeignPtr)
import Control.DeepSeq (NFData (rnf), rwhnf)
import qualified OpenCascade.TopoDS.Builder as TopoDS.Builder
import qualified OpenCascade.TopoDS.Compound as TopoDS.Compound
import Control.Monad ((<=<), forM_)
import qualified OpenCascade.TopAbs.ShapeEnum as ShapeEnum
import Waterfall.Internal.FromOpenCascade (containsShapeKind, deduplicateTopoDSShapes)
import qualified OpenCascade.BOPAlgo.CellsBuilder as CellsBuilder
import qualified OpenCascade.NCollection.List as NCollection.List
import OpenCascade.BRepAlgoAPI (BooleanOperation, BuilderAlgo)
import Waterfall.Internal.ToOpenCascade (shapeSingletonList)
import qualified OpenCascade.BRepAlgoAPI.BuilderAlgo as BuilderAlgo
import qualified OpenCascade.BRepAlgoAPI.BooleanOperation as BooleanOperation

-- | A Region in 2D Space 
-- 
-- In general, this is used as a face, and extruded along some sort of path
--
-- Under the hood, this is represented by an OpenCascade `TopoDS.Shape`
-- 
-- This should be of type `TopoDS.Face`, constrained to the plane \( z=0 \).
--
-- Please feel free to report a bug if you're able to construct a `Shape`
-- which does not lie on this plane (without using Internal functions).
-- Or which is not either a `TopoDS.Face`, or a composite of faces.
newtype Shape = Shape { rawShape :: ForeignPtr TopoDS.Shape }

instance NFData Shape where
    rnf = rwhnf . rawShape

acquireShape :: Shape -> Acquire (Ptr TopoDS.Shape)
acquireShape (Shape ptr) = acquireForeignPtr ptr

shapeFromAcquire :: Acquire (Ptr TopoDS.Shape) -> Shape
shapeFromAcquire = Shape . unsafeFromAcquirePtr

toBoolean2D
    :: (SubTypeOf MakeShape a
    , SubTypeOf BooleanOperation a
    , SubTypeOf BuilderAlgo a)
    => (Acquire (Ptr a)) -> Shape -> Shape -> Shape
toBoolean2D f (Shape ptrA) (Shape ptrB) = Shape . unsafeFromAcquirePtr $ do
    a <- acquireForeignPtr ptrA
    b <- acquireForeignPtr ptrB
    builder <- f 
    liftIO $ BuilderAlgo.setNonDestructive (upcast builder) True
    liftIO . BuilderAlgo.setArguments (upcast builder) =<< shapeSingletonList a
    liftIO . BooleanOperation.setTools (upcast builder) =<< shapeSingletonList b
    liftIO $ MakeShape.build (upcast builder)

    r <- MakeShape.shape (upcast builder)
    unifier <- UnifySameDomain.fromShape r False True False
    liftIO $ UnifySameDomain.build unifier
    UnifySameDomain.shape unifier

-- | Take the union of two 2D shapes.
-- The region occupied by either one of them
union2D :: Shape -> Shape -> Shape
union2D = toBoolean2D Fuse.new

-- | Take the difference of two 2D shapes.
-- The region occupied by the first, but not the second
difference2D :: Shape -> Shape -> Shape
difference2D = toBoolean2D Cut.new

-- | Take the intersection of two 2D shapes.
-- The region occupied by both of them
intersection2D :: Shape -> Shape -> Shape
intersection2D = toBoolean2D Common.new

toBooleans2D :: BOPAlgo.Operation.Operation -> [Shape] -> Shape
toBooleans2D _ [] = emptyShape
toBooleans2D _ [x] = x
toBooleans2D op (h:shapes) = Shape . unsafeFromAcquirePtr $ do
    firstPtr <- acquireForeignPtr . rawShape $ h
    ptrs <- traverse (acquireForeignPtr . rawShape) shapes
    bop <- BOPAlgo.BOP.new
    let builder = upcast bop
    liftIO $ do
        BOPAlgo.BOP.setOperation bop op
        BOPAlgo.Builder.setNonDestructive builder True
        BOPAlgo.Builder.addArgument builder firstPtr
        traverse_ (BOPAlgo.BOP.addTool bop) ptrs
        BOPAlgo.Builder.setRunParallel builder True
        BOPAlgo.Builder.perform builder
    r <- BOPAlgo.Builder.shape builder
    unifier <- UnifySameDomain.fromShape r False True False
    liftIO $ UnifySameDomain.build unifier
    UnifySameDomain.shape unifier

-- | Take the union of a list of 2D shapes
-- May be more performant than chaining multiple applications of `union2D`
unions2D :: [Shape] -> Shape
unions2D = toBooleans2D BOPAlgo.Operation.Fuse 
    . filter (not . isEmptyShape)
    . deduplicateShapes

deduplicateShapes :: [Shape] -> [Shape]
deduplicateShapes = deduplicateTopoDSShapes acquireShape

isEmptyShape :: Shape -> Bool
isEmptyShape = 
    not . unsafeFromAcquire . (containsShapeKind ShapeEnum.Face <=< acquireShape)

intersections2D' :: [Shape] -> Shape
intersections2D' [] = emptyShape
intersections2D' [x] = x
intersections2D' ss
    | any isEmptyShape ss = emptyShape
    | otherwise  = shapeFromAcquire $ do
    builder <- CellsBuilder.new 
    liftIO $ BOPAlgo.Builder.setRunParallel (upcast builder) True
    liftIO $ BOPAlgo.Builder.setNonDestructive (upcast builder) True
    listToTake <- NCollection.List.newListOfShape
    shapes <- traverse acquireShape ss
    forM_ shapes (liftIO . NCollection.List.appendListOfShape listToTake)
    listToAvoid <- NCollection.List.newListOfShape
    liftIO $ forM_ shapes (BOPAlgo.Builder.addArgument (upcast builder))
    liftIO (BOPAlgo.Builder.perform (upcast builder))
    liftIO $ CellsBuilder.addToResult builder listToTake listToAvoid 1 False
    liftIO $ CellsBuilder.removeInternalBoundaries builder

    BOPAlgo.Builder.shape (upcast builder)

-- | Take the intersection of a list of 2D shapes
-- May be more performant than chaining multiple applications of `intersection2D`
intersections2D :: [Shape] -> Shape
intersections2D = intersections2D' . deduplicateShapes

-- | An empty 2D shape
emptyShape :: Shape
emptyShape = Shape . unsafeFromAcquirePtr $ do
    builder <- TopoDS.Builder.new
    compound <- TopoDS.Compound.new
    liftIO $ TopoDS.Builder.makeCompound builder compound
    pure (upcast compound)

-- defining these boolean operators here, rather than in Waterfall.TwoD.Booleans 
-- means that we can use them in typeclass instances without resorting to orphans

instance Semigroup Shape where
    (<>) = union2D

instance Monoid Shape where
    mempty = emptyShape
    mconcat = unions2D

instance Lattice Shape where 
    (/\) = intersection2D
    (\/) = union2D

instance BoundedJoinSemiLattice Shape where
    bottom = emptyShape