implicit 0.0.5 → 0.1.0
raw patch · 54 files changed
+3484/−2233 lines, 54 filesdep +criteriondep +downloaddep +hspecdep ~basenew-component:exe:Benchmarknew-component:exe:implicitsnapnew-uploaderPVP ok
version bump matches the API change (PVP)
Dependencies added: criterion, download, hspec, implicit, monads-tf, random, silently, snap-core, snap-server, transformers
Dependency ranges changed: base
API changes (from Hackage documentation)
- Graphics.Implicit: polygon :: [ℝ2] -> SymbolicObj2
- Graphics.Implicit.Definitions: Mirror2 :: ℝ -> SymbolicObj2 -> SymbolicObj2
- Graphics.Implicit.Definitions: Mirror3 :: (ℝ, ℝ, ℝ) -> SymbolicObj3 -> SymbolicObj3
- Graphics.Implicit.Definitions: class ComponentWiseMultable a
- Graphics.Implicit.Definitions: errorMessage :: Int -> String -> IO ()
- Graphics.Implicit.Definitions: instance [incoherent] ComponentWiseMultable ℝ2
- Graphics.Implicit.Definitions: instance [incoherent] ComponentWiseMultable ℝ3
- Graphics.Implicit.Definitions: instance [incoherent] Show (a -> b)
- Graphics.Implicit.Definitions: instance [incoherent] Show SymbolicObj2
- Graphics.Implicit.Definitions: instance [incoherent] Show SymbolicObj3
- Graphics.Implicit.Definitions: type M2 a = ((a, a), (a, a))
- Graphics.Implicit.Definitions: type M3 a = ((a, a, a), (a, a, a), (a, a, a))
- Graphics.Implicit.Definitions: xmlErrorOn :: IORef Bool
- Graphics.Implicit.Export: writeObject' :: DiscreteAproxable obj aprox => ℝ -> (FilePath -> aprox -> IO ()) -> FilePath -> obj -> IO ()
- Graphics.Implicit.ExtOpenScad: OBool :: Bool -> OVal
- Graphics.Implicit.ExtOpenScad: OError :: [String] -> OVal
- Graphics.Implicit.ExtOpenScad: OFunc :: (OVal -> OVal) -> OVal
- Graphics.Implicit.ExtOpenScad: OList :: [OVal] -> OVal
- Graphics.Implicit.ExtOpenScad: OModule :: ([OVal] -> ArgParser (IO [OVal])) -> OVal
- Graphics.Implicit.ExtOpenScad: ONum :: ℝ -> OVal
- Graphics.Implicit.ExtOpenScad: OObj2 :: SymbolicObj2 -> OVal
- Graphics.Implicit.ExtOpenScad: OObj3 :: SymbolicObj3 -> OVal
- Graphics.Implicit.ExtOpenScad: OString :: String -> OVal
- Graphics.Implicit.ExtOpenScad: OUndefined :: OVal
- Graphics.Implicit.ExtOpenScad: data OVal
- Graphics.Implicit.MathUtil: rmin :: ℝ -> ℝ -> ℝ -> ℝ
- Graphics.Implicit.Primitives: class Object obj vec | obj -> vec
- Graphics.Implicit.Primitives: instance [incoherent] Object SymbolicObj2 ℝ2
- Graphics.Implicit.Primitives: instance [incoherent] Object SymbolicObj3 ℝ3
- Graphics.Implicit.Primitives: polygon :: [ℝ2] -> SymbolicObj2
+ Graphics.Implicit: extrudeRM :: ℝ -> Maybe (ℝ -> ℝ) -> Maybe (ℝ -> ℝ) -> Maybe (ℝ -> ℝ2) -> SymbolicObj2 -> Either ℝ (ℝ2 -> ℝ) -> SymbolicObj3
+ Graphics.Implicit: extrudeRotateR :: ℝ -> ℝ -> SymbolicObj2 -> ℝ -> SymbolicObj3
+ Graphics.Implicit: pack2 :: ℝ2 -> ℝ -> [SymbolicObj2] -> Maybe SymbolicObj2
+ Graphics.Implicit: pack3 :: ℝ2 -> ℝ -> [SymbolicObj3] -> Maybe SymbolicObj3
+ Graphics.Implicit: polygonR :: ℝ -> [ℝ2] -> SymbolicObj2
+ Graphics.Implicit: rotate :: ℝ -> SymbolicObj2 -> SymbolicObj2
+ Graphics.Implicit: rotate3 :: (ℝ, ℝ, ℝ) -> SymbolicObj3 -> SymbolicObj3
+ Graphics.Implicit: rotate3V :: ℝ -> ℝ3 -> SymbolicObj3 -> SymbolicObj3
+ Graphics.Implicit: rotateExtrude :: ℝ -> Maybe ℝ -> Either ℝ2 (ℝ -> ℝ2) -> Either ℝ (ℝ -> ℝ) -> SymbolicObj2 -> SymbolicObj3
+ Graphics.Implicit.Definitions: instance GHC.Show.Show (Graphics.Implicit.Definitions.ℝ -> Graphics.Implicit.Definitions.ℝ)
+ Graphics.Implicit.Definitions: instance GHC.Show.Show (Graphics.Implicit.Definitions.ℝ -> Graphics.Implicit.Definitions.ℝ2)
+ Graphics.Implicit.Definitions: instance GHC.Show.Show (Graphics.Implicit.Definitions.ℝ2 -> Graphics.Implicit.Definitions.ℝ)
+ Graphics.Implicit.Definitions: instance GHC.Show.Show (Graphics.Implicit.Definitions.ℝ3 -> Graphics.Implicit.Definitions.ℝ)
+ Graphics.Implicit.Definitions: instance GHC.Show.Show Graphics.Implicit.Definitions.SymbolicObj2
+ Graphics.Implicit.Definitions: instance GHC.Show.Show Graphics.Implicit.Definitions.SymbolicObj3
+ Graphics.Implicit.Definitions: instance Graphics.Implicit.Definitions.ComponentWiseMultable Graphics.Implicit.Definitions.ℝ2
+ Graphics.Implicit.Definitions: instance Graphics.Implicit.Definitions.ComponentWiseMultable Graphics.Implicit.Definitions.ℝ3
+ Graphics.Implicit.Definitions: minℝ :: ℝ
+ Graphics.Implicit.Export.DiscreteAproxable: class DiscreteAproxable obj aprox
+ Graphics.Implicit.Export.DiscreteAproxable: discreteAprox :: DiscreteAproxable obj aprox => ℝ -> obj -> aprox
+ Graphics.Implicit.Export.DiscreteAproxable: instance Graphics.Implicit.Export.DiscreteAproxable.DiscreteAproxable Graphics.Implicit.Definitions.SymbolicObj2 Codec.Picture.Types.DynamicImage
+ Graphics.Implicit.Export.DiscreteAproxable: instance Graphics.Implicit.Export.DiscreteAproxable.DiscreteAproxable Graphics.Implicit.Definitions.SymbolicObj2 [Graphics.Implicit.Definitions.Polyline]
+ Graphics.Implicit.Export.DiscreteAproxable: instance Graphics.Implicit.Export.DiscreteAproxable.DiscreteAproxable Graphics.Implicit.Definitions.SymbolicObj3 Codec.Picture.Types.DynamicImage
+ Graphics.Implicit.Export.DiscreteAproxable: instance Graphics.Implicit.Export.DiscreteAproxable.DiscreteAproxable Graphics.Implicit.Definitions.SymbolicObj3 Graphics.Implicit.Definitions.NormedTriangleMesh
+ Graphics.Implicit.Export.DiscreteAproxable: instance Graphics.Implicit.Export.DiscreteAproxable.DiscreteAproxable Graphics.Implicit.Definitions.SymbolicObj3 Graphics.Implicit.Definitions.TriangleMesh
+ Graphics.Implicit.Export.PolylineFormats: hacklabLaserGCode :: [Polyline] -> Text
+ Graphics.Implicit.Export.PolylineFormats: svg :: [Polyline] -> Text
+ Graphics.Implicit.Export.SymbolicObj2: symbolicGetContour :: ℝ -> SymbolicObj2 -> [Polyline]
+ Graphics.Implicit.Export.SymbolicObj2: symbolicGetContourMesh :: ℝ -> SymbolicObj2 -> [(ℝ2, ℝ2, ℝ2)]
+ Graphics.Implicit.Export.SymbolicObj2: symbolicGetOrientedContour :: ℝ -> SymbolicObj2 -> [Polyline]
+ Graphics.Implicit.Export.SymbolicObj3: symbolicGetMesh :: ℝ -> SymbolicObj3 -> [(ℝ3, ℝ3, ℝ3)]
+ Graphics.Implicit.Export.TriangleMeshFormats: binaryStl :: [Triangle] -> ByteString
+ Graphics.Implicit.Export.TriangleMeshFormats: float32LE :: Float -> Write
+ Graphics.Implicit.Export.TriangleMeshFormats: jsTHREE :: TriangleMesh -> Text
+ Graphics.Implicit.Export.TriangleMeshFormats: normal :: (ℝ3, ℝ3, ℝ3) -> ℝ3
+ Graphics.Implicit.Export.TriangleMeshFormats: stl :: [Triangle] -> Text
+ Graphics.Implicit.Export.TriangleMeshFormats: toFloat :: Real a => a -> Float
+ Graphics.Implicit.ExtOpenScad.Definitions: (:$) :: Expr -> [Expr] -> Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: (:=) :: Pattern -> Expr -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: AP :: String -> (Maybe OVal) -> String -> (OVal -> ArgParser a) -> ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: APBranch :: [ArgParser a] -> ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: APExample :: String -> (ArgParser a) -> ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: APFailIf :: Bool -> String -> (ArgParser a) -> ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: APTerminator :: a -> ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: APTest :: String -> [TestInvariant] -> (ArgParser a) -> ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: DoNothing :: Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: Echo :: [Expr] -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: EulerCharacteristic :: Int -> TestInvariant
+ Graphics.Implicit.ExtOpenScad.Definitions: For :: Pattern -> Expr -> [st] -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: If :: Expr -> [st] -> [st] -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: Include :: String -> Bool -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: LamE :: [Pattern] -> Expr -> Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: ListE :: [Expr] -> Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: ListP :: [Pattern] -> Pattern
+ Graphics.Implicit.ExtOpenScad.Definitions: LitE :: OVal -> Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: ModuleCall :: Symbol -> [(Maybe Symbol, Expr)] -> [st] -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: Name :: Symbol -> Pattern
+ Graphics.Implicit.ExtOpenScad.Definitions: NewModule :: Symbol -> [(Symbol, Maybe Expr)] -> [st] -> Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: OBool :: Bool -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OError :: [String] -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OFunc :: (OVal -> OVal) -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OList :: [OVal] -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OModule :: ([OVal] -> ArgParser (IO [OVal])) -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: ONum :: ℝ -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OObj2 :: SymbolicObj2 -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OObj3 :: SymbolicObj3 -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OString :: String -> OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: OUndefined :: OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: StatementI :: Int -> (Statement StatementI) -> StatementI
+ Graphics.Implicit.ExtOpenScad.Definitions: Var :: Symbol -> Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: Wild :: Pattern
+ Graphics.Implicit.ExtOpenScad.Definitions: collector :: Symbol -> [Expr] -> Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: data ArgParser a
+ Graphics.Implicit.ExtOpenScad.Definitions: data Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: data OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: data Pattern
+ Graphics.Implicit.ExtOpenScad.Definitions: data Statement st
+ Graphics.Implicit.ExtOpenScad.Definitions: data StatementI
+ Graphics.Implicit.ExtOpenScad.Definitions: data TestInvariant
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Base.Alternative Graphics.Implicit.ExtOpenScad.Definitions.ArgParser
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Base.Applicative Graphics.Implicit.ExtOpenScad.Definitions.ArgParser
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Base.Functor Graphics.Implicit.ExtOpenScad.Definitions.ArgParser
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Base.Monad Graphics.Implicit.ExtOpenScad.Definitions.ArgParser
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Base.MonadPlus Graphics.Implicit.ExtOpenScad.Definitions.ArgParser
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Classes.Eq Graphics.Implicit.ExtOpenScad.Definitions.Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Classes.Eq Graphics.Implicit.ExtOpenScad.Definitions.OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Classes.Eq Graphics.Implicit.ExtOpenScad.Definitions.Pattern
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Classes.Eq Graphics.Implicit.ExtOpenScad.Definitions.StatementI
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Classes.Eq st => GHC.Classes.Eq (Graphics.Implicit.ExtOpenScad.Definitions.Statement st)
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Show.Show Graphics.Implicit.ExtOpenScad.Definitions.Expr
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Show.Show Graphics.Implicit.ExtOpenScad.Definitions.OVal
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Show.Show Graphics.Implicit.ExtOpenScad.Definitions.Pattern
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Show.Show Graphics.Implicit.ExtOpenScad.Definitions.StatementI
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Show.Show Graphics.Implicit.ExtOpenScad.Definitions.TestInvariant
+ Graphics.Implicit.ExtOpenScad.Definitions: instance GHC.Show.Show st => GHC.Show.Show (Graphics.Implicit.ExtOpenScad.Definitions.Statement st)
+ Graphics.Implicit.ExtOpenScad.Definitions: type FStack = [OVal]
+ Graphics.Implicit.ExtOpenScad.Definitions: type Symbol = String
+ Graphics.Implicit.ExtOpenScad.Definitions: type VarLookup = Map String OVal
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A0 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A1 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A10 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A11 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A12 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A2 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A3 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A4 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A5 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A6 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A7 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A8 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: A9 :: ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: data ExprIdx
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: expr0 :: GenParser Char st Expr
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: exprN :: ExprIdx -> GenParser Char st Expr
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: literal :: GenParser Char st Expr
+ Graphics.Implicit.ExtOpenScad.Parser.Expr: variable :: GenParser Char st Expr
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: assignment :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: computation :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: echo :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: forStatementI :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: function :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: ifStatementI :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: include :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: lineNumber :: forall s u (m :: * -> *). Monad m => ParsecT s u m Line
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: moduleArgsUnit :: GenParser Char st [(Maybe String, Expr)]
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: moduleArgsUnitDecl :: GenParser Char st [(String, Maybe Expr)]
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: parseProgram :: SourceName -> [Char] -> Either ParseError [StatementI]
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: suite :: GenParser Char st [StatementI]
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: throwAway :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: userModule :: GenParser Char st StatementI
+ Graphics.Implicit.ExtOpenScad.Parser.Statement: userModuleDeclaration :: GenParser Char st StatementI
+ Graphics.Implicit.Primitives: extrudeRotateR :: ℝ -> ℝ -> SymbolicObj2 -> ℝ -> SymbolicObj3
+ Graphics.Implicit.Primitives: instance Graphics.Implicit.Primitives.Object Graphics.Implicit.Definitions.SymbolicObj2 Graphics.Implicit.Definitions.ℝ2
+ Graphics.Implicit.Primitives: instance Graphics.Implicit.Primitives.Object Graphics.Implicit.Definitions.SymbolicObj3 Graphics.Implicit.Definitions.ℝ3
- Graphics.Implicit: difference :: Object obj vec => [obj] -> obj
+ Graphics.Implicit: difference :: forall obj vec. Object obj vec => [obj] -> obj
- Graphics.Implicit: intersect :: Object obj vec => [obj] -> obj
+ Graphics.Implicit: intersect :: forall obj vec. Object obj vec => [obj] -> obj
- Graphics.Implicit: union :: Object obj vec => [obj] -> obj
+ Graphics.Implicit: union :: forall obj vec. Object obj vec => [obj] -> obj
- Graphics.Implicit.Definitions: Rotate3 :: (ℝ, ℝ, ℝ) -> SymbolicObj3 -> SymbolicObj3
+ Graphics.Implicit.Definitions: Rotate3 :: ℝ3 -> SymbolicObj3 -> SymbolicObj3
- Graphics.Implicit.Definitions: type ℕ = Int
+ Graphics.Implicit.Definitions: type ℕ = Integer
- Graphics.Implicit.Definitions: type ℝ = Float
+ Graphics.Implicit.Definitions: type ℝ = Double
- Graphics.Implicit.Export: formatObject :: DiscreteAproxable obj aprox => ℝ -> (aprox -> Text) -> obj -> Text
+ Graphics.Implicit.Export: formatObject :: (DiscreteAproxable obj aprox) => ℝ -> (aprox -> Text) -> obj -> Text
- Graphics.Implicit.Export: writeBinSTL :: DiscreteAproxable obj [Triangle] => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeBinSTL :: forall obj. DiscreteAproxable obj [Triangle] => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writeGCodeHacklabLaser :: DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeGCodeHacklabLaser :: forall obj. DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writeOBJ :: DiscreteAproxable obj [((ℝ3, ℝ3), (ℝ3, ℝ3), (ℝ3, ℝ3))] => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeOBJ :: forall obj. DiscreteAproxable obj [NormedTriangle] => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writeObject :: DiscreteAproxable obj aprox => ℝ -> (aprox -> Text) -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeObject :: (DiscreteAproxable obj aprox) => ℝ -> (aprox -> Text) -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writePNG :: DiscreteAproxable obj DynamicImage => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writePNG :: forall obj. DiscreteAproxable obj DynamicImage => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writeSTL :: DiscreteAproxable obj [(ℝ3, ℝ3, ℝ3)] => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeSTL :: forall obj. DiscreteAproxable obj [Triangle] => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writeSVG :: DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeSVG :: forall obj. DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Export: writeTHREEJS :: DiscreteAproxable obj TriangleMesh => ℝ -> FilePath -> obj -> IO ()
+ Graphics.Implicit.Export: writeTHREEJS :: forall obj. DiscreteAproxable obj TriangleMesh => ℝ -> FilePath -> obj -> IO ()
- Graphics.Implicit.Primitives: difference :: Object obj vec => [obj] -> obj
+ Graphics.Implicit.Primitives: difference :: forall obj vec. Object obj vec => [obj] -> obj
- Graphics.Implicit.Primitives: intersect :: Object obj vec => [obj] -> obj
+ Graphics.Implicit.Primitives: intersect :: forall obj vec. Object obj vec => [obj] -> obj
- Graphics.Implicit.Primitives: union :: Object obj vec => [obj] -> obj
+ Graphics.Implicit.Primitives: union :: forall obj vec. Object obj vec => [obj] -> obj
Files
- Graphics/Implicit.hs +59/−23
- Graphics/Implicit/Definitions.hs +123/−73
- Graphics/Implicit/Export.hs +63/−128
- Graphics/Implicit/Export/Definitions.hs +0/−14
- Graphics/Implicit/Export/DiscreteAproxable.hs +105/−0
- Graphics/Implicit/Export/MarchingSquares.hs +51/−44
- Graphics/Implicit/Export/MarchingSquaresFill.hs +38/−30
- Graphics/Implicit/Export/NormedTriangleMeshFormats.hs +14/−9
- Graphics/Implicit/Export/PolylineFormats.hs +20/−11
- Graphics/Implicit/Export/RayTrace.hs +41/−84
- Graphics/Implicit/Export/Render.hs +123/−101
- Graphics/Implicit/Export/Render/Definitions.hs +11/−6
- Graphics/Implicit/Export/Render/GetLoops.hs +17/−9
- Graphics/Implicit/Export/Render/GetSegs.hs +29/−25
- Graphics/Implicit/Export/Render/HandlePolylines.hs +19/−17
- Graphics/Implicit/Export/Render/HandleSquares.hs +43/−31
- Graphics/Implicit/Export/Render/Interpolate.hs +23/−16
- Graphics/Implicit/Export/Render/RefineSegs.hs +22/−18
- Graphics/Implicit/Export/Render/TesselateLoops.hs +19/−15
- Graphics/Implicit/Export/Symbolic/Rebound2.hs +11/−4
- Graphics/Implicit/Export/Symbolic/Rebound3.hs +11/−4
- Graphics/Implicit/Export/SymbolicFormats.hs +103/−44
- Graphics/Implicit/Export/SymbolicObj2.hs +26/−24
- Graphics/Implicit/Export/SymbolicObj3.hs +18/−31
- Graphics/Implicit/Export/TextBuilderUtils.hs +32/−46
- Graphics/Implicit/Export/TriangleMeshFormats.hs +32/−14
- Graphics/Implicit/Export/Util.hs +29/−23
- Graphics/Implicit/ExtOpenScad.hs +23/−22
- Graphics/Implicit/ExtOpenScad/Default.hs +80/−60
- Graphics/Implicit/ExtOpenScad/Definitions.hs +81/−33
- Graphics/Implicit/ExtOpenScad/Eval/Expr.hs +30/−24
- Graphics/Implicit/ExtOpenScad/Eval/Statement.hs +41/−28
- Graphics/Implicit/ExtOpenScad/Parser/Expr.hs +108/−96
- Graphics/Implicit/ExtOpenScad/Parser/Statement.hs +93/−62
- Graphics/Implicit/ExtOpenScad/Parser/Util.hs +42/−26
- Graphics/Implicit/ExtOpenScad/Primitives.hs +124/−89
- Graphics/Implicit/ExtOpenScad/Util/ArgParser.hs +36/−103
- Graphics/Implicit/ExtOpenScad/Util/OVal.hs +52/−34
- Graphics/Implicit/ExtOpenScad/Util/StateC.hs +22/−13
- Graphics/Implicit/MathUtil.hs +39/−34
- Graphics/Implicit/ObjectUtil.hs +11/−6
- Graphics/Implicit/ObjectUtil/GetBox2.hs +37/−42
- Graphics/Implicit/ObjectUtil/GetBox3.hs +42/−62
- Graphics/Implicit/ObjectUtil/GetImplicit2.hs +35/−38
- Graphics/Implicit/ObjectUtil/GetImplicit3.hs +68/−73
- Graphics/Implicit/Primitives.hs +123/−43
- LICENSE +583/−261
- bench/ParserBench.hs +61/−0
- extopenscad.hs +0/−182
- implicit.cabal +176/−58
- programs/Benchmark.hs +81/−0
- programs/extopenscad.hs +239/−0
- programs/implicitsnap.hs +167/−0
- tests/Main.hs +8/−0
Graphics/Implicit.hs view
@@ -1,21 +1,26 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- FIXME: Required. why? {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} -{- The sole purpose of this file it to pass on the- functionality we want to be accessible to the end user. -}+{- The purpose of this file is to pass on the functionality we want+ to be accessible to an end user who is compiling objects using+ this haskell library. -} +-- MAYBEFIXME: impliment slice operation , regularPolygon and zsurface primitives.+ module Graphics.Implicit( -- Operations translate, scale,- complement,- union, intersect, difference,+ complement, union, intersect, difference, unionR, intersectR, differenceR, shell,- --slice, extrudeR,+ extrudeRotateR,+ extrudeRM, extrudeOnEdgeOf, -- Primitives sphere,@@ -24,9 +29,13 @@ cylinder, cylinder2, rectR,- --regularPolygon,- --zsurface,- polygon,+ polygonR,+ rotateExtrude,+ rotate3,+ rotate3V,+ pack3,+ rotate,+ pack2, -- Export writeSVG, writeSTL,@@ -44,23 +53,50 @@ SymbolicObj3 ) where --- Let's be explicit about where things come from :)-import Graphics.Implicit.Primitives+import Prelude(FilePath, IO)++-- The primitive objects, and functions for manipulating them.+import Graphics.Implicit.Primitives (translate, scale, complement, union, intersect, difference, unionR, intersectR, differenceR, shell, extrudeR, extrudeRM, extrudeRotateR, extrudeOnEdgeOf, sphere, rect3R, circle, cylinder, cylinder2, rectR, polygonR, rotateExtrude, rotate3, rotate3V, pack3, rotate, pack2, implicit)++-- The Extended OpenScad interpreter. import Graphics.Implicit.ExtOpenScad (runOpenscad)-import qualified Graphics.Implicit.Export as Export-import Graphics.Implicit.Definitions +-- Functions for writing files based on the result of operations on primitives.+import qualified Graphics.Implicit.Export as Export (writeSVG, writeSTL, writeBinSTL, writeOBJ, writeSCAD2, writeSCAD3, writeTHREEJS, writeGCodeHacklabLaser, writePNG)++-- Datatypes/classes defining the world, or part of the world.+import Graphics.Implicit.Definitions (ℝ, SymbolicObj2, SymbolicObj3)+ -- We want Export to be a bit less polymorphic -- (so that types will collapse nicely) -writeSVG = Export.writeSVG :: ℝ -> FilePath -> SymbolicObj2 -> IO ()-writeSTL = Export.writeSTL :: ℝ -> FilePath -> SymbolicObj3 -> IO ()-writeBinSTL = Export.writeBinSTL :: ℝ -> FilePath -> SymbolicObj3 -> IO ()-writeOBJ = Export.writeOBJ :: ℝ -> FilePath -> SymbolicObj3 -> IO ()-writeSCAD2 = Export.writeSCAD2 :: ℝ -> FilePath -> SymbolicObj2 -> IO ()-writeSCAD3 = Export.writeSCAD3 :: ℝ -> FilePath -> SymbolicObj3 -> IO ()-writeTHREEJS = Export.writeTHREEJS :: ℝ -> FilePath -> SymbolicObj3 -> IO ()-writeGCodeHacklabLaser = Export.writeGCodeHacklabLaser :: ℝ -> FilePath -> SymbolicObj2 -> IO () -writePNG2 = Export.writePNG :: ℝ -> FilePath -> SymbolicObj2 -> IO ()-writePNG3 = Export.writePNG :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeSVG :: ℝ -> FilePath -> SymbolicObj2 -> IO ()+writeSVG = Export.writeSVG++writeSTL :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeSTL = Export.writeSTL++writeBinSTL :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeBinSTL = Export.writeBinSTL++writeOBJ :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeOBJ = Export.writeOBJ++writeSCAD2 :: ℝ -> FilePath -> SymbolicObj2 -> IO ()+writeSCAD2 = Export.writeSCAD2++writeSCAD3 :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeSCAD3 = Export.writeSCAD3++writeTHREEJS :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeTHREEJS = Export.writeTHREEJS++writeGCodeHacklabLaser :: ℝ -> FilePath -> SymbolicObj2 -> IO ()+writeGCodeHacklabLaser = Export.writeGCodeHacklabLaser++writePNG2 :: ℝ -> FilePath -> SymbolicObj2 -> IO ()+writePNG2 = Export.writePNG++writePNG3 :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writePNG3 = Export.writePNG
Graphics/Implicit/Definitions.hs view
@@ -1,28 +1,122 @@-{-# LANGUAGE FlexibleInstances, TypeSynonymInstances #-}- -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Copyright 2015 2016, Mike MacHenry (mike.machenry@gmail.com)+-- Released under the GNU AGPLV3+, see LICENSE -module Graphics.Implicit.Definitions where+-- This module deliberately declares orphan instances of Show.+{-# OPTIONS_GHC -fno-warn-orphans #-} --- a few imports for great evil :(--- we want global IO refs.-import Data.IORef (IORef, newIORef, readIORef)-import System.IO.Unsafe (unsafePerformIO)-import Data.VectorSpace +-- Required. FIXME: why?+{-# LANGUAGE FlexibleInstances #-} +-- Definitions of the types used when modeling, and a few operators.++module Graphics.Implicit.Definitions (+ ℝ,+ ℝ2,+ ℝ3,+ minℝ,+ ℕ,+ (⋅),+ (⋯*),+ (⋯/),+ Polyline,+ Triangle,+ NormedTriangle,+ TriangleMesh,+ NormedTriangleMesh,+ Obj2,+ Obj3,+ Box2,+ Box3,+ Boxed2,+ Boxed3,+ BoxedObj2,+ BoxedObj3,+ SymbolicObj2(+ RectR,+ Circle,+ PolygonR,+ Complement2,+ UnionR2,+ DifferenceR2,+ IntersectR2,+ Translate2,+ Scale2,+ Rotate2,+ Shell2,+ Outset2,+ EmbedBoxedObj2),+ SymbolicObj3(+ Rect3R,+ Sphere,+ Cylinder,+ Complement3,+ UnionR3,+ IntersectR3,+ DifferenceR3,+ Translate3,+ Scale3,+ Rotate3,+ Rotate3V,+ Shell3,+ Outset3,+ EmbedBoxedObj3,+ ExtrudeR,+ ExtrudeRotateR,+ ExtrudeRM,+ ExtrudeOnEdgeOf,+ RotateExtrude),+ Rectilinear2,+ Rectilinear3,+ )+where++import Prelude (Show, Double, Integer, Maybe, Either, show, (*), (/))++import Data.VectorSpace (Scalar, InnerSpace, (<.>))+ -- Let's make things a bit nicer. --- Following math notation ℝ, ℝ², ℝ³...-type ℝ = Float+-- Following the math notation ℝ, ℝ², ℝ³...+-- Supports changing Float to Double for more precision!+-- FIXME: what about using rationals instead of Float/Double?+type ℝ = Double type ℝ2 = (ℝ,ℝ) type ℝ3 = (ℝ,ℝ,ℝ) -type ℕ = Int+minℝ :: ℝ+-- for Floats.+--minℝ = 0.00000011920928955078125 * 2 +-- for Doubles.+minℝ = 0.0000000000000002++type ℕ = Integer+ -- TODO: Find a better place for this (⋅) :: InnerSpace a => a -> a -> Scalar a (⋅) = (<.>) ++-- handle additional instances of Show.+instance Show (ℝ -> ℝ) where+ show _ = "<function ℝ>"++instance Show (ℝ -> ℝ2) where+ show _ = "<expand ℝ -> ℝ2>"++instance Show (ℝ2 -> ℝ) where+ show _ = "<collapse ℝ2 -> ℝ>"++instance Show (ℝ3 -> ℝ) where+ show _ = "<collapse ℝ3 -> ℝ>"++--instance Show BoxedObj2 where+-- show _ = "<BoxedObj2>"++--instance Show BoxedObj3 where+-- show _ = "<BoxedObj3>"+ -- TODO: Find a better way to do this? class ComponentWiseMultable a where (⋯*) :: a -> a -> a@@ -34,36 +128,23 @@ (x,y,z) ⋯* (x',y',z') = (x*x', y*y', z*z') (x,y,z) ⋯/ (x',y',z') = (x/x', y/y', z/z') --- nxn matrices--- eg. M2 ℝ = M₂(ℝ)-type M2 a = ((a,a),(a,a))-type M3 a = ((a,a,a),(a,a,a),(a,a,a))-- -- | A chain of line segments, as in SVG -- eg. [(0,0), (0.5,1), (1,0)] ---> /\ type Polyline = [ℝ2] --- | A triangle (a,b,c) = a trinagle with vertices a, b and c+-- | A triangle (a,b,c) = a triangle with vertices a, b and c type Triangle = (ℝ3, ℝ3, ℝ3) -- | A triangle ((v1,n1),(v2,n2),(v3,n3)) has vertices v1, v2, v3 -- with corresponding normals n1, n2, and n3 type NormedTriangle = ((ℝ3, ℝ3), (ℝ3, ℝ3), (ℝ3, ℝ3)) - -- | A triangle mesh is a bunch of triangles :) type TriangleMesh = [Triangle] -- | A normed triangle mesh is a bunch of normed trianlges!! type NormedTriangleMesh = [NormedTriangle] --- $ In Implicit CAD, we consider objects as functions--- of `outwardness'. The boundary is 0, negative is the--- interior and positive the exterior. The magnitude is--- how far out or in.--- For more details, refer to http://christopherolah.wordpress.com/2011/11/06/manipulation-of-implicit-functions-with-an-eye-on-cad/- -- | A 2D object type Obj2 = (ℝ2 -> ℝ) @@ -76,24 +157,27 @@ -- | A 3D box type Box3 = (ℝ3, ℝ3) --- | Boxed 2D object+-- | A Box for containing a 2D object type Boxed2 a = (a, Box2) --- | Boxed 3D object+-- | A Box for containing a 3D object type Boxed3 a = (a, Box3) +-- | A Boxed 2D object type BoxedObj2 = Boxed2 Obj2++-- | A Boxed 3D object type BoxedObj3 = Boxed3 Obj3 -- | A symbolic 2D object format.--- We want to have a symbolic object so that we can +-- We want to have a symbolic object so that we can -- accelerate rendering & give ideal meshes for simple -- cases. data SymbolicObj2 = -- Primitives- RectR ℝ ℝ2 ℝ2- | Circle ℝ- | PolygonR ℝ [ℝ2]+ RectR ℝ ℝ2 ℝ2 -- rounding, start, stop.+ | Circle ℝ -- radius+ | PolygonR ℝ [ℝ2] -- rounding, points. -- (Rounded) CSG | Complement2 SymbolicObj2 | UnionR2 ℝ [SymbolicObj2]@@ -103,7 +187,6 @@ | Translate2 ℝ2 SymbolicObj2 | Scale2 ℝ2 SymbolicObj2 | Rotate2 ℝ SymbolicObj2- | Mirror2 ℝ SymbolicObj2 -- Boundary mods | Outset2 ℝ SymbolicObj2 | Shell2 ℝ SymbolicObj2@@ -112,23 +195,21 @@ deriving Show -- | A symbolic 3D format!- data SymbolicObj3 = -- Primitives Rect3R ℝ ℝ3 ℝ3 | Sphere ℝ- | Cylinder ℝ ℝ ℝ -- h r1 r2+ | Cylinder ℝ ℝ ℝ -- (Rounded) CSG | Complement3 SymbolicObj3 | UnionR3 ℝ [SymbolicObj3]- | IntersectR3 ℝ [SymbolicObj3] | DifferenceR3 ℝ [SymbolicObj3]+ | IntersectR3 ℝ [SymbolicObj3] -- Simple transforms | Translate3 ℝ3 SymbolicObj3 | Scale3 ℝ3 SymbolicObj3- | Rotate3 (ℝ,ℝ,ℝ) SymbolicObj3+ | Rotate3 ℝ3 SymbolicObj3 | Rotate3V ℝ ℝ3 SymbolicObj3- | Mirror3 (ℝ,ℝ,ℝ) SymbolicObj3 -- Boundary mods | Outset3 ℝ SymbolicObj3 | Shell3 ℝ SymbolicObj3@@ -137,7 +218,7 @@ -- 2D based | ExtrudeR ℝ SymbolicObj2 ℝ | ExtrudeRotateR ℝ ℝ SymbolicObj2 ℝ- | ExtrudeRM + | ExtrudeRM ℝ -- rounding radius (Maybe (ℝ -> ℝ)) -- twist (Maybe (ℝ -> ℝ)) -- scale@@ -145,11 +226,11 @@ SymbolicObj2 -- object to extrude (Either ℝ (ℝ2 -> ℝ)) -- height to extrude to | RotateExtrude- ℝ -- Angle to sweep to- (Maybe ℝ) -- Loop or path (rounded corner)+ ℝ -- Angle to sweep to+ (Maybe ℝ) -- Loop or path (rounded corner) (Either ℝ2 (ℝ -> ℝ2)) -- translate function (Either ℝ (ℝ -> ℝ )) -- rotate function- SymbolicObj2 -- object to extrude+ SymbolicObj2 -- object to extrude | ExtrudeOnEdgeOf SymbolicObj2 SymbolicObj2 deriving Show @@ -159,34 +240,3 @@ -- | Rectilinear 2D set type Rectilinear3 = [Box3] --- | Now for something that makes me a bad person...--- I promise I'll use it for good, not evil!--- I don't want to reparse the program arguments --- everytime I want to know if XML errors are needed.--{-# NOINLINE xmlErrorOn #-}--xmlErrorOn :: IORef Bool-xmlErrorOn = unsafePerformIO $ newIORef False--errorMessage :: Int -> String -> IO()-errorMessage line msg = do- useXML <- readIORef xmlErrorOn- let- msg' = "At line <line>" ++ show line ++ "</line>:" ++ msg- -- dropXML inTag (x:xs)- dropXML inQuote False ('"':xs) = '"':dropXML (not inQuote) False xs- dropXML True _ ( x :xs) = x:dropXML True False xs- dropXML False False ('<':xs) = dropXML False True xs- dropXML False True ('>':xs) = dropXML False False xs- dropXML inQuote True ( _ :xs) = dropXML inQuote True xs- dropXML inQuote False ( x :xs) = x:dropXML inQuote False xs- dropXML _ _ [] = []- putStrLn $ if useXML - then "<error>" ++ msg' ++ "</error>"- else dropXML False False msg'- return ()---- HACK: This needs to be fixed correctly someday-instance Show (a -> b) where- show _ = "<function>"
Graphics/Implicit/Export.hs view
@@ -1,153 +1,88 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE-{-# LANGUAGE FlexibleContexts #-}--module Graphics.Implicit.Export where--import Graphics.Implicit.Definitions---import Graphics.Implicit.Operations (slice)+-- Copyright (C) 2014 2015, Julia Longtin (julial@turinglace.com)+-- Copyright (C) 2015 2016, Mike MacHenry (mike.machenry@gmail.com)+-- Released under the GNU AGPLV3+, see LICENSE -import Data.Text.Lazy (Text,pack)-import Data.Text.Lazy.IO (writeFile)-import Prelude hiding (writeFile)-import qualified Data.ByteString.Lazy as LBS+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} --- class DiscreteApproxable-import Graphics.Implicit.Export.Definitions+-- FIXME: Required. why?+{-# LANGUAGE FlexibleContexts #-} --- instances of DiscreteApproxable...-import Graphics.Implicit.Export.SymbolicObj2 ()-import Graphics.Implicit.Export.SymbolicObj3 ()-import Graphics.Implicit.Export.RayTrace ()+module Graphics.Implicit.Export (writeObject, formatObject, writeSVG, writeSTL, writeBinSTL, writeOBJ, writeTHREEJS, writeGCodeHacklabLaser, writeSCAD3, writeSCAD2, writePNG) where --- File formats-import qualified Graphics.Implicit.Export.PolylineFormats as PolylineFormats-import qualified Graphics.Implicit.Export.TriangleMeshFormats as TriangleMeshFormats-import qualified Graphics.Implicit.Export.NormedTriangleMeshFormats as NormedTriangleMeshFormats-import qualified Graphics.Implicit.Export.SymbolicFormats as SymbolicFormats+import Prelude (FilePath, IO, (.), ($)) -import qualified Codec.Picture as ImageFormatCodecs+-- The types of our objects (before rendering), and the type of the resolution to render with.+import Graphics.Implicit.Definitions (SymbolicObj2, SymbolicObj3, ℝ, Polyline, TriangleMesh, Triangle, NormedTriangle) --- Write an object in a given formet...+-- The functions for writing our output, as well as a type used.+import Data.Text.Lazy (Text)+import qualified Data.Text.Lazy.IO as LT (writeFile)+import qualified Data.ByteString.Lazy as LBS (writeFile) -writeObject :: (DiscreteAproxable obj aprox) => - ℝ -- ^ Resolution- -> (aprox -> Text) -- ^ File Format (Function that formats)- -> FilePath -- ^ File Name- -> obj -- ^ Object to render- -> IO () -- ^ Writing Action!+-- Import instances of DiscreteApproxable...+import Graphics.Implicit.Export.DiscreteAproxable (DiscreteAproxable, discreteAprox) -writeObject res format filename obj = writeFile filename $ formatObject res format obj+-- Object formats+import qualified Graphics.Implicit.Export.PolylineFormats as PolylineFormats (svg, hacklabLaserGCode)+import qualified Graphics.Implicit.Export.TriangleMeshFormats as TriangleMeshFormats (stl, binaryStl, jsTHREE)+import qualified Graphics.Implicit.Export.NormedTriangleMeshFormats as NormedTriangleMeshFormats (obj)+import qualified Graphics.Implicit.Export.SymbolicFormats as SymbolicFormats (scad3, scad2)+import qualified Codec.Picture as ImageFormatCodecs (DynamicImage, savePngImage) -writeObject' :: (DiscreteAproxable obj aprox) => - ℝ -- ^ Resolution- -> (FilePath -> aprox -> IO ()) -- ^ File Format writer- -> FilePath -- ^ File Name- -> obj -- ^ Object to render- -> IO () -- ^ Writing Action!+-- Write an object using the given format function.+writeObject :: (DiscreteAproxable obj aprox)+ => ℝ -- ^ Resolution+ -> (aprox -> Text) -- ^ File Format (Function that formats)+ -> FilePath -- ^ File Name+ -> obj -- ^ Object to render+ -> IO () -- ^ Writing Action!+writeObject res format filename obj =+ let aprox = formatObject res format obj+ in LT.writeFile filename aprox +-- Write an object using the given format writer.+writeObject' :: (DiscreteAproxable obj aprox)+ => ℝ -- ^ Resolution+ -> (FilePath -> aprox -> IO ()) -- ^ File Format writer+ -> FilePath -- ^ File Name+ -> obj -- ^ Object to render+ -> IO () -- ^ Writing Action! writeObject' res formatWriter filename obj =- let- aprox = discreteAprox res obj- in - formatWriter filename aprox--formatObject :: (DiscreteAproxable obj aprox) =>- ℝ -- ^ Resolution- -> (aprox -> Text) -- ^ File Format (Function that formats)- -> obj -- ^ Object to render- -> Text -- ^ Resulting lazy ByteString+ let aprox = discreteAprox res obj+ in formatWriter filename aprox +formatObject :: (DiscreteAproxable obj aprox)+ => ℝ -- ^ Resolution+ -> (aprox -> Text) -- ^ File Format (Function that formats)+ -> obj -- ^ Object to render+ -> Text -- ^ Resulting lazy ByteString formatObject res format = format . discreteAprox res +writeSVG :: forall obj. DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO () writeSVG res = writeObject res PolylineFormats.svg -writeSTL res = writeObject res TriangleMeshFormats.stl+writeSTL :: forall obj. DiscreteAproxable obj [Triangle] => ℝ -> FilePath -> obj -> IO ()+writeSTL res = writeObject res TriangleMeshFormats.stl +writeBinSTL :: forall obj. DiscreteAproxable obj [Triangle] => ℝ -> FilePath -> obj -> IO () writeBinSTL res file obj = LBS.writeFile file $ TriangleMeshFormats.binaryStl $ discreteAprox res obj -writeOBJ res = writeObject res NormedTriangleMeshFormats.obj-writeTHREEJS res = writeObject res TriangleMeshFormats.jsTHREE--writeGCodeHacklabLaser res = writeObject res PolylineFormats.hacklabLaserGCode--writeSCAD3 res filename obj = writeFile filename $ SymbolicFormats.scad3 res obj-writeSCAD2 res filename obj = writeFile filename $ SymbolicFormats.scad2 res obj--writePNG res = writeObject' res ImageFormatCodecs.savePngImage+writeOBJ :: forall obj. DiscreteAproxable obj [NormedTriangle] => ℝ -> FilePath -> obj -> IO ()+writeOBJ res = writeObject res NormedTriangleMeshFormats.obj -{--renderRaw :: ℝ3 -> ℝ3 -> ℝ -> String -> Obj3 -> IO()-renderRaw (x1, y1, z1) (x2, y2, z2) res name obj = - -- A hacky way to encode to chars, but it will do- let convert n = if n > 1 then 'a' else if n > 0.5 then 'b' else if n > 0.1 then 'c' else if n == 0 then 'd' else if n > -0.5 then 'e' else 'd' in- do- putStrLn $ show $ length $ [ obj (x,y,z) | x <- [x1, x1+res.. x2], y <- [y1, y1+res.. y2], z <- [z1, z1+res.. z2] ]- out <- openFile name WriteMode- mapM_ ( (hPutChar out) . convert) $ - [ obj (x,y,z) | x <- [x1, x1+res.. x2], y <- [y1, y1+res.. y2], z <- [z1, z1+res.. z2] ]- hClose out+writeTHREEJS :: forall obj. DiscreteAproxable obj TriangleMesh => ℝ -> FilePath -> obj -> IO ()+writeTHREEJS res = writeObject res TriangleMeshFormats.jsTHREE -renderRaw2D :: ℝ2 -> ℝ2 -> ℝ -> String -> Obj2 -> IO()-renderRaw2D (x1, y1) (x2, y2) res name obj = - -- A hacky way to encode to chars, but it will do- let convert n = if n > 1 then 'a' else if n > 0.5 then 'b' else if n > 0.1 then 'c' else if n == 0 then 'd' else if n > -0.5 then 'e' else 'd' in- do- putStrLn $ show $ length $ [x1, x1+res.. x2]- putStrLn $ show $ length $ [ obj (x,y) | x <- [x1, x1+res.. x2], y <- [y1, y1+res.. y2] ]- out <- openFile name WriteMode- mapM_ (mapM_ ( (hPutChar out) . convert)) $ - [[ obj (x,y) | x <- [x1, x1+res.. x2] ] | y <- [y1, y1+res.. y2] ]- hClose out+writeGCodeHacklabLaser :: forall obj. DiscreteAproxable obj [Polyline] => ℝ -> FilePath -> obj -> IO ()+writeGCodeHacklabLaser res = writeObject res PolylineFormats.hacklabLaserGCode +writeSCAD3 :: ℝ -> FilePath -> SymbolicObj3 -> IO ()+writeSCAD3 res filename obj = LT.writeFile filename $ SymbolicFormats.scad3 res obj -{-writeGCodeMakerbot :: - ℝ3 -- ^ lower corner of bounding box- -> ℝ3 -- ^ upper corner of bounding box- -> ℝ -- ^ resolution of rendering- -> FilePath -- ^ Filename to write gcode to- -> Obj3 -- ^ 3D object to make gcode for- -> IO () -- ^ Resulting IO action that will write gcode+writeSCAD2 :: ℝ -> FilePath -> SymbolicObj2 -> IO ()+writeSCAD2 res filename obj = LT.writeFile filename $ SymbolicFormats.scad2 res obj - writeGCodeMakerbot (x1,y1,z1) (x2,y2,z2) d name obj = - let - slices = [slice zheight obj | zheight <- [z1, z1+0.1.. z2] ]- prep obj (x,y) = (obj (x,y), obj (x+d,y), obj (x+d,y+d), obj (x,y+d), obj (x+d/2,y+d/2) , (x,y), d ) - layer obj2 = (filter polylineNotNull) $ (map reducePolyline) $ orderLines $ concat $ map getLineSeg [prep obj2 (x,y) | x <- [x1, x1+d.. x2], y <- [y1, y1 +d.. y2] ]- levelmultilines = map layer slices- gcodeHeader = - "(generated by ImplicitCAD, based of skeinforge default makerbot results)\n"- ++ "(**** Initialization ****)\n"- ++ "M104 S220 T0 (Temperature to 220 celsius)\n"- ++ "M109 S110 T0 (set heated-build-platform temperature)\n"- ++ "G21 (Metric FTW)\n"- ++ "G90 (Absolute Positioning)\n"- ++ "G92 X0 Y0 Z0 (You are now at 0,0,0)\n"- ++ "M108 S255 (Extruder speed = max; not turning it on yet!)\n"- ++ "(**** Prep the extruder... ****)\n"- ++ "G0 Z15 (Move up for test extrusion)\n"- ++ "M6 T0 (Wait for tool to heat up)\n"- ++ "G04 P5000 (Wait 5 seconds)\n"- ++ "M101 (Extruder on, forward)\n"- ++ "G04 P5000 (Wait 5 seconds)\n"- ++ "M103 (Extruder off)\n"- ++ "M01 (The heater is warming up and will do a test extrusion. Click yes after you have cleared the nozzle of the extrusion.)\n"- ++ "G0 Z0(Go back to zero.)\n"- gcodeFooter = - "M104 S0 (extruder heating off!)\n"- ++"G00 X0.0 Y0.0 (move to 0)\n"- ++"M2 (end)"- gcodeXYZ :: ℝ3 -> [Char]- gcodeXYZ (x,y,z) = "X"++ show x ++" Y"++ show y ++" Z"++ show z- interpretPolyline (start:others) = - "G00 "++ gcodeXY start ++ "\n"- ++ "M101 (extruder forward!)\n"- ++ concat (map (\p -> "G01 " ++ (gcodeXY p) ++ "\n") others)- ++ "M103 (extruder off)\n\n"- text = gcodeHeader- ++ (concat $ map interpretPolyline multilines)- ++ gcodeFooter- in do - writeFile name text--}--}+writePNG :: forall obj. DiscreteAproxable obj ImageFormatCodecs.DynamicImage => ℝ -> FilePath -> obj -> IO ()+writePNG res = writeObject' res ImageFormatCodecs.savePngImage
− Graphics/Implicit/Export/Definitions.hs
@@ -1,14 +0,0 @@--{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-}--module Graphics.Implicit.Export.Definitions where--import Graphics.Implicit.Definitions---- | There is a discrete way to aproximate this object.--- eg. Aproximating a 3D object with a tirangle mesh--- would be DiscreteApproxable Obj3 TriangleMesh-class DiscreteAproxable obj aprox where- discreteAprox :: ℝ -> obj -> aprox--
+ Graphics/Implicit/Export/DiscreteAproxable.hs view
@@ -0,0 +1,105 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- Allow our DiscreteAproxable class to handle multiple parameters.+{-# LANGUAGE MultiParamTypeClasses #-}++-- FIXME: why is this here?+{-# LANGUAGE TypeSynonymInstances, FlexibleInstances #-}++module Graphics.Implicit.Export.DiscreteAproxable where++import Prelude(Int, (-), (/), ($), (<), map, round, (+), maximum, abs, (*), fromIntegral, max, realToFrac)++import Graphics.Implicit.Definitions (ℝ, ℝ2, SymbolicObj3, SymbolicObj2, Polyline, TriangleMesh, NormedTriangleMesh)++import Graphics.Implicit.ObjectUtil (getImplicit3, getImplicit2, getBox3, getBox2)++import Graphics.Implicit.Export.SymbolicObj3 (symbolicGetMesh)+import Graphics.Implicit.Export.SymbolicObj2 (symbolicGetContour)+import Graphics.Implicit.Export.Util (normTriangle) + +import Graphics.Implicit.Export.RayTrace (dynamicImage, Color, average, Camera(Camera), Light(Light), Scene(Scene), traceRay, cameraRay)++import Codec.Picture (DynamicImage, generateImage, PixelRGBA8(PixelRGBA8))++import Data.VectorSpace ((^+^), (^/), (*^), (^-^))+import Data.AffineSpace ((.-^), (.+^))+++-- | There is a discrete way to aproximate this object.+-- eg. Aproximating a 3D object with a tirangle mesh+-- would be DiscreteApproxable Obj3 TriangleMesh+class DiscreteAproxable obj aprox where+ discreteAprox :: ℝ -> obj -> aprox++instance DiscreteAproxable SymbolicObj3 TriangleMesh where+ discreteAprox res obj = symbolicGetMesh res obj++instance DiscreteAproxable SymbolicObj3 NormedTriangleMesh where+ discreteAprox res obj = map (normTriangle res (getImplicit3 obj)) $ symbolicGetMesh res obj++-- FIXME: magic numbers.+instance DiscreteAproxable SymbolicObj3 DynamicImage where+ discreteAprox _ symbObj = dynamicImage $ generateImage pixelRenderer (round w) (round h)+ where+ (w,h) = (150, 150) :: ℝ2+ obj = getImplicit3 symbObj+ box@((x1,y1,z1), (_,y2,z2)) = getBox3 symbObj+ av :: ℝ -> ℝ -> ℝ+ av a b = (a+b)/(2::ℝ)+ avY = av y1 y2+ avZ = av z1 z2+ deviation = maximum [abs $ y1 - avY, abs $ y2 - avY, abs $ z1 - avZ, abs $ z2 - avZ]+ camera = Camera (x1-deviation*(2.2::ℝ), avY, avZ) (0, -1, 0) (0,0, -1) 1.0+ lights = [Light (x1-deviation*(1.5::ℝ), y1 - (0.4::ℝ)*(y2-y1), avZ) ((0.03::ℝ)*deviation) ]+ scene = Scene obj (PixelRGBA8 200 200 230 255) lights (PixelRGBA8 255 255 255 0)+ pixelRenderer :: Int -> Int -> Color+ pixelRenderer a b = renderScreen + ((fromIntegral a :: ℝ)/w - (0.5::ℝ)) ((fromIntegral b :: ℝ)/h - (0.5 ::ℝ))+ renderScreen :: ℝ -> ℝ -> Color+ renderScreen a b =+ average $ [+ traceRay + (cameraRay camera ((a,b) ^+^ ( 0.25/w, 0.25/h)))+ 2 box scene,+ traceRay + (cameraRay camera ((a,b) ^+^ (-0.25/w, 0.25/h)))+ 0.5 box scene,+ traceRay + (cameraRay camera ((a,b) ^+^ (0.25/w, -0.25/h)))+ 0.5 box scene,+ traceRay + (cameraRay camera ((a,b) ^+^ (-0.25/w,-0.25/h)))+ 0.5 box scene+ ]++instance DiscreteAproxable SymbolicObj2 [Polyline] where+ discreteAprox res obj = symbolicGetContour res obj++instance DiscreteAproxable SymbolicObj2 DynamicImage where+ discreteAprox _ symbObj = dynamicImage $ generateImage pixelRenderer (round w) (round h)+ where+ (w,h) = (150, 150) :: ℝ2+ obj = getImplicit2 symbObj+ (p1@(x1,_), p2@(_,y2)) = getBox2 symbObj+ (dx, dy) = p2 ^-^ p1+ dxy = max dx dy+ pixelRenderer :: Int -> Int -> Color+ pixelRenderer mya myb = mycolor+ where+ xy a b = ((x1,y2) .-^ (dxy-dx, dy-dxy)^/2) .+^ dxy*^(a/w, -b/h)+ s = 0.25 :: ℝ+ (a', b') = (realToFrac mya, realToFrac myb) :: (ℝ2)+ mycolor = average [objColor $ xy a' b', objColor $ xy a' b',+ objColor $ xy (a'+s) (b'+s),+ objColor $ xy (a'-s) (b'-s),+ objColor $ xy (a'+s) (b'+s),+ objColor $ xy (a'-s) (b'-s)]+ objColor p = if obj p < 0 then PixelRGBA8 150 150 160 255 else PixelRGBA8 255 255 255 0+++++
Graphics/Implicit/Export/MarchingSquares.hs view
@@ -1,13 +1,19 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE module Graphics.Implicit.Export.MarchingSquares (getContour) where -import Graphics.Implicit.Definitions-import Control.Parallel.Strategies (using, parList, rdeepseq)-import Debug.Trace-import Data.VectorSpace+import Prelude(Int, Bool(True, False), ceiling, fromIntegral, (/), (+), (-), filter, map, ($), (*), (/=), (<=), (>), (.), splitAt, div, unzip, length, (++), (<), (++), head, concat, not, null, (||), Eq, Int, fst, snd) +import Graphics.Implicit.Export.Render.HandlePolylines (reducePolyline)++import Graphics.Implicit.Definitions (ℝ2, Polyline, Obj2, (⋯/), (⋯*))++-- FIXME: commented out for now, parallelism is not properly implemented.+-- import Control.Parallel.Strategies (using, parList, rdeepseq)+import Data.VectorSpace ((^-^), (^+^))+ both :: (a -> b) -> (a,a) -> (b,b) both f (x,y) = (f x, f y) @@ -19,12 +25,19 @@ getContour p1 p2 d obj = let -- How many steps will we take on each axis?- n@(nx,ny) = (fromIntegral . ceiling) `both` ((p2 ^-^ p1) ⋯/ d)+ n :: (Int, Int)+ n = (ceiling) `both` ((p2 ^-^ p1) ⋯/ d)+ nx = fst n+ ny = snd n -- Divide it up and compute the polylines gridPos :: (Int,Int) -> (Int,Int) -> ℝ2- gridPos (nx,ny) (mx,my) = let p = ( fromIntegral mx / fromIntegral nx- , fromIntegral my / fromIntegral ny)- in p1 ^+^ (p2 ^-^ p1) ⋯* p+ gridPos (nx',ny') (mx,my) =+ let+ p :: ℝ2+ p = ( fromIntegral mx / fromIntegral nx'+ , fromIntegral my / fromIntegral ny')+ in+ p1 ^+^ (p2 ^-^ p1) ⋯* p linesOnGrid :: [[[Polyline]]] linesOnGrid = [[getSquareLineSegs (gridPos n (mx,my))@@ -37,8 +50,10 @@ in multilines +-- FIXME: Commented out, not used?+{- getContour2 :: ℝ2 -> ℝ2 -> ℝ2 -> Obj2 -> [Polyline]-getContour2 p1@(x1, y1) p2@(x2, y2) d obj = +getContour2 p1@(x1, y1) p2@(x2, y2) d obj = let -- How many steps will we take on each axis? n@(nx,ny) = (fromIntegral . ceiling) `both` ((p2 ^-^ p1) ⋯/ d)@@ -61,16 +76,16 @@ multilines = (filter polylineNotNull) $ (map reducePolyline) $ orderLinesDC $ linesOnGrid in multilines- +-} -- | This function gives line segments to divide negative interior--- regions and positive exterior ones inside a square, based on its +-- regions and positive exterior ones inside a square, based on its -- values at its vertices. -- It is based on the linearly-interpolated marching squares algorithm. getSquareLineSegs :: ℝ2 -> ℝ2 -> Obj2 -> [Polyline]-getSquareLineSegs p1@(x1, y1) p2@(x2, y2) obj =- let +getSquareLineSegs (x1, y1) (x2, y2) obj =+ let (x,y) = (x1, y1) -- Let's evlauate obj at a few points...@@ -93,51 +108,55 @@ -- | | -- | | -- | |- -- -----------*----------- -- midy1+ -- ---------*----------+ -- midy1 midx1 = (x, y + dy*x1y1/(x1y1-x1y2)) midx2 = (x + dx, y + dy*x2y1/(x2y1-x2y2)) midy1 = (x + dx*x1y1/(x1y1-x2y1), y ) midy2 = (x + dx*x1y2/(x1y2-x2y2), y + dy)+ notPointLine :: Eq a => [a] -> Bool notPointLine (p1:p2:[]) = p1 /= p2+ notPointLine ([]) = False+ notPointLine ([_]) = False+ notPointLine (_ : (_ : (_ : _))) = False in filter (notPointLine) $ case (x1y2 <= 0, x2y2 <= 0, x1y1 <= 0, x2y1 <= 0) of -- Yes, there's some symetries that could reduce the amount of code... -- But I don't think they're worth exploiting...- (True, True, + (True, True, True, True) -> [] (False, False, False, False) -> []- (True, True, + (True, True, False, False) -> [[midx1, midx2]] (False, False, True, True) -> [[midx1, midx2]]- (False, True, + (False, True, False, True) -> [[midy1, midy2]] (True, False, True, False) -> [[midy1, midy2]] (True, False, False, False) -> [[midx1, midy2]]- (False, True, + (False, True, True, True) -> [[midx1, midy2]]- (True, True, + (True, True, False, True) -> [[midx1, midy1]] (False, False, True, False) -> [[midx1, midy1]]- (True, True, + (True, True, True, False) -> [[midx2, midy1]] (False, False, False, True) -> [[midx2, midy1]] (True, False, True, True) -> [[midx2, midy2]]- (False, True, + (False, True, False, False) -> [[midx2, midy2]] (True, False, False, True) -> if c > 0 then [[midx1, midy2], [midx2, midy1]] else [[midx1, midy1], [midx2, midy2]]- (False, True, + (False, True, True, False) -> if c <= 0 then [[midx1, midy2], [midx2, midy1]] else [[midx1, midy1], [midx2, midy2]]@@ -148,7 +167,7 @@ -- Many have multiple implementations as efficiency experiments. -- At some point, we'll get rid of the redundant ones.... -+{- orderLines :: [Polyline] -> [Polyline] orderLines [] = [] orderLines (present:remaining) =@@ -161,31 +180,18 @@ case findNext remaining of (Nothing, _) -> present:(orderLines remaining) (Just match, others) -> orderLines $ (present ++ tail match): others--reducePolyline ((x1,y1):(x2,y2):(x3,y3):others) = - if (x1,y1) == (x2,y2) then reducePolyline ((x2,y2):(x3,y3):others) else- if abs ( (y2-y1)/(x2-x1) - (y3-y1)/(x3-x1) ) < 0.0001 - || ( (x2-x1) == 0 && (x3-x1) == 0 && (y2-y1)*(y3-y1) > 0)- then reducePolyline ((x1,y1):(x3,y3):others)- else (x1,y1) : reducePolyline ((x2,y2):(x3,y3):others)-reducePolyline ((x1,y1):(x2,y2):others) = - if (x1,y1) == (x2,y2) then reducePolyline ((x2,y2):others) else (x1,y1):(x2,y2):others-reducePolyline l = l-+-} orderLinesDC :: [[[Polyline]]] -> [Polyline] orderLinesDC segs = let halve :: [a] -> ([a], [a]) halve l = splitAt (div (length l) 2) l- splitOrder segs = case (\(x,y) -> (halve x, halve y)) . unzip . map (halve) $ segs of+ splitOrder segs' = case (\(x,y) -> (halve x, halve y)) . unzip . map (halve) $ segs' of ((a,b),(c,d)) -> orderLinesDC a ++ orderLinesDC b ++ orderLinesDC c ++ orderLinesDC d in if (length segs < 5 || length (head segs) < 5 ) then concat $ concat segs else- case (\(x,y) -> (halve x, halve y)) $ unzip $ map (halve) segs of- ((a,b),(c,d)) ->orderLines $ - orderLinesDC a ++ orderLinesDC b ++ orderLinesDC c ++ orderLinesDC d-+ splitOrder segs {- orderLinesP :: [[[Polyline]]] -> [Polyline] orderLinesP segs =@@ -200,17 +206,18 @@ in if (length segs < 5 || length (head segs) < 5 ) then concat $ concat segs else case (\(x,y) -> (halve x, halve y)) $ unzip $ map (halve) segs of- ((a,b),(c,d)) -> orderLines $ + ((a,b),(c,d)) -> orderLines $ let a' = orderLinesP a b' = orderLinesP b c' = orderLinesP c d' = orderLinesP d- in (force a' `par` force b' `par` force c' `par` force d') `pseq` + in (force a' `par` force b' `par` force c' `par` force d') `pseq` (a' ++ b' ++ c' ++ d') -} -polylineNotNull (a:l) = not (null l)+polylineNotNull :: [a] -> Bool+polylineNotNull (_:l) = not (null l) polylineNotNull [] = False
Graphics/Implicit/Export/MarchingSquaresFill.hs view
@@ -1,21 +1,28 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- define getContour, which gets a polyline describe the edge of your 2D object. module Graphics.Implicit.Export.MarchingSquaresFill (getContourMesh) where -import Graphics.Implicit.Definitions-import Control.Parallel (par, pseq)+import Prelude(Bool(True, False), fromInteger, ($), (-), (+), (/), (*), (<=), (>), ceiling, concat) --- | getContour gets a polyline describe the edge of your 2D--- object. It's really the only function in this file you need--- to care about from an external perspective.+import Graphics.Implicit.Definitions (ℝ, ℝ2, Obj2) +-- FIXME: commented out, test how to apply..+-- import Control.Parallel (par, pseq)+ getContourMesh :: ℝ2 -> ℝ2 -> ℝ2 -> Obj2 -> [(ℝ2,ℝ2,ℝ2)]-getContourMesh (x1, y1) (x2, y2) (dx, dy) obj = +getContourMesh (x1, y1) (x2, y2) (dx, dy) obj = let -- How many steps will we take on each axis?- nx = fromIntegral $ ceiling $ (x2 - x1) / dx- ny = fromIntegral $ ceiling $ (y2 - y1) / dy+ nx :: ℝ+ nx = fromInteger $ ceiling $ (x2 - x1) / dx+ ny :: ℝ+ ny = fromInteger $ ceiling $ (y2 - y1) / dy -- Divide it up and compute the polylines trisOnGrid :: [[[(ℝ2,ℝ2,ℝ2)]]] trisOnGrid = [[getSquareTriangles@@ -26,16 +33,15 @@ triangles = concat $ concat trisOnGrid in triangles- --- | This function gives line segmensts to divde negative interior--- regions and positive exterior ones inside a square, based on its +-- | This function gives line segments to divide negative interior+-- regions and positive exterior ones inside a square, based on its -- values at its vertices. -- It is based on the linearly-interpolated marching squares algorithm. getSquareTriangles :: ℝ2 -> ℝ2 -> Obj2 -> [(ℝ2,ℝ2,ℝ2)]-getSquareTriangles (x1, y1) (x2, y2) obj = - let +getSquareTriangles (x1, y1) (x2, y2) obj =+ let (x,y) = (x1, y1) -- Let's evlauate obj at a few points...@@ -66,49 +72,51 @@ midy1 = (x + dx*x1y1/(x1y1-x2y1), y ) midy2 = (x + dx*x1y2/(x1y2-x2y2), y + dy) - square a b c d = [(a,b,c), (a,c,d)]+ -- decompose a square into two triangles...+ square :: forall t t1. t -> t1 -> t1 -> t1 -> [(t, t1, t1)]+ square aa bb cc dd = [(aa,bb,cc), (aa,cc,dd)] in case (x1y2 <= 0, x2y2 <= 0, x1y1 <= 0, x2y1 <= 0) of -- Yes, there's some symetries that could reduce the amount of code... -- But I don't think they're worth exploiting...- (True, True, + (True, True, True, True) -> square (x1,y1) (x2,y1) (x2,y2) (x1,y2) (False, False, False, False) -> []- (True, True, - False, False) -> square midx1 midx2 (x2,y2) (x1,y2) + (True, True,+ False, False) -> square midx1 midx2 (x2,y2) (x1,y2) (False, False,- True, True) -> square (x1,y1) (x2,y1) midx2 midx1 - (False, True, + True, True) -> square (x1,y1) (x2,y1) midx2 midx1+ (False, True, False, True) -> square midy1 (x2,y1) (x2,y2) midy2 (True, False, True, False) -> square (x1,y1) midy1 midy2 (x1,y2) (True, False, False, False) -> [((x1,y2), midx1, midy2)]- (False, True, - True, True) -> + (False, True,+ True, True) -> [(midx1, (x1,y1), midy2), ((x1,y1), (x2,y1), midy2), (midy2, (x2,y1), (x2,y2))]- (True, True, - False, True) -> - [((x1,y2), midx1, (x2,y2)), (midx1, midy1, (x2,y2)), ((x2,y2), midy1, (x2,y1))] + (True, True,+ False, True) ->+ [((x1,y2), midx1, (x2,y2)), (midx1, midy1, (x2,y2)), ((x2,y2), midy1, (x2,y1))] (False, False, True, False) -> [(midx1, (x1,y1), midy1)]- (True, True, - True, False) -> + (True, True,+ True, False) -> [(midy1,midx2,(x2,y2)), ((x2,y2), (x1,y2), midy1), (midy1, (x1,y2), (x1,y1))] (False, False, False, True) -> [(midx2, midy1, (x2,y1))] (True, False,- True, True) -> + True, True) -> [(midy2, (x2,y1), midx2), ((x2,y1), midy2, (x1,y1)), ((x1,y1), midy2, (x1,y2))]- (False, True, + (False, True, False, False) -> [(midx2, (x2,y2), midy2)] (True, False, False, True) -> if c > 0 then [((x1,y2), midx1, midy2), ((x2,y1), midy1, midx2)] else [] --[[midx1, midy1], [midx2, midy2]]- (False, True, + (False, True, True, False) -> if c <= 0 then [] --[[midx1, midy2], [midx2, midy1]] else [((x1,y1), midy1, midx1), ((x2,y2), midx2, midy2)] --[[midx1, midy1], [midx2, midy2]]
Graphics/Implicit/Export/NormedTriangleMeshFormats.hs view
@@ -1,14 +1,19 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016 Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- FIXME: describe why we need this. {-# LANGUAGE OverloadedStrings #-} --- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+module Graphics.Implicit.Export.NormedTriangleMeshFormats (obj) where -module Graphics.Implicit.Export.NormedTriangleMeshFormats where+import Prelude(($), map, (+), (.), (*), length, (-), return) -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.TextBuilderUtils+import Graphics.Implicit.Definitions (NormedTriangle, ℝ3)+import Graphics.Implicit.Export.TextBuilderUtils (Text, Builder, toLazyText, (<>), bf, mconcat, buildInt) +obj :: [NormedTriangle] -> Text obj normedtriangles = toLazyText $ vertcode <> normcode <> trianglecode where -- A vertex line; v (0.0, 0.0, 1.0) = "v 0.0 0.0 1.0\n"@@ -31,10 +36,10 @@ vertcode = mconcat $ map v verts normcode = mconcat $ map n norms trianglecode = mconcat $ do- n <- map ((+1).(*3)) [0,1 .. length normedtriangles -1]+ n' <- map ((+1).(*3)) [0,1 .. length normedtriangles -1] let- vta = buildInt n- vtb = buildInt (n+1)- vtc = buildInt (n+2)+ vta = buildInt n'+ vtb = buildInt (n'+1)+ vtc = buildInt (n'+2) return $ "f " <> vta <> " " <> vtb <> " " <> vtc <> " " <> "\n"
Graphics/Implicit/Export/PolylineFormats.hs view
@@ -1,21 +1,25 @@-{-# LANGUAGE OverloadedStrings #-}- -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++{-# LANGUAGE OverloadedStrings #-}+ module Graphics.Implicit.Export.PolylineFormats where -import Graphics.Implicit.Definitions+import Prelude((.), ($), (-), minimum, maximum, unzip, concat, show, (++), unwords, map, mapM_, snd, compare, min, max, Ord, Num) -import Graphics.Implicit.Export.TextBuilderUtils+import Graphics.Implicit.Definitions (Polyline, ℝ2) +import Graphics.Implicit.Export.TextBuilderUtils (Text, Builder, mempty, toLazyText, mconcat, bf, (<>), buildTruncFloat)+ import Text.Blaze.Svg.Renderer.Text (renderSvg)-import Text.Blaze.Svg import Text.Blaze.Svg11 ((!),docTypeSvg,g,polyline,toValue) import Text.Blaze.Internal (stringValue) import qualified Text.Blaze.Svg11.Attributes as A -import Data.List (foldl') import qualified Data.List as List svg :: [Polyline] -> Text@@ -42,19 +46,23 @@ thinBlueGroup = g ! A.stroke "rgb(0,0,255)" ! A.strokeWidth "1" ! A.fill "none" -- obj hacklabLaserGCode :: [Polyline] -> Text-hacklabLaserGCode polylines = toLazyText $ gcodeHeader <> mconcat (map interpretPolyline orderedPoylines) <> gcodeFooter+hacklabLaserGCode polylines = toLazyText $ gcodeHeader <> mconcat (map interpretPolyline orderedPolylines) <> gcodeFooter where - orderedPoylines = + orderedPolylines = snd . unzip . List.sortBy (\(a,_) (b, _) -> compare a b) . map (\x -> (polylineRadius x, x)) $ polylines+ polylineRadius :: forall t. (Ord t, Num t) => [(t, t)] -> t polylineRadius [] = 0- polylineRadius polyline = max (xmax - xmin) (ymax - ymin) where- ((xmin, xmax), (ymin, ymax)) = polylineRadius' polyline+ polylineRadius polyline' = max (xmax' - xmin') (ymax' - ymin') where+ ((xmin', xmax'), (ymin', ymax')) = polylineRadius' polyline'+ polylineRadius' :: forall a a1. (Ord a1, Ord a, Num a1, Num a) => [(a, a1)] -> ((a, a), (a1, a1))+ polylineRadius' [] = ((0,0),(0,0)) polylineRadius' [(x,y)] = ((x,x),(y,y)) polylineRadius' ((x,y):ps) = ((min x xmin,max x xmax),(min y ymin, max y ymax)) where ((xmin, xmax), (ymin, ymax)) = polylineRadius' ps+ gcodeHeader :: Builder gcodeHeader = mconcat [ "(generated by ImplicitCAD, based of hacklab wiki example)\n" ,"M63 P0 (laser off)\n"@@ -62,6 +70,7 @@ ,"G21 (units=mm)\n" ,"F400 (set feedrate)\n" ,"M3 S1 (enable laser)\n\n"]+ gcodeFooter :: Builder gcodeFooter = mconcat [ "M5 (disable laser)\n" ,"G00 X0.0 Y0.0 (move to 0)\n"
Graphics/Implicit/Export/RayTrace.hs view
@@ -1,52 +1,67 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- FIXME: why are these needed? {-# LANGUAGE TypeSynonymInstances, MultiParamTypeClasses, FlexibleContexts #-} module Graphics.Implicit.Export.RayTrace where -import Graphics.Implicit.ObjectUtil-import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.Definitions-import Codec.Picture-import Control.Monad-import Data.VectorSpace -import Data.AffineSpace -import Data.Cross+import Prelude(Show, RealFrac, Maybe(Just, Nothing), Int, Bool(False, True), (-), (.), ($), (*), (/), min, fromInteger, max, round, fromIntegral, unzip, map, length, sum, maximum, minimum, (>), (+), (<), (==), pred, flip, (++), not, abs, floor, fromIntegral, toRational) -import Debug.Trace+import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, (⋅), Obj3)+import Codec.Picture (Pixel8, Image, DynamicImage(ImageRGBA8), PixelRGBA8(PixelRGBA8))+import Control.Monad (guard, return)+import Data.VectorSpace (Scalar, magnitude, (^+^), (*^), normalized, (^-^), InnerSpace)+import Data.Cross (cross3) -- Definitions data Camera = Camera ℝ3 ℝ3 ℝ3 ℝ deriving Show+ data Ray = Ray ℝ3 ℝ3 deriving Show+ data Light = Light ℝ3 ℝ deriving Show+ data Scene = Scene Obj3 Color [Light] Color type Color = PixelRGBA8++color :: Pixel8 -> Pixel8 -> Pixel8 -> Pixel8 -> PixelRGBA8 color r g b a = PixelRGBA8 r g b a++dynamicImage :: Image PixelRGBA8 -> DynamicImage dynamicImage = ImageRGBA8 -- Math -d a b = magnitude (b-a)+vectorDistance :: ℝ3 -> ℝ3 -> Scalar ℝ3+vectorDistance a b = magnitude (b-a) +colorMult :: Pixel8 -> PixelRGBA8 -> PixelRGBA8 s `colorMult` (PixelRGBA8 a b c d) = color (s `mult` a) (s `mult` b) (s `mult` c) d- where + where+ bound :: RealFrac a => a -> a bound = max 0 . min 254- mult a b = fromIntegral . round . bound $ a * fromIntegral b+ mult :: Pixel8 -> Pixel8 -> Pixel8+ mult x y = round . bound . toRational $ x * y average :: [Color] -> Color average l = - let - ((rs, gs), (bs, as)) = (\(a,b) -> (unzip a, unzip b)) $ unzip $ map + let + ((rs, gs), (bs, as)) = (\(a'',b'') -> (unzip a'', unzip b'')) $ unzip $ map (\(PixelRGBA8 r g b a) -> ((fromIntegral r, fromIntegral g), (fromIntegral b, fromIntegral a))) l :: (([ℝ], [ℝ]), ([ℝ],[ℝ])) n = fromIntegral $ length l :: ℝ- (r, g, b, a) = (sum rs/n, sum gs/n, sum bs/n, sum as/n)+ (r', g', b', a') = (sum rs/n, sum gs/n, sum bs/n, sum as/n) in PixelRGBA8- (fromIntegral . round $ r) (fromIntegral . round $ g) (fromIntegral . round $ b) (fromIntegral . round $ a)+ (fromInteger . round $ r') (fromInteger . round $ g') (fromInteger . round $ b') (fromInteger . round $ a') -- Ray Utilities @@ -65,7 +80,7 @@ rayBounds :: Ray -> (ℝ3, ℝ3) -> ℝ2 rayBounds ray box = let- Ray (cPx, cPy, cPz) cameraV@(cVx, cVy, cVz) = ray+ Ray (cPx, cPy, cPz) (cVx, cVy, cVz) = ray ((x1,y1,z1),(x2,y2,z2)) = box xbounds = [(x1 - cPx)/cVx, (x2-cPx)/cVx] ybounds = [(y1-cPy)/cVy, (y2-cPy)/cVy]@@ -104,7 +119,7 @@ else refine' 10 (b, a) (aval, bval) obj refine' :: Int -> ℝ2 -> ℝ2 -> (ℝ -> ℝ) -> ℝ-refine' 0 (a, b) _ _ = a+refine' 0 (a, _) _ _ = a refine' n (a, b) (aval, bval) obj = let mid = (a+b)/(2::ℝ)@@ -116,6 +131,7 @@ then refine' (pred n) (a, mid) (aval, midval) obj else refine' (pred n) (mid, b) (midval, bval) obj +intersects :: Ray -> ((ℝ, ℝ), ℝ) -> ℝ -> Obj3 -> Bool intersects a b c d = case intersection a b c d of Nothing -> False Just _ -> True@@ -127,7 +143,7 @@ let (a,b) = rayBounds ray box in case intersection ray ((a, obj (cameraP ^+^ a*^cameraV)), b) step obj of- Just p -> flip colorMult objColor $ (sum $ [0.2] ++ do+ Just p -> flip colorMult objColor $ floor (sum $ [0.2] ++ do Light lightPos lightIntensity <- lights let ray'@(Ray _ v) = rayFromTo p lightPos@@ -135,82 +151,23 @@ guard . not $ intersects ray' ((0, obj p),20) step obj let pval = obj p- step = 0.1 :: ℝ dirDeriv :: ℝ3 -> ℝ- dirDeriv v = (obj (p ^+^ step*^v) ^-^ pval)/step+ dirDeriv v'' = (obj (p ^+^ step*^v'') ^-^ pval)/step deriv = (dirDeriv (1,0,0), dirDeriv (0,1,0), dirDeriv (0,0,1)) normal = normalized $ deriv unitV = normalized $ v'- proj a b = (a⋅b)*^b- dist = d p lightPos+ proj :: forall v. InnerSpace v => v -> v -> v+ proj a' b' = (a'⋅b')*^b'+ dist = vectorDistance p lightPos illumination = (max 0 (normal ⋅ unitV)) * lightIntensity * (25 /dist) rV = let normalComponent = proj v' normal parComponent = v' - normalComponent in- normalComponent - parComponent - return $ illumination*(3 + 0.3*(abs $ rV ⋅ cameraV)^2)+ normalComponent - parComponent + return $ illumination*(3 + 0.3*(abs $ rV ⋅ cameraV)*(abs $ rV ⋅ cameraV)) ) Nothing -> defaultColor--instance DiscreteAproxable SymbolicObj3 DynamicImage where- discreteAprox res symbObj = dynamicImage $ generateImage pixelRenderer (round w) (round h)- where- (w,h) = (150, 150) :: ℝ2- obj = getImplicit3 symbObj- box@((x1,y1,z1), (x2,y2,z2)) = getBox3 symbObj- av :: ℝ -> ℝ -> ℝ- av a b = (a+b)/(2::ℝ)- avY = av y1 y2- avZ = av z1 z2- deviation = maximum [abs $ y1 - avY, abs $ y2 - avY, abs $ z1 - avZ, abs $ z2 - avZ]- camera = Camera (x1-deviation*(2.2::ℝ), avY, avZ) (0, -1, 0) (0,0, -1) 1.0- lights = [Light (x1-deviation*(1.5::ℝ), y1 - (0.4::ℝ)*(y2-y1), avZ) ((0.03::ℝ)*deviation) ]- scene = Scene obj (PixelRGBA8 200 200 230 255) lights (PixelRGBA8 255 255 255 0)- pixelRenderer :: Int -> Int -> Color- pixelRenderer a b = renderScreen - ((fromIntegral a :: ℝ)/w - (0.5::ℝ)) ((fromIntegral b :: ℝ)/h - (0.5 ::ℝ))- renderScreen :: ℝ -> ℝ -> Color- renderScreen a b =- let- ray = cameraRay camera (a,b)- in - average $ [- traceRay - (cameraRay camera ((a,b) ^+^ ( 0.25/w, 0.25/h)))- 2 box scene,- traceRay - (cameraRay camera ((a,b) ^+^ (-0.25/w, 0.25/h)))- 0.5 box scene,- traceRay - (cameraRay camera ((a,b) ^+^ (0.25/w, -0.25/h)))- 0.5 box scene,- traceRay - (cameraRay camera ((a,b) ^+^ (-0.25/w,-0.25/h)))- 0.5 box scene- ]---instance DiscreteAproxable SymbolicObj2 DynamicImage where- discreteAprox res symbObj = dynamicImage $ generateImage pixelRenderer (round w) (round h)- where- (w,h) = (150, 150) :: ℝ2- obj = getImplicit2 symbObj- (p1@(x1,y1), p2@(x2,y2)) = getBox2 symbObj- (dx, dy) = p2 ^-^ p1- dxy = max dx dy- pixelRenderer :: Int -> Int -> Color- pixelRenderer a b = color- where- xy a b = ((x1,y2) .-^ (dxy-dx, dy-dxy)^/2) .+^ dxy*^(a/w, -b/h)- s = 0.25 :: ℝ- (a', b') = (realToFrac a, realToFrac b)- color = average [objColor $ xy a' b', objColor $ xy a' b',- objColor $ xy (a'+s) (b'+s),- objColor $ xy (a'-s) (b'-s),- objColor $ xy (a'+s) (b'+s),- objColor $ xy (a'-s) (b'-s)]- objColor p = if obj p < 0 then PixelRGBA8 150 150 160 255 else PixelRGBA8 255 255 255 0
Graphics/Implicit/Export/Render.hs view
@@ -1,50 +1,50 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- Allow us to use the tearser parallel list comprehension syntax, to avoid having to call zip in the complicated comprehensions below. {-# LANGUAGE ParallelListComp #-} module Graphics.Implicit.Export.Render where -import Debug.Trace+import Prelude(Float, Bool, ceiling, ($), (/), fromIntegral, (+), (*), fromInteger, max, div, tail, map, concat, realToFrac, (==), (||), filter, not, reverse, (.), Integral, Eq, Integer, concatMap) -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.Render.Definitions-import Data.VectorSpace+import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, Obj2, Obj3, TriangleMesh, Triangle, Polyline) +import Data.VectorSpace ((^-^))+ -- Here's the plan for rendering a cube (the 2D case is trivial): -- (1) We calculate midpoints using interpolate. -- This guarentees that our mesh will line up everywhere. -- (Contrast with calculating them in getSegs)- import Graphics.Implicit.Export.Render.Interpolate (interpolate) -- (2) We calculate the segments separating the inside and outside of our -- object on the sides of the cube. -- getSegs internally uses refine from RefineSegs to subdivide the segs -- to better match the boundary.--import Graphics.Implicit.Export.Render.GetSegs (getSegs, getSegs')--- import Graphics.Implicit.Export.Render.RefineSegs (refine)+import Graphics.Implicit.Export.Render.GetSegs (getSegs) -- (3) We put the segments from all sides of the cube together -- and extract closed loops.- import Graphics.Implicit.Export.Render.GetLoops (getLoops) -- (4) We tesselate the loops, using a mixture of triangles and squares- import Graphics.Implicit.Export.Render.TesselateLoops (tesselateLoop) -- (5) We try to merge squares, then turn everything into triangles.- import Graphics.Implicit.Export.Render.HandleSquares (mergedSquareTris) -- Success: This is our mesh. -- Each step is done in parallel using Control.Parallel.Strategies+import Control.Parallel.Strategies (using, rdeepseq, parBuffer) -import Control.Parallel.Strategies (using, rdeepseq, parListChunk)+import Control.DeepSeq (NFData) -- The actual code is just a bunch of ugly argument passing. -- Utility functions can be found at the end.@@ -61,114 +61,109 @@ -- Note: As far as the actual results of the rendering algorithm, nothing in -- this file really matters. All the actual decisions about how to build--- the mesh are abstracted into the imported files. They are likely what--- you are interested in.+-- the mesh are abstracted into the imported files. -- For the 2D case, we need one last thing, cleanLoopsFromSegs:--import Graphics.Implicit.Export.Render.HandlePolylines ( cleanLoopsFromSegs )+import Graphics.Implicit.Export.Render.HandlePolylines (cleanLoopsFromSegs) getMesh :: ℝ3 -> ℝ3 -> ℝ -> Obj3 -> TriangleMesh-getMesh p1@(x1,y1,z1) p2@(x2,y2,z2) res obj = +getMesh p1@(x1,y1,z1) p2 res obj = let+ -- How much space are we rendering? (dx,dy,dz) = p2 ^-^ p1 -- How many steps will we take on each axis?+ nx :: Integral a => a nx = ceiling $ dx / res+ ny :: Integral a => a ny = ceiling $ dy / res+ nz :: Integral a => a nz = ceiling $ dz / res - rx = dx/fromIntegral nx- ry = dy/fromIntegral ny- rz = dz/fromIntegral nz-- l ! (a,b,c) = l !! c !! b !! a-- pZs = [ z1 + rz*n | n <- [0.. fromIntegral nz] ]- pYs = [ y1 + ry*n | n <- [0.. fromIntegral ny] ]- pXs = [ x1 + rx*n | n <- [0.. fromIntegral nx] ]-+ -- How big are the steps?+ rx = dx / fromInteger nx+ ry = dy / fromInteger ny+ rz = dz / fromInteger nz - {-# INLINE par3DList #-}- par3DList lenx leny lenz f = - [[[f - (\n -> x1 + rx*fromIntegral (mx+n)) mx - (\n -> y1 + ry*fromIntegral (my+n)) my - (\n -> z1 + rz*fromIntegral (mz+n)) mz- | mx <- [0..lenx] ] | my <- [0..leny] ] | mz <- [0..lenz] ] - `using` (parListChunk (max 1 $ div lenz 32) rdeepseq)+ -- The positions we're rendering.+ pXs = [ x1 + rx*n | n <- [0.. fromInteger nx] ]+ pYs = [ y1 + ry*n | n <- [0.. fromInteger ny] ]+ pZs = [ z1 + rz*n | n <- [0.. fromInteger nz] ] + par3DList :: forall t. NFData t => Integer -> Integer -> Integer -> ((Integer -> ℝ) -> Integer -> (Integer -> ℝ) -> Integer -> (Integer -> ℝ) -> Integer -> t) -> [[[t]]]+ par3DList lenx leny lenz f =+ [[[f+ (\n -> x1 + rx*fromInteger (mx+n)) mx+ (\n -> y1 + ry*fromInteger (my+n)) my+ (\n -> z1 + rz*fromInteger (mz+n)) mz+ | mx <- [0..lenx] ] | my <- [0..leny] ] | mz <- [0..lenz] ]+ `using` (parBuffer (max 1 . fromInteger $ div lenz 32) rdeepseq) -- Evaluate obj to avoid waste in mids, segs, later.- objV = par3DList (nx+2) (ny+2) (nz+2) $ \x _ y _ z _ -> obj (x 0, y 0, z 0) - -- (1) Calculate mid poinsts on X, Y, and Z axis in 3D space.-+ -- (1) Calculate mid points on X, Y, and Z axis in 3D space. midsZ = [[[- interpolate (z0, objX0Y0Z0) (z1, objX0Y0Z1) (appAB obj x0 y0) res+ interpolate (z0, objX0Y0Z0) (z1', objX0Y0Z1) (appAB obj x0 y0) res | x0 <- pXs | objX0Y0Z0 <- objY0Z0 | objX0Y0Z1 <- objY0Z1 ]| y0 <- pYs | objY0Z0 <- objZ0 | objY0Z1 <- objZ1- ]| z0 <- pZs | z1 <- tail pZs | objZ0 <- objV | objZ1 <- tail objV- ] `using` (parListChunk (max 1 $ div nz 32) rdeepseq)+ ]| z0 <- pZs | z1' <- tail pZs | objZ0 <- objV | objZ1 <- tail objV+ ] `using` (parBuffer (max 1 . fromInteger $ div nz 32) rdeepseq) midsY = [[[- interpolate (y0, objX0Y0Z0) (y1, objX0Y1Z0) (appAC obj x0 z0) res+ interpolate (y0, objX0Y0Z0) (y1', objX0Y1Z0) (appAC obj x0 z0) res | x0 <- pXs | objX0Y0Z0 <- objY0Z0 | objX0Y1Z0 <- objY1Z0- ]| y0 <- pYs | y1 <- tail pYs | objY0Z0 <- objZ0 | objY1Z0 <- tail objZ0- ]| z0 <- pZs | objZ0 <- objV - ] `using` (parListChunk (max 1 $ div nz 32) rdeepseq)+ ]| y0 <- pYs | y1' <- tail pYs | objY0Z0 <- objZ0 | objY1Z0 <- tail objZ0+ ]| z0 <- pZs | objZ0 <- objV+ ] `using` (parBuffer (max 1 $ fromInteger $ div nz 32) rdeepseq) midsX = [[[- interpolate (x0, objX0Y0Z0) (x1, objX1Y0Z0) (appBC obj y0 z0) res- | x0 <- pXs | x1 <- tail pXs | objX0Y0Z0 <- objY0Z0 | objX1Y0Z0 <- tail objY0Z0- ]| y0 <- pYs | objY0Z0 <- objZ0 - ]| z0 <- pZs | objZ0 <- objV - ] `using` (parListChunk (max 1 $ div nz 32) rdeepseq)+ interpolate (x0, objX0Y0Z0) (x1', objX1Y0Z0) (appBC obj y0 z0) res+ | x0 <- pXs | x1' <- tail pXs | objX0Y0Z0 <- objY0Z0 | objX1Y0Z0 <- tail objY0Z0+ ]| y0 <- pYs | objY0Z0 <- objZ0+ ]| z0 <- pZs | objZ0 <- objV+ ] `using` (parBuffer (max 1 $ fromInteger $ div nz 32) rdeepseq) -- Calculate segments for each side-- segsZ = [[[ - map2 (inj3 z0) $ getSegs (x0,y0) (x1,y1) (obj **$ z0)+ segsZ = [[[+ map2 (inj3 z0) $ getSegs (x0,y0) (x1',y1') (obj **$ z0) (objX0Y0Z0, objX1Y0Z0, objX0Y1Z0, objX1Y1Z0) (midA0, midA1, midB0, midB1)- |x0<-pXs|x1<-tail pXs|midB0<-mX'' |midB1<-mX'T |midA0<-mY'' |midA1<-tail mY''+ |x0<-pXs|x1'<-tail pXs|midB0<-mX'' |midB1<-mX'T |midA0<-mY'' |midA1<-tail mY'' |objX0Y0Z0<-objY0Z0|objX1Y0Z0<-tail objY0Z0|objX0Y1Z0<-objY1Z0|objX1Y1Z0<-tail objY1Z0- ]|y0<-pYs|y1<-tail pYs|mX'' <-mX' |mX'T <-tail mX'|mY'' <-mY'+ ]|y0<-pYs|y1'<-tail pYs|mX'' <-mX' |mX'T <-tail mX'|mY'' <-mY' |objY0Z0 <- objZ0 | objY1Z0 <- tail objZ0 ]|z0<-pZs |mX' <-midsX| mY' <-midsY |objZ0 <- objV- ] `using` (parListChunk (max 1 $ div nz 32) rdeepseq)+ ] `using` (parBuffer (max 1 $ fromInteger $ div nz 32) rdeepseq) - segsY = [[[ - map2 (inj2 y0) $ getSegs (x0,z0) (x1,z1) (obj *$* y0) + segsY = [[[+ map2 (inj2 y0) $ getSegs (x0,z0) (x1',z1') (obj *$* y0) (objX0Y0Z0,objX1Y0Z0,objX0Y0Z1,objX1Y0Z1) (midA0, midA1, midB0, midB1)- |x0<-pXs|x1<-tail pXs|midB0<-mB'' |midB1<-mBT' |midA0<-mA'' |midA1<-tail mA''+ |x0<-pXs|x1'<-tail pXs|midB0<-mB'' |midB1<-mBT' |midA0<-mA'' |midA1<-tail mA'' |objX0Y0Z0<-objY0Z0|objX1Y0Z0<-tail objY0Z0|objX0Y0Z1<-objY0Z1|objX1Y0Z1<-tail objY0Z1 ]|y0<-pYs| mB'' <-mB' |mBT' <-mBT |mA'' <-mA' |objY0Z0 <- objZ0 | objY0Z1 <- objZ1- ]|z0<-pZs|z1<-tail pZs|mB' <-midsX|mBT <-tail midsX|mA' <-midsZ + ]|z0<-pZs|z1'<-tail pZs|mB' <-midsX|mBT <-tail midsX|mA' <-midsZ |objZ0 <- objV | objZ1 <- tail objV- ] `using` (parListChunk (max 1 $ div nz 32) rdeepseq)+ ] `using` (parBuffer (max 1 $ fromInteger $ div nz 32) rdeepseq) - segsX = - [[[ - map2 (inj1 x0) $ getSegs (y0,z0) (y1,z1) (obj $** x0) + segsX = [[[+ map2 (inj1 x0) $ getSegs (y0,z0) (y1',z1') (obj $** x0) (objX0Y0Z0,objX0Y1Z0,objX0Y0Z1,objX0Y1Z1) (midA0, midA1, midB0, midB1) |x0<-pXs| midB0<-mB'' |midB1<-mBT' |midA0<-mA'' |midA1<-mA'T |objX0Y0Z0<-objY0Z0|objX0Y1Z0<- objY1Z0|objX0Y0Z1<-objY0Z1|objX0Y1Z1<- objY1Z1- ]|y0<-pYs|y1<-tail pYs|mB'' <-mB' |mBT' <-mBT |mA'' <-mA' |mA'T <-tail mA'- |objY0Z0 <-objZ0 |objY1Z0 <-tail objZ0 |objY0Z1 <-objZ1 |objY1Z1 <-tail objZ1 - ]|z0<-pZs|z1<-tail pZs|mB' <-midsY|mBT <-tail midsY|mA' <-midsZ + ]|y0<-pYs|y1'<-tail pYs|mB'' <-mB' |mBT' <-mBT |mA'' <-mA' |mA'T <-tail mA'+ |objY0Z0 <-objZ0 |objY1Z0 <-tail objZ0 |objY0Z1 <-objZ1 |objY1Z1 <-tail objZ1+ ]|z0<-pZs|z1'<-tail pZs|mB' <-midsY|mBT <-tail midsY|mA' <-midsZ |objZ0 <- objV | objZ1 <- tail objV- ] `using` (parListChunk (max 1 $ div nz 32) rdeepseq)+ ] `using` (parBuffer (max 1 $ fromInteger $ div nz 32) rdeepseq) -- (3) & (4) : get and tesselate loops- sqTris = [[[- concat $ map (tesselateLoop res obj) $ getLoops $ concat [+ concatMap (tesselateLoop res obj) $ getLoops $ concat [ segX''', mapR segX''T, mapR segY''',@@ -188,98 +183,125 @@ ]| segZ' <- segsZ | segZT <- tail segsZ | segY' <- segsY | segX' <- segsX- ]- - in mergedSquareTris $ concat $ concat $ concat sqTris -- (5) merge squares, etc-+ ] `using` (parBuffer (max 1 $ fromInteger $ div nz 32) rdeepseq) + in cleanupTris $ mergedSquareTris $ concat $ concat $ concat sqTris -- (5) merge squares, etc +-- Removes triangles that are empty, when converting their positions to Float resolution.+-- NOTE: this will need to be disabled for AMF, and other triangle formats that can handle Double.+cleanupTris :: TriangleMesh -> TriangleMesh+cleanupTris tris =+ let+ toFloat :: ℝ -> Float+ toFloat = realToFrac+ floatPoint :: (ℝ, ℝ, ℝ) -> (Float, Float, Float)+ floatPoint (a,b,c) = (toFloat a, toFloat b, toFloat c)+ isDegenerateTriFloat :: Eq t => (t,t,t) -> Bool+ isDegenerateTriFloat (a,b,c) = (a == b) || (b == c) || (a == c)+ isDegenerateTri :: Triangle -> Bool+ isDegenerateTri (a, b, c) = isDegenerateTriFloat (floatPoint a, floatPoint b, floatPoint c)+ in filter (not . isDegenerateTri) tris getContour :: ℝ2 -> ℝ2 -> ℝ -> Obj2 -> [Polyline]-getContour p1@(x1, y1) p2@(x2, y2) res obj = +getContour p1@(x1, y1) p2 res obj = let (dx,dy) = p2 ^-^ p1 -- How many steps will we take on each axis?+ nx :: Integral a => a nx = ceiling $ dx / res+ ny :: Integral a => a ny = ceiling $ dy / res - rx = dx/fromIntegral nx- ry = dy/fromIntegral ny-- l ! (a,b) = l !! b !! a-- pYs = [ y1 + ry*n | n <- [0.. fromIntegral ny] ]- pXs = [ x1 + rx*n | n <- [0.. fromIntegral nx] ]+ rx = dx/fromInteger nx+ ry = dy/fromInteger ny + pYs = [ y1 + ry*n | n <- [0.. fromInteger ny] ]+ pXs = [ x1 + rx*n | n <- [0.. fromInteger nx] ] - {-# INLINE par2DList #-}- par2DList lenx leny f = + par2DList :: forall t. NFData t => Integer -> Integer -> ((Integer -> ℝ) -> Integer -> (Integer -> ℝ) -> Integer -> t) -> [[t]]+ par2DList lenx leny f = [[ f- (\n -> x1 + rx*fromIntegral (mx+n)) mx + (\n -> x1 + rx*fromIntegral (mx+n)) mx (\n -> y1 + ry*fromIntegral (my+n)) my | mx <- [0..lenx] ] | my <- [0..leny] ]- `using` (parListChunk (max 1 $ div leny 32) rdeepseq)+ `using` (parBuffer (max 1 $ fromInteger $ div leny 32) rdeepseq) -- Evaluate obj to avoid waste in mids, segs, later. objV = par2DList (nx+2) (ny+2) $ \x _ y _ -> obj (x 0, y 0) - -- (1) Calculate mid poinsts on X, Y, and Z axis in 3D space.+ -- (1) Calculate mid points on X, and Y axis in 2D space. midsY = [[- interpolate (y0, objX0Y0) (y1, objX0Y1) (obj $* x0) res+ interpolate (y0, objX0Y0) (y1', objX0Y1) (obj $* x0) res | x0 <- pXs | objX0Y0 <- objY0 | objX0Y1 <- objY1- ]| y0 <- pYs | y1 <- tail pYs | objY0 <- objV | objY1 <- tail objV- ] `using` (parListChunk (max 1 $ div ny 32) rdeepseq)+ ]| y0 <- pYs | y1' <- tail pYs | objY0 <- objV | objY1 <- tail objV+ ] `using` (parBuffer (max 1 $ fromInteger $ div ny 32) rdeepseq) midsX = [[- interpolate (x0, objX0Y0) (x1, objX1Y0) (obj *$ y0) res- | x0 <- pXs | x1 <- tail pXs | objX0Y0 <- objY0 | objX1Y0 <- tail objY0- ]| y0 <- pYs | objY0 <- objV - ] `using` (parListChunk (max 1 $ div ny 32) rdeepseq)+ interpolate (x0, objX0Y0) (x1', objX1Y0) (obj *$ y0) res+ | x0 <- pXs | x1' <- tail pXs | objX0Y0 <- objY0 | objX1Y0 <- tail objY0+ ]| y0 <- pYs | objY0 <- objV+ ] `using` (parBuffer (max 1 $ fromInteger $ div ny 32) rdeepseq) -- Calculate segments for each side - segs = [[ - getSegs (x0,y0) (x1,y1) obj+ segs = [[+ getSegs (x0,y0) (x1',y1') obj (objX0Y0, objX1Y0, objX0Y1, objX1Y1) (midA0, midA1, midB0, midB1)- |x0<-pXs|x1<-tail pXs|midB0<-mX'' |midB1<-mX'T |midA0<-mY'' |midA1<-tail mY''+ |x0<-pXs|x1'<-tail pXs|midB0<-mX'' |midB1<-mX'T |midA0<-mY'' |midA1<-tail mY'' |objX0Y0<-objY0|objX1Y0<-tail objY0|objX0Y1<-objY1|objX1Y1<-tail objY1- ]|y0<-pYs|y1<-tail pYs|mX'' <-midsX|mX'T <-tail midsX|mY'' <-midsY+ ]|y0<-pYs|y1'<-tail pYs|mX'' <-midsX|mX'T <-tail midsX|mY'' <-midsY |objY0 <- objV | objY1 <- tail objV- ] `using` (parListChunk (max 1 $ div ny 32) rdeepseq)+ ] `using` (parBuffer (max 1 $ fromInteger $ div ny 32) rdeepseq) in cleanLoopsFromSegs $ concat $ concat $ segs -- (5) merge squares, etc --- silly utility functions+-- utility functions +inj1 :: forall t t1 t2. t -> (t1, t2) -> (t, t1, t2) inj1 a (b,c) = (a,b,c)+inj2 :: forall t t1 t2. t1 -> (t, t2) -> (t, t1, t2) inj2 b (a,c) = (a,b,c)+inj3 :: forall t t1 t2. t2 -> (t, t1) -> (t, t1, t2) inj3 c (a,b) = (a,b,c) +($**) :: forall t t1 t2 t3. ((t1, t2, t3) -> t) -> t1 -> (t2, t3) -> t infixr 0 $**+(*$*) :: forall t t1 t2 t3. ((t1, t2, t3) -> t) -> t2 -> (t1, t3) -> t infixr 0 *$*+(**$) :: forall t t1 t2 t3. ((t1, t2, t3) -> t) -> t3 -> (t1, t2) -> t infixr 0 **$++($*) :: forall t t1 t2. ((t1, t2) -> t) -> t1 -> t2 -> t infixr 0 $*+(*$) :: forall t t1 t2. ((t1, t2) -> t) -> t2 -> t1 -> t infixr 0 *$+ f $* a = \b -> f (a,b) f *$ b = \a -> f (a,b) f $** a = \(b,c) -> f (a,b,c) f *$* b = \(a,c) -> f (a,b,c) f **$ c = \(a,b) -> f (a,b,c) +appAB :: forall t t1 t2 t3. ((t1, t2, t3) -> t) -> t1 -> t2 -> t3 -> t appAB f a b = \c -> f (a,b,c)+appBC :: forall t t1 t2 t3. ((t1, t2, t3) -> t) -> t2 -> t3 -> t1 -> t appBC f b c = \a -> f (a,b,c)+appAC :: forall t t1 t2 t3. ((t1, t2, t3) -> t) -> t1 -> t3 -> t2 -> t appAC f a c = \b -> f (a,b,c) +map2 :: forall a b. (a -> b) -> [[a]] -> [[b]] map2 f = map (map f)+map2R :: forall a a1. (a1 -> a) -> [[a1]] -> [[a]] map2R f = map (reverse . map f)+mapR :: forall a. [[a]] -> [[a]] mapR = map reverse {-
Graphics/Implicit/Export/Render/Definitions.hs view
@@ -1,18 +1,23 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Released under the GNU AGPLV3+, see LICENSE -module Graphics.Implicit.Export.Render.Definitions where+module Graphics.Implicit.Export.Render.Definitions (TriSquare(Tris, Sq)) where -import Graphics.Implicit.Definitions-import Control.DeepSeq+import Prelude() +import Graphics.Implicit.Definitions(ℝ, ℝ2, ℝ3, Triangle)++import Control.DeepSeq (NFData, rnf)+ -- We want a format that can represent squares/quads and triangles. -- So that we can merge squares and thereby reduces triangles. --- Regarding Sq: Sq Basis@(b1,b2,b3) (Height on b3) +-- Regarding Sq: Sq Basis@(b1,b2,b3) (Height on b3) -- (b1 pos 1, b2 pos 1) (b1 pos 2, b2 pos 2) -data TriSquare = Sq (ℝ3,ℝ3,ℝ3) ℝ ℝ2 ℝ2 | Tris [Triangle]+data TriSquare =+ Sq (ℝ3,ℝ3,ℝ3) ℝ ℝ2 ℝ2+ | Tris [Triangle] -- For use with Parallel.Strategies later
Graphics/Implicit/Export/Render/GetLoops.hs view
@@ -1,13 +1,18 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}+ module Graphics.Implicit.Export.Render.GetLoops (getLoops) where +-- Explicitly include what we want from Prelude.+import Prelude (Eq, head, last, tail, (==), Bool(False), filter, not, (.), null, error, (++)) --- The goal of getLoops is, if you can imagine, extracting loops--- from a list of segments.+-- The goal of getLoops is to extract loops from a list of segments. --- The input is a list of segments+-- The input is a list of segments. -- the output a list of loops, where each loop is a list of -- segments, which each piece representing a "side". @@ -31,16 +36,15 @@ getLoops a = getLoops' a [] - getLoops' :: Eq a => [[a]] -> [[a]] -> [[[a]]] --- Obviously if there aren't any segments,+-- If there aren't any segments, -- and the "building loop" is empty, -- we produce no loops. getLoops' [] [] = [] --- And if the building loop is empty,+-- If the building loop is empty, -- we stick the first segment we have onto it -- to give us something to build on. @@ -56,10 +60,14 @@ -- and stick one on if we find it. -- Otherwise... something is really screwed up. +-- FIXME: connects should be used with a singleton.+ getLoops' segs workingLoop = let- presEnd = last $ last workingLoop- connects (x:xs) = x == presEnd+ presEnd :: forall c. [[c]] -> c+ presEnd = last . last+ connects (x:_) = x == presEnd workingLoop+ connects [] = False -- Handle the empty case. possibleConts = filter connects segs nonConts = filter (not . connects) segs (next, unused) = if null possibleConts
Graphics/Implicit/Export/Render/GetSegs.hs view
@@ -1,15 +1,19 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -module Graphics.Implicit.Export.Render.GetSegs where+module Graphics.Implicit.Export.Render.GetSegs (getSegs, getSegs') where -import Graphics.Implicit.Definitions+import Prelude(Eq, Bool(True, False), sqrt, (+), (*), (/=), map, (.), filter, ($), (<=))++import Graphics.Implicit.Definitions (ℝ, ℝ2, Obj2, Polyline) import Graphics.Implicit.Export.Render.RefineSegs (refine) import Graphics.Implicit.Export.Util (centroid)-import Data.VectorSpace -{- The goal of getSegs is to create polylines to separate - the interior and exterior vertices of a square intersectiong+import Data.VectorSpace ((^-^))++{- The goal of getSegs is to create polylines to separate+ the interior and exterior vertices of a square intersecting an object described by an implicit function. O.....O O.....O@@ -20,11 +24,11 @@ #.....# #.....# An interior point is one at which obj is negative.- + What are all the variables? =========================== - To allow data sharing, lots of values we + To allow data sharing, lots of values we could calculate are instead arguments. @@ -54,10 +58,8 @@ -} getSegs :: ℝ2 -> ℝ2 -> Obj2 -> (ℝ,ℝ,ℝ,ℝ) -> (ℝ,ℝ,ℝ,ℝ) -> [Polyline]-{-- # INLINE getSegs #-}--getSegs p1 p2 obj (x1y1, x2y1, x1y2, x2y2) (midx1V,midx2V,midy1V,midy2V) = - let +getSegs p1 p2 obj (x1y1, x2y1, x1y2, x2y2) (midx1V,midx2V,midy1V,midy2V) =+ let (x,y) = p1 -- Let's evaluate obj at a few points...@@ -71,7 +73,11 @@ midy1 = (midy1V , y ) midy2 = (midy2V, y + dy) - notPointLine (p1:p2:[]) = p1 /= p2+ notPointLine :: Eq a => [a] -> Bool+ notPointLine (np1:np2:[]) = np1 /= np2+ notPointLine [] = False+ notPointLine [_] = False+ notPointLine (_ : (_ : (_ : _))) = False -- takes straight lines between mid points and subdivides them to -- account for sharp corners, etc.@@ -84,7 +90,7 @@ -- Empty Cases - (True, True, + (True, True, True, True) -> [] (False, False,@@ -92,7 +98,7 @@ -- Horizontal Cases - (True, True, + (True, True, False, False) -> [[midx1, midx2]] (False, False,@@ -100,7 +106,7 @@ -- Vertical Cases - (False, True, + (False, True, False, True) -> [[midy2, midy1]] (True, False,@@ -111,16 +117,16 @@ (True, False, False, False) -> [[midx1, midy2]] - (False, True, + (False, True, True, True) -> [[midy2, midx1]] - (True, True, + (True, True, False, True) -> [[midx1, midy1]] (False, False, True, False) -> [[midy1, midx1]] - (True, True, + (True, True, True, False) -> [[midy1, midx2]] (False, False,@@ -129,7 +135,7 @@ (True, False, True, True) -> [[midx2, midy2]] - (False, True, + (False, True, False, False) -> [[midy2, midx2]] -- Dual Corner Cases@@ -139,17 +145,15 @@ then [[midx1, midy1], [midx2, midy2]] else [[midx1, midy2], [midx2, midy1]] - (False, True, + (False, True, True, False) -> if c <= 0 then [[midy2, midx1], [midy1, midx2]] else [[midy1, midx1], [midy2, midx2]] -- A convenience function, we don't actually care too much about--{-- # INLINE getSegs' #-}--getSegs' (x1, y1) (x2, y2) obj (midx1V,midx2V,midy1V,midy2V) = +getSegs' :: (ℝ, ℝ) -> (ℝ, ℝ) -> ((ℝ, ℝ) -> ℝ) -> (ℝ, ℝ, ℝ, ℝ) -> [Polyline]+getSegs' (x1, y1) (x2, y2) obj (midx1V,midx2V,midy1V,midy2V) = let x1y1 = obj (x1, y1) x2y1 = obj (x2, y1)
Graphics/Implicit/Export/Render/HandlePolylines.hs view
@@ -1,21 +1,22 @@ -- Implicit CAD. Copyright (C) 2012, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -module Graphics.Implicit.Export.Render.HandlePolylines (cleanLoopsFromSegs) where+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.Render.Definitions-import GHC.Exts (groupWith)-import Data.List (sortBy)-import Data.VectorSpace +module Graphics.Implicit.Export.Render.HandlePolylines (cleanLoopsFromSegs, reducePolyline) where +import Prelude(Bool(False), Maybe(Just, Nothing), map, (.), filter, (==), last, reverse, ($), (++), tail, (-), (/), abs, (<=), (||), (&&), (*), (>), not, null)++import Graphics.Implicit.Definitions (minℝ, Polyline, ℝ)+ cleanLoopsFromSegs :: [Polyline] -> [Polyline] cleanLoopsFromSegs = map reducePolyline . joinSegs . filter polylineNotNull - joinSegs :: [Polyline] -> [Polyline] joinSegs [] = [] joinSegs (present:remaining) =@@ -24,31 +25,32 @@ if last ps == last present then (Just (reverse $ p3:ps), segs) else case findNext segs of (res1,res2) -> (res1,(p3:ps):res2) findNext [] = (Nothing, [])+ findNext (([]):_) = (Nothing, []) in case findNext remaining of (Nothing, _) -> present:(joinSegs remaining) (Just match, others) -> joinSegs $ (present ++ tail match): others -reducePolyline ((x1,y1):(x2,y2):(x3,y3):others) = +reducePolyline :: [(ℝ, ℝ)] -> [(ℝ, ℝ)]+reducePolyline ((x1,y1):(x2,y2):(x3,y3):others) = if (x1,y1) == (x2,y2) then reducePolyline ((x2,y2):(x3,y3):others) else- if abs ( (y2-y1)/(x2-x1) - (y3-y1)/(x3-x1) ) < 0.0001 + if abs ( (y2-y1)/(x2-x1) - (y3-y1)/(x3-x1) ) <= minℝ || ( (x2-x1) == 0 && (x3-x1) == 0 && (y2-y1)*(y3-y1) > 0) then reducePolyline ((x1,y1):(x3,y3):others) else (x1,y1) : reducePolyline ((x2,y2):(x3,y3):others)-reducePolyline ((x1,y1):(x2,y2):others) = +reducePolyline ((x1,y1):(x2,y2):others) = if (x1,y1) == (x2,y2) then reducePolyline ((x2,y2):others) else (x1,y1):(x2,y2):others reducePolyline l = l -polylineNotNull (a:l) = not (null l)+polylineNotNull :: [a] -> Bool+polylineNotNull (_:l) = not (null l) polylineNotNull [] = False ---{-cleanLoopsFromSegs = +{-cleanLoopsFromSegs = connectPolys -- . joinSegs . filter (not . degeneratePoly)- + polylinesFromSegsOnGrid = undefined degeneratePoly [] = True@@ -95,7 +97,7 @@ connectPolys [] = [] connectPolys (present:remaining) = let- findNext (ps@(p:_):segs) = + findNext (ps@(p:_):segs) = if p == last present then (Just ps, segs) else (a, ps:b) where (a,b) = findNext segs
Graphics/Implicit/Export/Render/HandleSquares.hs view
@@ -1,14 +1,19 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE module Graphics.Implicit.Export.Render.HandleSquares (mergedSquareTris) where -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.Render.Definitions-import GHC.Exts (groupWith)-import Data.List (sortBy)-import Data.VectorSpace +import Prelude(concatMap, (++)) +import Graphics.Implicit.Definitions (Triangle)+import Graphics.Implicit.Export.Render.Definitions (TriSquare(Tris, Sq))+import Data.VectorSpace ((^*), (*^), (^+^))++-- Disable square merging temporarily.+--import GHC.Exts (groupWith)+--import Data.List (sortBy)+ -- We want small meshes. Essential to this, is getting rid of triangles. -- We secifically mark quads in tesselation (refer to Graphics.Implicit. -- Export.Render.Definitions, Graphics.Implicit.Export.Render.TesselateLoops)@@ -16,76 +21,79 @@ {- Core idea of mergedSquareTris: - Many Quads on Plane - ____________ + Many Quads on Plane+ ____________ | | | | |____|____| | |____|____|__| | joinXaligned- v - ____________ + v+ ____________ | | | |_________|__| |_________|__| | joinYaligned- v - ____________ + v+ ____________ | | | | | | |_________|__| | joinXaligned (presently disabled)- v - ____________ + v+ ____________ | | | | |____________| | squareToTri- v - ____________ + v+ ____________ |\ | | ---------- | |___________\| -} -mergedSquareTris sqTris = +mergedSquareTris :: [TriSquare] -> [Triangle]+mergedSquareTris sqTris = let -- We don't need to do any work on triangles. They'll just be part of -- the list of triangles we give back. So, the triangles coming from -- triangles...- triTriangles = concat $ map (\(Tris a) -> a) $ filter isTris sqTris + triTriangles = [tri | Tris tris <- sqTris, tri <- tris ]+ --concat $ map (\(Tris a) -> a) $ filter isTris sqTris -- We actually want to work on the quads, so we find those- squares = filter (not . isTris) sqTris+ squaresFromTris = [ (Sq x y z q) | Sq x y z q <- sqTris ]+{- -- Collect ones that are on the same plane. planeAligned = groupWith (\(Sq basis z _ _) -> (basis,z)) squares -- For each plane: -- Select for being the same range on X and then merge them on Y -- Then vice versa.- joined = map + joined = map ( -- concat . (map joinXaligned) . groupWith (\(Sq _ _ xS _) -> xS) concat . (map joinYaligned) . groupWith (\(Sq _ _ _ yS) -> yS)- . concat . (map joinXaligned) . groupWith (\(Sq _ _ xS _) -> xS)) + . concat . (map joinXaligned) . groupWith (\(Sq _ _ xS _) -> xS)) planeAligned -- Merge them back together, and we have the desired reult! finishedSquares = concat joined+-} in- -- merge them to triangles, and combine with the original triagneles.- triTriangles ++ concat (map squareToTri finishedSquares)-+ -- merge them to triangles, and combine with the original triangles.+ -- Disable square merging temporarily.+ --triTriangles ++ concat (map squareToTri finishedSquares)+ triTriangles ++ concatMap squareToTri squaresFromTris -- And now for a bunch of helper functions that do the heavy lifting... -isTris (Tris _) = True-isTris _ = False--+{-+joinXaligned :: [TriSquare] -> [TriSquare] joinXaligned quads@((Sq b z xS _):_) = let- orderedQuads = sortBy + orderedQuads = sortBy (\(Sq _ _ _ (ya,_)) (Sq _ _ _ (yb,_)) -> compare ya yb) quads mergeAdjacent (pres@(Sq _ _ _ (y1a,y2a)) : next@(Sq _ _ _ (y1b,y2b)) : others) =@@ -99,9 +107,10 @@ mergeAdjacent orderedQuads joinXaligned [] = [] +joinYaligned :: [TriSquare] -> [TriSquare] joinYaligned quads@((Sq b z _ yS):_) = let- orderedQuads = sortBy + orderedQuads = sortBy (\(Sq _ _ (xa,_) _) (Sq _ _ (xb,_) _) -> compare xa xb) quads mergeAdjacent (pres@(Sq _ _ (x1a,x2a) _) : next@(Sq _ _ (x1b,x2b) _) : others) =@@ -114,9 +123,10 @@ in mergeAdjacent orderedQuads joinYaligned [] = []-+-} -- Reconstruct a triangle+squareToTri :: TriSquare -> [Triangle] squareToTri (Sq (b1,b2,b3) z (x1,x2) (y1,y2)) = let zV = b3 ^* z@@ -128,5 +138,7 @@ d = zV ^+^ x2V ^+^ y2V in [(a,b,c),(c,b,d)]++squareToTri(Tris t) = t
Graphics/Implicit/Export/Render/Interpolate.hs view
@@ -1,10 +1,16 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}+ module Graphics.Implicit.Export.Render.Interpolate (interpolate) where -import Graphics.Implicit.Definitions+import Prelude(Integer, (*), (>), (<), (/=), (+), (-), (/), (==), (&&), abs) +import Graphics.Implicit.Definitions (ℝ, ℝ2)+ -- Consider a function f(x): {-@@ -16,14 +22,14 @@ -} -- The purpose of interpolate is to find the value of x where f(x) crosses zero.--- This should be accomplished cheaply and accuratly.+-- This should be accomplished cheaply and accurately. -- We are given the constraint that x will be between a and b. -- We are also given the values of f at a and b: aval and bval. -- Additionaly, we get f (continuous and differentiable almost everywhere),--- and the resolution of the object (so that we can make decisions about +-- and the resolution of the object (so that we can make decisions about -- how precise we need to be). -- While the output will never be used, interpolate will be called@@ -38,9 +44,7 @@ -- just that it's cheap. interpolate :: ℝ2 -> ℝ2 -> (ℝ -> ℝ) -> ℝ -> ℝ-interpolate (a,aval) (b,bval) _ _ | aval*bval > 0 = a---- The obvious:+interpolate (a,aval) (_,bval) _ _ | aval*bval > 0 = a -- The obvious: interpolate (a, 0) _ _ _ = a@@ -48,7 +52,7 @@ -- It may seem, at first, that our task is trivial. -- Just use linear interpolation!--- Unfortunatly, there's a nasty failure case+-- Unfortunately, there's a nasty failure case {- / /@@ -67,7 +71,7 @@ -- at it (shrink domain to guess within fromm (a,b) to (a',b')) -- :) -{-interpolate (a,aval) (b,bval) f res = +{-interpolate (a,aval) (b,bval) f res = let -- a' and b' are just a and b shifted inwards slightly. a' = (a*95+5*b)/100@@ -105,8 +109,8 @@ else interpolate_lin 0 (a',a'val) (b',b'val) f -} -interpolate (a,aval) (b,bval) f res =- -- Make sure aval > bval, then pass to interpolate_bin+interpolate (a,aval) (b,bval) f _ =+ -- Make sure aval > bval, then pass to interpolate_lin if aval > bval then interpolate_lin 0 (a,aval) (b,bval) f else interpolate_lin 0 (b,bval) (a,aval) f@@ -115,10 +119,11 @@ -- Try the answer linear interpolation gives us... -- (n is to cut us off if recursion goes too deep)--interpolate_lin n (a, aval) (b, bval) obj | aval /= bval= +interpolate_lin :: Integer -> ℝ2 -> ℝ2 -> (ℝ -> ℝ) -> ℝ+interpolate_lin n (a, aval) (b, bval) obj | aval /= bval= let -- Interpolate and evaluate+ mid :: ℝ mid = a + (b-a)*aval/(aval-bval) midval = obj mid -- Are we done?@@ -126,7 +131,7 @@ then mid -- else let- (a', a'val, b', b'val, improveRatio) = + (a', a'val, b', b'val, improveRatio) = if midval > 0 then (mid, midval, b, bval, midval/aval) else (a, aval, mid, midval, midval/bval)@@ -140,7 +145,7 @@ in if improveRatio < 0.3 && n < 4 -- And we continue on. then interpolate_lin (n+1) (a', a'val) (b', b'val) obj- -- But if not, we switch to binary interpolate, which is + -- But if not, we switch to binary interpolate, which is -- immune to this problem else interpolate_bin (n+1) (a', a'val) (b', b'val) obj @@ -148,10 +153,11 @@ interpolate_lin _ (a, _) _ _ = a -- Now for binary searching!+interpolate_bin :: Integer -> ℝ2 -> ℝ2 -> (ℝ -> ℝ) -> ℝ -- The termination case: -interpolate_bin 5 (a,aval) (b,bval) f = +interpolate_bin 5 (a,aval) (b,bval) _ = if abs aval < abs bval then a else b@@ -160,6 +166,7 @@ interpolate_bin n (a,aval) (b,bval) f = let+ mid :: ℝ mid = (a+b)/2 midval = f mid in if midval > 0
Graphics/Implicit/Export/Render/RefineSegs.hs view
@@ -1,26 +1,30 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -module Graphics.Implicit.Export.Render.RefineSegs where+module Graphics.Implicit.Export.Render.RefineSegs (refine) where -import Data.VectorSpace-import Graphics.Implicit.Definitions+import Prelude(Int, (<), (/), (++), (*), ($), (&&), (-), (+), (.), (>), abs, tail, sqrt, (<=))++import Graphics.Implicit.Definitions (ℝ, ℝ2, minℝ, Obj2, (⋅)) import Graphics.Implicit.Export.Util (centroid) +import Data.VectorSpace (normalized, magnitude, (^-^), (^*), (^+^))+ -- The purpose of refine is to add detail to a polyline aproximating -- the boundary of an implicit function and to remove redundant points. -refine :: ℝ -> Obj2 -> [ℝ2] -> [ℝ2]- -- We break this into two steps: detail and then simplify. +refine :: ℝ -> Obj2 -> [ℝ2] -> [ℝ2] refine res obj = simplify res . detail' res obj --- we wrap detail to make it ignore very small segments, and to pass in +-- we wrap detail to make it ignore very small segments, and to pass in -- an initial value for a pointer counter argument. This is detail' --detail' res obj [p1@(x1,y1), p2@(x2,y2)] | (x2-x1)^2 + (y2-y1)^2 > res^2/200 = +-- FIXME: magic number.+detail' :: ℝ -> (ℝ2 -> ℝ) -> [ℝ2] -> [ℝ2]+detail' res obj [p1@(x1,y1), p2@(x2,y2)] | (x2-x1)*(x2-x1) + (y2-y1)*(y2-y1) > res*res/200 = detail 0 res obj [p1,p2] detail' _ _ a = a @@ -30,21 +34,21 @@ detail n res obj [p1, p2] | n < 2 = let mid = centroid [p1,p2]- midval = obj mid + midval = obj mid in if abs midval < res / 40 then [p1, p2] else let- normal = (\(a,b) -> (b, -a)) $ normalized (p2 ^-^ p1) + normal = (\(a,b) -> (b, -a)) $ normalized (p2 ^-^ p1) derivN = -(obj (mid ^-^ (normal ^* (midval/2))) - midval) * (2/midval) in if abs derivN > 0.5 && abs derivN < 2 && abs (midval/derivN) < 3*res then let mid' = mid ^-^ (normal ^* (midval / derivN))- in detail (n+1) res obj [p1, mid'] + in detail (n+1) res obj [p1, mid'] ++ tail (detail (n+1) res obj [mid', p2] ) else let derivX = (obj (mid ^+^ (res/100, 0)) - midval)*100/res derivY = (obj (mid ^+^ (0, res/100)) - midval)*100/res- derivNormSq = derivX^2 + derivY^2+ derivNormSq = derivX*derivX + derivY*derivY in if abs derivNormSq > 0.09 && abs derivNormSq < 4 && abs (midval/sqrt derivNormSq) < 3*res then let (dX, dY) = (- derivX*midval/derivNormSq, - derivY*midval/derivNormSq)@@ -52,25 +56,25 @@ midval' = obj mid' posRatio = midval/(midval - midval') mid'' = mid ^+^ (dX*posRatio, dY*posRatio)- in + in detail (n+1) res obj [p1, mid''] ++ tail (detail (n+1) res obj [mid'', p2] ) else [p1, p2] - detail _ _ _ x = x -simplify res = {-simplify3 . simplify2 res . -} simplify1+simplify :: ℝ -> [ℝ2] -> [ℝ2]+simplify _ = {-simplify3 . simplify2 res . -} simplify1 simplify1 :: [ℝ2] -> [ℝ2] simplify1 (a:b:c:xs) =- if abs ( ((b ^-^ a) ⋅ (c ^-^ a)) - magnitude (b ^-^ a) * magnitude (c ^-^ a) ) < 0.0001+ if abs ( ((b ^-^ a) ⋅ (c ^-^ a)) - magnitude (b ^-^ a) * magnitude (c ^-^ a) ) <= minℝ then simplify1 (a:c:xs) else a : simplify1 (b:c:xs) simplify1 a = a {- simplify2 :: ℝ -> [ℝ2] -> [ℝ2]-simplify2 res [a,b,c,d] = +simplify2 res [a,b,c,d] = if norm (b - c) < res/10 then [a, ((b + c) / (2::ℝ)), d] else [a,b,c,d]
Graphics/Implicit/Export/Render/TesselateLoops.hs view
@@ -1,13 +1,15 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE module Graphics.Implicit.Export.Render.TesselateLoops (tesselateLoop) where -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.Render.Definitions+import Prelude(Int, return, ($), length, (==), zip, init, tail, reverse, (<), (/), null, foldl1, (++), head, (*), abs, (>), (&&), (+), concatMap)+import Graphics.Implicit.Definitions (ℝ, Obj3, ℝ3, Triangle, (⋅))+import Graphics.Implicit.Export.Render.Definitions (TriSquare(Tris, Sq)) import Graphics.Implicit.Export.Util (centroid)-import Data.VectorSpace-import Data.Cross +import Data.VectorSpace (normalized, (^-^), (^+^), magnitude, (^/), (^*))+import Data.Cross (cross3) tesselateLoop :: ℝ -> Obj3 -> [[ℝ3]] -> [TriSquare] @@ -25,12 +27,12 @@ -} tesselateLoop res obj [[_,_], as@(_:_:_:_),[_,_], bs@(_:_:_:_)] | length as == length bs =- concat $ map (tesselateLoop res obj) $ + concatMap (tesselateLoop res obj) $ [[[a1,b1],[b1,b2],[b2,a2],[a2,a1]] | ((a1,b1),(a2,b2)) <- zip (init pairs) (tail pairs)] where pairs = zip (reverse as) bs tesselateLoop res obj [as@(_:_:_:_),[_,_], bs@(_:_:_:_), [_,_] ] | length as == length bs =- concat $ map (tesselateLoop res obj) $ + concatMap (tesselateLoop res obj) $ [[[a1,b1],[b1,b2],[b2,a2],[a2,a1]] | ((a1,b1),(a2,b2)) <- zip (init pairs) (tail pairs)] where pairs = zip (reverse as) bs @@ -40,7 +42,9 @@ #__# -} -tesselateLoop res obj [[a,_],[b,_],[c,_],[d,_]] | centroid [a,c] == centroid [b,d] =+-- NOTE: colah thought this was broken.++tesselateLoop _ _ [[a,_],[b,_],[c,_],[d,_]] | centroid [a,c] == centroid [b,d] = let b1 = normalized $ a ^-^ b b2 = normalized $ c ^-^ b@@ -60,12 +64,12 @@ tesselateLoop res obj pathSides = return $ Tris $ let- path' = concat $ map init pathSides+ path' = concatMap init pathSides (early_tris,path) = shrinkLoop 0 path' res obj in if null path then early_tris else let- mid@(midx,midy,midz) = centroid path+ mid@(_,_,_) = centroid path midval = obj mid preNormal = foldl1 (^+^) $ [ a `cross3` b | (a,b) <- zip path (tail path ++ [head path]) ]@@ -73,7 +77,7 @@ normal = preNormal ^/ preNormalNorm deriv = (obj (mid ^+^ (normal ^* (res/100)) ) ^-^ midval)/res*100 mid' = mid ^-^ normal ^* (midval/deriv)- in if abs midval > res/50 && preNormalNorm > 0.5 && abs deriv > 0.5 + in if abs midval > res/50 && preNormalNorm > 0.5 && abs deriv > 0.5 && abs (midval/deriv) < 2*res && 3*abs (obj mid') < abs midval then early_tris ++ [(a,b,mid') | (a,b) <- zip path (tail path ++ [head path]) ] else early_tris ++ [(a,b,mid) | (a,b) <- zip path (tail path ++ [head path]) ]@@ -83,17 +87,17 @@ shrinkLoop _ path@[a,b,c] res obj = if abs (obj $ centroid [a,b,c]) < res/50- then + then ( [(a,b,c)], [])- else + else ([], path) shrinkLoop n path@(a:b:c:xs) res obj | n < length path = if abs (obj (centroid [a,c])) < res/50- then + then let (tris,remainder) = shrinkLoop 0 (a:c:xs) res obj in ((a,b,c):tris, remainder)- else + else shrinkLoop (n+1) (b:c:xs ++ [a]) res obj shrinkLoop _ path _ _ = ([],path)
Graphics/Implicit/Export/Symbolic/Rebound2.hs view
@@ -1,12 +1,19 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016 Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE+ module Graphics.Implicit.Export.Symbolic.Rebound2 (rebound2) where -import Data.VectorSpace-import Graphics.Implicit.Definitions+import Prelude() +import Graphics.Implicit.Definitions (BoxedObj2, ℝ2)++import Data.VectorSpace ((^-^), (^+^), (^/))+ rebound2 :: BoxedObj2 -> BoxedObj2-rebound2 (obj, (a,b)) = +rebound2 (obj, (a,b)) = let d :: ℝ2 d = (b ^-^ a) ^/ 10- in + in (obj, ((a ^-^ d), (b ^+^ d)))
Graphics/Implicit/Export/Symbolic/Rebound3.hs view
@@ -1,13 +1,20 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016 Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE+ module Graphics.Implicit.Export.Symbolic.Rebound3 (rebound3) where -import Graphics.Implicit.Definitions-import Data.VectorSpace+import Prelude() +import Graphics.Implicit.Definitions(BoxedObj3, ℝ3)++import Data.VectorSpace((^-^), (^+^), (^/))+ rebound3 :: BoxedObj3 -> BoxedObj3-rebound3 (obj, (a,b)) = +rebound3 (obj, (a,b)) = let d :: ℝ3 d = (b ^-^ a) ^/ 10- in + in (obj, ((a ^-^ d), (b ^+^ d)))
Graphics/Implicit/Export/SymbolicFormats.hs view
@@ -1,99 +1,158 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016 Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- FIXME: describe why we need this. {-# LANGUAGE OverloadedStrings #-} --- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- output SCAD code, AKA an implicitcad to openscad converter.+module Graphics.Implicit.Export.SymbolicFormats (scad2, scad3) where -module Graphics.Implicit.Export.SymbolicFormats where+import Prelude(Maybe(Just, Nothing), Either(Left), ($), (.), (*), map, ($!), (-), (/), pi, error, (+), init, (==)) -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.TextBuilderUtils+import Graphics.Implicit.Definitions(ℝ, SymbolicObj2(RectR, Circle, PolygonR, Complement2, UnionR2, DifferenceR2, IntersectR2, Translate2, Scale2, Rotate2, Outset2, Shell2, EmbedBoxedObj2), SymbolicObj3(Rect3R, Sphere, Cylinder, Complement3, UnionR3, IntersectR3, DifferenceR3, Translate3, Scale3, Rotate3, Rotate3V, Outset3, Shell3, ExtrudeR, ExtrudeRotateR, ExtrudeRM, EmbedBoxedObj3, RotateExtrude, ExtrudeOnEdgeOf))+import Graphics.Implicit.Export.TextBuilderUtils(Text, Builder, toLazyText, (<>), mconcat, fromLazyText, bf) -import Control.Monad.Reader-import Control.Monad (sequence)+import Control.Monad.Reader (Reader, runReader, return, fmap, sequence, ask) import Data.List (intersperse) - scad2 :: ℝ -> SymbolicObj2 -> Text scad2 res obj = toLazyText $ runReader (buildS2 obj) res scad3 :: ℝ -> SymbolicObj3 -> Text scad3 res obj = toLazyText $ runReader (buildS3 obj) res -+-- used by rotate2 and rotate3+rad2deg :: ℝ -> ℝ+rad2deg r = r * (180/pi) -- Format an openscad call given that all the modified objects are in the Reader monad... -call :: Builder -> [Builder] -> [Reader a Builder] -> Reader a Builder-call name args [] = return $ name <> buildArgs args <> ";"-call name args [obj] = fmap ((name <> buildArgs args) <>) obj-call name args objs = do+callToken :: (Text, Text) -> Builder -> [Builder] -> [Reader a Builder] -> Reader a Builder+callToken cs name args [] = return $ name <> buildArgs cs args <> ";"+callToken cs name args [obj] = fmap ((name <> buildArgs cs args) <>) obj+callToken cs name args objs = do objs' <- fmap (mconcat . map (<> "\n")) $ sequence objs- return $! name <> buildArgs args <> "{\n" <> objs' <> "}\n"--buildArgs [] = "()"-buildArgs args = "([" <> mconcat (intersperse "," args) <> "])"---buildS3 :: SymbolicObj3 -> Reader ℝ Builder--buildS3 (UnionR3 0 objs) = call "union" [] $ map buildS3 objs+ return $! name <> buildArgs cs args <> "{\n" <> objs' <> "}\n" -buildS3 (DifferenceR3 0 objs) = call "difference" [] $ map buildS3 objs+buildArgs :: (Text, Text) -> [Builder] -> Builder+buildArgs _ [] = "()"+buildArgs (c1, c2) args = "(" <> (fromLazyText c1) <> mconcat (intersperse "," args) <> (fromLazyText c2) <> ")" -buildS3 (IntersectR3 0 objs) = call " intersection" [] $ map buildS3 objs+call :: Builder -> [Builder] -> [Reader a Builder] -> Reader a Builder+call = callToken ("[", "]") -buildS3 (Translate3 (x,y,z) obj) = call "translate" [bf x, bf y, bf z] [buildS3 obj]+callNaked :: Builder -> [Builder] -> [Reader a Builder] -> Reader a Builder+callNaked = callToken ("", "") -buildS3 (Scale3 (x,y,z) obj) = call "scale" [bf x, bf y, bf x] [buildS3 obj]+-- First, the 3D objects.+buildS3 :: SymbolicObj3 -> Reader ℝ Builder -buildS3 (Rect3R 0 (x1,y1,z1) (x2,y2,z2)) = call "translate" [bf x1, bf y1, bf z1] [+buildS3 (Rect3R r (x1,y1,z1) (x2,y2,z2)) | r == 0 = call "translate" [bf x1, bf y1, bf z1] [ call "cube" [bf $ x2 - x1, bf $ y2 - y1, bf $ z2 - z1] [] ]++buildS3 (Sphere r) = callNaked "sphere" ["r = " <> bf r] []+ buildS3 (Cylinder h r1 r2) = call "cylinder" [ "r1 = " <> bf r1 ,"r2 = " <> bf r2 , bf h ] [] -buildS3 (Sphere r) = call "sphere" ["r = " <> bf r] []+buildS3 (Complement3 obj) = call "complement" [] [buildS3 obj] -buildS3 (ExtrudeR 0 obj h) = call "linear_extrude" [bf h] [buildS2 obj]+buildS3 (UnionR3 r objs) | r == 0 = call "union" [] $ map buildS3 objs -buildS3 (ExtrudeRotateR 0 twist obj h) =- call "linear_extrude" [bf h, "twist = " <> bf twist] [buildS2 obj]+buildS3 (IntersectR3 r objs) | r == 0 = call "intersection" [] $ map buildS3 objs -buildS3 (ExtrudeRM 0 (Just twist) Nothing Nothing obj (Left height)) = do+buildS3 (DifferenceR3 r objs) | r == 0 = call "difference" [] $ map buildS3 objs++buildS3 (Translate3 (x,y,z) obj) = call "translate" [bf x, bf y, bf z] [buildS3 obj]++buildS3 (Scale3 (x,y,z) obj) = call "scale" [bf x, bf y, bf z] [buildS3 obj]++buildS3 (Rotate3 (x,y,z) obj) = call "rotate" [bf (rad2deg x), bf (rad2deg y), bf (rad2deg z)] [buildS3 obj]++-- FIXME: where is Rotate3V?+buildS3 (Rotate3V _ _ _) = error "Rotate3V not implemented."++buildS3 (Outset3 r obj) | r == 0 = call "outset" [] [buildS3 obj]++buildS3 (Shell3 r obj) | r == 0 = call "shell" [] [buildS3 obj]++-- FIXME: where is EmbedBoxedObj3?++buildS3 (ExtrudeR r obj h) | r == 0 = callNaked "linear_extrude" ["height = " <> bf h] [buildS2 obj]++buildS3 (ExtrudeRotateR r twist obj h) | r == 0 = callNaked "linear_extrude" ["height = " <> bf h, "twist = " <> bf twist] [buildS2 obj]++buildS3 (ExtrudeRM r (Just twist) Nothing Nothing obj (Left height)) | r == 0 = do res <- ask call "union" [] [ call "rotate" ["0","0", bf $ twist h] [- call "linear_extrude" [bf res, "twist = " <> bf (twist (h+res) - twist h)][+ callNaked "linear_extrude" ["height = " <> bf res, "twist = " <> bf (twist (h+res) - twist h)][ buildS2 obj ] ] | h <- init [0, res .. height] ] +-- FIXME: where are RotateExtrude, ExtrudeOnEdgeOf?++buildS3(Rect3R _ _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(UnionR3 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(IntersectR3 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(DifferenceR3 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(Outset3 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(Shell3 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(ExtrudeR _ _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(ExtrudeRotateR _ _ _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(ExtrudeRM _ _ _ _ _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(EmbedBoxedObj3 _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(RotateExtrude _ _ _ _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS3(ExtrudeOnEdgeOf _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."++-- Now the 2D objects/transforms.+ buildS2 :: SymbolicObj2 -> Reader ℝ Builder -buildS2 (UnionR2 0 objs) = call "union" [] $ map buildS2 objs+buildS2 (RectR r (x1,y1) (x2,y2)) | r == 0 = call "translate" [bf x1, bf y1] [+ call "cube" [bf $ x2 - x1, bf $ y2 - y1] []+ ] -buildS2 (DifferenceR2 0 objs) = call "difference" [] $ map buildS2 objs+buildS2 (Circle r) = call "circle" [bf r] [] -buildS2 (IntersectR2 0 objs) = call "intersection" [] $ map buildS2 objs+buildS2 (PolygonR r points) | r == 0 = call "polygon" [buildVector [x,y] | (x,y) <- points] []+ where buildVector comps = "[" <> mconcat (intersperse "," $ map bf comps) <> "]" +buildS2 (Complement2 obj) = call "complement" [] $ [buildS2 obj]++buildS2 (UnionR2 r objs) | r == 0 = call "union" [] $ map buildS2 objs++buildS2 (DifferenceR2 r objs) | r == 0 = call "difference" [] $ map buildS2 objs++buildS2 (IntersectR2 r objs) | r == 0 = call "intersection" [] $ map buildS2 objs+ buildS2 (Translate2 (x,y) obj) = call "translate" [bf x, bf y] $ [buildS2 obj] buildS2 (Scale2 (x,y) obj) = call "scale" [bf x, bf y] $ [buildS2 obj] -buildS2 (RectR 0 (x1,y1) (x2,y2)) = call "translate" [bf x1, bf y1] [- call "cube" [bf $ x2 - x1, bf $ y2 - y1] []- ]+buildS2 (Rotate2 (r) obj) = call "rotate" [bf (rad2deg r)] $ [buildS2 obj] -buildS2 (Circle r) = call "circle" [bf r] []+buildS2 (Outset2 r obj) | r == 0 = call "outset" [] $ [buildS2 obj] -buildS2 (PolygonR 0 points) =- call "polygon" [buildVector [x,y] | (x,y) <- points] []- where buildVector comps =- "[" <> mconcat (intersperse "," $ map bf comps) <> "]"+buildS2 (Shell2 r obj) | r == 0 = call "shell" [] $ [buildS2 obj] +-- Generate errors for rounding requests. OpenSCAD does not support rounding.+buildS2 (RectR _ _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS2 (PolygonR _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS2 (UnionR2 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS2 (DifferenceR2 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS2 (IntersectR2 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS2 (Outset2 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."+buildS2 (Shell2 _ _) = error "cannot provide roundness when exporting openscad; unsupported in target format."++-- FIXME: missing EmbedBoxedObj2?+buildS2 (EmbedBoxedObj2 _) = error "EmbedBoxedObj2 not implemented."
Graphics/Implicit/Export/SymbolicObj2.hs view
@@ -1,6 +1,8 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- FIXME: why is all of this needed? {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} -- This file symbolicaly renders contours and contour fillings.@@ -9,31 +11,29 @@ module Graphics.Implicit.Export.SymbolicObj2 where -import Graphics.Implicit.Definitions+import Prelude(map, ($), (-), (/), (+), (>), (*), (.), reverse, cos, pi, sin, max, fromInteger, ceiling) -import Graphics.Implicit.Export.Definitions-import Graphics.Implicit.Export.MarchingSquares-import Graphics.Implicit.Export.MarchingSquaresFill-import Graphics.Implicit.Primitives-import Graphics.Implicit.ObjectUtil+import Graphics.Implicit.Definitions (ℝ, ℝ2, SymbolicObj2(RectR, Circle, Translate2, Scale2), Polyline, (⋯*)) -import Graphics.Implicit.Export.Symbolic.Rebound2-import Graphics.Implicit.Export.Symbolic.Rebound3+import Graphics.Implicit.Export.MarchingSquaresFill (getContourMesh) +import Graphics.Implicit.ObjectUtil (getImplicit2, getBox2)++import Graphics.Implicit.Export.Symbolic.Rebound2 (rebound2)+ import qualified Graphics.Implicit.Export.Render as Render (getContour)- -import Data.VectorSpace -instance DiscreteAproxable SymbolicObj2 [Polyline] where- discreteAprox res obj = symbolicGetContour res obj+import Data.VectorSpace ((^/), magnitude) symbolicGetOrientedContour :: ℝ -> SymbolicObj2 -> [Polyline] symbolicGetOrientedContour res symbObj = map orient $ symbolicGetContour res symbObj where obj = getImplicit2 symbObj orient :: Polyline -> Polyline- orient points@(x:y:_) = - let + orient [] = []+ orient [_] = []+ orient points@(x:y:_) =+ let v = (\(a,b) -> (b, -a)) (y - x) dv = v ^/ (magnitude v / res / 0.1) in if obj (x + dv) - obj x > 0@@ -43,28 +43,30 @@ symbolicGetContour :: ℝ -> SymbolicObj2 -> [Polyline] symbolicGetContour _ (RectR 0 (x1,y1) (x2,y2)) = [[ (x1,y1), (x2,y1), (x2,y2), (x1,y2), (x1,y1) ]] symbolicGetContour res (Circle r) = [[ ( r*cos(2*pi*m/n), r*sin(2*pi*m/n) ) | m <- [0.. n] ]] where- n = max 5 (fromIntegral $ ceiling $ 2*pi*r/res)+ n :: ℝ+ n = max 5 (fromInteger . ceiling $ 2*pi*r/res) symbolicGetContour res (Translate2 v obj) = map (map (+ v) ) $ symbolicGetContour res obj symbolicGetContour res (Scale2 s@(a,b) obj) = map (map (⋯* s)) $ symbolicGetContour (res/sc) obj where sc = max a b symbolicGetContour res obj = case rebound2 (getImplicit2 obj, getBox2 obj) of- (obj, (a,b)) -> Render.getContour a b res obj+ (obj', (a,b)) -> Render.getContour a b res obj' symbolicGetContourMesh :: ℝ -> SymbolicObj2 -> [(ℝ2,ℝ2,ℝ2)] symbolicGetContourMesh res (Translate2 v obj) = map (\(a,b,c) -> (a + v, b + v, c + v) ) $ symbolicGetContourMesh res obj-symbolicGetContourMesh res (Scale2 s@(a,b) obj) = map (\(a,b,c) -> (a ⋯* s, b ⋯* s, c ⋯* s) ) $+symbolicGetContourMesh res (Scale2 s@(a,b) obj) = map (\(c,d,e) -> (c ⋯* s, d ⋯* s, e ⋯* s) ) $ symbolicGetContourMesh (res/sc) obj where sc = max a b symbolicGetContourMesh _ (RectR 0 (x1,y1) (x2,y2)) = [((x1,y1), (x2,y1), (x2,y2)), ((x2,y2), (x1,y2), (x1,y1)) ]-symbolicGetContourMesh res (Circle r) = +symbolicGetContourMesh res (Circle r) = [ ((0,0),- (r*cos(2*pi*m/n), r*sin(2*pi*m/n)), - (r*cos(2*pi*(m+1)/n), r*sin(2*pi*(m+1)/n)) - )| m <- [0.. n-1] ] + (r*cos(2*pi*m/n), r*sin(2*pi*m/n)),+ (r*cos(2*pi*(m+1)/n), r*sin(2*pi*(m+1)/n))+ )| m <- [0.. n-1] ] where- n = max 5 (fromIntegral $ ceiling $ 2*pi*r/res)+ n :: ℝ+ n = max 5 (fromInteger . ceiling $ 2*pi*r/res) symbolicGetContourMesh res obj = case rebound2 (getImplicit2 obj, getBox2 obj) of- (obj, (a,b)) -> getContourMesh a b (res,res) obj+ (obj', (a,b)) -> getContourMesh a b (res,res) obj'
Graphics/Implicit/Export/SymbolicObj3.hs view
@@ -1,38 +1,25 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- FIXME: why are these needed? {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} --- The purpose of this function is to symbolicaly compute triangle meshes where possible.+-- The purpose of this function is to symbolicaly compute triangle meshes using the symbolic system where possible. -- Otherwise we coerce it into an implicit function and apply our modified marching cubes algorithm. --- We just want to export the instance... module Graphics.Implicit.Export.SymbolicObj3 (symbolicGetMesh) where -import Graphics.Implicit.Definitions+import Prelude(map, zip, length, filter, (>), ($), null, concat, (++), concatMap) -import Graphics.Implicit.Export.Definitions+import Graphics.Implicit.Definitions (ℝ, ℝ3, SymbolicObj3(UnionR3)) import Graphics.Implicit.Export.Render (getMesh)--import Graphics.Implicit.Primitives-import Graphics.Implicit.ObjectUtil-import Graphics.Implicit.MathUtil--import Graphics.Implicit.Export.SymbolicObj2--import qualified Data.Maybe as Maybe--import Graphics.Implicit.Export.Symbolic.Rebound2-import Graphics.Implicit.Export.Symbolic.Rebound3---import Graphics.Implicit.Export.Util (divideMeshTo, dividePolylineTo)-import Graphics.Implicit.Export.Util (normTriangle)---instance DiscreteAproxable SymbolicObj3 TriangleMesh where- discreteAprox res obj = symbolicGetMesh res obj--instance DiscreteAproxable SymbolicObj3 NormedTriangleMesh where- discreteAprox res obj = map (normTriangle res (getImplicit3 obj)) $ symbolicGetMesh res obj+import Graphics.Implicit.ObjectUtil (getBox3, getImplicit3)+import Graphics.Implicit.MathUtil(box3sWithin)+import Graphics.Implicit.Export.Symbolic.Rebound3 (rebound3) symbolicGetMesh :: ℝ -> SymbolicObj3 -> [(ℝ3, ℝ3, ℝ3)] @@ -213,6 +200,7 @@ boxes = map getBox3 objs boxedObjs = zip boxes objs + sepFree :: forall a. [((ℝ3, ℝ3), a)] -> ([a], [a]) sepFree ((box,obj):others) = if length (filter (box3sWithin r box) boxes) > 1 then (\(a,b) -> (obj:a,b)) $ sepFree others@@ -224,16 +212,15 @@ then case rebound3 (getImplicit3 inputObj, getBox3 inputObj) of (obj, (a,b)) -> getMesh a b res obj else if null dependants- then concat $ map (symbolicGetMesh res) independents- else concat $ - map (symbolicGetMesh res) independents - ++ [symbolicGetMesh res (UnionR3 r dependants)]+ then concatMap (symbolicGetMesh res) independents+ else concatMap (symbolicGetMesh res) independents+ ++ concat [symbolicGetMesh res (UnionR3 r dependants)] -- If all that fails, coerce and apply marching cubes :( -- (rebound is for being safe about the bounding box -- -- it slightly streches it to make sure nothing will -- have problems because it is right at the edge )-symbolicGetMesh res obj = +symbolicGetMesh res obj = case rebound3 (getImplicit3 obj, getBox3 obj) of- (obj, (a,b)) -> getMesh a b res obj + (obj', (a,b)) -> getMesh a b res obj'
Graphics/Implicit/Export/TextBuilderUtils.hs view
@@ -1,55 +1,43 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE+ -- This module exists to re-export a coherent set of functions to define -- Data.Text.Lazy builders with. - module Graphics.Implicit.Export.TextBuilderUtils ( -- Values from Data.Text.Lazy- Text- ,pack- -- Values from Data.Text.Lazy.Builder, as well as some special builders- ,Builder- ,toLazyText- ,fromLazyText- ,buildInt- -- Serialize a float in full precision- ,bf- -- Serialize a float with four decimal places- ,buildTruncFloat- -- Values from Data.Monoid- ,(<>)- ,Monoid.mconcat- ,Monoid.mempty- - ) where-import Data.Text.Lazy--- We manually redefine this operator to avoid a dependency on base >= 4.5--- This will become unnecessary later.-import qualified Data.Monoid as Monoid--import Data.Text.Lazy-import Data.Text.Lazy.Builder hiding (toLazyText)-import Data.Text.Lazy.Builder.RealFloat-import Data.Text.Lazy.Builder.Int+ Text,+ pack,+ -- Values from Data.Text.Lazy.Builder, as well as some special builders+ Builder,+ toLazyText,+ fromLazyText,+ buildInt,+ -- Serialize a float in full precision+ bf,+ -- Serialize a float with four decimal places+ buildTruncFloat,+ -- Values from Data.Monoid+ (<>),+ mconcat,+ mempty+ ) where -import Foreign.Storable (sizeOf)-import Data.Bits (shiftL)+import Prelude (Int, Maybe(Nothing, Just), ($)) -import Graphics.Implicit.Definitions+import Data.Text.Lazy (Text, pack)+-- We manually redefine this operator to avoid a dependency on base >= 4.5+-- This will become unnecessary later.+import Data.Monoid (Monoid, mappend, mconcat, mempty) --- Helper functions from Data.Text.Internal.Lazy. These functions are needed--- here instead of imported as the API is not meant to be used in this way and--- is broken in some version of the Text library.--- DO NOT EXPORT from this module-defaultChunkSize :: Int-defaultChunkSize = 16384 - chunkOverhead-{-# INLINE defaultChunkSize #-}+import Data.Text.Internal.Lazy (defaultChunkSize)+import Data.Text.Lazy.Builder (Builder, toLazyTextWith, fromLazyText)+import Data.Text.Lazy.Builder.RealFloat (formatRealFloat, FPFormat(Exponent, Fixed))+import Data.Text.Lazy.Builder.Int (decimal) --- DO NOT EXPORT from this module--- | The memory management overhead. Currently this is tuned for GHC only.-chunkOverhead :: Int-chunkOverhead = sizeOf (undefined :: Int) `shiftL` 1-{-# INLINE chunkOverhead #-}+import Graphics.Implicit.Definitions (ℝ) -- The chunk size for toLazyText is very small (128 bytes), so we export -- a version with a much larger size (~16 K)@@ -59,7 +47,6 @@ bf, buildTruncFloat :: ℝ -> Builder bf = formatRealFloat Exponent Nothing-{-# INLINE bf #-} buildTruncFloat = formatRealFloat Fixed $ Just 4 @@ -68,6 +55,5 @@ -- This is directly copied from base 4.5.1.0 infixr 6 <>-(<>) :: Monoid.Monoid m => m -> m -> m-(<>) = Monoid.mappend-{-# INLINE (<>) #-}+(<>) :: Monoid m => m -> m -> m+(<>) = mappend
Graphics/Implicit/Export/TriangleMeshFormats.hs view
@@ -1,30 +1,40 @@-{-# LANGUAGE OverloadedStrings #-}- -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2014, 2015, 2016 Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- Make string litearls more polymorphic, so we can use them with Builder.+{-# LANGUAGE OverloadedStrings #-}+ module Graphics.Implicit.Export.TriangleMeshFormats where -import Graphics.Implicit.Definitions-import Graphics.Implicit.Export.TextBuilderUtils+import Prelude (Real, Float, Int, ($), (+), map, (.), mconcat, realToFrac, toEnum, length, zip, return) -import Blaze.ByteString.Builder hiding (Builder)-import Blaze.ByteString.Builder.ByteString+import Graphics.Implicit.Definitions (Triangle, TriangleMesh, ℝ3)+import Graphics.Implicit.Export.TextBuilderUtils (Text, Builder, toLazyText, (<>), bf, buildInt)++import Blaze.ByteString.Builder (Write, writeStorable, toLazyByteString, fromByteString, fromWord32le, fromWord16le, fromWrite)+import qualified Data.ByteString.Builder.Internal as BI (Builder)+ import Data.ByteString (replicate) import Data.ByteString.Lazy (ByteString)-import Data.Storable.Endian+import Data.Storable.Endian (LittleEndian(LE)) -import Prelude hiding (replicate)-import Data.VectorSpace-import Data.Cross hiding (normal)+import Data.VectorSpace (normalized, negateV)+import Data.Cross (cross3) normal :: (ℝ3,ℝ3,ℝ3) -> ℝ3 normal (a,b,c) = normalized $ (b + negateV a) `cross3` (c + negateV a) +stl :: [Triangle] -> Text stl triangles = toLazyText $ stlHeader <> mconcat (map triangle triangles) <> stlFooter where+ stlHeader :: Builder stlHeader = "solid ImplictCADExport\n"+ stlFooter :: Builder stlFooter = "endsolid ImplictCADExport\n" vector :: ℝ3 -> Builder vector (x,y,z) = bf x <> " " <> bf y <> " " <> bf z@@ -41,6 +51,11 @@ -- Write a 32-bit little-endian float to a buffer.++-- convert Floats and Doubles to Float.+toFloat :: Real a => a -> Float+toFloat = realToFrac :: (Real a) => a -> Float+ float32LE :: Float -> Write float32LE = writeStorable . LE @@ -49,14 +64,16 @@ where header = fromByteString $ replicate 80 0 lengthField = fromWord32le $ toEnum $ length triangles triangle (a,b,c) = normalV (a,b,c) <> point a <> point b <> point c <> fromWord16le 0- point (x,y,z) = fromWrite $ float32LE x <> float32LE y <> float32LE z+ point :: forall a a1 a2. (Real a2, Real a1, Real a) => (a, a1, a2) -> BI.Builder+ point (x,y,z) = fromWrite $ float32LE (toFloat x) <> float32LE (toFloat y) <> float32LE (toFloat z) normalV ps = let (x,y,z) = normal ps- in fromWrite $ float32LE x <> float32LE y <> float32LE z+ in fromWrite $ float32LE (toFloat x) <> float32LE (toFloat y) <> float32LE (toFloat z) jsTHREE :: TriangleMesh -> Text jsTHREE triangles = toLazyText $ header <> vertcode <> facecode <> footer where -- some dense JS. Let's make helper functions so that we don't repeat code each line+ header :: Builder header = mconcat [ "var Shape = function(){\n" ,"var s = this;\n"@@ -66,6 +83,7 @@ ,"function f(a,b,c){" ,"s.faces.push(new THREE.Face3(a,b,c));" ,"}\n" ]+ footer :: Builder footer = mconcat [ "}\n" ,"Shape.prototype = new THREE.Geometry();\n"@@ -87,5 +105,5 @@ facecode = mconcat $ do (n,_) <- zip [0, 3 ..] triangles let- (posa, posb, posc) = (n, n+1, n+2)+ (posa, posb, posc) = (n, n+1, n+2) :: (Int, Int, Int) return $ f posa posb posc
Graphics/Implicit/Export/Util.hs view
@@ -1,19 +1,24 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- FIXME: why are these needed? {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} -- Functions to make meshes/polylines finer. -module Graphics.Implicit.Export.Util {-(divideMesh2To, divideMeshTo, dividePolylineTo)-} where+module Graphics.Implicit.Export.Util (normTriangle, normVertex, centroid) where -import Graphics.Implicit.Definitions-import Data.VectorSpace+import Prelude(Fractional, (/), (-), ($), foldl, recip, realToFrac, length) +import Graphics.Implicit.Definitions (ℝ, ℝ3, Obj3, Triangle, NormedTriangle)++import Data.VectorSpace (VectorSpace, Scalar, (^+^), (*^), (^/), (^-^), normalized, zeroV)+ normTriangle :: ℝ -> Obj3 -> Triangle -> NormedTriangle-normTriangle res obj tri@(a,b,c) = - (normify a', normify b', normify c') - where +normTriangle res obj (a,b,c) =+ (normify a', normify b', normify c')+ where normify = normVertex res obj a' = (a ^+^ r*^b ^+^ r*^c) ^/ 1.02 b' = (b ^+^ r*^a ^+^ r*^c) ^/ 1.02@@ -21,7 +26,7 @@ r = 0.01 :: ℝ normVertex :: ℝ -> Obj3 -> ℝ3 -> (ℝ3, ℝ3)-normVertex res obj p = +normVertex res obj p = let -- D_vf(p) = ( f(p) - f(p+v) ) /|v| -- but we'll actually scale v by res, so then |v| = res@@ -38,26 +43,27 @@ centroid :: (VectorSpace v, Fractional (Scalar v)) => [v] -> v centroid pts = (norm *^) $ foldl (^+^) zeroV pts- where norm = recip $ realToFrac $ length pts-{-# INLINE centroid #-}+ where+ norm :: Fractional a => a+ norm = recip $ realToFrac $ length pts {--- If we need to make a 2D mesh finer... divideMesh2To :: ℝ -> [(ℝ2, ℝ2, ℝ2)] -> [(ℝ2, ℝ2, ℝ2)] divideMesh2To res mesh =- let + let av :: ℝ2 -> ℝ2 -> ℝ2 av a b = (a S.+ b) S./ (2.0 :: ℝ) divideTriangle :: (ℝ2, ℝ2, ℝ2) -> [(ℝ2, ℝ2, ℝ2)] divideTriangle (a,b,c) = case (S.norm (a S.- b) > res, S.norm (b S.- c) > res, S.norm (c S.- a) > res) of (False, False, False) -> [(a,b,c)]- (True, False, False) -> [(a, av a b, c), + (True, False, False) -> [(a, av a b, c), (av a b, b, c) ]- (True, True, False) -> [(a, av a b, av a c), - (av a b, b, av a c), + (True, True, False) -> [(a, av a b, av a c),+ (av a b, b, av a c), (b, c, av a c)]- (True, True, True ) -> [(a, av a b, av a c), - (b, av b c, av b a), + (True, True, True ) -> [(a, av a b, av a c),+ (b, av b c, av b a), (c, av c a, av c b), (av b c, av a c, av a b)] (_,_,_) -> divideTriangle (c, a, b)@@ -66,20 +72,20 @@ divideMeshTo :: ℝ -> [(ℝ3, ℝ3, ℝ3)] -> [(ℝ3, ℝ3, ℝ3)] divideMeshTo res mesh =- let + let av :: ℝ3 -> ℝ3 -> ℝ3 av a b = (a S.+ b) S./ (2.0 :: ℝ) divideTriangle :: (ℝ3, ℝ3, ℝ3) -> [(ℝ3, ℝ3, ℝ3)] divideTriangle (a,b,c) = case (S.norm (a S.- b) > res, S.norm (b S.- c) > res, S.norm (c S.- a) > res) of (False, False, False) -> [(a,b,c)]- (True, False, False) -> [(a, av a b, c), + (True, False, False) -> [(a, av a b, c), (av a b, b, c) ]- (True, True, False) -> [(a, av a b, av a c), - (av a b, b, av a c), + (True, True, False) -> [(a, av a b, av a c),+ (av a b, b, av a c), (b, c, av a c)]- (True, True, True ) -> [(a, av a b, av a c), - (b, av b c, av b a), + (True, True, True ) -> [(a, av a b, av a c),+ (b, av b c, av b a), (c, av c a, av c b), (av b c, av a c, av a b)] (_,_,_) -> divideTriangle (c, a, b)@@ -91,7 +97,7 @@ let av :: ℝ2 -> ℝ2 -> ℝ2 av a b = (a S.+ b) S./ (2.0 :: ℝ)- divide a b = + divide a b = if S.norm (a S.- b) <= res then [a] else concat [divide a (av a b), divide (av a b) b]
Graphics/Implicit/ExtOpenScad.hs view
@@ -1,41 +1,42 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- FIXME: why are these required?+{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-}+ -- We'd like to parse openscad code, with some improvements, for backwards compatability. -module Graphics.Implicit.ExtOpenScad (runOpenscad, OVal (..) ) where+module Graphics.Implicit.ExtOpenScad (runOpenscad) where -import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Parser.Statement-import Graphics.Implicit.ExtOpenScad.Eval.Statement+import Prelude(Char, Either(Left, Right), IO, ($), fmap)++import Graphics.Implicit.Definitions (SymbolicObj2, SymbolicObj3)+import Graphics.Implicit.ExtOpenScad.Definitions (VarLookup, OVal)+import Graphics.Implicit.ExtOpenScad.Parser.Statement (parseProgram)+import Graphics.Implicit.ExtOpenScad.Eval.Statement (runStatementI) import Graphics.Implicit.ExtOpenScad.Default (defaultObjects)-import Graphics.Implicit.ExtOpenScad.Util.OVal+import Graphics.Implicit.ExtOpenScad.Util.OVal (divideObjs) -import qualified Data.Maybe as Maybe-import qualified Data.List as List-import qualified Data.Map as Map-import Data.Map (Map)-import qualified Control.Monad as Monad-import qualified Control.Monad.State as State-import Control.Monad.State (State,StateT, get, put, modify, liftIO)-import qualified System.Directory as Dir+import qualified Text.Parsec.Error as Parsec (ParseError)+import qualified Control.Monad as Monad (mapM_)+import qualified Control.Monad.State as State (runStateT)+import qualified System.Directory as Dir (getCurrentDirectory) --- Small wrapper to handle parse errors, etc+-- Small wrapper to handle parse errors, etc.+runOpenscad :: [Char] -> Either Parsec.ParseError (IO (VarLookup, [SymbolicObj2], [SymbolicObj3])) runOpenscad s = let initial = defaultObjects+ rearrange :: forall t t1 t2 t3 t4. (t, (t4, [OVal], t1, t2, t3)) -> (t4, [SymbolicObj2], [SymbolicObj3]) rearrange (_, (varlookup, ovals, _ , _ , _)) = (varlookup, obj2s, obj3s) where- (obj2s, obj3s, others) = divideObjs ovals+ (obj2s, obj3s, _ ) = divideObjs ovals in case parseProgram "" s of Left e -> Left e Right sts -> Right $ fmap rearrange- $ (\sts -> do+ $ (\sts' -> do path <- Dir.getCurrentDirectory- State.runStateT sts (initial, [], path, (), () )+ State.runStateT sts' (initial, [], path, (), () ) ) $ Monad.mapM_ runStatementI sts---
Graphics/Implicit/ExtOpenScad/Default.hs view
@@ -1,18 +1,25 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}+ -- We'd like to parse openscad code, with some improvements, for backwards compatability. module Graphics.Implicit.ExtOpenScad.Default where -import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Util.OVal-import Graphics.Implicit.ExtOpenScad.Primitives-import Data.Map (Map, fromList) +import Prelude (Char, String, Bool(True, False), Maybe(Just, Nothing), Int, ($), (++), map, pi, sin, cos, tan, asin, acos, atan, sinh, cosh, tanh, abs, signum, fromInteger, (.), floor, ceiling, round, exp, log, sqrt, max, min, atan2, (**), flip, (<), (>), (<=), (>=), (==), (/=), (&&), (||), not, show, foldl, (*), (/), mod, (+), zipWith, (-), (!!), length, otherwise, fromIntegral)++import Graphics.Implicit.Definitions (ℝ)+import Graphics.Implicit.ExtOpenScad.Definitions(VarLookup, OVal(OList, ONum, OString, OUndefined, OError, OModule, OFunc))+import Graphics.Implicit.ExtOpenScad.Util.OVal (toOObj, oTypeStr)+import Graphics.Implicit.ExtOpenScad.Primitives (primitives)+import Data.Map (fromList)+ defaultObjects :: VarLookup -- = Map String OVal-defaultObjects = fromList $ +defaultObjects = fromList $ defaultConstants ++ defaultFunctions ++ defaultFunctions2@@ -21,11 +28,13 @@ ++ defaultPolymorphicFunctions -- Missing standard ones:--- rand, lookup, +-- rand, lookup, +defaultConstants :: [([Char], OVal)] defaultConstants = map (\(a,b) -> (a, toOObj (b::ℝ) )) [("pi", pi)] +defaultFunctions :: [([Char], OVal)] defaultFunctions = map (\(a,b) -> (a, toOObj ( b :: ℝ -> ℝ))) [ ("sin", sin),@@ -39,9 +48,9 @@ ("tanh", tanh), ("abs", abs), ("sign", signum),- ("floor", fromIntegral . floor ),- ("ceil", fromIntegral . ceiling ),- ("round", fromIntegral . round ),+ ("floor", fromInteger . floor ),+ ("ceil", fromInteger . ceiling ),+ ("round", fromInteger . round ), ("exp", exp), ("ln", log), ("log", log),@@ -49,6 +58,7 @@ ("sqrt", sqrt) ] +defaultFunctions2 :: [([Char], OVal)] defaultFunctions2 = map (\(a,b) -> (a, toOObj (b :: ℝ -> ℝ -> ℝ) )) [ ("max", max),@@ -57,15 +67,17 @@ ("pow", (**)) ] -defaultFunctionsSpecial = +defaultFunctionsSpecial :: [([Char], OVal)]+defaultFunctionsSpecial = [- ("map", toOObj $ flip $ - (map :: (OVal -> OVal) -> [OVal] -> [OVal] ) + ("map", toOObj $ flip $+ (map :: (OVal -> OVal) -> [OVal] -> [OVal] ) ) ] +defaultModules :: [(String, OVal)] defaultModules = map (\(a,b) -> (a, OModule b)) primitives @@ -73,16 +85,18 @@ -- more complicated ones: -defaultPolymorphicFunctions = - [ - ("+", sum),- ("sum", sum),+defaultPolymorphicFunctions :: [([Char], OVal)]+defaultPolymorphicFunctions =+ [+ ("+", sumtotal),+ ("sum", sumtotal), ("*", prod), ("prod", prod),- ("/", div),- ("-", toOObj sub), - ("^", toOObj ((**) :: ℝ -> ℝ -> ℝ)), - ("negate", toOObj negate),+ ("/", divide),+ ("-", toOObj sub),+ ("%", toOObj omod),+ ("^", toOObj ((**) :: ℝ -> ℝ -> ℝ)),+ ("negate", toOObj negatefun), ("index", toOObj index), ("splice", toOObj osplice), ("<", toOObj ((<) :: ℝ -> ℝ -> Bool) ),@@ -96,7 +110,7 @@ ("||", toOObj (||) ), ("!", toOObj not ), ("list_gen", toOObj list_gen),- ("++", concat),+ ("++", concatenate), ("len", toOObj olength), ("str", toOObj (show :: OVal -> String)) ] where@@ -104,16 +118,16 @@ -- Some key functions are written as OVals in optimizations attempts prod = OFunc $ \x -> case x of- (OList (x:xs)) -> foldl mult x xs+ (OList (y:ys)) -> foldl mult y ys (OList []) -> ONum 1- a -> OError ["Product takes a list"]+ _ -> OError ["Product takes a list"] mult (ONum a) (ONum b) = ONum (a*b) mult (ONum a) (OList b) = OList (map (mult (ONum a)) b) mult (OList a) (ONum b) = OList (map (mult (ONum b)) a) mult a b = errorAsAppropriate "multiply" a b - div = OFunc $ \x -> case x of+ divide = OFunc $ \x -> case x of (ONum a) -> OFunc $ \y -> case y of (ONum b) -> ONum (a/b) b -> errorAsAppropriate "divide" (ONum a) b@@ -124,22 +138,22 @@ div' (OList a) (ONum b) = OList (map (\x -> div' x (ONum b)) a) div' a b = errorAsAppropriate "divide" a b - omod (ONum a) (ONum b) = ONum $ fromIntegral $ mod (floor a) (floor b)+ omod (ONum a) (ONum b) = ONum $ fromInteger $ mod (floor a) (floor b) omod a b = errorAsAppropriate "modulo" a b append (OList a) (OList b) = OList $ a++b append (OString a) (OString b) = OString $ a++b append a b = errorAsAppropriate "append" a b - concat = OFunc $ \x -> case x of- (OList (x:xs)) -> foldl append x xs+ concatenate = OFunc $ \x -> case x of+ (OList (y:ys)) -> foldl append y ys (OList []) -> OList [] _ -> OError ["concat takes a list"] - sum = OFunc $ \x -> case x of- (OList (x:xs)) -> foldl add x xs+ sumtotal = OFunc $ \x -> case x of+ (OList (y:ys)) -> foldl add y ys (OList []) -> ONum 0- a -> OError ["Product takes a list"]+ _ -> OError ["Sum takes a list"] add (ONum a) (ONum b) = ONum (a+b) add (OList a) (OList b) = OList $ zipWith add a b@@ -149,9 +163,9 @@ sub (OList a) (OList b) = OList $ zipWith sub a b sub a b = errorAsAppropriate "subtract" a b - negate (ONum n) = ONum (-n)- negate (OList l) = OList $ map negate l- negate a = OError ["Can't negate " ++ oTypeStr a ++ "(" ++ show a ++ ")"]+ negatefun (ONum n) = ONum (-n)+ negatefun (OList l) = OList $ map negatefun l+ negatefun a = OError ["Can't negate " ++ oTypeStr a ++ "(" ++ show a ++ ")"] {-numCompareToExprCompare :: (ℝ -> ℝ -> Bool) -> Oval -> OVal -> Bool numCompareToExprCompare f a b =@@ -159,35 +173,40 @@ (Just a, Just b) -> f a b _ -> False-} - index (OList l) (ONum ind) = - let n = floor ind - in if n < length l then l !! n else OError ["List accessd out of bounds"]- index (OString s) (ONum ind) = - let n = floor ind + index (OList l) (ONum ind) =+ let+ n :: Int+ n = floor ind+ in+ if n < length l then l !! n else OError ["List accessd out of bounds"]+ index (OString s) (ONum ind) =+ let+ n :: Int+ n = floor ind in if n < length s then OString [s !! n] else OError ["List accessd out of bounds"] index a b = errorAsAppropriate "index" a b - osplice (OList list) (ONum a) ( ONum b ) = + osplice (OList list) (ONum a) ( ONum b ) = OList $ splice list (floor a) (floor b)- osplice (OString str) (ONum a) ( ONum b ) = + osplice (OString str) (ONum a) ( ONum b ) = OString $ splice str (floor a) (floor b)- osplice (OList list) (OUndefined) (ONum b ) = + osplice (OList list) (OUndefined) (ONum b ) = OList $ splice list 0 (floor b)- osplice (OString str) (OUndefined) (ONum b ) = + osplice (OString str) (OUndefined) (ONum b ) = OString $ splice str 0 (floor b)- osplice (OList list) (ONum a) ( OUndefined) = + osplice (OList list) (ONum a) ( OUndefined) = OList $ splice list (floor a) (length list + 1)- osplice (OString str) (ONum a) ( OUndefined) = + osplice (OString str) (ONum a) ( OUndefined) = OString $ splice str (floor a) (length str + 1)- osplice (OList list) (OUndefined) (OUndefined) = + osplice (OList list) (OUndefined) (OUndefined) = OList $ splice list 0 (length list + 1)- osplice (OString str) (OUndefined) (OUndefined) = + osplice (OString str) (OUndefined) (OUndefined) = OString $ splice str 0 (length str + 1) osplice _ _ _ = OUndefined splice :: [a] -> Int -> Int -> [a] splice [] _ _ = []- splice (l@(x:xs)) a b + splice (l@(x:xs)) a b | a < 0 = splice l (a+n) b | b < 0 = splice l a (b+n) | a > 0 = splice xs (a-1) (b-1)@@ -197,27 +216,28 @@ errorAsAppropriate _ err@(OError _) _ = err errorAsAppropriate _ _ err@(OError _) = err- errorAsAppropriate name a b = OError + errorAsAppropriate name a b = OError ["Can't " ++ name ++ " objects of types " ++ oTypeStr a ++ " and " ++ oTypeStr b ++ "."] list_gen :: [ℝ] -> Maybe [ℝ]- list_gen [a,b] = Just [fromIntegral (ceiling a).. fromIntegral (floor b)]+ list_gen [a,b] = Just [fromInteger (ceiling a).. fromInteger (floor b)] list_gen [a, b, c] = let nr = (c-a)/b- n = fromIntegral (floor nr)+ n :: ℝ+ n = fromInteger (floor nr) in if nr - n > 0- then Just - [fromIntegral (ceiling a), fromIntegral (ceiling (a+b)).. fromIntegral (floor (c - b*(nr -n)))]- else Just - [fromIntegral (ceiling a), fromIntegral (ceiling (a+b)).. fromIntegral (floor c)]+ then Just+ [fromInteger (ceiling a), fromInteger (ceiling (a+b)).. fromInteger (floor (c - b*(nr -n)))]+ else Just+ [fromInteger (ceiling a), fromInteger (ceiling (a+b)).. fromInteger (floor c)] list_gen _ = Nothing - ternary True a b = a- ternary False a b = b+ ternary :: forall t. Bool -> t -> t -> t+ ternary True a _ = a+ ternary False _ b = b - olegnth (OString s) = ONum $ fromIntegral $ length s+ olength (OString s) = ONum $ fromIntegral $ length s olength (OList s) = ONum $ fromIntegral $ length s olength a = OError ["Can't take length of a " ++ oTypeStr a ++ "."]-
Graphics/Implicit/ExtOpenScad/Definitions.hs view
@@ -1,28 +1,94 @@-module Graphics.Implicit.ExtOpenScad.Definitions where+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -import Graphics.Implicit.Definitions+module Graphics.Implicit.ExtOpenScad.Definitions (ArgParser(AP, APTest, APBranch, APTerminator, APFailIf, APExample),+ Symbol,+ Pattern(Wild, Name, ListP),+ Expr(LitE, Var, ListE, LamE, (:$)),+ StatementI(StatementI),+ Statement(DoNothing, NewModule, Include, Echo, If, For, ModuleCall, (:=)),+ OVal(ONum, OBool, OString, OList, OFunc, OUndefined, OModule,OError, OObj2, OObj3),+ VarLookup,+ FStack,+ TestInvariant(EulerCharacteristic),+ collector) where++import Prelude(Eq, Show, String, Maybe, Bool(True, False), Int, IO, (==), show, map, ($), (++), undefined, all, id, zipWith, foldl1)++import Graphics.Implicit.Definitions (ℝ, SymbolicObj2, SymbolicObj3)++import Control.Applicative (Applicative, Alternative((<|>), empty), pure, (<*>))+import Control.Monad (Functor, Monad, fmap, (>>=), mzero, mplus, MonadPlus, liftM, ap) import Data.Map (Map)-import qualified Control.Monad as Monad-import Control.Monad.State (State,StateT)-import qualified Data.List as List +-----------------------------------------------------------------+-- | Handles parsing arguments to modules+data ArgParser a+ -- | For actual argument entries:+ -- ArgParser (argument name) (default) (doc) (next Argparser...)+ = AP String (Maybe OVal) String (OVal -> ArgParser a)+ -- | For returns:+ -- ArgParserTerminator (return value)+ | APTerminator a+ -- | For failure:+ -- ArgParserFailIf (test) (error message) (child for if true)+ | APFailIf Bool String (ArgParser a)+ -- An example, then next+ | APExample String (ArgParser a)+ -- A string to run as a test, then invariants for the results, then next+ | APTest String [TestInvariant] (ArgParser a)+ -- A branch where there are a number of possibilities for the parser underneath+ | APBranch [ArgParser a]++instance Functor ArgParser where+ fmap = liftM++instance Applicative ArgParser where+ pure a = APTerminator a+ (<*>) = ap++instance Monad ArgParser where+ -- We need to describe how (>>=) works.+ -- Let's get the hard ones out of the way first.+ -- ArgParser actually+ (AP str fallback d f) >>= g = AP str fallback d (\a -> (f a) >>= g)+ (APFailIf b errmsg child) >>= g = APFailIf b errmsg (child >>= g)+ -- These next to is easy, they just pass the work along to their child+ (APExample str child) >>= g = APExample str (child >>= g)+ (APTest str tests child) >>= g = APTest str tests (child >>= g)+ -- And an ArgParserTerminator happily gives away the value it contains+ (APTerminator a) >>= g = g a+ (APBranch bs) >>= g = APBranch $ map (>>= g) bs++instance MonadPlus ArgParser where+ mzero = APFailIf True "" undefined+ mplus (APBranch as) (APBranch bs) = APBranch ( as ++ bs )+ mplus (APBranch as) b = APBranch ( as ++ [b] )+ mplus a (APBranch bs) = APBranch ( [a] ++ bs )+ mplus a b = APBranch [ a , b ]++instance Alternative ArgParser where+ (<|>) = mplus+ empty = mzero+ type Symbol = String data Pattern = Name Symbol | ListP [Pattern] | Wild | Symbol :@ Pattern- deriving Show+ deriving (Show, Eq) data Expr = Var Symbol | LitE OVal | ListE [Expr] | LamE [Pattern] Expr | Expr :$ [Expr]- deriving Show+ deriving (Show, Eq) data StatementI = StatementI Int (Statement StatementI)- deriving Show+ deriving (Show, Eq) data Statement st = Include String Bool | Pattern := Expr@@ -32,14 +98,14 @@ | NewModule Symbol [(Symbol, Maybe Expr)] [st] | ModuleCall Symbol [(Maybe Symbol, Expr)] [st] | DoNothing- deriving Show+ deriving (Show, Eq) -- | Objects for our OpenSCAD-like language-data OVal = OUndefined +data OVal = OUndefined | OError [String]- | OBool Bool + | OBool Bool | ONum ℝ | OList [OVal] | OString String@@ -61,7 +127,7 @@ show (ONum n) = show n show (OList l) = show l show (OString s) = show s- show (OFunc f) = "<function>"+ show (OFunc _) = "<function>" show (OModule _) = "module" show (OError msgs) = "Execution Error:\n" ++ foldl1 (\a b -> a ++ "\n" ++ b) msgs show (OObj2 obj) = "<obj2: " ++ show obj ++ ">"@@ -70,28 +136,10 @@ type VarLookup = Map String OVal type FStack = [OVal] -collector s [x] = x+collector :: Symbol -> [Expr] -> Expr+collector _ [x] = x collector s l = Var s :$ [ListE l] --------------------------------------------------------------------- | Handles parsing arguments to modules-data ArgParser a - -- | For actual argument entries:- -- ArgParser (argument name) (default) (doc) (next Argparser...)- = AP String (Maybe OVal) String (OVal -> ArgParser a) - -- | For returns:- -- ArgParserTerminator (return value)- | APTerminator a - -- | For failure:- -- ArgParserFailIf (test) (error message) (child for if true)- | APFailIf Bool String (ArgParser a)- -- An example, then next- | APExample String (ArgParser a)- -- A string to run as a test, then invariants for the results, then next- | APTest String [TestInvariant] (ArgParser a)- -- A branch where there are a number of possibilities for the parser underneath- | APBranch [ArgParser a]--data TestInvariant = EulerCharacteristic Int +data TestInvariant = EulerCharacteristic Int deriving (Show)
Graphics/Implicit/ExtOpenScad/Eval/Expr.hs view
@@ -1,30 +1,35 @@-{-# LANGUAGE ViewPatterns #-}+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE module Graphics.Implicit.ExtOpenScad.Eval.Expr (evalExpr, matchPat) where -import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Util.OVal-import Graphics.Implicit.ExtOpenScad.Util.StateC+import Prelude (String, Maybe(Just, Nothing), IO, concat, ($), map, return, zip, (==), (!!), const, (++), foldr, concatMap) -import qualified Data.Maybe as Maybe-import qualified Data.List as List-import qualified Data.Map as Map-import Data.Map (Map)-import qualified Control.Monad as Monad-import qualified Control.Monad.State as State-import Control.Monad.State (State,StateT, get, put, modify, liftIO)+import Graphics.Implicit.ExtOpenScad.Definitions (+ Pattern(Name, ListP, Wild),+ OVal(OList, OError, OFunc),+ Expr(LitE, Var, ListE, LamE, (:$)),+ VarLookup) +import Graphics.Implicit.ExtOpenScad.Util.OVal (oTypeStr, getErrors)+import Graphics.Implicit.ExtOpenScad.Util.StateC (StateC, getVarLookup) +import Data.List (findIndex)+import Data.Map (fromList, lookup)+import Control.Monad (zipWithM, mapM, forM)+import Control.Monad.State (StateT, get, modify, liftIO, runStateT)++ patVars :: Pattern -> [String] patVars (Name name) = [name]-patVars (ListP pats) = concat $ map patVars pats+patVars (ListP pats) = concatMap patVars pats patVars _ = [] patMatch :: Pattern -> OVal -> Maybe [OVal] patMatch (Name _) val = Just [val] patMatch (ListP pats) (OList vals) = do- matches <- Monad.zipWithM patMatch pats vals+ matches <- zipWithM patMatch pats vals return $ concat matches patMatch Wild _ = Just [] patMatch _ _ = Nothing@@ -33,13 +38,13 @@ matchPat pat val = do let vars = patVars pat vals <- patMatch pat val- return $ Map.fromList $ zip vars vals+ return $ fromList $ zip vars vals evalExpr :: Expr -> StateC OVal evalExpr expr = do varlookup <- getVarLookup- (valf, _) <- liftIO $ State.runStateT (evalExpr' expr) (varlookup, [])+ (valf, _) <- liftIO $ runStateT (evalExpr' expr) (varlookup, []) return $ valf [] @@ -49,32 +54,32 @@ evalExpr' (Var name ) = do (varlookup, namestack) <- get return $- case (Map.lookup name varlookup, List.findIndex (==name) namestack) of+ case (lookup name varlookup, findIndex (==name) namestack) of (_, Just pos) -> \s -> s !! pos (Just val, _) -> const val- _ -> const $ OError ["Variable " ++ name ++ " not in scope" ] + _ -> const $ OError ["Variable " ++ name ++ " not in scope" ] evalExpr' (LitE val ) = return $ const val evalExpr' (ListE exprs) = do- valFuncs <- Monad.mapM evalExpr' exprs+ valFuncs <- mapM evalExpr' exprs return $ \s -> OList $ map ($s) valFuncs evalExpr' (fexpr :$ argExprs) = do fValFunc <- evalExpr' fexpr- argValFuncs <- Monad.mapM evalExpr' argExprs+ argValFuncs <- mapM evalExpr' argExprs return $ \s -> app (fValFunc s) (map ($s) argValFuncs)- where + where app f l = case (getErrors f, getErrors $ OList l) of (Nothing, Nothing) -> app' f l where- app' (OFunc f) (x:xs) = app (f x) xs+ app' (OFunc f') (x:xs) = app (f' x) xs app' a [] = a app' x _ = OError ["Can't apply arguments to " ++ oTypeStr x] (Just err, _ ) -> OError [err] (_, Just err) -> OError [err] evalExpr' (LamE pats fexpr) = do- fparts <- Monad.forM pats $ \pat -> do+ fparts <- forM pats $ \pat -> do modify (\(vl, names) -> (vl, patVars pat ++ names)) return $ \f xss -> OFunc $ \val -> case patMatch pat val of Just xs -> f (xs ++ xss)@@ -85,7 +90,7 @@ -------------- -+{- simplifyExpr ((simplifyExpr -> Var f) :$ args) = (Var f :$) $ let split b l = (filter b l, filter (not.b) l)@@ -97,3 +102,4 @@ "*" -> (LitE $ ONum $ product numArgs'):nonNumArgs _ -> args' simplifyExpr x = x+-}
Graphics/Implicit/ExtOpenScad/Eval/Statement.hs view
@@ -1,26 +1,34 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE+ {-# LANGUAGE ViewPatterns, ScopedTypeVariables #-} module Graphics.Implicit.ExtOpenScad.Eval.Statement where -import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Util.OVal-import Graphics.Implicit.ExtOpenScad.Util.ArgParser-import Graphics.Implicit.ExtOpenScad.Util.StateC-import Graphics.Implicit.ExtOpenScad.Eval.Expr-import Graphics.Implicit.ExtOpenScad.Parser.Statement (parseProgram)+import Prelude(Maybe(Just, Nothing), Bool(True, False), Either(Left, Right), FilePath, IO, (.), ($), show, putStrLn, concatMap, return, (++), fmap, reverse, fst, readFile) +import Graphics.Implicit.ExtOpenScad.Definitions (+ Statement(Include, (:=), Echo, For, If, NewModule, ModuleCall, DoNothing),+ Pattern(Name),+ Expr(LitE),+ OVal(OString, OBool, OList, OModule),+ VarLookup,+ StatementI(StatementI)+ ) -import qualified Data.Maybe as Maybe-import qualified Data.List as List+import Graphics.Implicit.ExtOpenScad.Util.OVal (getErrors)+import Graphics.Implicit.ExtOpenScad.Util.ArgParser (argument, defaultTo, argMap)+import Graphics.Implicit.ExtOpenScad.Util.StateC (StateC, errorC, modifyVarLookup, mapMaybeM, lookupVar, pushVals, getRelPath, withPathShiftedBy, getVals, putVals)+import Graphics.Implicit.ExtOpenScad.Eval.Expr (evalExpr, matchPat)+import Graphics.Implicit.ExtOpenScad.Parser.Statement (parseProgram)+ import qualified Data.Map as Map-import Data.Map (Map) import qualified Control.Monad as Monad-import qualified Control.Monad.State as State-import Control.Monad.State (State,StateT, get, put, modify, liftIO)+import Control.Monad.State (get, liftIO, mapM, runStateT, (>>)) import qualified System.FilePath as FilePath -+-- Run statements out of the OpenScad file. runStatementI :: StatementI -> StateC () runStatementI (StatementI lineN (pat := expr)) = do@@ -37,7 +45,7 @@ show2 x = show x vals <- mapM evalExpr exprs case getErrors (OList vals) of- Nothing -> liftIO $ putStrLn $ concat $ map show2 vals+ Nothing -> liftIO . putStrLn $ concatMap show2 vals Just err -> errorC lineN err runStatementI (StatementI lineN (For pat expr loopContent)) = do@@ -61,21 +69,23 @@ _ -> return () runStatementI (StatementI lineN (NewModule name argTemplate suite)) = do- argTemplate' <- Monad.forM argTemplate $ \(name, defexpr) -> do- defval <- mapMaybeM evalExpr defexpr - return (name, defval)+ argTemplate' <- Monad.forM argTemplate $ \(name', defexpr) -> do+ defval <- mapMaybeM evalExpr defexpr+ return (name', defval) (varlookup, _, path, _, _) <- get- runStatementI $ StatementI lineN $ (Name name :=) $ LitE $ OModule $ \vals -> do - newNameVals <- Monad.forM argTemplate' $ \(name, maybeDef) -> do+-- FIXME: \_? really?+ runStatementI $ StatementI lineN $ (Name name :=) $ LitE $ OModule $ \_ -> do+ newNameVals <- Monad.forM argTemplate' $ \(name', maybeDef) -> do val <- case maybeDef of- Just def -> argument name `defaultTo` def- Nothing -> argument name- return (name, val)+ Just def -> argument name' `defaultTo` def+ Nothing -> argument name'+ return (name', val) let+{- children = ONum $ fromIntegral $ length vals child = OModule $ \vals -> do n :: ℕ <- argument "n";- return $ return $ return $ + return $ return $ return $ if n <= length vals then vals !! n else OUndefined@@ -86,6 +96,7 @@ _ -> OUndefined _ -> OUndefined newNameVals' = newNameVals ++ [("children", children),("child", child), ("childBox", childBox)]+-} varlookup' = Map.union (Map.fromList newNameVals) varlookup suiteVals = runSuiteCapture varlookup' path suite return suiteVals@@ -93,13 +104,13 @@ runStatementI (StatementI lineN (ModuleCall name argsExpr suite)) = do maybeMod <- lookupVar name (varlookup, _, path, _, _) <- get- childVals <- fmap reverse $ liftIO $ runSuiteCapture varlookup path suite+ childVals <- fmap reverse . liftIO $ runSuiteCapture varlookup path suite argsVal <- Monad.forM argsExpr $ \(posName, expr) -> do val <- evalExpr expr return (posName, val) newVals <- case maybeMod of- Just (OModule mod) -> liftIO ioNewVals where- argparser = mod childVals+ Just (OModule mod') -> liftIO ioNewVals where+ argparser = mod' childVals ioNewVals = case fst $ argMap argsVal argparser of Just iovals -> iovals Nothing -> return []@@ -113,7 +124,7 @@ return [] pushVals newVals -runStatementI (StatementI lineN (Include name injectVals)) = do+runStatementI (StatementI _ (Include name injectVals)) = do name' <- getRelPath name content <- liftIO $ readFile name' case parseProgram name content of@@ -126,13 +137,15 @@ if injectVals then putVals (vals' ++ vals) else putVals vals +runStatementI (StatementI _ DoNothing) = do+ liftIO $ putStrLn $ "Do Nothing?" runSuite :: [StatementI] -> StateC () runSuite stmts = Monad.mapM_ runStatementI stmts runSuiteCapture :: VarLookup -> FilePath -> [StatementI] -> IO [OVal] runSuiteCapture varlookup path suite = do- (res, state) <- State.runStateT + (res, _) <- runStateT (runSuite suite >> getVals) (varlookup, [], path, (), () ) return res
Graphics/Implicit/ExtOpenScad/Parser/Expr.hs view
@@ -1,11 +1,20 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE+ module Graphics.Implicit.ExtOpenScad.Parser.Expr where -import Graphics.Implicit.Definitions-import Text.ParserCombinators.Parsec hiding (State)-import Text.ParserCombinators.Parsec.Expr-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Parser.Util+import Prelude (Char, Maybe(Nothing, Just), fmap, ($), (>>), return, Bool(True, False), read, (++), id, foldl, map, foldl1, unzip, tail, zipWith3) +-- the datatype representing the graininess of our world.+import Graphics.Implicit.Definitions (ℝ)++-- The parsec parsing library.+import Text.ParserCombinators.Parsec (GenParser, string, many1, digit, char, many, noneOf, sepBy, sepBy1, optionMaybe, try)++import Graphics.Implicit.ExtOpenScad.Definitions (Expr(Var, LitE, ListE, (:$)), OVal(ONum, OString, OBool, OUndefined), collector) +import Graphics.Implicit.ExtOpenScad.Parser.Util (variableSymb, (?:), (*<|>), genSpace, padString)+ variable :: GenParser Char st Expr variable = fmap Var variableSymb @@ -18,7 +27,7 @@ *<|> "number" ?: ( do a <- many1 digit- char '.'+ _ <- char '.' b <- many digit return $ LitE $ ONum (read (a ++ "." ++ b) :: ℝ) *<|> do@@ -26,72 +35,75 @@ return $ LitE $ ONum (read a :: ℝ) ) *<|> "string" ?: do- string "\""- strlit <- many $ (string "\\\"" >> return '\"') + _ <- string "\""+ strlit <- many $ (string "\\\"" >> return '\"') *<|> (string "\\n" >> return '\n') *<|> ( noneOf "\"\n")- string "\""+ _ <- string "\"" return $ LitE $ OString strlit -- We represent the priority or 'fixity' of different types of expressions -- by the Int argument expr0 :: GenParser Char st Expr-expr0 = exprN 0+expr0 = exprN A0 -exprN :: Integer -> GenParser Char st Expr+-- what state in the expression parser tree we are inside of.+data ExprIdx = A0 | A1 | A2 | A3 | A4 | A5 | A6 | A7 | A8 | A9 | A10 | A11 | A12 -exprN n@12 = +exprN :: ExprIdx -> GenParser Char st Expr++exprN A12 = literal *<|> variable *<|> "bracketed expression" ?: do -- eg. ( 1 + 5 )- string "("+ _ <- string "(" expr <- expr0- string ")"+ _ <- string ")" return expr *<|> "vector/list" ?: ( do -- eg. [ 3, a, a+1, b, a*b ]- string "["+ _ <- string "[" exprs <- sepBy expr0 (char ',' )- string "]"+ _ <- string "]" return $ ListE exprs- *<|> do + *<|> do -- eg. ( 1,2,3 )- string "("+ _ <- string "(" exprs <- sepBy expr0 (char ',' )- string ")"+ _ <- string ")" return $ ListE exprs ) *<|> "vector/list generator" ?: do -- eg. [ a : 1 : a + 10 ]- string "["+ _ <- string "[" exprs <- sepBy expr0 (char ':' )- string "]"+ _ <- string "]" return $ collector "list_gen" exprs -exprN n@11 = +exprN A11 = do- obj <- exprN $ n+1- genSpace+ obj <- exprN $ A12+ _ <- genSpace mods <- many1 ( "function application" ?: do- padString "("+ _ <- padString "(" args <- sepBy expr0 (padString ",")- padString ")"+ _ <- padString ")" return $ \f -> f :$ args *<|> "list indexing" ?: do- padString "["+ _ <- padString "[" i <- expr0- padString "]"+ _ <- padString "]" return $ \l -> Var "index" :$ [l, i] *<|> "list splicing" ?: do- padString "["+ _ <- padString "[" start <- optionMaybe expr0- padString ":"+ _ <- padString ":" end <- optionMaybe expr0- padString "]"+ _ <- padString "]" return $ case (start, end) of (Nothing, Nothing) -> id (Just s, Nothing) -> \l -> Var "splice" :$ [l, s, LitE OUndefined ]@@ -99,67 +111,67 @@ (Just s, Just e ) -> \l -> Var "splice" :$ [l, s, e] ) return $ foldl (\a b -> b a) obj mods- *<|> (exprN $ n+1 )+ *<|> (exprN $ A12 ) -exprN n@10 = +exprN A10 = "negation" ?: do- padString "-"- expr <- exprN $ n+1+ _ <- padString "-"+ expr <- exprN $ A11 return $ Var "negate" :$ [expr] *<|> do- padString "+"- expr <- exprN $ n+1+ _ <- padString "+"+ expr <- exprN $ A11 return expr- *<|> exprN (n+1)+ *<|> exprN (A11) -exprN n@9 = - "exponentiation" ?: do - a <- exprN $ n+1- padString "^"- b <- exprN n+exprN A9 =+ "exponentiation" ?: do+ a <- exprN $ A10+ _ <- padString "^"+ b <- exprN A9 return $ Var "^" :$ [a,b]- *<|> exprN (n+1)+ *<|> exprN (A10) -exprN n@8 = - "multiplication/division" ?: do +exprN A8 =+ "multiplication/division" ?: do -- outer list is multiplication, inner division. -- eg. "1*2*3/4/5*6*7/8" -- [[1],[2],[3,4,5],[6],[7,8]]- exprs <- sepBy1 - (sepBy1 (exprN $ n+1) (try $ padString "/" )) + exprs <- sepBy1+ (sepBy1 (exprN $ A9) (try $ padString "/" )) (try $ padString "*" )- let div a b = Var "/" :$ [a, b]- return $ collector "*" $ map (foldl1 div) exprs- *<|> exprN (n+1)+ let div' a b = Var "/" :$ [a, b]+ return $ collector "*" $ map (foldl1 div') exprs+ *<|> exprN (A9) -exprN n@7 =- "modulo" ?: do - exprs <- sepBy1 (exprN $ n+1) (try $ padString "%")- let mod a b = Var "%" :$ [a, b]- return $ foldl1 mod exprs - *<|> exprN (n+1)+exprN A7 =+ "modulo" ?: do+ exprs <- sepBy1 (exprN $ A8) (try $ padString "%")+ let mod' a b = Var "%" :$ [a, b]+ return $ foldl1 mod' exprs+ *<|> exprN (A8) -exprN n@6 =- "append" ?: do - exprs <- sepBy1 (exprN $ n+1) (try $ padString "++")+exprN A6 =+ "append" ?: do+ exprs <- sepBy1 (exprN $ A7) (try $ padString "++") return $ collector "++" exprs- *<|> exprN (n+1)+ *<|> exprN (A7) -exprN n@5 =- "addition/subtraction" ?: do +exprN A5 =+ "addition/subtraction" ?: do -- Similar to multiply & divide- -- eg. "1+2+3-4-5+6-7" + -- eg. "1+2+3-4-5+6-7" -- [[1],[2],[3,4,5],[6,7]]- exprs <- sepBy1 - (sepBy1 (exprN $ n+1) (try $ padString "-" )) + exprs <- sepBy1+ (sepBy1 (exprN $ A6) (try $ padString "-" )) (try $ padString "+" ) let sub a b = Var "-" :$ [a, b] return $ collector "+" $ map (foldl1 sub) exprs- *<|> exprN (n+1)+ *<|> exprN (A6) -exprN n@4 = +exprN A4 = do- firstExpr <- exprN $ n+1+ firstExpr <- exprN $ A5 otherComparisonsExpr <- many $ do comparisonSymb <- padString "=="@@ -168,48 +180,48 @@ *<|> padString "<=" *<|> padString ">" *<|> padString "<"- expr <- exprN $ n+1- return (Var comparisonSymb, expr) + expr <- exprN $ A5+ return (Var comparisonSymb, expr) let (comparisons, otherExprs) = unzip otherComparisonsExpr exprs = firstExpr:otherExprs- return $ case comparisons of + return $ case comparisons of [] -> firstExpr [x] -> x :$ exprs _ -> collector "all" $ zipWith3 (\c e1 e2 -> c :$ [e1,e2]) comparisons exprs (tail exprs)- *<|> exprN (n+1)+ *<|> exprN (A5) -exprN n@3 =+exprN A3 = "logical-not" ?: do- padString "!"- a <- exprN $ n+1+ _ <- padString "!"+ a <- exprN $ A4 return $ Var "!" :$ [a]- *<|> exprN (n+1)+ *<|> exprN (A4) -exprN n@2 = - "logical and/or" ?: do - a <- exprN $ n+1+exprN A2 =+ "logical and/or" ?: do+ a <- exprN $ A3 symb <- padString "&&" *<|> padString "||"- b <- exprN n+ b <- exprN A2 return $ Var symb :$ [a,b]- *<|> exprN (n+1)+ *<|> exprN (A3) -exprN n@1 = - "ternary" ?: do - a <- exprN $ n+1- padString "?"- b <- exprN n- padString ":"- c <- exprN n+exprN A1 =+ "ternary" ?: do+ a <- exprN $ A2+ _ <- padString "?"+ b <- exprN A1+ _ <- padString ":"+ c <- exprN A1 return $ Var "?" :$ [a,b,c]- *<|> exprN (n+1)+ *<|> exprN (A2) -exprN n@0 = - do - genSpace- expr <- exprN $ n+1- genSpace+exprN A0 =+ do+ _ <- genSpace+ expr <- exprN $ A1+ _ <- genSpace return expr- *<|> exprN (n+1)+ *<|> exprN (A1)
Graphics/Implicit/ExtOpenScad/Parser/Statement.hs view
@@ -1,13 +1,30 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- FIXME: required. why?+{-# LANGUAGE KindSignatures #-}+ module Graphics.Implicit.ExtOpenScad.Parser.Statement where -import Graphics.Implicit.Definitions-import Text.ParserCombinators.Parsec hiding (State)-import Text.ParserCombinators.Parsec.Expr-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Parser.Util-import Graphics.Implicit.ExtOpenScad.Parser.Expr+import Prelude(Char, Either, String, Maybe(Just, Nothing), Monad, return, fmap, ($), (>>), Bool(False, True), map) +import Text.ParserCombinators.Parsec (try, sepBy, sourceLine, GenParser, oneOf, space, char, getPosition, parse, many1, eof, string, SourceName, ParseError, many, noneOf, Line, (<|>), (<?>))++import Text.Parsec.Prim (ParsecT)++import Data.Functor.Identity(Identity)++import Graphics.Implicit.ExtOpenScad.Definitions (Pattern(Name), Statement(DoNothing, NewModule, Include, Echo, If, For, ModuleCall,(:=)),Expr(LamE), StatementI(StatementI))+import Graphics.Implicit.ExtOpenScad.Parser.Util (genSpace, tryMany, stringGS, (*<|>), (?:), patternMatcher, variableSymb)+import Graphics.Implicit.ExtOpenScad.Parser.Expr (expr0)++parseProgram :: SourceName -> [Char] -> Either ParseError [StatementI] parseProgram name s = parse program name s where+ program :: ParsecT [Char] u Identity [StatementI] program = do sts <- many1 computation eof@@ -15,9 +32,9 @@ -- | A in our programming openscad-like programming language. computation :: GenParser Char st StatementI-computation = - do -- suite statemetns: no semicolon...- genSpace+computation =+ do -- suite statements: no semicolon...+ _ <- genSpace s <- tryMany [ ifStatementI, forStatementI,@@ -32,22 +49,23 @@ unimplemented "import_stl"-} -- rotateExtrude ]- genSpace+ _ <- genSpace return s *<|> do -- Non suite s. Semicolon needed...- genSpace+ _ <- genSpace s <- tryMany [ echo,- assignment,- include--,+ include,+ function,+ assignment--, --use ]- stringGS " ; "+ _ <- stringGS " ; " return s- *<|> do- genSpace+ *<|> do -- Modules+ _ <- genSpace s <- userModule- genSpace+ _ <- genSpace return s {-@@ -64,16 +82,16 @@ -- union() sphere(3); -- -- We consider it to be a list of s which--- are in tern StatementI s.+-- are in turn StatementI s. -- So this parses them. -} suite :: GenParser Char st [StatementI]-suite = (fmap return computation <|> do - char '{'- genSpace+suite = (fmap return computation <|> do+ _ <- char '{'+ _ <- genSpace stmts <- many (try computation)- genSpace- char '}'+ _ <- genSpace+ _ <- char '}' return stmts ) <?> " suite" @@ -81,10 +99,10 @@ throwAway :: GenParser Char st StatementI throwAway = do line <- lineNumber- genSpace- oneOf "%*"- genSpace- computation+ _ <- genSpace+ _ <- oneOf "%*"+ _ <- genSpace+ _ <- computation return $ StatementI line DoNothing -- An included ! Basically, inject another openscad file here...@@ -93,9 +111,9 @@ line <- lineNumber injectVals <- (string "include" >> return True ) <|> (string "use" >> return False)- stringGS " < "+ _ <- stringGS " < " filename <- many (noneOf "<> ")- stringGS " > "+ _ <- stringGS " > " return $ StatementI line $ Include filename injectVals ) <?> "include " @@ -105,16 +123,19 @@ do line <- lineNumber pattern <- patternMatcher- stringGS " = "+ _ <- stringGS " = " valExpr <- expr0 return $ StatementI line$ pattern := valExpr- *<|> do++-- | A function declaration (parser)+function :: GenParser Char st StatementI+function = ("function " ?:) $+ do line <- lineNumber- varSymb <- (string "function" >> space >> genSpace >> variableSymb) - *<|> variableSymb- stringGS " ( "+ varSymb <- (string "function" >> space >> genSpace >> variableSymb)+ _ <- stringGS " ( " argVars <- sepBy patternMatcher (stringGS " , ")- stringGS " ) = "+ _ <- stringGS " ) = " valExpr <- expr0 return $ StatementI line $ Name varSymb := LamE argVars valExpr @@ -122,20 +143,20 @@ echo :: GenParser Char st StatementI echo = do line <- lineNumber- stringGS " echo ( "+ _ <- stringGS "echo ( " exprs <- expr0 `sepBy` (stringGS " , ")- stringGS " ) "+ _ <- stringGS " ) " return $ StatementI line $ Echo exprs ifStatementI :: GenParser Char st StatementI-ifStatementI = +ifStatementI = "if " ?: do line <- lineNumber- stringGS "if ( "+ _ <- stringGS "if ( " bexpr <- expr0- stringGS " ) "+ _ <- stringGS " ) " sTrueCase <- suite- genSpace+ _ <- genSpace sFalseCase <- (stringGS "else " >> suite ) *<|> (return []) return $ StatementI line $ If bexpr sTrueCase sFalseCase @@ -147,33 +168,32 @@ -- for ( vsymb = vexpr ) loops -- eg. for ( a = [1,2,3] ) {echo(a); echo "lol";} -- eg. for ( [a,b] = [[1,2]] ) {echo(a+b); echo "lol";}- stringGS " for ( "+ _ <- stringGS "for ( " pattern <- patternMatcher- stringGS " = "+ _ <- stringGS " = " vexpr <- expr0- stringGS " ) "+ _ <- stringGS " ) " loopContent <- suite return $ StatementI line $ For pattern vexpr loopContent - userModule :: GenParser Char st StatementI userModule = do line <- lineNumber name <- variableSymb- genSpace+ _ <- genSpace args <- moduleArgsUnit- genSpace+ _ <- genSpace s <- suite *<|> (stringGS " ; " >> return []) return $ StatementI line $ ModuleCall name args s userModuleDeclaration :: GenParser Char st StatementI userModuleDeclaration = do line <- lineNumber- stringGS "module "+ _ <- stringGS "module " newModuleName <- variableSymb- genSpace+ _ <- genSpace args <- moduleArgsUnitDecl- genSpace+ _ <- genSpace s <- suite return $ StatementI line $ NewModule newModuleName args s @@ -181,20 +201,20 @@ moduleArgsUnit :: GenParser Char st [(Maybe String, Expr)] moduleArgsUnit = do- stringGS " ( "- args <- sepBy ( + _ <- stringGS " ( "+ args <- sepBy ( do -- eg. a = 12 symb <- variableSymb- stringGS " = "+ _ <- stringGS " = " expr <- expr0 return $ (Just symb, expr) *<|> do -- eg. a(x,y) = 12 symb <- variableSymb- stringGS " ( "+ _ <- stringGS " ( " argVars <- sepBy variableSymb (try $ stringGS " , ")- stringGS " ) = "+ _ <- stringGS " ) = " expr <- expr0 return $ (Just symb, LamE (map Name argVars) expr) *<|> do@@ -202,31 +222,42 @@ expr <- expr0 return (Nothing, expr) ) (try $ stringGS " , ")- stringGS " ) "+ _ <- stringGS " ) " return args moduleArgsUnitDecl :: GenParser Char st [(String, Maybe Expr)] moduleArgsUnitDecl = do- stringGS " ( "+ _ <- stringGS " ( " argTemplate <- sepBy ( do symb <- variableSymb;- stringGS " = "+ _ <- stringGS " = " expr <- expr0 return (symb, Just expr) *<|> do symb <- variableSymb;- stringGS " ( "- argVars <- sepBy variableSymb (try $ stringGS " , ")- stringGS " ) = "+ _ <- stringGS " ( "+ -- FIXME: why match this content, then drop it?+ _ <- sepBy variableSymb (try $ stringGS " , ")+ _ <- stringGS " ) = " expr <- expr0+-- FIXME: this line looks right, but.. what does this change?+-- return $ (Just symb, LamE (map Name argVars) expr) return (symb, Just expr) *<|> do symb <- variableSymb return (symb, Nothing) ) (try $ stringGS " , ")- stringGS " ) "+ _ <- stringGS " ) " return argTemplate +lineNumber :: forall s u (m :: * -> *).+ Monad m => ParsecT s u m Line lineNumber = fmap sourceLine getPosition +--FIXME: use the below function to improve error reporting.+{-+columnNumber :: forall s u (m :: * -> *).+ Monad m => ParsecT s u m Column+columnNumber = fmap sourceColumn getPosition+-}
Graphics/Implicit/ExtOpenScad/Parser/Util.hs view
@@ -1,36 +1,53 @@-module Graphics.Implicit.ExtOpenScad.Parser.Util where+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016 Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -import Graphics.Implicit.Definitions-import Text.ParserCombinators.Parsec hiding (State)-import Text.ParserCombinators.Parsec.Expr-import Graphics.Implicit.ExtOpenScad.Definitions+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} +-- FIXME: required. why?+{-# LANGUAGE KindSignatures, FlexibleContexts #-}++module Graphics.Implicit.ExtOpenScad.Parser.Util (genSpace, pad, (*<|>), (?:), stringGS, padString, tryMany, variableSymb, patternMatcher) where++import Prelude (String, Char, ($), (++), foldl1, map, (>>), (.), return)++import Text.ParserCombinators.Parsec (GenParser, many, oneOf, noneOf, (<|>), try, string, manyTill, anyChar, (<?>), char, many1, sepBy)+import Text.Parsec.Prim (ParsecT, Stream)+import Data.Functor.Identity (Identity)+import Graphics.Implicit.ExtOpenScad.Definitions (Pattern(Wild, Name, ListP))+ -- white space, including tabs, newlines and comments-genSpace = many $ - oneOf " \t\n\r" +genSpace :: ParsecT [Char] u Identity [Char]+genSpace = many $+ oneOf " \t\n\r" <|> (try $ do- string "//"- many ( noneOf "\n")- string "\n"+ _ <- string "//"+ _ <- many ( noneOf "\n")+ _ <- string "\n" return ' ' ) <|> (try $ do- string "/*"- manyTill anyChar (try $ string "*/")+ _ <- string "/*"+ _ <- manyTill anyChar (try $ string "*/") return ' ' ) +pad :: forall b u. ParsecT [Char] u Identity b -> ParsecT [Char] u Identity b pad parser = do- genSpace+ _ <- genSpace a <- parser- genSpace+ _ <- genSpace return a infixr 1 *<|>+(*<|>) :: forall u a tok. GenParser tok u a -> ParsecT [tok] u Identity a -> ParsecT [tok] u Identity a a *<|> b = try a <|> b infixr 2 ?:+(?:) :: forall s u (m :: * -> *) a. String -> ParsecT s u m a -> ParsecT s u m a l ?: p = p <?> l +stringGS :: [Char] -> ParsecT [Char] u Identity [Char] stringGS (' ':xs) = do x' <- genSpace xs' <- stringGS xs@@ -41,21 +58,23 @@ return (x' : xs') stringGS "" = return "" +padString :: String -> ParsecT [Char] u Identity String padString s = do- genSpace+ _ <- genSpace s' <- string s- genSpace+ _ <- genSpace return s' +tryMany :: forall u a tok. [GenParser tok u a] -> ParsecT [tok] u Identity a tryMany = (foldl1 (<|>)) . (map try) +variableSymb :: forall s u (m :: * -> *). Stream s m Char => ParsecT s u m [Char] variableSymb = many1 (noneOf " ,|[]{}()+-*&^%#@!~`'\"\\/;:.,<>?=") <?> "variable" - patternMatcher :: GenParser Char st Pattern patternMatcher =- (do - char '_'+ (do+ _ <- char '_' return Wild ) <|> {-( do a <- literal@@ -67,13 +86,10 @@ symb <- variableSymb return $ Name symb ) <|> ( do- char '['- genSpace+ _ <- char '['+ _ <- genSpace components <- patternMatcher `sepBy` (try $ genSpace >> char ',' >> genSpace)- genSpace- char ']'+ _ <- genSpace+ _ <- char ']' return $ ListP components )---
Graphics/Implicit/ExtOpenScad/Primitives.hs view
@@ -1,51 +1,58 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE --- We'd like to parse openscad code, with some improvements, for backwards compatability.+-- Idealy, we'd like to parse openscad code, with some improvements, for backwards compatability. -- This file provides primitive objects for the openscad parser.--- The code is fairly straightforward; an explanation of how --- the first one works is provided. -{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances, ScopedTypeVariables #-}+-- FIXME: why are these required?+{-# LANGUAGE FlexibleContexts, ScopedTypeVariables #-} +-- Export one set containing all of the primitive object's patern matches. module Graphics.Implicit.ExtOpenScad.Primitives (primitives) where -import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Util.ArgParser-import Graphics.Implicit.ExtOpenScad.Util.OVal+import Prelude(String, IO, Char, Either(Left, Right), Bool(False), Maybe(Just, Nothing), Fractional, ($), return, either, id, (-), (==), (&&), (<), fromIntegral, (*), cos, sin, pi, (/), (>), const, uncurry, realToFrac, fmap, fromInteger, round, (/=), (||), not, null, map, (++), putStrLn) -import qualified Graphics.Implicit.Primitives as Prim-import Data.Maybe (fromMaybe, isNothing)-import qualified Data.Either as Either-import Data.Either (either)+import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, ℕ, SymbolicObj2, SymbolicObj3)++import Graphics.Implicit.ExtOpenScad.Definitions (OVal (OObj2, OObj3), ArgParser)++import Graphics.Implicit.ExtOpenScad.Util.ArgParser (doc, defaultTo, argument, example, test, eulerCharacteristic)++import Graphics.Implicit.ExtOpenScad.Util.OVal (caseOType, divideObjs, (<||>))++import qualified Graphics.Implicit.Primitives as Prim (sphere, rect3R, rectR, translate, circle, polygonR, extrudeR, cylinder2, union, unionR, intersect, intersectR, difference, differenceR, rotate, rotate3V, rotate3, scale, extrudeR, extrudeRM, rotateExtrude, shell, pack3, pack2)++import Data.Maybe (isNothing)+ import qualified Control.Monad as Monad- -import Data.VectorSpace +import Data.VectorSpace (VectorSpace, Scalar, (*^))+import GHC.Real (RealFrac)+ primitives :: [(String, [OVal] -> ArgParser (IO [OVal]) )] primitives = [ sphere, cube, square, cylinder, circle, polygon, union, difference, intersect, translate, scale, rotate, extrude, pack, shell, rotateExtrude, unit ] --- **Exmaple of implementing a module**--- sphere is a module without a suite named sphere,+-- sphere is a module without a suite. -- this means that the parser will look for this like -- sphere(args...);+sphere :: ([Char], [OVal] -> ArgParser (IO [OVal])) sphere = moduleWithoutSuite "sphere" $ do example "sphere(3);" example "sphere(r=5);"- -- What are the arguments?+ -- arguments: -- The radius, r, which is a (real) number. -- Because we don't provide a default, this ends right -- here if it doesn't get a suitable argument!- r :: ℝ <- argument "r" + r :: ℝ <- argument "r" `doc` "radius of the sphere"- -- So what does this module do?- -- It adds a 3D object, a sphere of radius r,+ -- This module adds a 3D object, a sphere of radius r, -- using the sphere implementation in Prim -- (Graphics.Implicit.Primitives) addObj3 $ Prim.sphere r +cube :: ([Char], [OVal] -> ArgParser (IO [OVal])) cube = moduleWithoutSuite "cube" $ do -- examples@@ -61,24 +68,26 @@ `doc` "y or y-interval" z :: Either ℝ ℝ2 <- argument "z" `doc` "z or z-interval"- center :: Bool <- argument "center" - `doc` "should center? (non-intervals)" + center :: Bool <- argument "center"+ `doc` "should center? (non-intervals)" `defaultTo` False- let toInterval' = toInterval center- return (either (toInterval center) id x,- either (toInterval center) id y,- either (toInterval center) id z)+ let+ toInterval' :: Fractional t => t -> (t, t)+ toInterval' = toInterval center+ return (either toInterval' id x,+ either toInterval' id y,+ either toInterval' id z) <|> do size :: Either ℝ ℝ3 <- argument "size"- `doc` "square size"- center :: Bool <- argument "center" - `doc` "should center?" + `doc` "cube size"+ center :: Bool <- argument "center"+ `doc` "should center?" `defaultTo` False let (x,y, z) = either (\w -> (w,w,w)) id size return (toInterval center x, toInterval center y, toInterval center z) r :: ℝ <- argument "r"- `doc` "radius of rounding" + `doc` "radius of rounding" `defaultTo` 0 -- Tests@@ -89,12 +98,10 @@ addObj3 $ Prim.rect3R r (x1, y1, z1) (x2, y2, z2) ---+square :: ([Char], [OVal] -> ArgParser (IO [OVal])) square = moduleWithoutSuite "square" $ do - -- examples + -- examples example "square(x=[-2,2], y=[-1,5]);" example "square(size = [3,4], center = true, r = 0.5);" example "square(4);"@@ -106,23 +113,25 @@ `doc` "x or x-interval" y :: Either ℝ ℝ2 <- argument "y" `doc` "y or y-interval"- center :: Bool <- argument "center" - `doc` "should center? (non-intervals)" + center :: Bool <- argument "center"+ `doc` "should center? (non-intervals)" `defaultTo` False- let toInterval' = toInterval center- return (either (toInterval center) id x,- either (toInterval center) id y)+ let+ toInterval' :: Fractional t => t -> (t, t)+ toInterval' = toInterval center+ return (either toInterval' id x,+ either toInterval' id y) <|> do size :: Either ℝ ℝ2 <- argument "size" `doc` "square size"- center :: Bool <- argument "center" - `doc` "should center?" + center :: Bool <- argument "center"+ `doc` "should center?" `defaultTo` False let (x,y) = either (\w -> (w,w)) id size return (toInterval center x, toInterval center y) r :: ℝ <- argument "r"- `doc` "radius of rounding" + `doc` "radius of rounding" `defaultTo` 0 -- Tests@@ -133,8 +142,7 @@ addObj2 $ Prim.rectR r (x1, y1) (x2, y2) --+cylinder :: ([Char], [OVal] -> ArgParser (IO [OVal])) cylinder = moduleWithoutSuite "cylinder" $ do example "cylinder(r=10, h=30, center=true);"@@ -170,19 +178,26 @@ let (h1, h2) = either (toInterval center) id h dh = h2 - h1- shift = if h1 == 0 then id else Prim.translate (0,0,h1)+ shift :: SymbolicObj3 -> SymbolicObj3+ shift =+ if h1 == 0+ then id+ else Prim.translate (0,0,h1) - -- The result is a computation state modifier that adds a 3D object, + -- The result is a computation state modifier that adds a 3D object, -- based on the args. addObj3 $ if r1 == 1 && r2 == 1 then let obj2 = if fn < 0 then Prim.circle r else Prim.polygonR 0 $- let sides = fromIntegral fn + let+ sides :: ℝ+ sides = fromIntegral fn in [(r*cos θ, r*sin θ )| θ <- [2*pi*n/sides | n <- [0.0 .. sides - 1.0]]] obj3 = Prim.extrudeR 0 obj2 dh in shift obj3 else shift $ Prim.cylinder2 r1 r2 dh +circle :: ([Char], [OVal] -> ArgParser (IO [OVal])) circle = moduleWithoutSuite "circle" $ do example "circle(r=10); // circle"@@ -191,7 +206,7 @@ -- Arguments r :: ℝ <- argument "r" `doc` "radius of the circle"- fn :: ℕ <- argument "$fn" + fn :: ℕ <- argument "$fn" `doc` "if defined, makes a regular polygon with n sides instead of a circle" `defaultTo` (-1) @@ -201,26 +216,30 @@ addObj2 $ if fn < 3 then Prim.circle r else Prim.polygonR 0 $- let sides = fromIntegral fn + let+ sides :: ℝ+ sides = fromIntegral fn in [(r*cos θ, r*sin θ )| θ <- [2*pi*n/sides | n <- [0.0 .. sides - 1.0]]] +polygon :: ([Char], [OVal] -> ArgParser (IO [OVal])) polygon = moduleWithoutSuite "polygon" $ do example "polygon ([(0,0), (0,10), (10,0)]);" - points :: [ℝ2] <- argument "points" + points :: [ℝ2] <- argument "points" `doc` "vertices of the polygon"- paths :: [ℕ ] <- argument "paths" + paths :: [ℕ ] <- argument "paths" `doc` "order to go through vertices; ignored for now" `defaultTo` [] r :: ℝ <- argument "r" `doc` "rounding of the polygon corners; ignored for now" `defaultTo` 0 case paths of- [] -> addObj2 $ Prim.polygonR 0 points+ [] -> addObj2 $ Prim.polygonR r points _ -> return $ return [] +union :: ([Char], [OVal] -> ArgParser (IO [OVal])) union = moduleWithSuite "union" $ \children -> do r :: ℝ <- argument "r" `defaultTo` 0.0@@ -229,6 +248,7 @@ then objReduce (Prim.unionR r) (Prim.unionR r) children else objReduce Prim.union Prim.union children +intersect :: ([Char], [OVal] -> ArgParser (IO [OVal])) intersect = moduleWithSuite "intersection" $ \children -> do r :: ℝ <- argument "r" `defaultTo` 0.0@@ -237,6 +257,7 @@ then objReduce (Prim.intersectR r) (Prim.intersectR r) children else objReduce Prim.intersect Prim.intersect children +difference :: ([Char], [OVal] -> ArgParser (IO [OVal])) difference = moduleWithSuite "difference" $ \children -> do r :: ℝ <- argument "r" `defaultTo` 0.0@@ -245,12 +266,13 @@ then objReduce (Prim.differenceR r) (Prim.differenceR r) children else objReduce Prim.difference Prim.difference children +translate :: ([Char], [OVal] -> ArgParser (IO [OVal])) translate = moduleWithSuite "translate" $ \children -> do example "translate ([2,3]) circle (4);" example "translate ([5,6,7]) sphere(5);" - (x,y,z) <- + (x,y,z) <- do x :: ℝ <- argument "x" `doc` "x amount to translate";@@ -268,12 +290,14 @@ Right (Left (x,y) ) -> (x,y,0) Right (Right (x,y,z)) -> (x,y,z) - return $ return $ + return $ return $ objMap (Prim.translate (x,y)) (Prim.translate (x,y,z)) children +deg2rad :: ℝ -> ℝ deg2rad x = x / 180.0 * pi -- This is mostly insane+rotate :: ([Char], [OVal] -> ArgParser (IO [OVal])) rotate = moduleWithSuite "rotate" $ \children -> do a <- argument "a" `doc` "value to rotate by; angle or list of angles"@@ -293,7 +317,7 @@ objMap id (Prim.rotate3 (deg2rad yz, deg2rad zx, 0)) children ) <||> const [] -+scale :: ([Char], [OVal] -> ArgParser (IO [OVal])) scale = moduleWithSuite "scale" $ \children -> do example "scale(2) square(5);"@@ -304,33 +328,32 @@ `doc` "vector or scalar to scale by" let- scaleObjs strech2 strech3 = - objMap (Prim.scale strech2) (Prim.scale strech3) children+ scaleObjs stretch2 stretch3 =+ objMap (Prim.scale stretch2) (Prim.scale stretch3) children return $ return $ case v of Left x -> scaleObjs (x,1) (x,1,1) Right (Left (x,y)) -> scaleObjs (x,y) (x,y,1) Right (Right (x,y,z)) -> scaleObjs (x,y) (x,y,z) +extrude :: ([Char], [OVal] -> ArgParser (IO [OVal])) extrude = moduleWithSuite "linear_extrude" $ \children -> do example "linear_extrude(10) square(5);" - height :: Either ℝ (ℝ -> ℝ -> ℝ) <- argument "height" `defaultTo` Left 1+ height :: Either ℝ (ℝ -> ℝ -> ℝ) <- argument "height" `defaultTo` (Left 1) `doc` "height to extrude to..." center :: Bool <- argument "center" `defaultTo` False `doc` "center? (the z component)" twist :: Maybe (Either ℝ (ℝ -> ℝ)) <- argument "twist" `defaultTo` Nothing `doc` "twist as we extrude, either a total amount to twist or a function..."- scale :: Maybe (Either ℝ (ℝ -> ℝ)) <- argument "scale" `defaultTo` Nothing- `doc` "scale according to this funciton as we extrud..."- translate :: Maybe (Either ℝ2 (ℝ -> ℝ2)) <- argument "translate" `defaultTo` Nothing+ scaleArg :: Maybe (Either ℝ (ℝ -> ℝ)) <- argument "scale" `defaultTo` Nothing+ `doc` "scale according to this funciton as we extrude..."+ translateArg :: Maybe (Either ℝ2 (ℝ -> ℝ2)) <- argument "translate" `defaultTo` Nothing `doc` "translate according to this funciton as we extrude..." r :: ℝ <- argument "r" `defaultTo` 0 `doc` "round the top?" let- degRotate = (\θ (x,y) -> (x * cos θ + y * sin θ, y * cos θ - x * sin θ)) . (*(2*pi/360))- heightn = case height of Left h -> h Right f -> f 0 0@@ -339,63 +362,67 @@ Right f -> Right $ uncurry f Left a -> Left a + shiftAsNeeded :: SymbolicObj3 -> SymbolicObj3 shiftAsNeeded = if center then Prim.translate (0,0,-heightn/2.0) else id- + funcify :: (VectorSpace a, Fractional (Scalar a)) => Either a (ℝ -> a) -> ℝ -> a funcify (Left val) h = realToFrac (h/heightn) *^ val funcify (Right f ) h = f h twist' = fmap funcify twist- scale' = fmap funcify scale- translate' = fmap funcify translate+ scale' = fmap funcify scaleArg+ translate' = fmap funcify translateArg return $ return $ obj2UpMap ( \obj -> case height of- Left constHeight | isNothing twist && isNothing scale && isNothing translate ->+ Left constHeight | isNothing twist && isNothing scaleArg && isNothing translateArg -> shiftAsNeeded $ Prim.extrudeR r obj constHeight- _ -> + _ -> shiftAsNeeded $ Prim.extrudeRM r twist' scale' translate' obj height' ) children +rotateExtrude :: ([Char], [OVal] -> ArgParser (IO [OVal])) rotateExtrude = moduleWithSuite "rotate_extrude" $ \children -> do example "rotate_extrude() translate(20) circle(10);" totalRot :: ℝ <- argument "a" `defaultTo` 360 `doc` "angle to sweep"- r :: ℝ <- argument "r" `defaultTo` 0- translate :: Either ℝ2 (ℝ -> ℝ2) <- argument "translate" `defaultTo` Left (0,0)- rotate :: Either ℝ (ℝ -> ℝ ) <- argument "rotate" `defaultTo` Left 0+ r :: ℝ <- argument "r" `defaultTo` 0+ translateArg :: Either ℝ2 (ℝ -> ℝ2) <- argument "translate" `defaultTo` Left (0,0)+ rotateArg :: Either ℝ (ℝ -> ℝ ) <- argument "rotate" `defaultTo` Left 0 let- is360m n = 360 * fromIntegral (round $ n / 360) /= n- n = fromIntegral $ round $ totalRot / 360- cap = is360m totalRot - || Either.either ( /= (0,0)) (\f -> f 0 /= f totalRot) translate- || Either.either is360m (\f -> is360m (f 0 - f totalRot)) rotate+ is360m :: RealFrac a => a -> Bool+ is360m n = 360 * fromInteger (round $ n / 360) /= n+ cap = is360m totalRot+ || (either ( /= (0,0)) (\f -> f 0 /= f totalRot) ) translateArg+ || (either (is360m) (\f -> is360m (f 0 - f totalRot)) ) rotateArg capM = if cap then Just r else Nothing- - return $ return $ obj2UpMap (Prim.rotateExtrude totalRot capM translate rotate) children + return $ return $ obj2UpMap (Prim.rotateExtrude totalRot capM translateArg rotateArg) children + {-rotateExtrudeStatement = moduleWithSuite "rotate_extrude" $ \suite -> do h <- realArgument "h" center <- boolArgumentWithDefault "center" False twist <- realArgumentWithDefault 0.0 r <- realArgumentWithDefault "r" 0.0- getAndModUpObj2s suite (\obj -> Prim.extrudeRMod r (\θ (x,y) -> (x*cos(θ)+y*sin(θ), y*cos(θ)-x*sin(θ)) ) obj h) + getAndModUpObj2s suite (\obj -> extrudeRMod r (\θ (x,y) -> (x*cos(θ)+y*sin(θ), y*cos(θ)-x*sin(θ)) ) obj h) -} +shell :: ([Char], [OVal] -> ArgParser (IO [OVal])) shell = moduleWithSuite "shell" $ \children-> do w :: ℝ <- argument "w" `doc` "width of the shell..."- + return $ return $ objMap (Prim.shell w) (Prim.shell w) children -- Not a perenant solution! Breaks if can't pack.+pack :: ([Char], [OVal] -> ArgParser (IO [OVal])) pack = moduleWithSuite "pack" $ \children -> do example "pack ([45,45], sep=2) { circle(10); circle(10); circle(10); circle(10); }"@@ -412,24 +439,26 @@ in if not $ null obj3s then case Prim.pack3 size sep obj3s of Just solution -> return $ OObj3 solution : (map OObj2 obj2s ++ others)- Nothing -> do + Nothing -> do putStrLn "Can't pack given objects in given box with present algorithm" return children else case Prim.pack2 size sep obj2s of Just solution -> return $ OObj2 solution : others- Nothing -> do + Nothing -> do putStrLn "Can't pack given objects in given box with present algorithm" return children +unit :: ([Char], [OVal] -> ArgParser (IO [OVal])) unit = moduleWithSuite "unit" $ \children -> do example "unit(\"inch\") {..}" -- arguments- unit :: String <- argument "unit"+ unitName :: String <- argument "unit" `doc` "the unit you wish to work in" - let + let+ mmRatio :: Fractional a => [Char] -> Maybe a mmRatio "inch" = Just 25.4 mmRatio "in" = mmRatio "inch" mmRatio "foot" = Just 304.8@@ -447,11 +476,11 @@ mmRatio _ = Nothing -- The actual work...- return $ case mmRatio unit of+ return $ case mmRatio unitName of Nothing -> do- putStrLn $ "unrecognized unit " ++ unit+ putStrLn $ "unrecognized unit " ++ unitName return children- Just r -> + Just r -> return $ objMap (Prim.scale (r,r)) (Prim.scale (r,r,r)) children @@ -460,7 +489,9 @@ (<|>) :: ArgParser a -> ArgParser a -> ArgParser a (<|>) = Monad.mplus +moduleWithSuite :: t -> t1 -> (t, t1) moduleWithSuite name modArgMapper = (name, modArgMapper)+moduleWithoutSuite :: t -> a -> (t, b -> a) moduleWithoutSuite name modArgMapper = (name, const modArgMapper) addObj3 :: SymbolicObj3 -> ArgParser (IO [OVal])@@ -469,24 +500,28 @@ addObj2 :: SymbolicObj2 -> ArgParser (IO [OVal]) addObj2 x = return $ return [OObj2 x] +objMap :: (SymbolicObj2 -> SymbolicObj2) -> (SymbolicObj3 -> SymbolicObj3) -> [OVal] -> [OVal] objMap obj2mod obj3mod (x:xs) = case x of OObj2 obj2 -> OObj2 (obj2mod obj2) : objMap obj2mod obj3mod xs OObj3 obj3 -> OObj3 (obj3mod obj3) : objMap obj2mod obj3mod xs a -> a : objMap obj2mod obj3mod xs objMap _ _ [] = [] +objReduce :: ([SymbolicObj2] -> SymbolicObj2) -> ([SymbolicObj3] -> SymbolicObj3) -> [OVal] -> [OVal] objReduce obj2reduce obj3reduce l = case divideObjs l of ( [], [], others) -> others ( [], obj3s, others) -> OObj3 (obj3reduce obj3s) : others (obj2s, [], others) -> OObj2 (obj2reduce obj2s) : others (obj2s, obj3s, others) -> OObj2 (obj2reduce obj2s) : OObj3 (obj3reduce obj3s) : others +obj2UpMap :: (SymbolicObj2 -> SymbolicObj3) -> [OVal] -> [OVal] obj2UpMap obj2upmod (x:xs) = case x of OObj2 obj2 -> OObj3 (obj2upmod obj2) : obj2UpMap obj2upmod xs a -> a : obj2UpMap obj2upmod xs obj2UpMap _ [] = [] -toInterval center h = +toInterval :: Fractional t => Bool -> t -> (t, t)+toInterval center h = if center then (-h/2, h/2) else (0, h)
Graphics/Implicit/ExtOpenScad/Util/ArgParser.hs view
@@ -1,73 +1,48 @@--{-# LANGUAGE ViewPatterns, RankNTypes, ScopedTypeVariables #-}-module Graphics.Implicit.ExtOpenScad.Util.ArgParser where--import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Util.OVal-import qualified Control.Exception as Ex-import qualified Data.Map as Map-import qualified Data.Maybe as Maybe-import Control.Applicative-import Control.Monad--instance Alternative ArgParser where- (<|>) = mplus- empty = mzero+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -instance Functor ArgParser where- fmap = liftM+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} -instance Applicative ArgParser where- pure = return- (<*>) = ap+-- FIXME: why is this required?+{-# LANGUAGE ScopedTypeVariables #-} -instance Monad ArgParser where+module Graphics.Implicit.ExtOpenScad.Util.ArgParser where - -- return is easy: if we want an ArgParser that just gives us a, that is - -- ArgParserTerminator a- return a = APTerminator a+import Prelude(String, Maybe(Just, Nothing), Int, ($), (++), concat, show, error, return, map, snd, filter, (.), fst, foldl1, not, null, (&&)) - -- Now things get more interesting. We need to describe how (>>=) works.- -- Let's get the hard ones out of the way first.- -- ArgParser actually - (AP str fallback doc f) >>= g = AP str fallback doc (\a -> (f a) >>= g)- (APFailIf b errmsg child) >>= g = APFailIf b errmsg (child >>= g)- -- These next to is easy, they just pass the work along to their child- (APExample str child) >>= g = APExample str (child >>= g)- (APTest str tests child) >>= g = APTest str tests (child >>= g)- -- And an ArgParserTerminator happily gives away the value it contains- (APTerminator a) >>= g = g a- (APBranch bs) >>= g = APBranch $ map (>>= g) bs+import Graphics.Implicit.ExtOpenScad.Definitions (ArgParser(AP, APTest, APBranch, APTerminator, APFailIf, APExample), OVal (OError), TestInvariant(EulerCharacteristic))+import Graphics.Implicit.ExtOpenScad.Util.OVal (fromOObj, toOObj, OTypeMirror) -instance MonadPlus ArgParser where- mzero = APFailIf True "" undefined- mplus (APBranch as) (APBranch bs) = APBranch ( as ++ bs )- mplus (APBranch as) b = APBranch ( as ++ [b] )- mplus a (APBranch bs) = APBranch ( [a] ++ bs )- mplus a b = APBranch [ a , b ]+import qualified Data.Map as Map+import Data.Maybe (isNothing, fromJust, isJust) -- * ArgParser building functions -- ** argument and combinators argument :: forall desiredType. (OTypeMirror desiredType) => String -> ArgParser desiredType-argument name = +argument name = AP name Nothing "" $ \oObjVal -> do let- val = fromOObj oObjVal :: Maybe desiredType+ val :: Maybe desiredType+ val = fromOObj oObjVal errmsg = case oObjVal of OError errs -> "error in computing value for arugment " ++ name ++ ": " ++ concat errs _ -> "arg " ++ show oObjVal ++ " not compatible with " ++ name -- Using /= Nothing would require Eq desiredType- APFailIf (Maybe.isNothing val) errmsg $ APTerminator $ (\(Just a) -> a) val+ APFailIf (isNothing val) errmsg $ APTerminator $ fromJust val +doc :: forall a. ArgParser a -> String -> ArgParser a doc (AP name defMaybeVal _ next) newDoc = AP name defMaybeVal newDoc next+doc _ _ = error "Impossible!" defaultTo :: forall a. (OTypeMirror a) => ArgParser a -> a -> ArgParser a-defaultTo (AP name oldDefMaybeVal doc next) newDefVal = - AP name (Just $ toOObj newDefVal) doc next+defaultTo (AP name _ doc' next) newDefVal =+ AP name (Just $ toOObj newDefVal) doc' next+defaultTo _ _ = error "Impossible!" -- ** example @@ -82,19 +57,20 @@ eulerCharacteristic :: ArgParser a -> Int -> ArgParser a eulerCharacteristic (APTest str tests child) χ = APTest str ((EulerCharacteristic χ) : tests) child+eulerCharacteristic _ _ = error "Impossible!" -- * Tools for handeling ArgParsers -- | Apply arguments to an ArgParser -argMap :: +argMap :: [(Maybe String, OVal)] -- ^ arguments -> ArgParser a -- ^ ArgParser to apply them to -> (Maybe a, [String]) -- ^ (result, error messages) argMap args = argMap2 unnamedArgs (Map.fromList namedArgs) where- unnamedArgs = map snd $ filter (Maybe.isNothing . fst) args- namedArgs = map (\(a,b) -> (Maybe.fromJust a, b)) $ filter (Maybe.isJust . fst) args+ unnamedArgs = map snd $ filter (isNothing . fst) args+ namedArgs = map (\(a,b) -> (fromJust a, b)) $ filter (isJust . fst) args argMap2 :: [OVal] -> Map.Map String OVal -> ArgParser a -> (Maybe a, [String])@@ -102,16 +78,17 @@ argMap2 uArgs nArgs (APBranch branches) = foldl1 merge solutions where solutions = map (argMap2 uArgs nArgs) branches+ merge :: forall t t1. (Maybe t, [t1]) -> (Maybe t, [t1]) -> (Maybe t, [t1]) merge a@(Just _, []) _ = a merge _ b@(Just _, []) = b merge a@(Just _, _) _ = a merge (Nothing, _) a = a -argMap2 unnamedArgs namedArgs (AP name fallback _ f) = +argMap2 unnamedArgs namedArgs (AP name fallback _ f) = case Map.lookup name namedArgs of- Just a -> argMap2 - unnamedArgs - (Map.delete name namedArgs) + Just a -> argMap2+ unnamedArgs+ (Map.delete name namedArgs) (f a) Nothing -> case unnamedArgs of x:xs -> argMap2 xs namedArgs (f x)@@ -119,62 +96,18 @@ Just b -> argMap2 [] namedArgs (f b) Nothing -> (Nothing, ["No value and no default for argument " ++ name]) -argMap2 a b (APTerminator val) = +argMap2 a b (APTerminator val) = (Just val, if not (null a && Map.null b) then ["unused arguments"] else [] ) -argMap2 a b (APFailIf test err child) = - if test +argMap2 a b (APFailIf testval err child) =+ if testval then (Nothing, [err]) else argMap2 a b child -argMap2 a b (APExample str child) = argMap2 a b child--argMap2 a b (APTest str tests child) = argMap2 a b child---{---- | We need a format to extract documentation into-data Doc = Doc String [DocPart]- deriving (Show)--data DocPart = ExampleDoc String- | ArgumentDoc String (Maybe String) String- deriving (Show)----- Here there be dragons!--- Because we made this a Monad instead of applicative functor, there's now sane way to do this.--- We give undefined (= an error) and let laziness prevent if from ever being touched.--- We're using IO so that we can catch an error if this backfires.--- If so, we *back off*.---- | Extract Documentation from an ArgParser--getArgParserDocs :: - (ArgParser a) -- ^ ArgParser- -> IO [DocPart] -- ^ Docs (sadly IO wrapped)--getArgParserDocs (ArgParser name fallback doc fnext) = - do- otherDocs <- Ex.catch (getArgParserDocs $ fnext undefined) (\(e :: Ex.SomeException) -> return [])- return $ (ArgumentDoc name (fmap show fallback) doc):otherDocs--getArgParserDocs (ArgParserExample str child) =- do- childResults <- getArgParserDocs child- return $ (ExampleDoc str) : childResults---- We try to look at as little as possible, to avoid the risk of triggering an error.--- Yay laziness!--getArgParserDocs (ArgParserTest _ _ child ) = getArgParserDocs child-getArgParserDocs (ArgParserFailIf _ _ child ) = getArgParserDocs child---- To look at this one would almost certainly be death (exception)-getArgParserDocs (ArgParserTerminator _ ) = return []+argMap2 a b (APExample _ child) = argMap2 a b child --}+argMap2 a b (APTest _ _ child) = argMap2 a b child
Graphics/Implicit/ExtOpenScad/Util/OVal.hs view
@@ -1,12 +1,27 @@-{-# LANGUAGE OverlappingInstances, ViewPatterns, RankNTypes, ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances #-}+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2014 2015, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- FIXME: required. why?+{-# LANGUAGE ViewPatterns, RankNTypes, ScopedTypeVariables, TypeSynonymInstances, FlexibleInstances #-}++{-# LANGUAGE CPP #-}+#if __GLASGOW_HASKELL__ < 710+{-# LANGUAGE OverlappingInstances #-}+#endif+ module Graphics.Implicit.ExtOpenScad.Util.OVal where -import Graphics.Implicit.Definitions-import Graphics.Implicit.ExtOpenScad.Definitions+import Prelude(Maybe(Just, Nothing), Bool(True, False), Either(Left,Right), String, Char, (==), fromInteger, floor, ($), (.), map, error, (++), show, fromIntegral, head, flip, filter, not, return)++import Graphics.Implicit.Definitions(ℝ, ℕ, SymbolicObj2, SymbolicObj3)+import Graphics.Implicit.ExtOpenScad.Definitions (OVal(ONum, OBool, OString, OList, OFunc, OUndefined, OModule, OError, OObj2, OObj3)) import qualified Control.Monad as Monad-import Data.Maybe (isJust)+import Data.Maybe (fromJust, isJust) +-- for some minimal paralellism.+import Control.Parallel.Strategies(runEval, rpar, rseq)+ -- | We'd like to be able to turn OVals into a given Haskell type class OTypeMirror a where fromOObj :: OVal -> Maybe a@@ -22,7 +37,7 @@ toOObj n = ONum n instance OTypeMirror ℕ where- fromOObj (ONum n) = if n == fromIntegral (floor n) then Just (floor n) else Nothing+ fromOObj (ONum n) = if n == fromInteger (floor n) then Just (floor n) else Nothing fromOObj _ = Nothing toOObj n = ONum $ fromIntegral n @@ -31,7 +46,11 @@ fromOObj _ = Nothing toOObj b = OBool b +#if __GLASGOW_HASKELL__ >= 710 instance {-# Overlapping #-} OTypeMirror String where+#else+instance OTypeMirror String where+#endif fromOObj (OString str) = Just str fromOObj _ = Nothing toOObj str = OString str@@ -41,7 +60,11 @@ toOObj (Just a) = toOObj a toOObj Nothing = OUndefined +#if __GLASGOW_HASKELL__ >= 710 instance {-# Overlappable #-} forall a. (OTypeMirror a) => OTypeMirror [a] where+#else+instance forall a. (OTypeMirror a) => OTypeMirror [a] where+#endif fromOObj (OList list) = Monad.sequence . map fromOObj $ list fromOObj _ = Nothing toOObj list = OList $ map toOObj list@@ -53,7 +76,7 @@ instance forall a b c. (OTypeMirror a, OTypeMirror b, OTypeMirror c) => OTypeMirror (a,b,c) where- fromOObj (OList ((fromOObj -> Just a):(fromOObj -> Just b):(fromOObj -> Just c):[])) = + fromOObj (OList ((fromOObj -> Just a):(fromOObj -> Just b):(fromOObj -> Just c):[])) = Just (a,b,c) fromOObj _ = Nothing toOObj (a,b,c) = OList [toOObj a, toOObj b, toOObj c]@@ -63,13 +86,14 @@ let oInput = toOObj input oOutput = f oInput- output = fromOObj oOutput :: Maybe b+ output :: Maybe b+ output = fromOObj oOutput in case output of Just out -> out Nothing -> error $ "coercing OVal to a -> b isn't always safe; use a -> Maybe b"- ++ " (trace: " ++ show oInput ++ " -> " ++ show oOutput ++ " )"+ ++ " (trace: " ++ show oInput ++ " -> " ++ show oOutput ++ " )" fromOObj _ = Nothing- toOObj f = OFunc $ \oObj -> + toOObj f = OFunc $ \oObj -> case fromOObj oObj :: Maybe a of Nothing -> OError ["bad input type"] Just obj -> toOObj $ f obj@@ -83,6 +107,7 @@ toOObj (Right x) = toOObj x toOObj (Left x) = toOObj x +oTypeStr :: OVal -> [Char] oTypeStr (OUndefined) = "Undefined" oTypeStr (OBool _ ) = "Bool" oTypeStr (ONum _ ) = "Number"@@ -91,46 +116,39 @@ oTypeStr (OFunc _ ) = "Function" oTypeStr (OModule _ ) = "Module" oTypeStr (OError _ ) = "Error"+oTypeStr (OObj2 _ ) = "2D Object"+oTypeStr (OObj3 _ ) = "3D Object" getErrors :: OVal -> Maybe String getErrors (OError er) = Just $ head er getErrors (OList l) = Monad.msum $ map getErrors l getErrors _ = Nothing --type Any = OVal-+caseOType :: forall c a. a -> (a -> c) -> c caseOType = flip ($) infixr 2 <||>- (<||>) :: forall desiredType out. (OTypeMirror desiredType)- => (desiredType -> out) + => (desiredType -> out) -> (OVal -> out) -> (OVal -> out)- (<||>) f g = \input -> let- coerceAttempt = fromOObj input :: Maybe desiredType- in + coerceAttempt :: Maybe desiredType+ coerceAttempt = fromOObj input+ in if isJust coerceAttempt -- ≅ (/= Nothing) but no Eq req- then f $ (\(Just a) -> a) coerceAttempt+ then f $ fromJust coerceAttempt else g input --divideObjs children = - (map fromOObj2 . filter isOObj2 $ children,- map fromOObj3 . filter isOObj3 $ children,- filter (not . isOObj) $ children)+divideObjs :: [OVal] -> ([SymbolicObj2], [SymbolicObj3], [OVal])+divideObjs children =+ runEval $ do+ obj2s <- rseq ([ x | OObj2 x <- children ])+ obj3s <- rseq ([ x | OObj3 x <- children ])+ objs <- rpar (filter (not . isOObj) $ children )+ return (obj2s, obj3s, objs) where- isOObj2 (OObj2 _) = True- isOObj2 _ = False- isOObj3 (OObj3 _) = True- isOObj3 _ = False- isOObj (OObj2 _) = True- isOObj (OObj3 _) = True- isOObj _ = False- fromOObj2 (OObj2 x) = x- fromOObj3 (OObj3 x) = x--+ isOObj (OObj2 _) = True+ isOObj (OObj3 _) = True+ isOObj _ = False
Graphics/Implicit/ExtOpenScad/Util/StateC.hs view
@@ -1,17 +1,24 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- FIXME: required. why?+{-# LANGUAGE KindSignatures, FlexibleContexts #-} {-# LANGUAGE ViewPatterns, RankNTypes, ScopedTypeVariables #-} -module Graphics.Implicit.ExtOpenScad.Util.StateC where+module Graphics.Implicit.ExtOpenScad.Util.StateC (getVarLookup, modifyVarLookup, lookupVar, pushVals, getVals, putVals, withPathShiftedBy, getPath, getRelPath, errorC, mapMaybeM, StateC) where -import Graphics.Implicit.Definitions-import Text.ParserCombinators.Parsec hiding (State)-import Graphics.Implicit.ExtOpenScad.Definitions-import Graphics.Implicit.ExtOpenScad.Util.ArgParser+import Prelude(FilePath, IO, String, Maybe(Just, Nothing), Show, Char, Monad, fmap, (.), ($), (++), return, putStrLn, show) -import qualified Data.Map as Map-import Data.Map (Map)-import Control.Monad.State (State,StateT, get, put, modify, liftIO)-import System.FilePath((</>))+import Graphics.Implicit.ExtOpenScad.Definitions(VarLookup, OVal) +import qualified Data.Map as Map+import Control.Monad.State (StateT, get, put, modify, liftIO)+import System.FilePath((</>))+import Control.Monad.IO.Class (MonadIO) type CompState = (VarLookup, [OVal], FilePath, (), ()) type StateC = StateT CompState IO@@ -32,12 +39,12 @@ getVals :: StateC [OVal] getVals = do- (a,b,c,d,e) <- get+ (_,b,_,_,_) <- get return b putVals :: [OVal] -> StateC () putVals vals = do- (a,b,c,d,e) <- get+ (a,_,c,d,e) <- get put (a,vals,c,d,e) withPathShiftedBy :: FilePath -> StateC a -> StateC a@@ -51,7 +58,7 @@ getPath :: StateC FilePath getPath = do- (a,b,c,d,e) <- get+ (_,_,c,_,_) <- get return c getRelPath :: FilePath -> StateC FilePath@@ -59,9 +66,11 @@ path <- getPath return $ path </> relPath +errorC :: forall (m :: * -> *) a. (Show a, MonadIO m) => a -> [Char] -> m () errorC lineN err = liftIO $ putStrLn $ "At " ++ show lineN ++ ": " ++ err +mapMaybeM :: forall t (m :: * -> *) a. Monad m => (t -> m a) -> Maybe t -> m (Maybe a) mapMaybeM f (Just a) = do b <- f a return (Just b)-mapMaybeM f Nothing = return Nothing+mapMaybeM _ Nothing = return Nothing
Graphics/Implicit/MathUtil.hs view
@@ -1,15 +1,24 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -module Graphics.Implicit.MathUtil (rmax, rmin, rmaximum, rminimum, distFromLineSeg, pack, box3sWithin) where+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} -import Data.List-import Data.VectorSpace-import Data.AffineSpace-import Graphics.Implicit.Definitions+-- A module of math utilities.+module Graphics.Implicit.MathUtil (rmax, rmaximum, rminimum, distFromLineSeg, pack, box3sWithin) where +-- Explicitly include what we need from Prelude.+import Prelude (Bool, Num, Ord, Ordering, (>), (<), (+), ($), (/), otherwise, not, (||), (&&), abs, (-), (*), sin, asin, pi, max, sqrt, min, compare, (<=), fst, snd, (++))++import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, Box2, (⋅))++import Data.List (sort, sortBy, reverse, (!!))+import Data.VectorSpace (magnitude, normalized, (^-^), (^+^), (*^))+import Data.AffineSpace ((.-.))+ -- | The distance a point p is from a line segment (a,b)-distFromLineSeg :: ℝ2 -> (ℝ2,ℝ2) -> ℝ+distFromLineSeg :: ℝ2 -> (ℝ2, ℝ2) -> ℝ distFromLineSeg p (a,b) = magnitude (closest .-. p) where ab = b ^-^ a@@ -20,9 +29,7 @@ | d > magnitude ab = b | otherwise = a ^+^ d *^ normalized ab - --box3sWithin :: ℝ -> (ℝ3, ℝ3) -> (ℝ3,ℝ3) -> Bool+box3sWithin :: ℝ -> (ℝ3, ℝ3) -> (ℝ3, ℝ3) -> Bool box3sWithin r ((ax1, ay1, az1),(ax2, ay2, az2)) ((bx1, by1, bz1),(bx2, by2, bz2)) = let near (a1, a2) (b1, b2) = not $ (a2 + r < b1) || (b2 + r < a1)@@ -31,27 +38,27 @@ && (ay1,ay2) `near` (by1, by2) && (az1,az2) `near` (bz1, bz2) - -- | Rounded Maximum--- Consider max(x,y) = 0, the generated curve --- has a square-like corner. We replace it with a +-- Consider max(x,y) = 0, the generated curve+-- has a square-like corner. We replace it with a -- quarter of a circle-rmax :: +rmax :: ℝ -- ^ radius -> ℝ -- ^ first number to round maximum -> ℝ -- ^ second number to round maximum -> ℝ -- ^ resulting number-rmax r x y = if abs (x-y) < r +rmax r x y = if abs (x-y) < r then y - r*sin(pi/4-asin((x-y)/r/sqrt 2)) + r else max x y + -- | Rounded minimum-rmin :: +rmin :: ℝ -- ^ radius -> ℝ -- ^ first number to round minimum -> ℝ -- ^ second number to round minimum -> ℝ -- ^ resulting number-rmin r x y = if abs (x-y) < r +rmin r x y = if abs (x-y) < r then y + r*sin(pi/4+asin((x-y)/r/sqrt 2)) - r else min x y @@ -59,14 +66,13 @@ -- Just as maximum is. -- The implementation is to take the maximum two -- and rmax those.- rmaximum :: ℝ -- ^ radius -> [ℝ] -- ^ numbers to take round maximum -> ℝ -- ^ resulting number rmaximum _ (a:[]) = a rmaximum r (a:b:[]) = rmax r a b-rmaximum r l = +rmaximum r l = let tops = reverse $ sort l in@@ -77,41 +83,43 @@ ℝ -- ^ radius -> [ℝ] -- ^ numbers to take round minimum -> ℝ -- ^ resulting number-rminimum r (a:[]) = a+rminimum _ (a:[]) = a rminimum r (a:b:[]) = rmin r a b-rminimum r l = +rminimum r l = let tops = sort l in rmin r (tops !! 0) (tops !! 1) --pack :: +-- | Pack the given objects in a box the given size.+pack :: Box2 -- ^ The box to pack within -> ℝ -- ^ The space seperation between items -> [(Box2, a)] -- ^ Objects with their boxes -> ([(ℝ2, a)], [(Box2, a)] ) -- ^ Packed objects with their positions, objects that could be packed- pack (dx, dy) sep objs = packSome sortedObjs (dx, dy) where- compareBoxesByY ((_, ay1), (_, ay2)) ((_, by1), (_, by2)) = + compareBoxesByY :: forall t t1 t2 t3 a. (Ord a, Num a) => ((t, a), (t1, a)) -> ((t2, a), (t3, a)) -> Ordering+ compareBoxesByY ((_, ay1), (_, ay2)) ((_, by1), (_, by2)) = compare (abs $ by2-by1) (abs $ ay2 - ay1) - sortedObjs = sortBy - (\(boxa, _) (boxb, _) -> compareBoxesByY boxa boxb ) + sortedObjs = sortBy+ (\(boxa, _) (boxb, _) -> compareBoxesByY boxa boxb ) objs + tmap1 :: forall t t1 t2. (t2 -> t) -> (t2, t1) -> (t, t1) tmap1 f (a,b) = (f a, b)+ tmap2 :: forall t t1 t2. (t2 -> t1) -> (t, t2) -> (t, t1) tmap2 f (a,b) = (a, f b) - --packSome :: [(Box2,a)] -> Box2 -> ([(ℝ2,a)], [(Box2,a)])- packSome (presObj@(((x1,y1),(x2,y2)),obj):otherBoxedObjs) box@((bx1, by1), (bx2, by2)) = + packSome :: [(Box2,a)] -> Box2 -> ([(ℝ2,a)], [(Box2,a)])+ packSome (presObj@(((x1,y1),(x2,y2)),obj):otherBoxedObjs) box@((bx1, by1), (bx2, by2)) = if abs (x2 - x1) <= abs (bx2-bx1) && abs (y2 - y1) <= abs (by2-by1)- then + then let row = tmap1 (((bx1-x1,by1-y1), obj):) $ packSome otherBoxedObjs ((bx1+x2-x1+sep, by1), (bx2, by1 + y2-y1))- rowAndUp = + rowAndUp = if abs (by2-by1) - abs (y2-y1) > sep then tmap1 ((fst row) ++ ) $ packSome (snd row) ((bx1, by1 + y2-y1+sep), (bx2, by2))@@ -121,6 +129,3 @@ else tmap2 (presObj:) $ packSome otherBoxedObjs box packSome [] _ = ([], [])---
Graphics/Implicit/ObjectUtil.hs view
@@ -1,12 +1,17 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-}+-- create a module that is just wrapping up these functions. module Graphics.Implicit.ObjectUtil(getImplicit3, getImplicit2, getBox3, getBox2) where -import Graphics.Implicit.ObjectUtil.GetImplicit3-import Graphics.Implicit.ObjectUtil.GetImplicit2-import Graphics.Implicit.ObjectUtil.GetBox3-import Graphics.Implicit.ObjectUtil.GetBox2+import Prelude() +import Graphics.Implicit.ObjectUtil.GetImplicit3 (getImplicit3)++import Graphics.Implicit.ObjectUtil.GetImplicit2 (getImplicit2)++import Graphics.Implicit.ObjectUtil.GetBox3 (getBox3)++import Graphics.Implicit.ObjectUtil.GetBox2 (getBox2)
Graphics/Implicit/ObjectUtil/GetBox2.hs view
@@ -1,18 +1,25 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} module Graphics.Implicit.ObjectUtil.GetBox2 (getBox2, getDist2) where -import Graphics.Implicit.Definitions-import qualified Graphics.Implicit.MathUtil as MathUtil-import Data.List (nub)-import Data.VectorSpace+import Prelude(Bool, Fractional, (==), (||), unzip, minimum, maximum, ($), filter, not, (.), (/), map, (-), (+), (*), cos, sin, sqrt, max, abs, head) +import Graphics.Implicit.Definitions (ℝ, ℝ2, Box2, (⋯*),+ SymbolicObj2(Shell2, Outset2, Circle, Translate2, Rotate2, UnionR2, Scale2, RectR,+ PolygonR, Complement2, DifferenceR2, IntersectR2, EmbedBoxedObj2))++import Data.VectorSpace (magnitude, (^-^), (^+^))++-- Is a Box2 empty?+-- Really, this checks if it is one dimensional, which is good enough. isEmpty :: Box2 -> Bool-isEmpty = (== ((0,0), (0,0)))+isEmpty ((a, b), (c, d)) = a==c || b==d +-- Define a Box2 around all of the given points. pointsBox :: [ℝ2] -> Box2 pointsBox points = let@@ -33,31 +40,24 @@ outsetBox r (a,b) = (a ^-^ (r,r), b ^+^ (r,r)) +-- Define a Box2 around the given object. getBox2 :: SymbolicObj2 -> Box2- -- Primitives-getBox2 (RectR r a b) = (a,b)-+getBox2 (RectR _ a b) = (a,b) getBox2 (Circle r ) = ((-r, -r), (r,r))--getBox2 (PolygonR r points) = ((minimum xs, minimum ys), (maximum xs, maximum ys)) +getBox2 (PolygonR _ points) = ((minimum xs, minimum ys), (maximum xs, maximum ys)) where (xs, ys) = unzip points- -- (Rounded) CSG-getBox2 (Complement2 symbObj) = - ((-infty, -infty), (infty, infty)) where infty = 1/0-+getBox2 (Complement2 _) =+ ((-infty, -infty), (infty, infty))+ where+ infty :: (Fractional t) => t+ infty = 1/0 getBox2 (UnionR2 r symbObjs) = outsetBox r $ unionBoxes (map getBox2 symbObjs)--getBox2 (DifferenceR2 r symbObjs) =- let - firstBox:_ = map getBox2 symbObjs- in- firstBox--getBox2 (IntersectR2 r symbObjs) = - let +getBox2 (DifferenceR2 _ symbObjs) = getBox2 $ head symbObjs+getBox2 (IntersectR2 r symbObjs) =+ let boxes = map getBox2 symbObjs (leftbot, topright) = unzip boxes (lefts, bots) = unzip leftbot@@ -68,7 +68,6 @@ top = minimum tops in ((left-r,bot-r),(right+r,top+r))- -- Simple transforms getBox2 (Translate2 v symbObj) = let@@ -77,14 +76,12 @@ if isEmpty (a,b) then ((0,0),(0,0)) else (a^+^v, b^+^v)- getBox2 (Scale2 s symbObj) = let (a,b) = getBox2 symbObj in (s ⋯* a, s ⋯* b)--getBox2 (Rotate2 θ symbObj) = +getBox2 (Rotate2 θ symbObj) = let ((x1,y1), (x2,y2)) = getBox2 symbObj rotate (x,y) = (cos(θ)*x - sin(θ)*y, sin(θ)*x + cos(θ)*y)@@ -94,33 +91,31 @@ , rotate (x2, y1) , rotate (x2, y2) ]- -- Boundary mods-getBox2 (Shell2 w symbObj) = +getBox2 (Shell2 w symbObj) = outsetBox (w/2) $ getBox2 symbObj- getBox2 (Outset2 d symbObj) = outsetBox d $ getBox2 symbObj- -- Misc-getBox2 (EmbedBoxedObj2 (obj,box)) = box+getBox2 (EmbedBoxedObj2 (_,box)) = box -- Get the maximum distance (read upper bound) an object is from a point.--- Sort of a circular -+-- Sort of a circular getDist2 :: ℝ2 -> SymbolicObj2 -> ℝ- getDist2 p (UnionR2 r objs) = r + maximum [getDist2 p obj | obj <- objs ]- getDist2 p (Translate2 v obj) = getDist2 (p ^+^ v) obj- getDist2 p (Circle r) = magnitude p + r--getDist2 p (PolygonR r points) = +getDist2 p (PolygonR r points) = r + maximum [magnitude (p ^-^ p') | p' <- points]-+-- FIXME: write optimized functions for the rest of the SymbObjs. getDist2 (x,y) symbObj = let ((x1,y1), (x2,y2)) = getBox2 symbObj in- sqrt ((max (abs (x1 - x)) (abs (x2 - x)))^2 + (max (abs (y1 - y)) (abs (y2 - y)))^2)+ sqrt (+ (max (abs (x1 - x)) (abs (x2 - x))) *+ (max (abs (x1 - x)) (abs (x2 - x))) ++ (max (abs (y1 - y)) (abs (y2 - y))) *+ (max (abs (y1 - y)) (abs (y2 - y)))+ )+
Graphics/Implicit/ObjectUtil/GetBox3.hs view
@@ -1,44 +1,45 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Copyright 2015 2016, Mike MacHenry (mike.machenry@gmail.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- FIXME: required. why? {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} module Graphics.Implicit.ObjectUtil.GetBox3 (getBox3) where -import Graphics.Implicit.Definitions-import qualified Graphics.Implicit.MathUtil as MathUtil-import Data.Maybe (fromMaybe)-import qualified Data.Maybe as Maybe-import Data.VectorSpace+import Prelude(Eq, Bool(False), Fractional, Either (Left, Right), Maybe(Nothing, Just), (==), (||), max, (/), (-), (+), map, unzip, ($), filter, not, (.), unzip3, minimum, maximum, min, sqrt, (>), (&&), head, (*), (<), abs, either, error, const) -import Graphics.Implicit.ObjectUtil.GetBox2 (getBox2, getDist2)+import Graphics.Implicit.Definitions (ℝ, Box3, SymbolicObj3 (Rect3R, Sphere, Cylinder, Complement3, UnionR3, IntersectR3, DifferenceR3, Translate3, Scale3, Rotate3, Rotate3V, Shell3, Outset3, EmbedBoxedObj3, ExtrudeR, ExtrudeOnEdgeOf, ExtrudeRM, RotateExtrude, ExtrudeRotateR), (⋯*))+import Graphics.Implicit.ObjectUtil.GetBox2 (getBox2, getDist2) -import Debug.Trace+import Data.Maybe (fromMaybe)+import Data.VectorSpace ((^-^), (^+^)) -isEmpty :: Box3 -> Bool-isEmpty = (== ((0,0,0), (0,0,0)))+-- test to see whether a Box3 has area.+isEmpty :: (Eq a2, Eq a1, Eq a) =>+ ((a, a1, a2), (a, a1, a2)) -> Bool+isEmpty ((a,b,c),(d,e,f)) = a==d || b==e || c==f outsetBox :: ℝ -> Box3 -> Box3 outsetBox r (a,b) = (a ^-^ (r,r,r), b ^+^ (r,r,r)) +-- Get a Box3 around the given object. getBox3 :: SymbolicObj3 -> Box3- -- Primitives-getBox3 (Rect3R r a b) = (a,b)-+getBox3 (Rect3R _ a b) = (a,b) getBox3 (Sphere r ) = ((-r, -r, -r), (r,r,r))- getBox3 (Cylinder h r1 r2) = ( (-r,-r,0), (r,r,h) ) where r = max r1 r2- -- (Rounded) CSG-getBox3 (Complement3 symbObj) = - ((-infty, -infty, -infty), (infty, infty, infty)) where infty = 1/0-+getBox3 (Complement3 _) =+ ((-infty, -infty, -infty), (infty, infty, infty))+ where+ infty :: (Fractional t) => t+ infty = 1/0 getBox3 (UnionR3 r symbObjs) = ((left-r,bot-r,inward-r), (right+r,top+r,out+r))- where + where boxes = map getBox3 symbObjs- isEmpty = ( == ((0,0,0),(0,0,0)) ) (leftbot, topright) = unzip $ filter (not.isEmpty) boxes (lefts, bots, ins) = unzip3 leftbot (rights, tops, outs) = unzip3 topright@@ -48,9 +49,8 @@ right = maximum rights top = maximum tops out = maximum outs--getBox3 (IntersectR3 r symbObjs) = - let +getBox3 (IntersectR3 _ symbObjs) =+ let boxes = map getBox3 symbObjs (leftbot, topright) = unzip boxes (lefts, bots, ins) = unzip3 leftbot@@ -62,80 +62,64 @@ top = minimum tops out = minimum outs in- if top > bot - && right > left + if top > bot+ && right > left && out > inward then ((left,bot,inward),(right,top,out)) else ((0,0,0),(0,0,0))--getBox3 (DifferenceR3 r symbObjs) = firstBox- where- firstBox:_ = map getBox3 symbObjs-+getBox3 (DifferenceR3 _ symbObjs) = getBox3 $ head symbObjs -- Simple transforms getBox3 (Translate3 v symbObj) = let (a,b) = getBox3 symbObj in (a^+^v, b^+^v)- getBox3 (Scale3 s symbObj) = let (a,b) = getBox3 symbObj in (s ⋯* a, s ⋯* b)- getBox3 (Rotate3 _ symbObj) = ( (-d, -d, -d), (d, d, d) ) where ((x1,y1, z1), (x2,y2, z2)) = getBox3 symbObj d = (sqrt 3 *) $ maximum $ map abs [x1, x2, y1, y2, z1, z2]- getBox3 (Rotate3V _ v symbObj) = getBox3 (Rotate3 v symbObj)- -- Boundary mods getBox3 (Shell3 w symbObj) = outsetBox (w/2) $ getBox3 symbObj- getBox3 (Outset3 d symbObj) = outsetBox d $ getBox3 symbObj- -- Misc-getBox3 (EmbedBoxedObj3 (obj,box)) = box-+getBox3 (EmbedBoxedObj3 (_,box)) = box -- 2D Based-getBox3 (ExtrudeR r symbObj h) = ((x1,y1,0),(x2,y2,h))+getBox3 (ExtrudeR _ symbObj h) = ((x1,y1,0),(x2,y2,h)) where ((x1,y1),(x2,y2)) = getBox2 symbObj- getBox3 (ExtrudeOnEdgeOf symbObj1 symbObj2) = let ((ax1,ay1),(ax2,ay2)) = getBox2 symbObj1 ((bx1,by1),(bx2,by2)) = getBox2 symbObj2 in- ((bx1+ax1, by1+ax1, ay2), (bx2+ax2, by2+ax2, ay2))---getBox3 (ExtrudeRM r twist scale translate symbObj eitherh) = + ((bx1+ax1, by1+ax1, ay1), (bx2+ax2, by2+ax2, ay2))+-- FIXME: magic numbers in range.+getBox3 (ExtrudeRM _ twist scale translate symbObj eitherh) = let+ range :: [ℝ] range = [0, 0.1 .. 1.0]- ((x1,y1),(x2,y2)) = getBox2 symbObj (dx,dy) = (x2 - x1, y2 - y1) (xrange, yrange) = (map (\s -> x1+s*dx) $ range, map (\s -> y1+s*dy) $ range ) h = case eitherh of- Left h -> h- Right hf -> hmax + 0.2*(hmax-hmin)+ Left h' -> h'+ Right hf -> hmax + 0.2*(hmax-hmin) where hs = [hf (x,y) | x <- xrange, y <- yrange] (hmin, hmax) = (minimum hs, maximum hs)- hrange = map (h*) $ range- sval = case scale of Nothing -> 1 Just scale' -> maximum $ map (abs . scale') hrange- (twistXmin, twistYmin, twistXmax, twistYmax) = case twist of Nothing -> (smin x1, smin y1, smax x2, smax y2) where@@ -143,24 +127,21 @@ smax y = max y (sval * y) Just _ -> (-d, -d, d, d) where d = sval * getDist2 (0,0) symbObj- translate' = fromMaybe (const (0,0)) translate (tvalsx, tvalsy) = unzip . map (translate' . (h*)) $ hrange (tminx, tminy) = (minimum tvalsx, minimum tvalsy) (tmaxx, tmaxy) = (maximum tvalsx, maximum tvalsy) in ((twistXmin + tminx, twistYmin + tminy, 0),(twistXmax + tmaxx, twistYmax + tmaxy, h))---getBox3 (RotateExtrude _ _ (Left (xshift,yshift)) rotate symbObj) = +-- Note: Assumes x2 is always greater than x1.+-- FIXME: Insert the above assumption as an assertion in the language structure?+getBox3 (RotateExtrude _ _ (Left (xshift,yshift)) _ symbObj) = let- ((x1,y1),(x2,y2)) = getBox2 symbObj- g = maximum $ map abs [x1, x2, y1, y2]+ ((_,y1),(x2,y2)) = getBox2 symbObj r = max x2 (x2 + xshift) in ((-r, -r, min y1 (y1 + yshift)),(r, r, max y2 (y2 + yshift)))--getBox3 (RotateExtrude rot _ (Right f) rotate symbObj) = +getBox3 (RotateExtrude rot _ (Right f) rotate symbObj) = let ((x1,y1),(x2,y2)) = getBox2 symbObj (xshifts, yshifts) = unzip [f θ | θ <- [0 , rot / 10 .. rot] ]@@ -170,13 +151,12 @@ xmax' = if xmax > 0 then xmax * 1.1 else if xmax < - x1 then 0 else xmax ymax' = ymax + 0.1 * (ymax - ymin) ymin' = ymin - 0.1 * (ymax - ymin)- (r, z1, z2) = if either (==0) (const False) rotate+ (r, _, _) = if either (==0) (const False) rotate then let s = maximum $ map abs [x2, y1, y2] in (s + xmax', s + ymin', y2 + ymax') else (x2 + xmax', y1 + ymin', y2 + ymax') in ((-r, -r, y1 + ymin'),(r, r, y2 + ymax'))---+-- FIXME: add case for ExtrudeRotateR!+getBox3(ExtrudeRotateR _ _ _ _ ) = error "ExtrudeRotateR implementation incomplete!"
Graphics/Implicit/ObjectUtil/GetImplicit2.hs view
@@ -1,26 +1,31 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE +-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++-- FIXME: required. why? {-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances #-} module Graphics.Implicit.ObjectUtil.GetImplicit2 (getImplicit2) where -import Graphics.Implicit.Definitions-import qualified Graphics.Implicit.MathUtil as MathUtil-import Data.VectorSpace +import Prelude(Int, Num, abs, (-), (/), sqrt, (*), (+), (!!), mod, length, map, (<=), (&&), (>=), (||), odd, ($), (>), filter, (<), minimum, (==), maximum, max, cos, sin, head, tail)++import Graphics.Implicit.Definitions (SymbolicObj2(RectR, Circle, PolygonR, Complement2, UnionR2, DifferenceR2, IntersectR2, Translate2, Scale2, Rotate2, Shell2, Outset2, EmbedBoxedObj2), Obj2, ℝ, ℝ2, (⋯/))+import Graphics.Implicit.MathUtil (rminimum, rmaximum, distFromLineSeg)++import Data.VectorSpace ((^-^)) import Data.List (nub) getImplicit2 :: SymbolicObj2 -> Obj2- -- Primitives-getImplicit2 (RectR r (x1,y1) (x2,y2)) = \(x,y) -> MathUtil.rmaximum r+getImplicit2 (RectR r (x1,y1) (x2,y2)) = \(x,y) -> rmaximum r [abs (x-dx/2-x1) - dx/2, abs (y-dy/2-y1) - dy/2] where (dx, dy) = (x2-x1, y2-y1)--getImplicit2 (Circle r ) = - \(x,y) -> sqrt (x**2 + y**2) - r--getImplicit2 (PolygonR r points) = +getImplicit2 (Circle r ) =+ \(x,y) -> sqrt (x * x + y * y) - r+getImplicit2 (PolygonR _ points) = \p -> let pair :: Int -> (ℝ2,ℝ2) pair n = (points !! n, points !! (mod (n + 1) (length points) ) )@@ -32,74 +37,66 @@ seemsInRight = odd $ length $ filter (>0) $ nub crossing_points seemsInLeft = odd $ length $ filter (<0) $ nub crossing_points isIn = seemsInRight && seemsInLeft- dists = map (MathUtil.distFromLineSeg p) pairs :: [ℝ]+ dists = map (distFromLineSeg p) pairs :: [ℝ] in minimum dists * if isIn then -1 else 1- -- (Rounded) CSG-getImplicit2 (Complement2 symbObj) = +getImplicit2 (Complement2 symbObj) = let obj = getImplicit2 symbObj in \p -> - obj p- getImplicit2 (UnionR2 r symbObjs) =- let + let objs = map getImplicit2 symbObjs in if r == 0- then \p -> minimum $ map ($p) objs - else \p -> MathUtil.rminimum r $ map ($p) objs-+ then \p -> minimum $ map ($p) objs+ else \p -> rminimum r $ map ($p) objs getImplicit2 (DifferenceR2 r symbObjs) =- let - obj:objs = map getImplicit2 symbObjs- complement obj = \p -> - obj p+ let+ objs = map getImplicit2 symbObjs+ obj = head objs+ complement :: forall a t. Num a => (t -> a) -> t -> a+ complement obj' = \p -> - obj' p in if r == 0- then \p -> maximum $ map ($p) $ obj:(map complement objs) - else \p -> MathUtil.rmaximum r $ map ($p) $ obj:(map complement objs) --getImplicit2 (IntersectR2 r symbObjs) = - let + then \p -> maximum $ map ($p) $ obj:(map complement $ tail objs)+ else \p -> rmaximum r $ map ($p) $ obj:(map complement $ tail objs)+getImplicit2 (IntersectR2 r symbObjs) =+ let objs = map getImplicit2 symbObjs in if r == 0- then \p -> maximum $ map ($p) objs - else \p -> MathUtil.rmaximum r $ map ($p) objs-+ then \p -> maximum $ map ($p) objs+ else \p -> rmaximum r $ map ($p) objs -- Simple transforms getImplicit2 (Translate2 v symbObj) = let obj = getImplicit2 symbObj in \p -> obj (p ^-^ v)- getImplicit2 (Scale2 s@(sx,sy) symbObj) = let obj = getImplicit2 symbObj in \p -> (max sx sy) * obj (p ⋯/ s)--getImplicit2 (Rotate2 θ symbObj) = +getImplicit2 (Rotate2 θ symbObj) = let obj = getImplicit2 symbObj in \(x,y) -> obj ( cos(θ)*x + sin(θ)*y, cos(θ)*y - sin(θ)*x)- -- Boundary mods-getImplicit2 (Shell2 w symbObj) = +getImplicit2 (Shell2 w symbObj) = let obj = getImplicit2 symbObj in \p -> abs (obj p) - w/2- getImplicit2 (Outset2 d symbObj) = let obj = getImplicit2 symbObj in \p -> obj p - d- -- Misc-getImplicit2 (EmbedBoxedObj2 (obj,box)) = obj+getImplicit2 (EmbedBoxedObj2 (obj,_)) = obj
Graphics/Implicit/ObjectUtil/GetImplicit3.hs view
@@ -1,130 +1,126 @@- -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Copyright 2015 2016, Mike MacHenry (mike.machenry@gmail.com)+-- Released under the GNU AGPLV3+, see LICENSE -{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances, ViewPatterns #-}+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} module Graphics.Implicit.ObjectUtil.GetImplicit3 (getImplicit3) where -import Graphics.Implicit.Definitions-import qualified Graphics.Implicit.MathUtil as MathUtil+import Prelude (Either(Left, Right), Int, abs, (-), (/), (*), sqrt, (+), atan2, max, cos, map, (==), minimum, ($), maximum, (**), sin, const, pi, (.), Bool(True, False), ceiling, floor, fromIntegral, return, error, head, tail, Num)++import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, (⋯/), Obj3,+ SymbolicObj3(Shell3, UnionR3, IntersectR3, DifferenceR3, Translate3, Scale3, Rotate3,+ Outset3, Rect3R, Sphere, Cylinder, Complement3, EmbedBoxedObj3, Rotate3V,+ ExtrudeR, ExtrudeRM, ExtrudeOnEdgeOf, RotateExtrude, ExtrudeRotateR))+import Graphics.Implicit.MathUtil (rmaximum, rminimum, rmax) import qualified Data.Maybe as Maybe import qualified Data.Either as Either-import Data.VectorSpace -import Data.AffineSpace-import Data.Cross (cross3)+import Data.VectorSpace ((^-^), (^+^), (^*), (<.>), normalized) import Graphics.Implicit.ObjectUtil.GetImplicit2 (getImplicit2) getImplicit3 :: SymbolicObj3 -> Obj3- -- Primitives-getImplicit3 (Rect3R r (x1,y1,z1) (x2,y2,z2)) = \(x,y,z) -> MathUtil.rmaximum r+getImplicit3 (Rect3R r (x1,y1,z1) (x2,y2,z2)) = \(x,y,z) -> rmaximum r [abs (x-dx/2-x1) - dx/2, abs (y-dy/2-y1) - dy/2, abs (z-dz/2-z1) - dz/2] where (dx, dy, dz) = (x2-x1, y2-y1, z2-z1)--getImplicit3 (Sphere r ) = - \(x,y,z) -> sqrt (x**2 + y**2 + z**2) - r-+getImplicit3 (Sphere r ) =+ \(x,y,z) -> sqrt (x*x + y*y + z*z) - r getImplicit3 (Cylinder h r1 r2) = \(x,y,z) -> let- d = sqrt(x^2+y^2) - ((r2-r1)/h*z+r1)+ d = sqrt(x*x + y*y) - ((r2-r1)/h*z+r1) θ = atan2 (r2-r1) h in max (d * cos θ) (abs(z-h/(2::ℝ)) - h/(2::ℝ))- -- (Rounded) CSG-getImplicit3 (Complement3 symbObj) = +getImplicit3 (Complement3 symbObj) = let obj = getImplicit3 symbObj in \p -> - obj p- getImplicit3 (UnionR3 r symbObjs) =- let + let objs = map getImplicit3 symbObjs in if r == 0- then \p -> minimum $ map ($p) objs - else \p -> MathUtil.rminimum r $ map ($p) objs--getImplicit3 (IntersectR3 r symbObjs) = - let + then \p -> minimum $ map ($p) objs+ else \p -> rminimum r $ map ($p) objs+getImplicit3 (IntersectR3 r symbObjs) =+ let objs = map getImplicit3 symbObjs in if r == 0- then \p -> maximum $ map ($p) objs - else \p -> MathUtil.rmaximum r $ map ($p) objs-+ then \p -> maximum $ map ($p) objs+ else \p -> rmaximum r $ map ($p) objs getImplicit3 (DifferenceR3 r symbObjs) =- let - obj:objs = map getImplicit3 symbObjs- complement obj = \p -> - obj p+ let+ objs = map getImplicit3 symbObjs+ obj = head objs+ complement :: forall a t. Num a => (t -> a) -> t -> a+ complement obj' = \p -> - obj' p in if r == 0- then \p -> maximum $ map ($p) $ obj:(map complement objs) - else \p -> MathUtil.rmaximum r $ map ($p) $ obj:(map complement objs) -+ then \p -> maximum $ map ($p) $ obj:(map complement $ tail objs)+ else \p -> rmaximum r $ map ($p) $ obj:(map complement $ tail objs) -- Simple transforms getImplicit3 (Translate3 v symbObj) = let obj = getImplicit3 symbObj in \p -> obj (p ^-^ v)- getImplicit3 (Scale3 s@(sx,sy,sz) symbObj) = let obj = getImplicit3 symbObj k = (sx*sy*sz)**(1/3) in \p -> k * obj (p ⋯/ s)--getImplicit3 (Rotate3 (yz, zx, xy) symbObj) = +getImplicit3 (Rotate3 (yz, zx, xy) symbObj) = let obj = getImplicit3 symbObj rotateYZ :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ)- rotateYZ θ obj = \(x,y,z) -> obj ( x, cos(θ)*y + sin(θ)*z, cos(θ)*z - sin(θ)*y)+ rotateYZ θ obj' = \(x,y,z) -> obj' ( x, cos(θ)*y + sin(θ)*z, cos(θ)*z - sin(θ)*y) rotateZX :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ)- rotateZX θ obj = \(x,y,z) -> obj ( cos(θ)*x - sin(θ)*z, y, cos(θ)*z + sin(θ)*x)+ rotateZX θ obj' = \(x,y,z) -> obj' ( cos(θ)*x - sin(θ)*z, y, cos(θ)*z + sin(θ)*x) rotateXY :: ℝ -> (ℝ3 -> ℝ) -> (ℝ3 -> ℝ)- rotateXY θ obj = \(x,y,z) -> obj ( cos(θ)*x + sin(θ)*y, cos(θ)*y - sin(θ)*x, z)+ rotateXY θ obj' = \(x,y,z) -> obj' ( cos(θ)*x + sin(θ)*y, cos(θ)*y - sin(θ)*x, z) in rotateYZ yz $ rotateZX zx $ rotateXY xy $ obj- getImplicit3 (Rotate3V θ axis symbObj) = let axis' = normalized axis obj = getImplicit3 symbObj+ -- Note: this is ripped from data.cross.+ cross3 :: forall t. Num t => (t, t, t) -> (t, t, t) -> (t, t, t)+ cross3 (ax,ay,az) (bx,by,bz) = ( ay * bz - az * by+ , az * bx - ax * bz+ , ax * by - ay * bx ) in- \v -> obj $ - v ^* cos(θ) - ^-^ (axis' `cross3` v) ^* sin(θ) + \v -> obj $+ v ^* cos(θ)+ ^-^ (axis' `cross3` v) ^* sin(θ) ^+^ (axis' ^* (axis' <.> (v ^* (1 - cos(θ)))))- -- Boundary mods-getImplicit3 (Shell3 w symbObj) = +getImplicit3 (Shell3 w symbObj) = let obj = getImplicit3 symbObj in \p -> abs (obj p) - w/2- getImplicit3 (Outset3 d symbObj) = let obj = getImplicit3 symbObj in \p -> obj p - d- -- Misc-getImplicit3 (EmbedBoxedObj3 (obj,box)) = obj-+getImplicit3 (EmbedBoxedObj3 (obj,_)) = obj -- 2D Based-getImplicit3 (ExtrudeR r symbObj h) = +getImplicit3 (ExtrudeR r symbObj h) = let obj = getImplicit2 symbObj in- \(x,y,z) -> MathUtil.rmax r (obj (x,y)) (abs (z - h/2) - h/2)--getImplicit3 (ExtrudeRM r twist scale translate symbObj height) = + \(x,y,z) -> rmax r (obj (x,y)) (abs (z - h/2) - h/2)+getImplicit3 (ExtrudeRM r twist scale translate symbObj height) = let obj = getImplicit2 symbObj twist' = Maybe.fromMaybe (const 0) twist@@ -136,40 +132,37 @@ scaleVec :: ℝ -> ℝ2 -> ℝ2 scaleVec s = \(x,y) -> (x/s, y/s) rotateVec :: ℝ -> ℝ2 -> ℝ2- rotateVec θ (x,y) = (x*cos(θ)+y*sin(θ), y*cos(θ)-x*sin(θ)) + rotateVec θ (x,y) = (x*cos(θ)+y*sin(θ), y*cos(θ)-x*sin(θ)) k = (pi :: ℝ)/(180:: ℝ) in \(x,y,z) -> let h = height' (x,y) in- MathUtil.rmax r + rmax r (obj . rotateVec (-k*twist' z) . scaleVec (scale' z) . (\a -> a ^-^ translate' z) $ (x,y)) (abs (z - h/2) - h/2)-- getImplicit3 (ExtrudeOnEdgeOf symbObj1 symbObj2) = let obj1 = getImplicit2 symbObj1 obj2 = getImplicit2 symbObj2 in \(x,y,z) -> obj1 (obj2 (x,y), z)----getImplicit3 (RotateExtrude totalRotation round translate rotate symbObj) = +getImplicit3 (RotateExtrude totalRotation round translate rotate symbObj) = let+ tau :: ℝ tau = 2 * pi+ k :: ℝ k = tau / 360 totalRotation' = totalRotation*k obj = getImplicit2 symbObj capped = Maybe.isJust round round' = Maybe.fromMaybe 0 round translate' :: ℝ -> ℝ2- translate' = Either.either - (\(a,b) -> \θ -> (a*θ/totalRotation', b*θ/totalRotation')) + translate' = Either.either+ (\(a,b) -> \θ -> (a*θ/totalRotation', b*θ/totalRotation')) (. (/k)) translate rotate' :: ℝ -> ℝ- rotate' = Either.either - (\t -> \θ -> t*θ/totalRotation' ) + rotate' = Either.either+ (\t -> \θ -> t*θ/totalRotation' ) (. (/k)) rotate twists = case rotate of@@ -178,23 +171,23 @@ in \(x,y,z) -> minimum $ do - let - r = sqrt (x^2 + y^2)+ let+ r = sqrt (x*x + y*y) θ = atan2 y x ns :: [Int] ns = if capped then -- we will cap a different way, but want leeway to keep the function cont- [-1 .. (ceiling (totalRotation' / tau) :: Int) + (1 :: Int)]+ [-1 .. (ceiling (totalRotation' / tau)) + 1] else [0 .. floor $ (totalRotation' - θ) /tau] n <- ns let θvirt = fromIntegral n * tau + θ- (rshift, zshift) = translate' θvirt + (rshift, zshift) = translate' θvirt twist = rotate' θvirt- rz_pos = if twists - then let + rz_pos = if twists+ then let (c,s) = (cos(twist*k), sin(twist*k)) (r',z') = (r-rshift, z-zshift) in@@ -202,8 +195,10 @@ else (r - rshift, z - zshift) return $ if capped- then MathUtil.rmax round' + then rmax round' (abs (θvirt - (totalRotation' / 2)) - (totalRotation' / 2)) (obj rz_pos) else obj rz_pos-+-- FIXME: implement this, or implement a fallthrough function.+--getImplicit3 (ExtrudeRotateR) =+getImplicit3 (ExtrudeRotateR _ _ _ _) = error "ExtrudeRotateR unimplimented!"
Graphics/Implicit/Primitives.hs view
@@ -1,11 +1,83 @@ -- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE+-- Copyright (C) 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE -{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, FlexibleInstances, FlexibleContexts, TypeSynonymInstances, UndecidableInstances, NoMonomorphismRestriction #-}+-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-} -module Graphics.Implicit.Primitives where+-- FIXME: Required. why?+{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, TypeSynonymInstances, FlexibleInstances #-} -import Graphics.Implicit.Definitions+-- A module exporting all of the primitives, and some operations on them.+module Graphics.Implicit.Primitives (+ translate,+ scale,+ outset,+ complement, union, intersect, difference,+ unionR, intersectR, differenceR,+ shell,+ getBox,+ getImplicit,+ extrudeR,+ extrudeRM,+ extrudeRotateR,+ extrudeOnEdgeOf,+ sphere,+ rect3R,+ circle,+ cylinder,+ cylinder2,+ rectR,+ polygonR,+ rotateExtrude,+ rotate3,+ rotate3V,+ pack3,+ rotate,+ pack2,+ implicit+ ) where++import Prelude(Maybe(Just, Nothing), Either, map, ($))++import Graphics.Implicit.Definitions (ℝ, ℝ2, ℝ3, Box2,+ SymbolicObj2(+ RectR,+ Circle,+ PolygonR,+ Complement2,+ UnionR2,+ DifferenceR2,+ IntersectR2,+ Translate2,+ Scale2,+ Rotate2,+ Outset2,+ Shell2,+ EmbedBoxedObj2+ ),+ SymbolicObj3(+ Rect3R,+ Sphere,+ Cylinder,+ Complement3,+ UnionR3,+ DifferenceR3,+ IntersectR3,+ Translate3,+ Scale3,+ Rotate3,+ Rotate3V,+ Outset3,+ Shell3,+ EmbedBoxedObj3,+ ExtrudeR,+ ExtrudeRotateR,+ ExtrudeRM,+ RotateExtrude,+ ExtrudeOnEdgeOf+ )+ ) import Graphics.Implicit.MathUtil (pack) import Graphics.Implicit.ObjectUtil (getBox2, getBox3, getImplicit2, getImplicit3) @@ -14,6 +86,7 @@ sphere :: ℝ -- ^ Radius of the sphere -> SymbolicObj3 -- ^ Resulting sphere+ sphere = Sphere rect3R ::@@ -25,14 +98,18 @@ rect3R = Rect3R cylinder2 ::- ℝ -- ^ Radius of the cylinder + ℝ -- ^ Radius of the cylinder -> ℝ -- ^ Second radius of the cylinder -> ℝ -- ^ Height of the cylinder -> SymbolicObj3 -- ^ Resulting cylinder cylinder2 r1 r2 h = Cylinder h r1 r2 -cylinder :: ℝ -> ℝ -> SymbolicObj3+cylinder ::+ ℝ -- ^ Radius of the cylinder+ -> ℝ -- ^ Height of the cylinder+ -> SymbolicObj3 -- ^ Resulting cylinder+ cylinder r = cylinder2 r r -- $ 2D Primitives@@ -55,73 +132,71 @@ ℝ -- ^ Rouding of the polygon -> [ℝ2] -- ^ Verticies of the polygon -> SymbolicObj2 -- ^ Resulting polygon-polygonR = PolygonR -polygon :: [ℝ2] -> SymbolicObj2-polygon = polygonR 0+polygonR = PolygonR -- $ Shared Operations class Object obj vec | obj -> vec where - -- | Translate an object by a vector of appropriate dimension. - translate :: - vec -- ^ Vector to translate by (Also: a is a vector, blah, blah)- -> obj -- ^ Object to translate- -> obj -- ^ Resulting object-- -- | Scale an object- scale :: - vec -- ^ Amount to scale by- -> obj -- ^ Object to scale- -> obj -- ^ Resulting scaled object - -- | Complement an Object- complement :: + complement :: obj -- ^ Object to complement -> obj -- ^ Result -- | Rounded union- unionR :: + unionR :: ℝ -- ^ The radius of rounding -> [obj] -- ^ objects to union -> obj -- ^ Resulting object- ++ -- | Rounded difference+ differenceR ::+ ℝ -- ^ The radius of rounding+ -> [obj] -- ^ Objects to difference+ -> obj -- ^ Resulting object+ -- | Rounded minimum- intersectR :: + intersectR :: ℝ -- ^ The radius of rounding -> [obj] -- ^ Objects to intersect -> obj -- ^ Resulting object - -- | Rounded difference- differenceR :: - ℝ -- ^ The radius of rounding- -> [obj] -- ^ Objects to difference + -- | Translate an object by a vector of appropriate dimension.+ translate ::+ vec -- ^ Vector to translate by (Also: a is a vector, blah, blah)+ -> obj -- ^ Object to translate -> obj -- ^ Resulting object - -- | Outset an object.- outset :: + -- | Scale an object+ scale ::+ vec -- ^ Amount to scale by+ -> obj -- ^ Object to scale+ -> obj -- ^ Resulting scaled object++ -- | Outset of an object.+ outset :: ℝ -- ^ distance to outset -> obj -- ^ object to outset -> obj -- ^ resulting object -- | Make a shell of an object.- shell :: + shell :: ℝ -- ^ width of shell -> obj -- ^ object to take shell of -> obj -- ^ resulting shell -- | Get the bounding box an object- getBox :: + getBox :: obj -- ^ Object to get box of -> (vec, vec) -- ^ Bounding box -- | Get the implicit function for an object- getImplicit :: + getImplicit :: obj -- ^ Object to get implicit function of -> (vec -> ℝ) -- ^ Implicit function - implicit :: + implicit :: (vec -> ℝ) -- ^ Implicit function -> (vec, vec) -- ^ Bounding box -> obj -- ^ Resulting object@@ -153,10 +228,13 @@ getImplicit = getImplicit3 implicit a b= EmbedBoxedObj3 (a,b) +union :: forall obj vec. Object obj vec => [obj] -> obj union = unionR 0++difference :: forall obj vec. Object obj vec => [obj] -> obj difference = differenceR 0 ---intersect :: forall obj vec. Object obj vec => [obj] -> obj+intersect :: forall obj vec. Object obj vec => [obj] -> obj intersect = intersectR 0 -- 3D operations@@ -164,6 +242,9 @@ extrudeR :: ℝ -> SymbolicObj2 -> ℝ -> SymbolicObj3 extrudeR = ExtrudeR +extrudeRotateR :: ℝ -> ℝ -> SymbolicObj2 -> ℝ -> SymbolicObj3+extrudeRotateR = ExtrudeRotateR+ extrudeRM :: ℝ -> Maybe (ℝ -> ℝ) -> Maybe (ℝ -> ℝ)@@ -190,30 +271,29 @@ rotate3V :: ℝ -> ℝ3 -> SymbolicObj3 -> SymbolicObj3 rotate3V = Rotate3V -+-- FIXME: shouldn't this pack into a 3d area, or have a 3d equivalent? pack3 :: ℝ2 -> ℝ -> [SymbolicObj3] -> Maybe SymbolicObj3-pack3 (_dx, dy) sep objs = +pack3 (dx, dy) sep objs = let+ boxDropZ :: forall t t1 t2 t3 t4 t5. ((t2, t3, t), (t4, t5, t1)) -> ((t2, t3), (t4, t5)) boxDropZ ((a,b,_),(d,e,_)) = ((a,b),(d,e)) withBoxes :: [(Box2, SymbolicObj3)] withBoxes = map (\obj -> ( boxDropZ $ getBox3 obj, obj)) objs- in case pack ((0,0),(dy,dy)) sep withBoxes of+ in case pack ((0,0),(dx,dy)) sep withBoxes of (a, []) -> Just $ union $ map (\((x,y),obj) -> translate (x,y,0) obj) a _ -> Nothing- -- 2D operations rotate :: ℝ -> SymbolicObj2 -> SymbolicObj2 rotate = Rotate2 - pack2 :: ℝ2 -> ℝ -> [SymbolicObj2] -> Maybe SymbolicObj2-pack2 (_dx, dy) sep objs = +pack2 (dx, dy) sep objs = let withBoxes :: [(Box2, SymbolicObj2)] withBoxes = map (\obj -> ( getBox2 obj, obj)) objs- in case pack ((0,0),(dy,dy)) sep withBoxes of+ in case pack ((0,0),(dx,dy)) sep withBoxes of (a, []) -> Just $ union $ map (\((x,y),obj) -> translate (x,y) obj) a _ -> Nothing
LICENSE view
@@ -1,282 +1,621 @@- GNU GENERAL PUBLIC LICENSE- Version 2, June 1991+GNU AFFERO GENERAL PUBLIC LICENSE+ Version 3, 19 November 2007 - Copyright (C) 1989, 1991 Free Software Foundation, Inc.,- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble - The licenses for most software are designed to take away your-freedom to share and change it. By contrast, the GNU General Public-License is intended to guarantee your freedom to share and change free-software--to make sure the software is free for all its users. This-General Public License applies to most of the Free Software-Foundation's software and to any other program whose authors commit to-using it. (Some other Free Software Foundation software is covered by-the GNU Lesser General Public License instead.) You can apply it to-your programs, too.+ The GNU Affero General Public License is a free, copyleft license for+software and other kinds of works, specifically designed to ensure+cooperation with the community in the case of network server software. + The licenses for most software and other practical works are designed+to take away your freedom to share and change the works. By contrast,+our General Public Licenses are intended to guarantee your freedom to+share and change all versions of a program--to make sure it remains free+software for all its users.+ When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for-this service if you wish), that you receive source code or can get it-if you want it, that you can change the software or use pieces of it-in new free programs; and that you know you can do these things.-- To protect your rights, we need to make restrictions that forbid-anyone to deny you these rights or to ask you to surrender the rights.-These restrictions translate to certain responsibilities for you if you-distribute copies of the software, or if you modify it.+them if you wish), that you receive source code or can get it if you+want it, that you can change the software or use pieces of it in new+free programs, and that you know you can do these things. - For example, if you distribute copies of such a program, whether-gratis or for a fee, you must give the recipients all the rights that-you have. You must make sure that they, too, receive or can get the-source code. And you must show them these terms so they know their-rights.+ Developers that use our General Public Licenses protect your rights+with two steps: (1) assert copyright on the software, and (2) offer+you this License which gives you legal permission to copy, distribute+and/or modify the software. - We protect your rights with two steps: (1) copyright the software, and-(2) offer you this license which gives you legal permission to copy,-distribute and/or modify the software.+ A secondary benefit of defending all users' freedom is that+improvements made in alternate versions of the program, if they+receive widespread use, become available for other developers to+incorporate. Many developers of free software are heartened and+encouraged by the resulting cooperation. However, in the case of+software used on network servers, this result may fail to come about.+The GNU General Public License permits making a modified version and+letting the public access it on a server without ever releasing its+source code to the public. - Also, for each author's protection and ours, we want to make certain-that everyone understands that there is no warranty for this free-software. If the software is modified by someone else and passed on, we-want its recipients to know that what they have is not the original, so-that any problems introduced by others will not reflect on the original-authors' reputations.+ The GNU Affero General Public License is designed specifically to+ensure that, in such cases, the modified source code becomes available+to the community. It requires the operator of a network server to+provide the source code of the modified version running there to the+users of that server. Therefore, public use of a modified version, on+a publicly accessible server, gives the public access to the source+code of the modified version. - Finally, any free program is threatened constantly by software-patents. We wish to avoid the danger that redistributors of a free-program will individually obtain patent licenses, in effect making the-program proprietary. To prevent this, we have made it clear that any-patent must be licensed for everyone's free use or not licensed at all.+ An older license, called the Affero General Public License and+published by Affero, was designed to accomplish similar goals. This is+a different license, not a version of the Affero GPL, but Affero has+released a new version of the Affero GPL which permits relicensing under+this license. The precise terms and conditions for copying, distribution and modification follow. - GNU GENERAL PUBLIC LICENSE- TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION+ TERMS AND CONDITIONS - 0. This License applies to any program or other work which contains-a notice placed by the copyright holder saying it may be distributed-under the terms of this General Public License. The "Program", below,-refers to any such program or work, and a "work based on the Program"-means either the Program or any derivative work under copyright law:-that is to say, a work containing the Program or a portion of it,-either verbatim or with modifications and/or translated into another-language. (Hereinafter, translation is included without limitation in-the term "modification".) Each licensee is addressed as "you".+ 0. Definitions. -Activities other than copying, distribution and modification are not-covered by this License; they are outside its scope. The act of-running the Program is not restricted, and the output from the Program-is covered only if its contents constitute a work based on the-Program (independent of having been made by running the Program).-Whether that is true depends on what the Program does.+ "This License" refers to version 3 of the GNU Affero General Public License. - 1. You may copy and distribute verbatim copies of the Program's-source code as you receive it, in any medium, provided that you-conspicuously and appropriately publish on each copy an appropriate-copyright notice and disclaimer of warranty; keep intact all the-notices that refer to this License and to the absence of any warranty;-and give any other recipients of the Program a copy of this License-along with the Program.+ "Copyright" also means copyright-like laws that apply to other kinds of+works, such as semiconductor masks. -You may charge a fee for the physical act of transferring a copy, and-you may at your option offer warranty protection in exchange for a fee.+ "The Program" refers to any copyrightable work licensed under this+License. Each licensee is addressed as "you". "Licensees" and+"recipients" may be individuals or organizations. - 2. You may modify your copy or copies of the Program or any portion-of it, thus forming a work based on the Program, and copy and-distribute such modifications or work under the terms of Section 1-above, provided that you also meet all of these conditions:+ To "modify" a work means to copy from or adapt all or part of the work+in a fashion requiring copyright permission, other than the making of an+exact copy. The resulting work is called a "modified version" of the+earlier work or a work "based on" the earlier work. - a) You must cause the modified files to carry prominent notices- stating that you changed the files and the date of any change.+ A "covered work" means either the unmodified Program or a work based+on the Program. - b) You must cause any work that you distribute or publish, that in- whole or in part contains or is derived from the Program or any- part thereof, to be licensed as a whole at no charge to all third- parties under the terms of this License.+ To "propagate" a work means to do anything with it that, without+permission, would make you directly or secondarily liable for+infringement under applicable copyright law, except executing it on a+computer or modifying a private copy. Propagation includes copying,+distribution (with or without modification), making available to the+public, and in some countries other activities as well. - c) If the modified program normally reads commands interactively- when run, you must cause it, when started running for such- interactive use in the most ordinary way, to print or display an- announcement including an appropriate copyright notice and a- notice that there is no warranty (or else, saying that you provide- a warranty) and that users may redistribute the program under- these conditions, and telling the user how to view a copy of this- License. (Exception: if the Program itself is interactive but- does not normally print such an announcement, your work based on- the Program is not required to print an announcement.)+ To "convey" a work means any kind of propagation that enables other+parties to make or receive copies. Mere interaction with a user through+a computer network, with no transfer of a copy, is not conveying. -These requirements apply to the modified work as a whole. If-identifiable sections of that work are not derived from the Program,-and can be reasonably considered independent and separate works in-themselves, then this License, and its terms, do not apply to those-sections when you distribute them as separate works. But when you-distribute the same sections as part of a whole which is a work based-on the Program, the distribution of the whole must be on the terms of-this License, whose permissions for other licensees extend to the-entire whole, and thus to each and every part regardless of who wrote it.+ An interactive user interface displays "Appropriate Legal Notices"+to the extent that it includes a convenient and prominently visible+feature that (1) displays an appropriate copyright notice, and (2)+tells the user that there is no warranty for the work (except to the+extent that warranties are provided), that licensees may convey the+work under this License, and how to view a copy of this License. If+the interface presents a list of user commands or options, such as a+menu, a prominent item in the list meets this criterion. -Thus, it is not the intent of this section to claim rights or contest-your rights to work written entirely by you; rather, the intent is to-exercise the right to control the distribution of derivative or-collective works based on the Program.+ 1. Source Code. -In addition, mere aggregation of another work not based on the Program-with the Program (or with a work based on the Program) on a volume of-a storage or distribution medium does not bring the other work under-the scope of this License.+ The "source code" for a work means the preferred form of the work+for making modifications to it. "Object code" means any non-source+form of a work. - 3. You may copy and distribute the Program (or a work based on it,-under Section 2) in object code or executable form under the terms of-Sections 1 and 2 above provided that you also do one of the following:+ A "Standard Interface" means an interface that either is an official+standard defined by a recognized standards body, or, in the case of+interfaces specified for a particular programming language, one that+is widely used among developers working in that language. - a) Accompany it with the complete corresponding machine-readable- source code, which must be distributed under the terms of Sections- 1 and 2 above on a medium customarily used for software interchange; or,+ The "System Libraries" of an executable work include anything, other+than the work as a whole, that (a) is included in the normal form of+packaging a Major Component, but which is not part of that Major+Component, and (b) serves only to enable use of the work with that+Major Component, or to implement a Standard Interface for which an+implementation is available to the public in source code form. A+"Major Component", in this context, means a major essential component+(kernel, window system, and so on) of the specific operating system+(if any) on which the executable work runs, or a compiler used to+produce the work, or an object code interpreter used to run it. - b) Accompany it with a written offer, valid for at least three- years, to give any third party, for a charge no more than your- cost of physically performing source distribution, a complete- machine-readable copy of the corresponding source code, to be- distributed under the terms of Sections 1 and 2 above on a medium- customarily used for software interchange; or,+ The "Corresponding Source" for a work in object code form means all+the source code needed to generate, install, and (for an executable+work) run the object code and to modify the work, including scripts to+control those activities. However, it does not include the work's+System Libraries, or general-purpose tools or generally available free+programs which are used unmodified in performing those activities but+which are not part of the work. For example, Corresponding Source+includes interface definition files associated with source files for+the work, and the source code for shared libraries and dynamically+linked subprograms that the work is specifically designed to require,+such as by intimate data communication or control flow between those+subprograms and other parts of the work. - c) Accompany it with the information you received as to the offer- to distribute corresponding source code. (This alternative is- allowed only for noncommercial distribution and only if you- received the program in object code or executable form with such- an offer, in accord with Subsection b above.)+ The Corresponding Source need not include anything that users+can regenerate automatically from other parts of the Corresponding+Source. -The source code for a work means the preferred form of the work for-making modifications to it. For an executable work, complete source-code means all the source code for all modules it contains, plus any-associated interface definition files, plus the scripts used to-control compilation and installation of the executable. However, as a-special exception, the source code distributed need not include-anything that is normally distributed (in either source or binary-form) with the major components (compiler, kernel, and so on) of the-operating system on which the executable runs, unless that component-itself accompanies the executable.+ The Corresponding Source for a work in source code form is that+same work. -If distribution of executable or object code is made by offering-access to copy from a designated place, then offering equivalent-access to copy the source code from the same place counts as-distribution of the source code, even though third parties are not-compelled to copy the source along with the object code.+ 2. Basic Permissions. - 4. You may not copy, modify, sublicense, or distribute the Program-except as expressly provided under this License. Any attempt-otherwise to copy, modify, sublicense or distribute the Program is-void, and will automatically terminate your rights under this License.-However, parties who have received copies, or rights, from you under-this License will not have their licenses terminated so long as such-parties remain in full compliance.+ All rights granted under this License are granted for the term of+copyright on the Program, and are irrevocable provided the stated+conditions are met. This License explicitly affirms your unlimited+permission to run the unmodified Program. The output from running a+covered work is covered by this License only if the output, given its+content, constitutes a covered work. This License acknowledges your+rights of fair use or other equivalent, as provided by copyright law. - 5. You are not required to accept this License, since you have not-signed it. However, nothing else grants you permission to modify or-distribute the Program or its derivative works. These actions are-prohibited by law if you do not accept this License. Therefore, by-modifying or distributing the Program (or any work based on the-Program), you indicate your acceptance of this License to do so, and-all its terms and conditions for copying, distributing or modifying-the Program or works based on it.+ You may make, run and propagate covered works that you do not+convey, without conditions so long as your license otherwise remains+in force. You may convey covered works to others for the sole purpose+of having them make modifications exclusively for you, or provide you+with facilities for running those works, provided that you comply with+the terms of this License in conveying all material for which you do+not control copyright. Those thus making or running the covered works+for you must do so exclusively on your behalf, under your direction+and control, on terms that prohibit them from making any copies of+your copyrighted material outside their relationship with you. - 6. Each time you redistribute the Program (or any work based on the-Program), the recipient automatically receives a license from the-original licensor to copy, distribute or modify the Program subject to-these terms and conditions. You may not impose any further-restrictions on the recipients' exercise of the rights granted herein.-You are not responsible for enforcing compliance by third parties to+ Conveying under any other circumstances is permitted solely under+the conditions stated below. Sublicensing is not allowed; section 10+makes it unnecessary.++ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.++ No covered work shall be deemed part of an effective technological+measure under any applicable law fulfilling obligations under article+11 of the WIPO copyright treaty adopted on 20 December 1996, or+similar laws prohibiting or restricting circumvention of such+measures.++ When you convey a covered work, you waive any legal power to forbid+circumvention of technological measures to the extent such circumvention+is effected by exercising rights under this License with respect to+the covered work, and you disclaim any intention to limit operation or+modification of the work as a means of enforcing, against the work's+users, your or third parties' legal rights to forbid circumvention of+technological measures.++ 4. Conveying Verbatim Copies.++ You may convey verbatim copies of the Program's source code as you+receive it, in any medium, provided that you conspicuously and+appropriately publish on each copy an appropriate copyright notice;+keep intact all notices stating that this License and any+non-permissive terms added in accord with section 7 apply to the code;+keep intact all notices of the absence of any warranty; and give all+recipients a copy of this License along with the Program.++ You may charge any price or no price for each copy that you convey,+and you may offer support or warranty protection for a fee.++ 5. Conveying Modified Source Versions.++ You may convey a work based on the Program, or the modifications to+produce it from the Program, in the form of source code under the+terms of section 4, provided that you also meet all of these conditions:++ a) The work must carry prominent notices stating that you modified+ it, and giving a relevant date.++ b) The work must carry prominent notices stating that it is+ released under this License and any conditions added under section+ 7. This requirement modifies the requirement in section 4 to+ "keep intact all notices".++ c) You must license the entire work, as a whole, under this+ License to anyone who comes into possession of a copy. This+ License will therefore apply, along with any applicable section 7+ additional terms, to the whole of the work, and all its parts,+ regardless of how they are packaged. This License gives no+ permission to license the work in any other way, but it does not+ invalidate such permission if you have separately received it.++ d) If the work has interactive user interfaces, each must display+ Appropriate Legal Notices; however, if the Program has interactive+ interfaces that do not display Appropriate Legal Notices, your+ work need not make them do so.++ A compilation of a covered work with other separate and independent+works, which are not by their nature extensions of the covered work,+and which are not combined with it such as to form a larger program,+in or on a volume of a storage or distribution medium, is called an+"aggregate" if the compilation and its resulting copyright are not+used to limit the access or legal rights of the compilation's users+beyond what the individual works permit. Inclusion of a covered work+in an aggregate does not cause this License to apply to the other+parts of the aggregate.++ 6. Conveying Non-Source Forms.++ You may convey a covered work in object code form under the terms+of sections 4 and 5, provided that you also convey the+machine-readable Corresponding Source under the terms of this License,+in one of these ways:++ a) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by the+ Corresponding Source fixed on a durable physical medium+ customarily used for software interchange.++ b) Convey the object code in, or embodied in, a physical product+ (including a physical distribution medium), accompanied by a+ written offer, valid for at least three years and valid for as+ long as you offer spare parts or customer support for that product+ model, to give anyone who possesses the object code either (1) a+ copy of the Corresponding Source for all the software in the+ product that is covered by this License, on a durable physical+ medium customarily used for software interchange, for a price no+ more than your reasonable cost of physically performing this+ conveying of source, or (2) access to copy the+ Corresponding Source from a network server at no charge.++ c) Convey individual copies of the object code with a copy of the+ written offer to provide the Corresponding Source. This+ alternative is allowed only occasionally and noncommercially, and+ only if you received the object code with such an offer, in accord+ with subsection 6b.++ d) Convey the object code by offering access from a designated+ place (gratis or for a charge), and offer equivalent access to the+ Corresponding Source in the same way through the same place at no+ further charge. You need not require recipients to copy the+ Corresponding Source along with the object code. If the place to+ copy the object code is a network server, the Corresponding Source+ may be on a different server (operated by you or a third party)+ that supports equivalent copying facilities, provided you maintain+ clear directions next to the object code saying where to find the+ Corresponding Source. Regardless of what server hosts the+ Corresponding Source, you remain obligated to ensure that it is+ available for as long as needed to satisfy these requirements.++ e) Convey the object code using peer-to-peer transmission, provided+ you inform other peers where the object code and Corresponding+ Source of the work are being offered to the general public at no+ charge under subsection 6d.++ A separable portion of the object code, whose source code is excluded+from the Corresponding Source as a System Library, need not be+included in conveying the object code work.++ A "User Product" is either (1) a "consumer product", which means any+tangible personal property which is normally used for personal, family,+or household purposes, or (2) anything designed or sold for incorporation+into a dwelling. In determining whether a product is a consumer product,+doubtful cases shall be resolved in favor of coverage. For a particular+product received by a particular user, "normally used" refers to a+typical or common use of that class of product, regardless of the status+of the particular user or of the way in which the particular user+actually uses, or expects or is expected to use, the product. A product+is a consumer product regardless of whether the product has substantial+commercial, industrial or non-consumer uses, unless such uses represent+the only significant mode of use of the product.++ "Installation Information" for a User Product means any methods,+procedures, authorization keys, or other information required to install+and execute modified versions of a covered work in that User Product from+a modified version of its Corresponding Source. The information must+suffice to ensure that the continued functioning of the modified object+code is in no case prevented or interfered with solely because+modification has been made.++ If you convey an object code work under this section in, or with, or+specifically for use in, a User Product, and the conveying occurs as+part of a transaction in which the right of possession and use of the+User Product is transferred to the recipient in perpetuity or for a+fixed term (regardless of how the transaction is characterized), the+Corresponding Source conveyed under this section must be accompanied+by the Installation Information. But this requirement does not apply+if neither you nor any third party retains the ability to install+modified object code on the User Product (for example, the work has+been installed in ROM).++ The requirement to provide Installation Information does not include a+requirement to continue to provide support service, warranty, or updates+for a work that has been modified or installed by the recipient, or for+the User Product in which it has been modified or installed. Access to a+network may be denied when the modification itself materially and+adversely affects the operation of the network or violates the rules and+protocols for communication across the network.++ Corresponding Source conveyed, and Installation Information provided,+in accord with this section must be in a format that is publicly+documented (and with an implementation available to the public in+source code form), and must require no special password or key for+unpacking, reading or copying.++ 7. Additional Terms.++ "Additional permissions" are terms that supplement the terms of this+License by making exceptions from one or more of its conditions.+Additional permissions that are applicable to the entire Program shall+be treated as though they were included in this License, to the extent+that they are valid under applicable law. If additional permissions+apply only to part of the Program, that part may be used separately+under those permissions, but the entire Program remains governed by+this License without regard to the additional permissions.++ When you convey a copy of a covered work, you may at your option+remove any additional permissions from that copy, or from any part of+it. (Additional permissions may be written to require their own+removal in certain cases when you modify the work.) You may place+additional permissions on material, added by you to a covered work,+for which you have or can give appropriate copyright permission.++ Notwithstanding any other provision of this License, for material you+add to a covered work, you may (if authorized by the copyright holders of+that material) supplement the terms of this License with terms:++ a) Disclaiming warranty or limiting liability differently from the+ terms of sections 15 and 16 of this License; or++ b) Requiring preservation of specified reasonable legal notices or+ author attributions in that material or in the Appropriate Legal+ Notices displayed by works containing it; or++ c) Prohibiting misrepresentation of the origin of that material, or+ requiring that modified versions of such material be marked in+ reasonable ways as different from the original version; or++ d) Limiting the use for publicity purposes of names of licensors or+ authors of the material; or++ e) Declining to grant rights under trademark law for use of some+ trade names, trademarks, or service marks; or++ f) Requiring indemnification of licensors and authors of that+ material by anyone who conveys the material (or modified versions of+ it) with contractual assumptions of liability to the recipient, for+ any liability that these contractual assumptions directly impose on+ those licensors and authors.++ All other non-permissive additional terms are considered "further+restrictions" within the meaning of section 10. If the Program as you+received it, or any part of it, contains a notice stating that it is+governed by this License along with a term that is a further+restriction, you may remove that term. If a license document contains+a further restriction but permits relicensing or conveying under this+License, you may add to a covered work material governed by the terms+of that license document, provided that the further restriction does+not survive such relicensing or conveying.++ If you add terms to a covered work in accord with this section, you+must place, in the relevant source files, a statement of the+additional terms that apply to those files, or a notice indicating+where to find the applicable terms.++ Additional terms, permissive or non-permissive, may be stated in the+form of a separately written license, or stated as exceptions;+the above requirements apply either way.++ 8. Termination.++ You may not propagate or modify a covered work except as expressly+provided under this License. Any attempt otherwise to propagate or+modify it is void, and will automatically terminate your rights under+this License (including any patent licenses granted under the third+paragraph of section 11).++ However, if you cease all violation of this License, then your+license from a particular copyright holder is reinstated (a)+provisionally, unless and until the copyright holder explicitly and+finally terminates your license, and (b) permanently, if the copyright+holder fails to notify you of the violation by some reasonable means+prior to 60 days after the cessation.++ Moreover, your license from a particular copyright holder is+reinstated permanently if the copyright holder notifies you of the+violation by some reasonable means, this is the first time you have+received notice of violation of this License (for any work) from that+copyright holder, and you cure the violation prior to 30 days after+your receipt of the notice.++ Termination of your rights under this section does not terminate the+licenses of parties who have received copies or rights from you under+this License. If your rights have been terminated and not permanently+reinstated, you do not qualify to receive new licenses for the same+material under section 10.++ 9. Acceptance Not Required for Having Copies.++ You are not required to accept this License in order to receive or+run a copy of the Program. Ancillary propagation of a covered work+occurring solely as a consequence of using peer-to-peer transmission+to receive a copy likewise does not require acceptance. However,+nothing other than this License grants you permission to propagate or+modify any covered work. These actions infringe copyright if you do+not accept this License. Therefore, by modifying or propagating a+covered work, you indicate your acceptance of this License to do so.++ 10. Automatic Licensing of Downstream Recipients.++ Each time you convey a covered work, the recipient automatically+receives a license from the original licensors, to run, modify and+propagate that work, subject to this License. You are not responsible+for enforcing compliance by third parties with this License.++ An "entity transaction" is a transaction transferring control of an+organization, or substantially all assets of one, or subdividing an+organization, or merging organizations. If propagation of a covered+work results from an entity transaction, each party to that+transaction who receives a copy of the work also receives whatever+licenses to the work the party's predecessor in interest had or could+give under the previous paragraph, plus a right to possession of the+Corresponding Source of the work from the predecessor in interest, if+the predecessor has it or can get it with reasonable efforts.++ You may not impose any further restrictions on the exercise of the+rights granted or affirmed under this License. For example, you may+not impose a license fee, royalty, or other charge for exercise of+rights granted under this License, and you may not initiate litigation+(including a cross-claim or counterclaim in a lawsuit) alleging that+any patent claim is infringed by making, using, selling, offering for+sale, or importing the Program or any portion of it.++ 11. Patents.++ A "contributor" is a copyright holder who authorizes use under this+License of the Program or a work on which the Program is based. The+work thus licensed is called the contributor's "contributor version".++ A contributor's "essential patent claims" are all patent claims+owned or controlled by the contributor, whether already acquired or+hereafter acquired, that would be infringed by some manner, permitted+by this License, of making, using, or selling its contributor version,+but do not include claims that would be infringed only as a+consequence of further modification of the contributor version. For+purposes of this definition, "control" includes the right to grant+patent sublicenses in a manner consistent with the requirements of this License. - 7. If, as a consequence of a court judgment or allegation of patent-infringement or for any other reason (not limited to patent issues),-conditions are imposed on you (whether by court order, agreement or+ Each contributor grants you a non-exclusive, worldwide, royalty-free+patent license under the contributor's essential patent claims, to+make, use, sell, offer for sale, import and otherwise run, modify and+propagate the contents of its contributor version.++ In the following three paragraphs, a "patent license" is any express+agreement or commitment, however denominated, not to enforce a patent+(such as an express permission to practice a patent or covenant not to+sue for patent infringement). To "grant" such a patent license to a+party means to make such an agreement or commitment not to enforce a+patent against the party.++ If you convey a covered work, knowingly relying on a patent license,+and the Corresponding Source of the work is not available for anyone+to copy, free of charge and under the terms of this License, through a+publicly available network server or other readily accessible means,+then you must either (1) cause the Corresponding Source to be so+available, or (2) arrange to deprive yourself of the benefit of the+patent license for this particular work, or (3) arrange, in a manner+consistent with the requirements of this License, to extend the patent+license to downstream recipients. "Knowingly relying" means you have+actual knowledge that, but for the patent license, your conveying the+covered work in a country, or your recipient's use of the covered work+in a country, would infringe one or more identifiable patents in that+country that you have reason to believe are valid.++ If, pursuant to or in connection with a single transaction or+arrangement, you convey, or propagate by procuring conveyance of, a+covered work, and grant a patent license to some of the parties+receiving the covered work authorizing them to use, propagate, modify+or convey a specific copy of the covered work, then the patent license+you grant is automatically extended to all recipients of the covered+work and works based on it.++ A patent license is "discriminatory" if it does not include within+the scope of its coverage, prohibits the exercise of, or is+conditioned on the non-exercise of one or more of the rights that are+specifically granted under this License. You may not convey a covered+work if you are a party to an arrangement with a third party that is+in the business of distributing software, under which you make payment+to the third party based on the extent of your activity of conveying+the work, and under which the third party grants, to any of the+parties who would receive the covered work from you, a discriminatory+patent license (a) in connection with copies of the covered work+conveyed by you (or copies made from those copies), or (b) primarily+for and in connection with specific products or compilations that+contain the covered work, unless you entered into that arrangement,+or that patent license was granted, prior to 28 March 2007.++ Nothing in this License shall be construed as excluding or limiting+any implied license or other defenses to infringement that may+otherwise be available to you under applicable patent law.++ 12. No Surrender of Others' Freedom.++ If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not-excuse you from the conditions of this License. If you cannot-distribute so as to satisfy simultaneously your obligations under this-License and any other pertinent obligations, then as a consequence you-may not distribute the Program at all. For example, if a patent-license would not permit royalty-free redistribution of the Program by-all those who receive copies directly or indirectly through you, then-the only way you could satisfy both it and this License would be to-refrain entirely from distribution of the Program.+excuse you from the conditions of this License. If you cannot convey a+covered work so as to satisfy simultaneously your obligations under this+License and any other pertinent obligations, then as a consequence you may+not convey it at all. For example, if you agree to terms that obligate you+to collect a royalty for further conveying from those to whom you convey+the Program, the only way you could satisfy both those terms and this+License would be to refrain entirely from conveying the Program. -If any portion of this section is held invalid or unenforceable under-any particular circumstance, the balance of the section is intended to-apply and the section as a whole is intended to apply in other-circumstances.+ 13. Remote Network Interaction; Use with the GNU General Public License. -It is not the purpose of this section to induce you to infringe any-patents or other property right claims or to contest validity of any-such claims; this section has the sole purpose of protecting the-integrity of the free software distribution system, which is-implemented by public license practices. Many people have made-generous contributions to the wide range of software distributed-through that system in reliance on consistent application of that-system; it is up to the author/donor to decide if he or she is willing-to distribute software through any other system and a licensee cannot-impose that choice.+ Notwithstanding any other provision of this License, if you modify the+Program, your modified version must prominently offer all users+interacting with it remotely through a computer network (if your version+supports such interaction) an opportunity to receive the Corresponding+Source of your version by providing access to the Corresponding Source+from a network server at no charge, through some standard or customary+means of facilitating copying of software. This Corresponding Source+shall include the Corresponding Source for any work covered by version 3+of the GNU General Public License that is incorporated pursuant to the+following paragraph. -This section is intended to make thoroughly clear what is believed to-be a consequence of the rest of this License.+ Notwithstanding any other provision of this License, you have+permission to link or combine any covered work with a work licensed+under version 3 of the GNU General Public License into a single+combined work, and to convey the resulting work. The terms of this+License will continue to apply to the part which is the covered work,+but the work with which it is combined will remain governed by version+3 of the GNU General Public License. - 8. If the distribution and/or use of the Program is restricted in-certain countries either by patents or by copyrighted interfaces, the-original copyright holder who places the Program under this License-may add an explicit geographical distribution limitation excluding-those countries, so that distribution is permitted only in or among-countries not thus excluded. In such case, this License incorporates-the limitation as if written in the body of this License.+ 14. Revised Versions of this License. - 9. The Free Software Foundation may publish revised and/or new versions-of the General Public License from time to time. Such new versions will-be similar in spirit to the present version, but may differ in detail to+ The Free Software Foundation may publish revised and/or new versions of+the GNU Affero General Public License from time to time. Such new versions+will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. -Each version is given a distinguishing version number. If the Program-specifies a version number of this License which applies to it and "any-later version", you have the option of following the terms and conditions-either of that version or of any later version published by the Free-Software Foundation. If the Program does not specify a version number of-this License, you may choose any version ever published by the Free Software-Foundation.+ Each version is given a distinguishing version number. If the+Program specifies that a certain numbered version of the GNU Affero General+Public License "or any later version" applies to it, you have the+option of following the terms and conditions either of that numbered+version or of any later version published by the Free Software+Foundation. If the Program does not specify a version number of the+GNU Affero General Public License, you may choose any version ever published+by the Free Software Foundation. - 10. If you wish to incorporate parts of the Program into other free-programs whose distribution conditions are different, write to the author-to ask for permission. For software which is copyrighted by the Free-Software Foundation, write to the Free Software Foundation; we sometimes-make exceptions for this. Our decision will be guided by the two goals-of preserving the free status of all derivatives of our free software and-of promoting the sharing and reuse of software generally.+ If the Program specifies that a proxy can decide which future+versions of the GNU Affero General Public License can be used, that proxy's+public statement of acceptance of a version permanently authorizes you+to choose that version for the Program. - NO WARRANTY+ Later license versions may give you additional or different+permissions. However, no additional obligations are imposed on any+author or copyright holder as a result of your choosing to follow a+later version. - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY-FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN-OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES-PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED-OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF-MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS-TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE-PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,-REPAIR OR CORRECTION.+ 15. Disclaimer of Warranty. - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR-REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,-INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING-OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED-TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY-YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER-PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE-POSSIBILITY OF SUCH DAMAGES.+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF+ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + 16. Limitation of Liability.++ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF+SUCH DAMAGES.++ 17. Interpretation of Sections 15 and 16.++ If the disclaimer of warranty and limitation of liability provided+above cannot be given local legal effect according to their terms,+reviewing courts shall apply local law that most closely approximates+an absolute waiver of all civil liability in connection with the+Program, unless a warranty or assumption of liability accompanies a+copy of the Program in return for a fee.+ END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs@@ -287,53 +626,36 @@ To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively-convey the exclusion of warranty; and each file should have at least+state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> - This program is free software; you can redistribute it and/or modify- it under the terms of the GNU General Public License as published by- the Free Software Foundation; either version 2 of the License, or+ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU Affero General Public License as published by+ the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- GNU General Public License for more details.+ GNU Affero General Public License for more details. - You should have received a copy of the GNU General Public License along- with this program; if not, write to the Free Software Foundation, Inc.,- 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.+ You should have received a copy of the GNU Affero General Public License+ along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. -If the program is interactive, make it output a short notice like this-when it starts in an interactive mode:-- Gnomovision version 69, Copyright (C) year name of author- Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.- This is free software, and you are welcome to redistribute it- under certain conditions; type `show c' for details.--The hypothetical commands `show w' and `show c' should show the appropriate-parts of the General Public License. Of course, the commands you use may-be called something other than `show w' and `show c'; they could even be-mouse-clicks or menu items--whatever suits your program.--You should also get your employer (if you work as a programmer) or your-school, if any, to sign a "copyright disclaimer" for the program, if-necessary. Here is a sample; alter the names:-- Yoyodyne, Inc., hereby disclaims all copyright interest in the program- `Gnomovision' (which makes passes at compilers) written by James Hacker.-- <signature of Ty Coon>, 1 April 1989- Ty Coon, President of Vice+ If your software can interact with users remotely through a computer+network, you should also make sure that it provides a way for users to+get its source. For example, if your program is a web application, its+interface could display a "Source" link that leads users to an archive+of the code. There are many ways you could offer source, and different+solutions will be better for different programs; see section 13 for the+specific requirements. -This General Public License does not permit incorporating your program into-proprietary programs. If your program is a subroutine library, you may-consider it more useful to permit linking proprietary applications with the-library. If this is what you want to do, use the GNU Lesser General-Public License instead of this License.+ You should also get your employer (if you work as a programmer) or school,+if any, to sign a "copyright disclaimer" for the program, if necessary.+For more information on this, and how to apply and follow the GNU AGPL, see+<http://www.gnu.org/licenses/>.
+ bench/ParserBench.hs view
@@ -0,0 +1,61 @@+import Criterion.Main+import Graphics.Implicit.ExtOpenScad.Definitions+import Graphics.Implicit.ExtOpenScad.Parser.Expr+import Graphics.Implicit.ExtOpenScad.Parser.Statement+import Text.ParserCombinators.Parsec hiding (State)+import Text.Printf++lineComment :: Int -> String+lineComment width = "//" ++ ['x' | _ <- [1..width]] ++ "\n"++lineComments :: Int -> String+lineComments n = concat [lineComment 80 | _ <- [1..n]]+ ++ assignments 1 -- to avoid empty file++blockComment :: Int -> Int -> String+blockComment lineCount width =+ "/*" ++ concat [['x' | _ <- [1..width]] ++ "\n" | _ <- [1..lineCount]] ++ "*/"++blockComments :: Int -> Int -> String+blockComments lineCount n = concat [blockComment lineCount 40 | _ <- [1..n]]+ ++ assignments 1 -- to avoid empty file++assignments :: Int -> String+assignments n = concat ["x = (foo + bar);\n" | _ <- [1..n]]++intList :: Int -> String+intList n = "[" ++ concat [(show i) ++ "," | i <- [1..n]] ++ "0]"++parseExpr :: String -> Expr+parseExpr s = case parse expr0 "src" s of+ Left err -> error (show err)+ Right e -> e++parseStatements :: String -> [StatementI]+parseStatements s = case parseProgram "src" s of+ Left err -> error (show err)+ Right e -> e++deepArithmetic :: Int -> String+deepArithmetic n+ | n == 0 = "1"+ | otherwise = printf "%s + %s * (%s - %s)" d d d d+ where+ d = deepArithmetic (n - 1)++run :: String -> (String -> a) -> String -> Benchmark+run name func input =+ env (return $ input) $ \s ->+ bench name $ whnf func s++main :: IO ()+main =+ defaultMain $+ [ bgroup "comments"+ [ run "line" parseStatements (lineComments 5000)+ , run "block" parseStatements (blockComments 10 500)+ ]+ , run "assignments" parseStatements (assignments 100)+ , run "int list" parseExpr (intList 1000)+ , run "deep arithmetic" parseExpr (deepArithmetic 3)+ ]
− extopenscad.hs
@@ -1,182 +0,0 @@--- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)--- Released under the GNU GPL, see LICENSE--{-# LANGUAGE ViewPatterns, PatternGuards #-}---- Let's make it convenient to run our extended openscad format code---- Let's be explicit about what we're getting from where :)-import Graphics.Implicit (runOpenscad, writeSVG, writeBinSTL, writeOBJ, writeSCAD3, writeSCAD2, writeGCodeHacklabLaser, writePNG2, writePNG3)-import Graphics.Implicit.ExtOpenScad.Definitions (OVal (ONum))-import Graphics.Implicit.ObjectUtil (getBox2, getBox3)-import Graphics.Implicit.Definitions (xmlErrorOn, SymbolicObj2, SymbolicObj3)-import qualified Data.Map as Map hiding (null)-import Data.Maybe as Maybe-import Data.Char-import Data.Tuple (swap)-import Data.IORef (writeIORef)-import Data.AffineSpace-import Control.Applicative--- The following is needed to ensure backwards/forwards compatibility--- make sure we don't import (<>) in new versions.-import Options.Applicative (fullDesc, progDesc, header, auto, info, helper, help, str, argument, switch, value, long, short, option, metavar, execParser, Parser)-import System.FilePath--import Data.Monoid ((<>), mappend, mempty)--data ExtOpenScadOpts = ExtOpenScadOpts- { outputFile :: Maybe FilePath- , outputFormat :: Maybe OutputFormat- , resolution :: Maybe Float- , xmlError :: Bool- , inputFile :: FilePath- }--data OutputFormat- = SVG- | SCAD- | PNG- | GCode- | STL- | OBJ- deriving (Show, Eq, Ord)--formatExtensions :: [(String, OutputFormat)]-formatExtensions =- [ ("svg", SVG)- , ("scad", SCAD)- , ("png", PNG)- , ("ngc", GCode)- , ("stl", STL)- , ("obj", OBJ)- ]--readOutputFormat :: Monad m => String -> m OutputFormat-readOutputFormat ext = case lookup (map toLower ext) formatExtensions of- Nothing -> fail ("unknown extension: "++ext)- Just x -> return x--guessOutputFormat :: FilePath -> OutputFormat-guessOutputFormat fileName =- Maybe.fromMaybe (error $ "Unrecognized output format: "<>ext)- $ readOutputFormat $ tail ext- where- (_,ext) = splitExtension fileName--extOpenScadOpts :: Parser ExtOpenScadOpts-extOpenScadOpts =- ExtOpenScadOpts- <$> option (pure <$> str)- ( short 'o'- <> long "output"- <> value Nothing- <> metavar "FILE"- <> help "Output file name"- )- <*> option (pure <$> (readOutputFormat =<< str))- ( short 'f'- <> long "format"- <> value Nothing- <> metavar "FORMAT"- <> help "Output format"- )- <*> option (pure <$> auto)- ( short 'r'- <> long "resolution"- <> value Nothing- <> metavar "RES"- <> help "Approximation quality"- )- <*> switch- ( long "xml-error"- <> help "Report XML errors"- )- <*> argument str ( metavar "FILE" )--getRes (Map.lookup "$res" -> Just (ONum res), _, _) = res--getRes (varlookup, _, obj:_) =- let- ((x1,y1,z1),(x2,y2,z2)) = getBox3 obj- (x,y,z) = (x2-x1, y2-y1, z2-z1)- in case Maybe.fromMaybe (ONum 1) $ Map.lookup "$quality" varlookup of- ONum qual | qual > 0 -> min (minimum [x,y,z]/2) ((x*y*z/qual)**(1/3) / 22)- _ -> min (minimum [x,y,z]/2) ((x*y*z )**(1/3) / 22)--getRes (varlookup, obj:_, _) =- let- (p1,p2) = getBox2 obj- (x,y) = p2 .-. p1- in case Maybe.fromMaybe (ONum 1) $ Map.lookup "$quality" varlookup of- ONum qual | qual > 0 -> min (min x y/2) (sqrt (x*y/qual) / 30)- _ -> min (min x y/2) (sqrt (x*y ) / 30)--getRes _ = 1--export3 :: Maybe OutputFormat -> Float -> FilePath -> SymbolicObj3 -> IO ()-export3 posFmt res output obj =- case posFmt of- Just STL -> writeBinSTL res output obj- Just SCAD -> writeSCAD3 res output obj- Just OBJ -> writeOBJ res output obj- Just PNG -> writePNG3 res output obj- Nothing -> writeBinSTL res output obj- Just fmt -> putStrLn $ "Unrecognized 3D format: "<>show fmt--export2 :: Maybe OutputFormat -> Float -> FilePath -> SymbolicObj2 -> IO ()-export2 posFmt res output obj =- case posFmt of- Just SVG -> writeSVG res output obj- Just SCAD -> writeSCAD2 res output obj- Just PNG -> writePNG2 res output obj- Just GCode -> writeGCodeHacklabLaser res output obj- Nothing -> writeSVG res output obj- Just fmt -> putStrLn $ "Unrecognized 2D format: "<>show fmt--main :: IO()-main = do- args <- execParser- $ info (helper <*> extOpenScadOpts)- ( fullDesc- <> progDesc "Extended OpenSCAD"- <> header "extopenscad - Extended OpenSCAD"- )- writeIORef xmlErrorOn (xmlError args)-- content <- readFile (inputFile args)- let format = case () of- _ | Just fmt <- outputFormat args -> Just fmt- _ | Just file <- outputFile args -> Just $ guessOutputFormat file- _ -> Nothing- case runOpenscad content of- Left err -> print err- Right openscadProgram -> do- s@(_vars, obj2s, obj3s) <- openscadProgram- let res = Maybe.fromMaybe (getRes s) (resolution args)- let basename = fst (splitExtension $ inputFile args)- let posDefExt = case format of- Just f -> lookup f (map swap formatExtensions)- Nothing -> Nothing -- We don't know the format -- it will be 2D/3D default- {-let Just defExtension = lookup format (map swap formatExtensions)- in maybe (fst (splitExtension $ inputFile args)<>"."<>defExtension) id- $ outputFile args-}- case (obj2s, obj3s) of- ([], [obj]) -> do- let output = fromMaybe - (basename ++ "." ++ fromMaybe "stl" posDefExt)- (outputFile args)- putStrLn $ "Rendering 3D object to " ++ output- putStrLn $ "With resolution " ++ show res- putStrLn $ "In box " ++ show (getBox3 obj)- export3 format res output obj- ([obj], []) -> do- let output = fromMaybe - (basename ++ "." ++ fromMaybe "stl" posDefExt)- (outputFile args)- putStrLn $ "Rendering 2D object to " ++ output- putStrLn $ "With resolution " ++ show res- putStrLn $ "In box " ++ show (getBox2 obj)- export2 format res output obj- ([], []) -> putStrLn "No objects to render"- _ -> putStrLn "Multiple objects, what do you want to render?"-
implicit.cabal view
@@ -1,26 +1,26 @@-Name: implicit-Version: 0.0.5-cabal-version: >= 1.6-Synopsis: Math-inspired programmatic 2&3D CAD: CSG, bevels, and shells; gcode export..-Description: A math-inspired programmatic CAD library in haskell.+name: implicit+version: 0.1.0+cabal-version: >= 1.8+synopsis: Math-inspired programmatic 2&3D CAD: CSG, bevels, and shells; gcode export..+description: A math-inspired programmatic CAD library in haskell. Build objects with constructive solid geometry, bevels,- shells and more in 2D & 3D. Then export to SVGs, STLs, + shells and more in 2D & 3D. Then export to SVGs, STLs, or produce gcode directly!-License: GPL-License-file: LICENSE-Author: Christopher Olah-Maintainer: Mike MacHenry <mike.machenry@gmail.com>-Homepage: https://github.com/colah/ImplicitCAD+license: AGPL-3+license-file: LICENSE+author: Christopher Olah+maintainer: Julia Longtin <julial@turinglace.com>+homepage: http://kalli1.faikvm.com/ImplicitCAD/Stable build-type: Simple-Category: Graphics+category: Graphics -Library+library - Build-Depends:+ build-depends: base >= 3 && < 5, filepath, directory,- optparse-applicative >= 0.10.0,+ download, parsec, unordered-containers, parallel,@@ -28,41 +28,31 @@ deepseq, vector-space, text,- mtl,+ monads-tf, bytestring, blaze-builder, blaze-markup, blaze-svg, storable-endian, JuicyPixels,- NumInstances- - ghc-options:- -O2 -optc-O3- -threaded- -rtsopts- -funfolding-use-threshold=16 - -fspec-constr-count=10+ NumInstances,+ criterion,+ snap-core,+ snap-server,+ silently,+ transformers - Extensions:- FlexibleContexts,- FlexibleInstances,- FunctionalDependencies,- GADTs,- IncoherentInstances,- KindSignatures,- MultiParamTypeClasses,- NoMonomorphismRestriction,- OverloadedStrings,- ParallelListComp,- RankNTypes,- ScopedTypeVariables,- TypeSynonymInstances,- UndecidableInstances,- ViewPatterns,- OverloadedStrings+ ghc-options:+ -Wall+-- for debugging only.+-- -Weverything+ -O2+ -optc-O3+-- cannot use, we use infinity in some calculations.+-- -optc-ffast-math - Exposed-Modules: + extensions:+ exposed-modules: Graphics.Implicit Graphics.Implicit.Definitions Graphics.Implicit.Primitives@@ -70,31 +60,36 @@ Graphics.Implicit.MathUtil Graphics.Implicit.ExtOpenScad Graphics.Implicit.ObjectUtil+ -- Note that these modules are only temporarily exposed, to+ -- allow coding the unit tests against the current parser+ -- interface.+ Graphics.Implicit.ExtOpenScad.Parser.Statement+ Graphics.Implicit.ExtOpenScad.Parser.Expr+ Graphics.Implicit.ExtOpenScad.Definitions+ -- these are exported for Benchmark.+ Graphics.Implicit.Export.SymbolicObj2+ Graphics.Implicit.Export.SymbolicObj3+ -- these are exported for implicitsnap.+ Graphics.Implicit.Export.TriangleMeshFormats+ Graphics.Implicit.Export.PolylineFormats+ Graphics.Implicit.Export.DiscreteAproxable - Other-Modules:+ other-modules: Graphics.Implicit.ObjectUtil.GetBox2 Graphics.Implicit.ObjectUtil.GetBox3 Graphics.Implicit.ObjectUtil.GetImplicit2 Graphics.Implicit.ObjectUtil.GetImplicit3 Graphics.Implicit.ExtOpenScad.Default Graphics.Implicit.ExtOpenScad.Parser.Util- Graphics.Implicit.ExtOpenScad.Parser.Statement- Graphics.Implicit.ExtOpenScad.Parser.Expr- Graphics.Implicit.ExtOpenScad.Definitions Graphics.Implicit.ExtOpenScad.Primitives Graphics.Implicit.ExtOpenScad.Eval.Statement Graphics.Implicit.ExtOpenScad.Eval.Expr Graphics.Implicit.ExtOpenScad.Util.StateC Graphics.Implicit.ExtOpenScad.Util.ArgParser Graphics.Implicit.ExtOpenScad.Util.OVal- Graphics.Implicit.Export.Definitions Graphics.Implicit.Export.MarchingSquares Graphics.Implicit.Export.MarchingSquaresFill- Graphics.Implicit.Export.SymbolicObj2- Graphics.Implicit.Export.SymbolicObj3 Graphics.Implicit.Export.RayTrace- Graphics.Implicit.Export.PolylineFormats- Graphics.Implicit.Export.TriangleMeshFormats Graphics.Implicit.Export.NormedTriangleMeshFormats Graphics.Implicit.Export.SymbolicFormats Graphics.Implicit.Export.Util@@ -111,18 +106,141 @@ Graphics.Implicit.Export.Render.TesselateLoops Graphics.Implicit.Export.Render.HandlePolylines -Executable extopenscad+executable extopenscad - Main-is: extopenscad.hs+ main-is: extopenscad.hs+ hs-source-dirs: programs+ build-depends:+ base,+ containers,+ vector-space,+ filepath,+ parallel,+ optparse-applicative >= 0.10.0,+ implicit ghc-options:- -O2 -optc-O3 -threaded -rtsopts- -funfolding-use-threshold=16 - -fspec-constr-count=10+ -Wall+ -O2+ -optc-O3+ -optc-ffast-math +-- FIXME: does not compile.+--Executable docgen++-- main-is: docgen.hs+-- build-depends:+-- base,+-- vector-space,+-- text,+-- JuicyPixels,+-- blaze-builder,+-- blaze-svg,+-- blaze-markup,+-- parallel,+-- deepseq,+-- vector-space,+-- monads-tf,+-- bytestring,+-- storable-endian,+-- parsec,+-- directory,+-- containers,+-- filepath,+-- snap-core,+-- snap-server,+-- silently,+-- transformers+-- ghc-options:+-- -optc-O3+-- -threaded+-- -rtsopts+-- -funfolding-use-threshold=16+-- -fspec-constr-count=10+ +executable implicitsnap++ main-is: implicitsnap.hs+ hs-source-dirs: programs+ build-depends:+ base,+ vector-space,+ text,+ JuicyPixels,+ blaze-builder,+ blaze-svg,+ blaze-markup,+ parallel,+ deepseq,+ vector-space,+ monads-tf,+ bytestring,+ storable-endian,+ parsec,+ directory,+ containers,+ filepath,+ snap-core,+ snap-server,+ silently,+ transformers,+ implicit+ ghc-options:+ -threaded+ -rtsopts+ -Wall+ -O2+ -optc-O3+ -optc-ffast-math++executable Benchmark++ main-is: Benchmark.hs+ hs-source-dirs: programs+ build-depends:+ base,+ text,+ JuicyPixels,+ blaze-svg,+ blaze-markup,+ parallel,+ deepseq,+ vector-space,+ monads-tf,+ blaze-builder,+ bytestring,+ storable-endian,+ parsec,+ directory,+ containers,+ filepath,+ criterion,+ transformers,+ implicit+ ghc-options:+ -threaded+ -rtsopts+ -Wall+ -O2+ -optc-O3+ -optc-ffast-math++test-suite test-implicit+ type: exitcode-stdio-1.0+ build-depends: base, mtl, containers, hspec, parsec, implicit+ main-is: Main.hs+ hs-source-dirs: tests++benchmark parser-bench+ type: exitcode-stdio-1.0+ hs-source-dirs: bench+ main-is: ParserBench.hs+ build-depends: base, criterion, random, parsec, implicit+ ghc-options:+ -Wall+ -O2 -optc-O3+ source-repository head type: git location: https://github.com/colah/ImplicitCAD.git--
+ programs/Benchmark.hs view
@@ -0,0 +1,81 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2014 2015 2016, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- Benchmarks++-- Let's be explicit about where things come from :)++-- Use criterion for benchmarking. see <http://www.serpentine.com/criterion/>+import Criterion.Main++-- The parts of ImplicitCAD we know how to benchmark (in theory).+import Graphics.Implicit (union, circle, writeSVG, writePNG2, writePNG3, writeSTL, SymbolicObj2, SymbolicObj3)+import Graphics.Implicit.Export.SymbolicObj2 (symbolicGetContour)+import Graphics.Implicit.Export.SymbolicObj3 (symbolicGetMesh)+import Graphics.Implicit.Primitives (translate, difference, extrudeRM, rect3R)++-- Haskell representations of objects to benchmark.++-- FIXME: move each of these objects into seperate compilable files.++obj2d_1 :: SymbolicObj2+obj2d_1 =+ union+ [ circle 10+ , translate (22,0) $ circle 10+ , translate (0,22) $ circle 10+ , translate (-22,0) $ circle 10+ , translate (0,-22) $ circle 10+ ]++object1 :: SymbolicObj3+object1 = extrudeRM 0 (Just twist) Nothing Nothing obj2d_1 (Left 40)+ where twist h = 35*cos(h*2*pi/60)++object2 :: SymbolicObj3+object2 = squarePipe (10,10,10) 1 100+ where squarePipe (x,y,z) diameter precision =+ union+ $ map (\start-> translate start+ $ rect3R 0 (0,0,0) (diameter,diameter,diameter)+ )+ $ zip3 (map (\n->(n/precision)*x) [0..precision])+ (map (\n->(n/precision)*y) [0..precision])+ (map (\n->(n/precision)*z) [0..precision])++object3 :: SymbolicObj3+object3 =+ difference+ [ rect3R 1 (-1,-1,-1) (1,1,1)+ , rect3R 1 (0,0,0) (2,2,2)+ ]++obj2Benchmarks :: String -> SymbolicObj2 -> Benchmark+obj2Benchmarks name obj =+ bgroup name+ [+-- bench "SVG write" $ writeSVG 1 "benchmark.svg" obj+-- , bench "PNG write" $ writePNG2 1 "benchmark.png" obj+-- ,+ bench "Get contour" $ nf (symbolicGetContour 1) obj+ ]++obj3Benchmarks :: String -> SymbolicObj3 -> Benchmark+obj3Benchmarks name obj =+ bgroup name+ [+-- bench "PNG write" $ writePNG3 1 "benchmark.png" obj+-- , bench "STL write" $ writeSTL 1 "benchmark.stl" obj+-- ,+ bench "Get mesh" $ nf (symbolicGetMesh 1) obj+ ]++benchmarks =+ [ obj3Benchmarks "Object 1" object1+ , obj3Benchmarks "Object 2" object2+ , obj3Benchmarks "Object 3" object3+ ]++main = defaultMain benchmarks+
+ programs/extopenscad.hs view
@@ -0,0 +1,239 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2014 2015, Julia Longtin (julial@turinglace.com)+-- Copyright (C) 2014 2016, Mike MacHenry (mike.machenry@gmail.com)+-- Released under the GNU GPL, see LICENSE++-- FIXME: add support for AMF.+-- An interpreter to run extended OpenScad code, outputing STL, OBJ, SVG, SCAD, PNG, or GCODE.++-- Enable additional syntax to make our code more readable.+{-# LANGUAGE ViewPatterns , PatternGuards #-}++-- Let's be explicit about what we're getting from where :)++-- Our Extended OpenScad interpreter, and functions to write out files in designated formats.+import Graphics.Implicit (runOpenscad, writeSVG, writeBinSTL, writeOBJ, writeSCAD2, writeSCAD3, writeGCodeHacklabLaser, writePNG2, writePNG3)++-- Functions for finding a box around an object, so we can define the area we need to raytrace inside of.+import Graphics.Implicit.ObjectUtil (getBox2, getBox3)++-- Definitions of the datatypes used for 2D objects, 3D objects, and for defining the resolution to raytrace at.+import Graphics.Implicit.Definitions (SymbolicObj2, SymbolicObj3, ℝ)++-- Use default values when a Maybe is Nothing.+import Data.Maybe (fromMaybe)++-- For making the format guesser case insensitive when looking at file extensions.+import Data.Char (toLower)++-- To flip around formatExtensions. Used when looking up an extension based on a format.+import Data.Tuple (swap)++-- Functions and types for dealing with the types used by runOpenscad.+-- Note that Map is different than the maps used by the prelude functions.+import qualified Data.Map.Strict as Map (Map, lookup)+import Graphics.Implicit.ExtOpenScad.Definitions (OVal (ONum))++-- Operator to subtract two points. Used when defining the resolution of a 2d object.+import Data.AffineSpace ((.-.))++-- NOTE: make sure we don't import (<>) in new versions.+import Options.Applicative (fullDesc, progDesc, header, auto, info, helper, help, str, argument, long, short, option, metavar, execParser, Parser, optional, strOption)++-- For handling input/output files.+import System.FilePath (splitExtension)++-- The following is needed to ensure backwards/forwards compatibility+-- Backwards compatibility with old versions of Data.Monoid:+infixr 6 <>+(<>) :: Monoid a => a -> a -> a+(<>) = mappend++-- A datatype for containing our command line options.+data ExtOpenScadOpts = ExtOpenScadOpts+ { outputFile :: Maybe FilePath+ , outputFormat :: Maybe OutputFormat+ , resolution :: Maybe ℝ+ , inputFile :: FilePath+ }++-- A datatype enumerating our output file formats types.+data OutputFormat+ = SVG+ | SCAD+ | PNG+ | GCode+ | STL+ | OBJ+-- | AMF+ deriving (Show, Eq, Ord)++-- A list mapping file extensions to output formats.+formatExtensions :: [(String, OutputFormat)]+formatExtensions =+ [ ("svg", SVG)+ , ("scad", SCAD)+ , ("png", PNG)+ , ("ngc", GCode)+ , ("gcode", GCode)+ , ("stl", STL)+ , ("obj", OBJ)+-- , ("amf", AMF)+ ]++-- Lookup an output format for a given output file. Throw an error if one cannot be found.+guessOutputFormat :: FilePath -> OutputFormat+guessOutputFormat fileName =+ maybe (error $ "Unrecognized output format: "<>ext) id+ $ readOutputFormat $ tail ext+ where+ (_,ext) = splitExtension fileName++-- The parser for our command line arguments.+extOpenScadOpts :: Parser ExtOpenScadOpts+extOpenScadOpts = ExtOpenScadOpts+ <$> optional (+ strOption+ ( short 'o'+ <> long "output"+ <> metavar "FILE"+ <> help "Output file name"+ )+ )+ <*> optional (+ option auto+ ( short 'f'+ <> long "format"+ <> metavar "FORMAT"+ <> help "Output format"+ )+ )+ <*> optional (+ option auto+ ( short 'r'+ <> long "resolution"+ <> metavar "RES"+ <> help "Approximation quality (smaller is better)"+ )+ )+ <*> argument str+ ( metavar "FILE"+ <> help "Input extended OpenSCAD file"+ )++-- Try to look up an output format from a supplied extension.+readOutputFormat :: String -> Maybe OutputFormat+readOutputFormat ext = lookup (map toLower ext) formatExtensions++-- A Read instance for our output format. Used by 'auto' in our command line parser.+-- Reads a string, and evaluates to the appropriate OutputFormat.+instance Read OutputFormat where+ readsPrec _ myvalue =+ tryParse formatExtensions+ where tryParse [] = [] -- If there is nothing left to try, fail+ tryParse ((attempt, result):xs) =+ if (take (length attempt) myvalue) == attempt+ then [(result, drop (length attempt) myvalue)]+ else tryParse xs++-- Find the resolution to raytrace at.+getRes :: (Map.Map [Char] OVal, [SymbolicObj2], [SymbolicObj3]) -> ℝ+-- First, use a resolution specified by a variable in the input file.+getRes (Map.lookup "$res" -> Just (ONum res), _, _) = res+-- Use a resolution chosen for 3D objects.+-- FIXME: magic numbers.+getRes (varlookup, _, obj:_) =+ let+ ((x1,y1,z1),(x2,y2,z2)) = getBox3 obj+ (x,y,z) = (x2-x1, y2-y1, z2-z1)+ in case fromMaybe (ONum 1) $ Map.lookup "$quality" varlookup of+ ONum qual | qual > 0 -> min (minimum [x,y,z]/2) ((x*y*z/qual)**(1/3) / 22)+ _ -> min (minimum [x,y,z]/2) ((x*y*z)**(1/3) / 22)+-- Use a resolution chosen for 2D objects.+-- FIXME: magic numbers.+getRes (varlookup, obj:_, _) =+ let+ (p1,p2) = getBox2 obj+ (x,y) = p2 .-. p1+ in case fromMaybe (ONum 1) $ Map.lookup "$quality" varlookup of+ ONum qual | qual > 0 -> min (min x y/2) ((x*y/qual)**0.5 / 30)+ _ -> min (min x y/2) ((x*y)**0.5 / 30)+-- fallthrough value.+getRes _ = 1++-- Output a file containing a 3D object.+export3 :: Maybe OutputFormat -> ℝ -> FilePath -> SymbolicObj3 -> IO ()+export3 posFmt res output obj =+ case posFmt of+ Just STL -> writeBinSTL res output obj+ Just SCAD -> writeSCAD3 res output obj+ Just OBJ -> writeOBJ res output obj+ Just PNG -> writePNG3 res output obj+ Nothing -> writeBinSTL res output obj+ Just fmt -> putStrLn $ "Unrecognized 3D format: "<>show fmt++-- Output a file containing a 2D object.+export2 :: Maybe OutputFormat -> ℝ -> FilePath -> SymbolicObj2 -> IO ()+export2 posFmt res output obj =+ case posFmt of+ Just SVG -> writeSVG res output obj+ Just SCAD -> writeSCAD2 res output obj+ Just PNG -> writePNG2 res output obj+ Just GCode -> writeGCodeHacklabLaser res output obj+ Nothing -> writeSVG res output obj+ Just fmt -> putStrLn $ "Unrecognized 2D format: "<>show fmt++-- Interpret arguments, and render the object defined in the supplied input file.+run :: ExtOpenScadOpts -> IO()+run args = do++ putStrLn $ "Loading File."+ content <- readFile (inputFile args)++ let format =+ case () of+ _ | Just fmt <- outputFormat args -> Just $ fmt+ _ | Just file <- outputFile args -> Just $ guessOutputFormat file+ _ -> Nothing+ putStrLn $ "Processing File."++ case runOpenscad content of+ Left err -> putStrLn $ show $ err+ Right openscadProgram -> do+ s@(_, obj2s, obj3s) <- openscadProgram+ let res = maybe (getRes s) id (resolution args)+ let basename = fst (splitExtension $ inputFile args)+ let posDefExt = case format of+ Just f -> Prelude.lookup f (map swap formatExtensions)+ Nothing -> Nothing -- We don't know the format -- it will be 2D/3D default+ case (obj2s, obj3s) of+ ([], [obj]) -> do+ let output = fromMaybe+ (basename ++ "." ++ fromMaybe "stl" posDefExt)+ (outputFile args)+ putStrLn $ "Rendering 3D object to " ++ output+ putStrLn $ "With resolution " ++ show res+ putStrLn $ "In box " ++ show (getBox3 obj)+ putStrLn $ show obj+ export3 format res output obj+ ([obj], []) -> do+ let output = fromMaybe+ (basename ++ "." ++ fromMaybe "svg" posDefExt)+ (outputFile args)+ putStrLn $ "Rendering 2D object to " ++ output+ putStrLn $ "With resolution " ++ show res+ putStrLn $ "In box " ++ show (getBox2 obj)+ putStrLn $ show obj+ export2 format res output obj+ ([], []) -> putStrLn "No objects to render."+ _ -> putStrLn "Multiple/No objects, what do you want to render?"++-- The entry point. Use the option parser then run the extended OpenScad code.+main :: IO()+main = execParser opts >>= run+ where+ opts= info (helper <*> extOpenScadOpts)+ ( fullDesc+ <> progDesc "ImplicitCAD: Extended OpenSCAD interpreter." + <> header "extopenscad - Extended OpenSCAD"+ )
+ programs/implicitsnap.hs view
@@ -0,0 +1,167 @@+-- Implicit CAD. Copyright (C) 2011, Christopher Olah (chris@colah.ca)+-- Copyright (C) 2014 2015, Julia Longtin (julial@turinglace.com)+-- Released under the GNU AGPLV3+, see LICENSE++-- Allow us to use explicit foralls when writing function type declarations.+{-# LANGUAGE ExplicitForAll #-}++{-# LANGUAGE OverloadedStrings, ViewPatterns #-}++-- A Snap(HTTP) server providing an ImplicitCAD REST API.++-- Let's be explicit about what we're getting from where :)++import Control.Applicative ((<|>))++import Snap.Core (Snap, route, writeBS, method, Method(GET), modifyResponse, setContentType, getRequest, rqParam)+import Snap.Http.Server (quickHttpServe)+import Snap.Util.GZip (withCompression)++-- Our Extended OpenScad interpreter, and the extrudeR function for making 2D objects 3D.+import Graphics.Implicit (runOpenscad, extrudeR)++import Graphics.Implicit.ExtOpenScad.Definitions (OVal (ONum))++-- Functions for finding a box around an object, so we can define the area we need to raytrace inside of.+import Graphics.Implicit.ObjectUtil (getBox2, getBox3)++import Graphics.Implicit.Definitions (SymbolicObj2, SymbolicObj3, ℝ)++import Graphics.Implicit.Export.TriangleMeshFormats (jsTHREE, stl)+import Graphics.Implicit.Export.PolylineFormats (svg, hacklabLaserGCode)++-- class DiscreteApprox+import Graphics.Implicit.Export.DiscreteAproxable (discreteAprox)++import Data.String (IsString)+import Data.Map.Strict as Map (lookup, Map)++import Text.ParserCombinators.Parsec (errorPos, sourceLine)+import Text.ParserCombinators.Parsec.Error (errorMessages, showErrorMessages)++import System.IO.Unsafe (unsafePerformIO)+import System.IO.Silently (capture)++import qualified Data.ByteString.Char8 as BS.Char (pack, unpack)+import qualified Data.Text.Lazy as TL (unpack)++main :: IO ()+main = quickHttpServe site++site :: Snap ()+site = route+ [+ ("render/", renderHandler)+ ] <|> writeBS "fall through"++renderHandler :: Snap ()+renderHandler = method GET $ withCompression $ do+ modifyResponse $ setContentType "application/x-javascript"+ request <- getRequest+ case (rqParam "source" request, rqParam "callback" request, rqParam "format" request) of+ (Just [source], Just [callback], Nothing) -> do+ writeBS $ BS.Char.pack $ executeAndExport+ (BS.Char.unpack source)+ (BS.Char.unpack callback)+ Nothing+ (Just [source], Just [callback], Just [format]) -> do+ writeBS $ BS.Char.pack $ executeAndExport+ (BS.Char.unpack source)+ (BS.Char.unpack callback)+ (Just $ BS.Char.unpack format)+ (_, _, _) -> writeBS "must provide source and callback as 1 GET variable each"++getRes :: forall k. (Data.String.IsString k, Ord k) => (Map k OVal, [SymbolicObj2], [SymbolicObj3]) -> ℝ+getRes (varlookup, obj2s, obj3s) =+ let+ qual = case Map.lookup "$quality" varlookup of+ Just (ONum n) | n >= 1 -> n+ _ -> 1+ (defaultRes, qualRes) = case (obj2s, obj3s) of+ (_, obj:_) -> ( min (minimum [x,y,z]/2) ((x*y*z )**(1/3) / 22)+ , min (minimum [x,y,z]/2) ((x*y*z/qual)**(1/3) / 22))+ where+ ((x1,y1,z1),(x2,y2,z2)) = getBox3 obj+ (x,y,z) = (x2-x1, y2-y1, z2-z1)+ (obj:_, _) -> ( min (min x y/2) ((x*y )**0.5 / 30)+ , min (min x y/2) ((x*y/qual)**0.5 / 30) )+ where+ ((x1,y1),(x2,y2)) = getBox2 obj+ (x,y) = (x2-x1, y2-y1)+ _ -> (1, 1)+ in case Map.lookup "$res" varlookup of+ Just (ONum requestedRes) ->+ if defaultRes <= 30*requestedRes+ then requestedRes+ else -1+ _ ->+ if qual <= 30+ then qualRes+ else -1+++getWidth :: forall t. (t, [SymbolicObj2], [SymbolicObj3]) -> ℝ+getWidth (_, _, obj:_) = maximum [x2-x1, y2-y1, z2-z1]+ where ((x1,y1,z1),(x2,y2,z2)) = getBox3 obj+getWidth (_, obj:_, _) = max (x2-x1) (y2-y1)+ where ((x1,y1),(x2,y2)) = getBox2 obj+getWidth (_, [], []) = 0++-- | Give an openscad object to run and the basename of+-- the target to write to... write an object!+executeAndExport :: String -> String -> Maybe String -> String+executeAndExport content callback maybeFormat =+ let+ showB True = "true"+ showB False = "false"+ callbackF :: Bool -> Bool -> ℝ -> String -> String+ callbackF False is2D w msg =+ callback ++ "([null," ++ show msg ++ "," ++ showB is2D ++ "," ++ show w ++ "]);"+ callbackF True is2D w msg =+ callback ++ "([new Shape()," ++ show msg ++ "," ++ showB is2D ++ "," ++ show w ++ "]);"+ callbackS str msg = callback ++ "([" ++ show str ++ "," ++ show msg ++ ",null,null]);"+ in case runOpenscad content of+ Left err ->+ let+ line = sourceLine . errorPos $ err+ showErrorMessages' = showErrorMessages+ "or" "unknown parse error" "expecting" "unexpected" "end of input"+ msgs :: String+ msgs = showErrorMessages' $ errorMessages err+ in callbackF False False 1 $ (\s-> "error (" ++ show line ++ "):" ++ s) msgs+ Right openscadProgram -> unsafePerformIO $ do+ (msgs,s) <- capture $ openscadProgram+ let+ res = getRes s+ w = getWidth s+ is2D = case s of+ (_, _, _:_) -> False+ (_, _:_, _) -> True+ _ -> False+ highResError = "Unreasonable resolution requested: "+ ++ "the server imps revolt! "+ ++ "(Install ImplicitCAD locally -- github.com/colah/ImplicitCAD/)"+ objOrErr = case s of+ (_, _, x:_) ->+ if res > 0+ then Right (Nothing, x)+ else Left highResError+ (_, x:_, _) ->+ if res > 0+ then Right (Just x, extrudeR 0 x res)+ else Left highResError+ _ -> Left $ msgs ++ "Nothing to render."++ return $ case (objOrErr, maybeFormat) of+ (Left errmsg, _) -> callbackF False False 1 errmsg+ (Right (_,obj), Nothing) ->+ TL.unpack (jsTHREE (discreteAprox res obj)) ++ callbackF True is2D w msgs+ (Right (_,obj), Just "STL") ->+ callbackS (TL.unpack (stl (discreteAprox res obj))) msgs+ (Right (Just obj, _), Just "SVG") ->+ callbackS (TL.unpack (svg (discreteAprox res obj))) msgs+ (Right (Just obj, _), Just "gcode/hacklab-laser") ->+ callbackS (TL.unpack (hacklabLaserGCode (discreteAprox res obj))) msgs+++
+ tests/Main.hs view
@@ -0,0 +1,8 @@+import Test.Hspec+import ParserSpec.Statement+import ParserSpec.Expr++main :: IO ()+main = hspec $ do+ describe "expressions" $ exprSpec+ describe "statements" $ statementSpec