step

    A high-level 3D modeling DSL and lossless STEP (ISO 10303-21) parser/serializer in MoonBit.

    cad
    step
    3d
    modeling
    components
    Download zip
    Author
    Version
    0.2.27
    License
    Apache-2.0
    Last updated
    yesterday
    Downloads
    1K

    #gmlewis/step (MoonBit)

    moonbit step mascot

    A 3D modeling DSL and lossless STEP (ISO 10303-21) parser/serializer in MoonBit. Describe parametric parts and assemblies with a fluent API, write exact B-Rep STEP files that open in CAD viewers and slicers, and parse or rewrite existing STEP files without losing entities the library does not model.

    • Pure MoonBit. Authoring models needs no external CAD kernel, OpenCASCADE, or Python dependency.
    • Deterministic. Pin the header timestamp and every export emits the same bytes, so generated parts are diffable and versionable.
    • Units and axes. Millimetres for lengths, degrees for rotations, Z up.

    #Install

    Requires the MoonBit toolchain; the module's preferred target is native. It is published on mooncakes.io as gmlewis/step:

    moon add gmlewis/step

    moon add records the resolved version in your moon.mod import { ... } block (for example "gmlewis/step@0.2.24"); edit that entry to change or pin a release. Add the packages you use to moon.pkg; aliases come from the last path component, so gmlewis/step/cad is @cad:

    PackageContents
    gmlewis/stepSTEP entity core: Entity, RawEntity, EntityId, Ref, fmt_num, step_str.
    gmlewis/step/cadModeling DSL, STEP/assembly/CSG writers, glTF and Blender backends, face queries.
    gmlewis/step/parsePart 21 tokenizer and parser.
    gmlewis/step/repository, header, entities/*Entity repository, HEADER section, typed entity families.
    gmlewis/step/components/*Parametric mechanical parts, mechanisms, and design families.
    gmlewis/step/cliArgument parsing and error-reporting helpers for programs.

    #Quick start

    moon.pkg:

    import { "gmlewis/step/cad", } pkgtype(kind: "executable")

    main.mbt:

    ///|
    async fn main {
    let design = @cad.Design::new(name="my-model")
    .add(
    @cad.Cuboid::new(20, 20, 20)
    .with_name("base")
    .with_color(@cad.Rgb::orange()),
    )
    .add(
    @cad.CalibrationChamferBlock::new(10, 10, 5, chamfer_size_mm=1.0)
    .with_name("top-part")
    .translate(z=20),
    )

    design.write_step(Some("model.step"), checked=true)
    }

    moon run .

    A small piece of the root package, exercised by moon test itself:

    ///|
    test "fmt_num emits ISO 10303-21 reals" {
    inspect(@step.fmt_num(2.0), content="2.0")
    inspect(@step.fmt_num(0.25), content="0.25")
    }

    Exporters are unchecked by default; checked=true refuses designs with error diagnostics. For runnable programs and a larger API tour see examples/README.md; for the parts library see components/README.md.

    #Modeling

    A Design holds a scene graph of SceneNodes: each node pairs a Shape with a name, color, and placement. Models are authored as intent (a cuboid at (10, 0, 0)) and compiled to STEP entities only when exported. Every builder returns a new value; nothing mutates a B-Rep.

    Available shapes include boxes and primitives (Cuboid, Cylinder, RevolvedProfile, ToroidalBend, ExtrudedArcProfile, PipeJunction), profile-based solids (ExtrudedProfile, ConicalExtrusion, ExtrudedBezierProfile, SweptProfile, ChamferedPrism, SocketedSolid), hardware forms (ConicalNut, SlitTube, AcornNut, SquareNut, SquareHoleWasher, TabWasher, HexHeadWasherFace, CalibrationChamferBlock, BevelGearBody), edge features (Fillet, Chamfer), booleans (Union, Difference), and ImportedStep. Prefer analytic primitives and seamless sweeps over polygon-sampled circles so the exported B-Rep stays exact.

    • Chain .with_name(), .with_color(), .translate(x=, y=, z=), and .rotate_x/y/z() to place a shape. A SceneNode evaluates rotations (Rz * Ry * Rx) before translation, regardless of call order.
    • Design::planar_faces() and @cad.cut_on_face(...) support face queries and sketch-on-face placement.
    • Programmatic text and vector artwork use @cad.load_font("baloo"); the font is vendored at assets/fonts/baloo.json.gz. Set MOONBIT_STEP_ROOT when the font is not in the working directory.

    #Profile helpers and fits

    Profile2D computes exact coordinates, so output depends only on your numbers:

    @cad.bolt_circle(6, 22.0) // 6 centers at radius 22.0
    @cad.grid_of_holes(3, 2, 20.0, 15.0) // centered, row-major centers
    @cad.point_on_circle(10.0, 90.0) // one point at an angle

    let profile = @cad.Profile2D::new(@cad.Profile2D::centered_circle(60.0))
    .with_hole_at(0.0, 0.0, 20.0) // central bore
    .with_bolt_circle(6, 22.0, 5.0, fit=@cad.Fit::Free) // radius 22, bore dia 5
    let plate = @cad.ExtrudedProfile::new(profile.outer, 8.0, holes=profile.holes)

    centered_circle(60.0) takes a diameter; bolt_circle, point_on_circle, and with_bolt_circle take a radius.

    Fit is the per-face clearance of a printed hole: Nominal (0.00 mm), Close (0.10), Free (0.25), and Press (-0.05, interference). A hole's diameter grows by 2 * per_face_mm. A fit changes the modelled void; it is not a printer compensation layer.

    #Components, assemblies, and mate connectors

    components/ supplies dimensioned fasteners, bearings, gears, T-slot profiles, motors, linear guides, mechanism envelopes, and a typed ParamSpec/ParamSet/DesignFamily API. Components expose named MateConnectors (bore, shaft, plane face, slot, thread, datum) placed on the exact contact plane, and MatePairs assemble two parts without manual offsets. Use Design::to_assembly_step() for an AP214 product structure or Design::to_instanced_step_string() to share one part definition across repeated instances. The full catalogue and command-line builders are in components/README.md.

    #Export

    Every format a design can be written to, with both the library API and the ./run-example.sh flag:

    FormatExtensionrun-example.shLibrary APIContents
    STEP (flat).step, .stpdefault, -o part.step, --step part.stepwrite_step(), to_step_file()Exact B-Rep; opens in CAD viewers and slicers.
    STEP (assembly).step—to_assembly_step(), to_instanced_step_string()AP214 product structure; instanced form shares one part definition.
    STEP (CSG).step—to_csg_step(), write_csg_step()Real CSG_SOLID / BOOLEAN_RESULT tree.
    STEP (evaluated).step--eval [path]to_step_evaluated(), write_step_evaluated()OCCT-trimmed B-Rep when the design has booleans; otherwise the flat B-Rep.
    STL.stl-stl [path], -o part.stl—Binary triangulated mesh for printers; derived from STEP.
    3MF.3mf--3mf [path], -o part.3mf—OrcaSlicer-ready package derived from STEP.
    PNG.png--png [path], -o part.png—Four-view preview (iso/top/front/side) derived from STEP.
    glTF.gltf--gltf [path], -o scene.gltfto_gltf(), to_gltf_file()Z-up preview mesh for web viewers.
    Blender scene.blend--blend [path], -o scene.blendcreate_blender_file()Editable scene with real booleans.
    Blender Python.py--bpy [path], -o scene.pyto_blender_python(), write_blender_python()Blender Python script.

    ./run-example.sh <example> [options] (a symlink to examples/run-example.sh) writes STEP by default, to stdout when no -o is given:

    ./run-example.sh --list # numbered and component examples ./run-example.sh 12 -o coil.step ./run-example.sh 12 -o coil.step -stl # no path: derives coil.stl ./run-example.sh 12 -o coil.step -stl mesh.stl # explicit STL path ./run-example.sh 12 --gltf # writes 12-bifilar-electromagnet.gltf ./run-example.sh 12 --help # example-specific parameters

    Every output flag takes an optional path, given as the next argument or after =. With no path, -stl, --3mf, and --png derive <step-basename>.<ext> beside the STEP file; --eval, --gltf, --blend, and --bpy write <example-name>.<ext> in the current directory. When no -o path is given, all of them use <example-name>.<ext>. -o/--out and --step need a path.

    All example programs — the numbered examples and the parametric component builders — register these flags through the shared examples/common output layer. Numbered examples use with_output_args plus one write_output_for (or write_output_evaluated_for) call; component builders use add_output_args plus write_alternate_output, which leaves their own STEP writer in place so .connectors.tsv sidecars and checked diagnostics are preserved. A new example needs only those two calls.

    -o/--out picks the format from the extension; --step is the explicit STEP spelling. Repeat -o for several outputs of different kinds; a STEP or derived output cannot be combined with .gltf/.blend/.py, because an example writes one output format per run. --eval needs solidcraft-cli or OCCT (occt-draw / DRAWEXE) only when the design contains booleans; a design without a boolean tree passes its flat B-Rep straight through. STL_DEFLECTION=<mm> sets the OCCT tessellation tolerance (default 0.05). STL and PNG previews use solidcraft-cli when available, otherwise OCCT (occt-draw / DRAWEXE); PNG compositing uses vectorcraft-cli or Inkscape. The glTF writer tessellates PLANE, CYLINDRICAL_SURFACE, and SURFACE_OF_LINEAR_EXTRUSION faces; designs built from other analytic surfaces report a clear export error. The Blender writers likewise reject unsupported shape families with a clear message. --view opens the model in SolidCraft (streaming a native script for examples that support --scScript), while --headless generates to /tmp (or the -o path) and prints the paths without opening a window. Component examples write a <step>.connectors.tsv sidecar with named mate connectors by default; suppress it with --no-connectors. ./run-example.sh --help lists every wrapper option.

    to_step_file_checked() and write_step(..., checked=true) refuse designs with error diagnostics; to_step_file_checked_result() returns Result[String, Diagnostic] for library callers that need to recover. Design::diagnostics() reports nominal booleans, dropped nested booleans, unresolved edge features, and empty solids.

    For byte-reproducible files, pin the FILE_NAME timestamp on the design intent: Design::new(...).with_timestamp("2025-01-01T00:00:00"). Every STEP exporter (flat, assembly, instanced, CSG, and evaluated) then emits the same bytes for the same invocation; without it the header carries the current time. Every generated STEP and 3MF file also records the library version (from get_version()) and the command line that produced it in its metadata, so files from different invocations are deliberately not byte-identical.

    #CAD kernel boundary

    This library is kernel-free by design. difference() and union_all() concatenate child faces into a valid closed nominal shell; they do not trim or subtract. Real boolean trimming, fillets and chamfers, tessellation, vendor part imports, and interactive edits belong to SolidCore / SolidCraft, the required CAD engine. Resolve a nominal model with --view, --eval, or write_step_evaluated(), then export from the engine for downstream work. The full tier boundary is in docs/boundaries.md.

    For a static vendor B-Rep in the flat output, use @cad.ImportedStep. Parse it with ImportedStep::from_string(step_text) (a Result), then place it in the design with .as_shape().with_name(...).translate(...). Design::compile() seeds the repository with the imported entity graph (ids and internal references intact) and bakes the node's rigid transform into the imported CARTESIAN_POINT / DIRECTION entities. Multiple imported files per design are supported. Imported geometry is placed exactly, never trimmed or repaired; ImportedStep::bounding_box() provides a bounding-box fallback.

    #Parsing STEP files

    ///|
    async fn parse_example(step_text : String) -> Unit {
    match @parse.parse_repository_from_string_result(step_text) {
    @parse.ParseRepositoryResult::Ok(repo) => {
    println("entities=" + repo.len().to_string())
    println(repo.to_step_file())
    }
    @parse.ParseRepositoryResult::Err(info) =>
    @cli.eprintln(@parse.format_step_parse_error(info))
    }
    }

    Parsing is lossless at the entity level: entities whose types are not modeled are kept as RawEntity and re-emitted verbatim, so parse → serialize → parse is idempotent. Repository offers get, add, insert_with_id, each, and to_step_file(). The serializer writes ISO 10303-21 reals with a mandatory decimal point and an upper-case E exponent.

    #Verification

    ./test-all.sh # moon fmt, moon info, moon test python3 scripts/validate_step.py part.step python3 scripts/validate_step.py --no-mesh part.step # syntax/topology only python3 scripts/validate_step.py --gmsh part.step # second mesher

    validate_step.py checks Part 21 syntax, #id references, per-shell edge usage and orientation, PLANE planarity, OCCT checkshape, and watertight tessellation (--no-mesh skips tessellation). OCCT is an optional development tool; the library itself has no native dependency. scripts/manage_examples.py all --validate --render validates and renders the registered numbered examples; components/examples/generate_all.sh covers the parametric builders.

    tools/inspect and tools/step-stats are pure-MoonBit utilities for inspecting in-memory scene graphs and STEP statistics; see tools/README.md.

    #API documentation

    Doc comments on every public declaration feed hover docs in editors and the command line:

    moon doc # static site into _build/doc/ moon doc --serve # ... served locally moon ide doc 'Sketch2D::rounded_rect' # signature + doc for one symbol moon ide doc 'Sketch2D' # a type and its methods moon ide doc '' # every symbol in the package

    moon info regenerates pkg.generated.mbti, the committed public-API surface; CI fails on unreviewed changes to it.

    #Repository layout

    PathContents
    cad/Intent-based DSL, shape compilers, STEP writers, analysis, glTF/Blender backends.
    entities/, parse/, repository/, header/STEP entity model, parser, repository, serializer.
    cli/Argument parsing and error-reporting helpers.
    components/Parametric parts, mechanisms, gears, assemblies, collision, catalogue, design-family API.
    examples/Runnable example programs (examples/README.md).
    tools/Inspection and STEP statistics utilities (tools/README.md).
    scripts/Validation, rendering, and example-management harnesses.
    tests/Cross-package integration tests.
    docs/Architecture boundary notes.

    #License

    Apache-2.0; see LICENSE. The vendored baloo font at assets/fonts/baloo.json.gz is SIL Open Font License 1.1 (license). Measured DIN 472 free-state outline data for the 10/14/16/18/24/28/32/40 mm sizes is derived from FreeCAD-parts_library and remains CC BY-SA 4.0; components/README.md has the attribution details.

    #Status

    Built and tested with this MoonBit toolchain:

    $ moon version --all moon 0.1.20261126 (ccd306a 2026-11-26) ~/.moon/bin/moon moonc v1.0.0-rc1+3c0520448 (2026-11-26) ~/.moon/bin/moonc moonrun 0.1.20261126 (ccd306a 2026-11-26) ~/.moon/bin/moonrun

    Entity

    pub(open) trait Entity {
    fn to_step(Self) -> String
    }

    EntityId

    pub(all) struct EntityId {
    value : Int
    }

    STEP entity instance id (#<id> in the file).

    Distinct from plain Int32 so entity ids cannot be confused with other integers. Ids are assigned sequentially by the repository on write.

    RawEntity

    pub struct RawEntity {
    name : String
    args : String
    }

    An untyped STEP entity captured verbatim from the source file.

    args is the raw argument list exactly as written in the file (including surrounding parentheses); to_step re-emits name + args unchanged, so unknown entities round-trip through a parse/write cycle losslessly. Compare with UnknownEntity, which marks references whose target type is not modeled yet.
    impl Entity for RawEntity

    RawEntity::new

    fn RawEntity::new(name : String, args : String) -> RawEntity

    Construct a raw entity from an entity name and its raw argument list.

    args must include the surrounding parentheses exactly as they should be re-emitted (for example "(#1,#2)").

    RawEntity::to_step

    fn RawEntity::to_step(self : RawEntity) -> String

    Ref

    pub(all) struct Ref {
    id : EntityId
    }

    Reference to another entity in the same repository, by EntityId.

    The type parameter is not tracked, mirroring the untyped #id reference syntax of STEP: type checking of references happens at the entity-decoder layer, not in Ref itself.

    UnknownEntity

    pub struct UnknownEntity {
    }

    Placeholder type for a STEP entity whose type is not modeled yet.

    Carries no data; it only marks "some entity exists here" where a typed representation is unavailable. Unlike RawEntity it does not round-trip the entity's content.

    TOL_1E12

    let TOL_1E12 : Double

    TOL_1E14

    let TOL_1E14 : Double

    TOL_1E15

    let TOL_1E15 : Double

    TOL_1E18

    let TOL_1E18 : Double

    TOL_1E2

    let TOL_1E2 : Double

    TOL_1E24

    let TOL_1E24 : Double

    TOL_1E3

    let TOL_1E3 : Double

    TOL_1E4

    let TOL_1E4 : Double

    TOL_1E6

    let TOL_1E6 : Double

    TOL_1E7

    let TOL_1E7 : Double

    TOL_1E8

    let TOL_1E8 : Double

    TOL_1E9

    let TOL_1E9 : Double

    fmt_num

    fn fmt_num(n : Double) -> String

    Format a double as an ISO 10303-21 real literal.

    Always emits a decimal point (1.0, never 1) and upper-cases the exponent marker; inputs with magnitude below 1e-12 are emitted as 0.0 so trigonometric residue stays out of exponent form. Non-finite inputs are not special-cased.

    get_version

    fn get_version() -> String

    Return the library version string, kept in sync with moon.mod by release tooling.

    step_str

    fn step_str(s : String) -> String

    Quote a string as a STEP string literal.

    Wraps s in single quotes and doubles every embedded apostrophe, as required by ISO 10303-21 string encoding. The result includes the surrounding quotes; it does not add them at use sites.

    unknown_entity_witness

    let unknown_entity_witness : UnknownEntity