@rulecad/cad

The command line at the centre: every measurement a variable with its rule, checks for printing and fit, previews, print files and links.

npm 0.8.0sourceMITNode >=20.6
npm install @rulecad/cad

See it

A project made with create-rulecad, checked with the published packages as this site was built:

$ npx cad check home/soap-tray
Soap tray 0.1.0
  ✓ files match their schemas
  ✓ every measurement is a variable
  ✓ 110 × 75 × 12 mm, fits the bed
  ✓ 6955.8 mm² flat on the bed
  ✓ no sloped overhangs past 45°; flat undersides are checked on their own
  ✓ one piece
  ✓ nothing starts in mid-air
  ✓ on the first layer, nothing printed in place stands within 0.6 mm of another part (the first layer spreads 0.15 mm each side)
  ✓ every layer lies within 45° and a line of the one below (sliced at 0.2 mm; flat undersides are checked on their own)
  ✓ no islands in 60 layers of 0.2 mm
  ✓ closed solid
  orientation: Flat side down on the bed. Walls are straight up, so it prints without supports.
The soap tray: front, side, top, bottom and three-quarter views, as cad preview draws them
$ npx cad rules home/soap-tray
length             110 mm         Long enough for a bar of soap
width              75 mm          Wide enough for a bar of soap
height             12 mm          = x1c.layer * 60  A whole number of layers
wall               1.68 mm        = x1c.line * 4  Four print lines: stiff, and no gaps between lines
floor              1.6 mm         = x1c.layer * 8  Eight layers under the ribs
rib_height         3 mm           = x1c.layer * 15  Holds the soap up out of the water
rib_width          1.68 mm        = x1c.line * 4  Four print lines
pitch              12 mm          Ribs this far apart: soap rests on several, water runs between
slot               3.1 mm         = 3 + x1c.hole_comp  Drain slots between the ribs, widened for how holes print small
margin             6 mm           Solid floor between the slots and the walls
x1c.bed            256 mm         Build volume is 256 × 256 × 256 mm  [spec: https://dyer.lafayette.edu/makerspace/bambu-lab-x1-carbon/]
x1c.nozzle         0.4 mm         Stock hardened steel nozzle  [spec: https://dyer.lafayette.edu/makerspace/bambu-lab-x1-carbon/]
x1c.line           0.42 mm        Bambu Studio's default line width for a 0.4 mm nozzle: walls are whole numbers of lines  [default: Bambu Studio 0.4 mm nozzle process profile]
x1c.layer          0.2 mm         Default layer height; heights that matter should be whole numbers of layers  [default: Bambu Studio 0.20 mm Standard profile]
x1c.wall_min       0.84 mm        = line * 2  Thinnest wall worth printing: two lines  [community: Common FDM practice]
x1c.hole_comp      0.1 mm         Printed holes and slots come out small: widen them by this much  [community: Common FDM practice; tune with a test print]
x1c.fit            0.2 mm         Gap between parts that slide together  [community: Common FDM practice; tune with a test print]
x1c.press          0.05 mm        How much smaller across a printed bore is than a bought part pressed into it, once printed (a ball bearing's outer race): hole_comp is added as well  [estimate: A reasoned guess, half a typical 0.1 mm hole error; measure it with the seats coupon (examples/bench/projects/benchmarks/objects/seats-coupon)]
x1c.slip           0.1 mm         How much larger across a printed bore is than a bought part that slides into it by hand, once printed: hole_comp is added as well  [estimate: A reasoned guess; measure it with the seats coupon (examples/bench/projects/benchmarks/objects/seats-coupon)]
x1c.print_flow     12 mm³/s       Average plastic laid per second over a whole print, walls, travel and all: for estimating minutes from a part's volume  [estimate: A rule of thumb for a 0.4 mm nozzle on default settings; check it against a real print's time]
x1c.print_gap      0.3 mm         Narrowest gap between parts printed in place, side by side, that still prints apart (a flexure and the frame round it, a shuttle in its slot): the gap each side, not the total  [estimate: A reasoned guess for a 0.42 mm line; measure it with the fit test plate (examples/bench/projects/launcher/objects/fittest)]
x1c.overhang       45 °           Steepest overhang from vertical that prints without supports  [community: Common FDM practice]
x1c.bridge         5 mm           Widest gap a flat underside can span with no support (the widest circle that fits in it)  [community: https://grandavehousing.calpoly.edu/news/iibambu-lab-x1-carbon-support]
x1c.support_gap    0.2 mm         = layer  Gap between a built-in breakaway support and the part: one layer, so it snaps off  [community: dmote-keycap printing advice (0.2 mm lift), https://cljdoc.org/d/dmote-keycap/dmote-keycap/0.8.0/doc/printing-advice]
…

Turn it round in the model page

Reference

The cad command: design physical things in JSCAD from rules you can trace, check them for printing and for fit, version them by what fits, share them as links, and export them for the printer (a 3MF in Bambu Studio's layout with each part on its own filament; an STL from the model's link). Every measurement in a design is a variable, and every variable says which rule it comes from: the printer, a standard (Cherry MX), or something you measured.

npm create rulecad my-designs        # a workspace with a soap tray to start from; or by hand:
mkdir my-designs && cd my-designs
npm init -y && npm pkg set type=module
npm install @rulecad/cad @jscad/modeling
npx cad new bathroom/soap-tray       # a design to start from: soap-tray.js (the shape) and .json (its variables)
npx cad check bathroom/soap-tray     # raw numbers in the design, then printability
npx cad preview bathroom/soap-tray   # six views as a PNG in .preview/ (needs Chrome or Chromium)
npx cad export bathroom/soap-tray    # a 3MF for your slicer, in exports/
npx cad link bathroom/soap-tray      # a link that opens the model in a browser (nothing is uploaded)

New here? The tutorial walks from an empty folder to a part of your own, checked against the thing it fits, in about twenty minutes. This page is the reference. The worked examples go on from there: parts, variants and a release, a lid on a hinge, a model measured into rules, an optimised arm, a board, and a mechanism printed flat, each tested as written.

rules/                     shared facts, one file per set: x1c.json (printer), mx.json (Cherry MX). A set from
                           @rulecad/rules is copied here the first time a design uses it: yours to keep and correct
projects/<project>/
  project.json             name, title, description, default material, printer, objects, filaments (AMS slots)
                           (schemas/project.schema.json; written by cad new <project>, changed by cad set <project>)
  objects/<object>.json    variables (value, unit, rule, source, label, show, interface, tweak), variants, parts
  objects/<object>.js      main(v): the shape, from variables only
  layouts/<name>.json      where the keys go, with each key's own properties (@rulecad/keyboard-layout)
  assemblies/<name>.json   objects placed together: to check a fit, or to print together
  CHANGELOG.md, prints.jsonl   release notes, and what was printed
cad.config.json            the workspace: printer, model page, targets
exports/ .preview/ .versions/ .cache/   generated (ignore them in git); .cache/builds holds built parts
npx cad rules bathroom/soap-tray                 # every variable, its rule and source
npx cad check bathroom/soap-tray --set width=60   # change variables that have a tweak range
npx cad variants keyboard/keycap                 # named sets of inputs: keyboard/keycap:legend-f
npx cad compare keyboard/keycap dsa legend-f     # two variants (or releases) side by side
npx cad import-kle layout.json keyboard/mine     # a layout from keyboard-layout-editor.com, into layouts/
npx cad clone <github link to a .kicad_pcb> sea_picro   # a published board's circuit, into rules/, to redraw by rules
npx cad measure cover.3mf --rules cover          # a model from elsewhere, measured into draft rules
npx cad measure beam.stl --profile profile-2020-mine   # a beam's profile from its maker's model or a DXF of its section
npx cad rules draft profile 2020-mine   # a beam's profile to fill from its maker's spec sheet; then cad rules check and draw
npx cad match legion-go/rail cover.3mf           # how closely a design matches that model, both ways

The keyboard examples below come from the project rulecad grew out of: a keycap, a switch plate, a case and their circuit boards.

Looking into a design, and changing it

npx cad values bathroom/soap-tray                # its variables, resolved (names after it pick some; --json)
npx cad why bathroom/soap-tray.wall              # what a value reads, down to the rules and their sources
npx cad set bathroom/soap-tray length=120        # change a variable, keeping the file's layout
npx cad set bathroom/soap-tray --new lip=3 --unit mm --rule "A lip to hold the soap"
npx cad add fit bathroom/tray-on-shelf --a tray.body --b shelf.body --min 0.2 --max 1 --note "Tray on its shelf"
npx cad check bathroom/soap-tray --json          # findings as data: each with a level, a code, its numbers

set and add (fit, joint, item, loop, pose) refuse an edit that leaves the file broken: its JSON, its schema, or variables that no longer resolve. Options go before or after the names; a misspelt command or option is refused by name. cad --version says which cad this is. Two switches for the tool itself: CAD_NO_CACHE=1 builds afresh, and CAD_TRUST=1 runs designs in the tool's own process (see Sandbox).

Projects and assemblies, by command

Every edit to a project's or an assembly's file has a command that makes it and checks it, so neither file need be written by hand, and a program (or a graphical front end) can drive the same edits:

npx cad new bench --title "A bench rig" --material PETG --printer x1c       # projects/bench/project.json
npx cad set bench material=PLA "filaments.legend.slot=2"                    # its own fields
npx cad new bench/rig --assembly --title "The rig"                          # an empty assembly that checks
npx cad new bench/box --assembly --frame box --inside 300,300,350 --profile 2020-misumi-hfs5 --join blind --feet levelling
npx cad add beam bench/rig --id x1 --profile 2020-misumi-hfs5 --from 0,10,10 --to 300,10,10
npx cad add guide bench/box --kind rail rail=rail-mgn12 carriage=MGN12H on=x3.top from=25 length=250
npx cad add load bench/box --mass 5 --at x3.top@50%
npx cad set bench/box frame.join.fitting=printed "frame.inside=[300,300,400]" loads.0.mass=8
npx cad move bench/rig x1 --at 0,10,40                                       # a beam by its ends: both move
npx cad remove bench/rig x1 --with-refs                                      # and the joins that name it
CommandWhat it writes
cad new <project> [--title] [--description] [--material] [--printer]project.json, PLA unless told; refused if it is there, or the printer has no rule set
cad set <project> field=value …A project's title, description, material, printer or filaments.<name>.slot; its objects are kept by cad new <project>/<object>
cad new <project>/<assembly> --assembly [--title] [--frame <kind> --inside x,y,z --profile <set> --join … --fitting … --feet … --caps …] [field=value …]An assembly, empty or a generated frame, expanded and checked before it is written; its project too, where there is none. A kind other than fit is refused (a mechanism is a fit with joints, a plate is written by cad plates)
cad add fit\|joint\|item\|beam\|loop\|pose\|fasten\|join\|guide\|load\|wire <project>/<assembly> --option … [field=value …]An entry, any field as field=value (motor.model=nema17 nests); every name it gives checked against the assembly's items, a generated frame's beams included
cad set <project>/<assembly> <address>=<value> …A field. An address is an entry's id and a field (x1.at, hinge.max), an entry by its place (joins.3.kind, fits.0.min), or a field of the assembly's own (title, frame.join, task.speed); a key with a dot in it goes in brackets and quotes (frame.supports["z1.a"])
cad move <project>/<assembly> <id> --at x,y,z \| --to <address> [--rotate x,y,z]An item to a point or an address (a beam placed by its ends moves both ends, as one), or a guide to another face (--to x4.top) or along its own (--at 40)
cad remove <project>/<assembly> <id \| list.n \| id.field> [--with-refs]An entry or a field; refused while other entries name it, listing them, unless --with-refs removes them too

A value is JSON where it is JSON (8, true, [300, 300, 400], {"kind": "bracket"}), a list in brackets without quotes ([1515-openbeam, 2020-misumi-hfs5]), and otherwise text; quote one with brackets or spaces for the shell. A text standing where an object is asked for is its kind: "join": "blind" is { "kind": "blind" }, so frame.join.fitting=printed keeps the blind.

Each command keeps the file's layout, checks the edit against the schema and against what it could break (a generated frame must still expand; a join's beams, a fit's parts, a fasten's items, a guide's beam, a joint's parent and child, a pose's joints, a wire's ends and route (its anchors, path joints and runs along a beam's slot), a loop's anchors, a load's joint and anchor, and a placed or mounted item's address must be there, in the entry changed and in every other entry that had them before), and refuses a bad one by name with nothing written: --json gives the refusal as { "error": { "code", "message", "file", "path", "refs" } }. --dry-run does it all and writes nothing. Done, it prints each change (set frame.feet: "levelling" → "foot") and the checks; --json gives { "command", "file", "written", "dryRun", "changes": [{ "op", "path", "before", "after" }], "findings" }, the findings in the kit's one shape. A generated frame's beams are not in the file, so cad set and cad move refuse them by name (edit.generated): change the frame's own fields, or write it out with cad frame <ref> --expand first.

RefusalWhen
project.exists, assembly.existscad new of one that is there, or a field given to cad new <project> or --material or --printer given to cad new <project>/<assembly> --assembly that differs from the project's own (they are the project's: cad set <project> material=PETG, as the refusal names). Fields that match it change nothing and pass, so a step can run twice. Where the project is not there, the assembly makes it with them, each checked as cad new <project> checks it
project.printerA printer with no rule set
project.materialA material printed fittings cannot be sized from: anything but PLA, PETG or a rule set in rules/ giving strength, modulus and density. Every frame command reads the project's material as it builds the joins, guides and panels, so one it cannot read would stop them all
edit.kindAn assembly kind other than fit
frame.refusedA generated frame the generator refuses (a portal with nothing holding its feet, an end-tap join its profile cannot take)
edit.address, edit.ambiguous, edit.generatedAn address nothing has, an id two lists share, a generated frame's part
edit.part, edit.incomplete, edit.duplicateA name that is not in the assembly, an entry missing what it needs, an id already taken. A name the build makes counts as there only where an entry makes it, by its exact pattern: a repeated item's copies (key-0, key-0-3), a mounted item's mount (psu-mount), a panel's clips, hinges, leaves, handle and catch, a levelling foot's pad, a join's fitting (y1-x1-bracket), a wire's clips, a guide's parts (g1-carriage-1) and joints (g1-1, door-hinge). So rail-3 is no name where rail is one beam
edit.referencedcad remove of what other entries name (each listed in refs)
edit.renumbercad remove of a guide while guides after it have no id of their own: they are named g1, g2 .. by place, so they would be renamed
edit.danglingAn edit that leaves another entry naming what is no longer there: a beam renamed or removed that a join, a load, a wire or a mount names, a frame changed or removed whose beams a join or a guide uses (each listed in refs). A name that was already missing before the edit is left to cad check
edit.moveA move its entry cannot take (a beam placed by its ends sent to an address)
schemaThe edit leaves the file outside its schema

The workspace

The workspace is $CAD_WORKSPACE, else the nearest folder at or above the current one with a cad.config.json, else the current folder:

{ "printer": "x1c", "viewUrl": "https://…/", "targets": { "show": "targets/show.mjs", "shorten": "gist" } }

Links

cad link <project>/<object> (and cad show) prints three links to the model page (viewUrl; a public one by default): view the model in a browser, or download its STL or 3MF as soon as the link opens. The model travels in the link's fragment, which never reaches the web host, so the public page can open private designs. A link records exactly which version it holds (keyboard/keycap@0.1.0, or +changes if it isn't a release). The page is @rulecad/viewer: host your own copy anywhere and name it in viewUrl.

Variables

"slot_arm": { "value": "mx.slot_arm + x1c.hole_comp", "unit": "mm", "rule": "Cross slot arm: spec plus hole compensation",
              "label": "Slot arm", "show": true, "interface": true }

Versions

Every object has its own semver version, kept as a git tag (keyboard/keycap@1.2.0), so any release can be rebuilt (cad export keyboard/keycap@1.0.0). cad release compares the design with its last release and suggests the bump:

A lower --bump than the changes need is refused (--force overrides). Releases are logged in the project's CHANGELOG.md. A project release (cad release keyboard) records the version of each object, and its bump is the biggest of theirs. cad printed logs what you printed and how it came out in prints.jsonl; cad history shows releases and prints together.

npx cad status                                     # versions, and what has changed since
npx cad release keyboard/keycap -m "Looser slot" --dry-run    # see the suggested bump
npx cad release keyboard/keycap -m "Looser slot" --push
npx cad release keyboard --all -m "Legends" --push   # every changed object, then the project
npx cad printed keyboard/keycap --result failed --note "slot too tight" --material PETG
npx cad history keyboard/keycap
npx cad diff keyboard/keycap 1.0.0 1.1.0

Parts

main() can return named parts instead of one shape, described in the .json:

"parts": { "cap": { "label": "Keycap" }, "pillar": { "role": "support", "label": "Breakaway pillar" } }

A support part is printed and then removed (a breakaway pillar, a brim tab). Checks, exports and links use every part; previews and the model page draw supports faint, so what they hold up shows through; cad show leaves them out. --part cap works on one part; cad preview --explode moves the parts apart.

Models from elsewhere

To fit something someone else made (a maker's connector, a part from a model site), measure their model rather than guessing, then check your design against it.

cad measure <model.stl|model.3mf> finds the stretches along the model's longest axis (or --along y) where its cross-section stays the same, numbers the distinct sections (a section seen again gets the same letter), and describes each one: its extent and its height bands, the heights over which it has the same pieces across, split again at steps. It draws every distinct section in .preview/measure/. --line 0.6,2.5 reports where a line along the axis is inside the model (where notches start and stop); --at 10,50 adds sections there. --rules <name> writes the numbers as a draft rule set, every value kind: derived with the file, --source and --licence it came from: rename the placeholder names (stretch3_from, sectionB_w) for what they are before a design uses them. Sections are compared by shape, within 0.05 mm, so a curve faceted differently along its length is still one section.

cad match <project>/<object> <model> lays the model over the design (trying every quarter turn whose size fits, then shifting it onto the design's surface; --place "rz90 t1,2,3" pins it) and samples both surfaces: how far the design is from the model, and the model from the design, signed (outside: extra material; inside: missing material, or a clearance you meant). It passes when everything is within --tol (the printer's sliding fit by default), warns when only the worst 5% is past it, and fails otherwise, listing the worst places. The pictures show the model over the design, and sections through the worst places with the model dashed. Deliberate differences (a clearance on sliding faces) show up as an even offset: set --tol above them.

A model's licence limits what you make from it, not what you learn: measurements are facts, but a non-commercial or share-alike model's shape shouldn't be copied into a design under another licence. measure warns about those.

A beam's profile from its maker's model. cad measure <beam.stl|beam.3mf|section.dxf> --profile <name> reads an aluminium extrusion's section and writes it as a profile rule set, for a beam the kit has no set for:

npx cad measure hfs5-2020.stl --profile profile-2020-mine --source https://example.com/hfs5-2020 --licence "the maker's terms"
It doesHow
Takes the sectionFrom a model: across its longest axis (or --along y), in the middle of the longest stretch that keeps one cross-section. From a DXF: its LINE, LWPOLYLINE (with bulges), ARC and CIRCLE entities, joined into closed loops; inches, centimetres and metres are turned into mm. A SPLINE, an ELLIPSE or a block is refused by name: export the section as lines and arcs
Finds each slotOn every face: the opening at its narrowest, the lip's thickness at its tip, the width under the lips, the depth, the floor's width and the flanks' angle, and a V mouth (track_width, track_angle) where there is one. An opening with no room under lips is told as a groove, or as the channel of a C section
Finds the boresRound holes at the middles of the cells are the profile's bores; other round holes and hollows are listed, and stay in the outline
Names the slot familyThe known family (the kit's, or your workspace's) whose opening, lip, width and depth are all within --tol (0.1 mm) of what was found; where none is, a new family is drafted as rules/slot-<opening>-<name>.json
Writesrules/<name>.json, a draft profile with every figure derived and carrying the source and licence; rules/outlines/<name>.json, the section itself; .preview/measure/<name>-profile.svg (and .png), the section with each slot and bore marked and listed, to check against the bar in hand

Then cad rules check <name> and cad rules draw <name>, which use the measured outline in place of a drawn one, and add what a model cannot say: the maker, the alloy, a material set for its mass, the thread its bore taps to. The outline is the model's shape, so it goes into your own workspace and nowhere else: the kit publishes no maker's outline, and under a non-commercial, no-derivatives or share-alike licence the command says to keep it there.

A beam's profile from its spec sheet. cad rules draft profile <name> writes rules/<name>.json with every field a profile can have, each with a starting value, "kind": "estimate", a rule saying what the field is and a source that starts DRAFT (cad rules draft slot <name> and slot_nut <name> do the same for a slot family and a slot nut). Fill each field the sheet gives (its value, "kind": "spec", the sheet and page as source, the date as checked) and delete the rest. cad rules check <name> then holds it to the vocabulary, draws the section from its dimensions and its slot family's, and warns where the sheet's area, second moments or mass per metre differ from the drawn outline's by more than 5% (profile.section.*: check the typed figure first; if it is right the drawing lacks a shape, such as corner hollows, and the frame checks use the sheet's figures anyway); while any field's source is still the draft's it warns rules.draft, naming each. cad rules draw <name> writes <name>.svg, the section to scale with each slot and bore dimensioned, to hold against the sheet's drawing. The frames guide walks one from a sheet to a checked box.

Assemblies

projects/<project>/assemblies/<name>.json places objects together. Positions are expressions over rules and the other items' variables, so a keycap can sit exactly where its slot meets the switch stem:

{ "title": "Keycap on an MX switch", "kind": "fit", "uses": ["mx", "x1c"],
  "requires": { "keycap": "^0.2.0" },
  "items": [ { "id": "switch", "object": "mx-switch" },
             { "id": "cap", "object": "keycap", "at": [0, 0, "switch.housing_top - cap.lift"] } ],
  "fits": [ { "a": "cap.cap", "b": "switch.stem", "min": "-x1c.hole_comp", "max": "x1c.fit", "note": "Slot over the stem" } ] }

Screwed joints: fasten

A joint held by screws is one relation, and it knows the screw:

"fasten": [
  { "screw": "M3 cap", "through": ["bracket"], "into": "base", "at": ["bracket.h1", "bracket.h2"] },
  { "screw": "M3x16 cap", "through": ["cover", "frame"], "into": "frame-back", "holes": "cover.body", "nut": true, "washer": true }
]

screw names the thread and head as @rulecad/fixings reads them (M3 cap, M4 button, M3x12 countersunk, 6-32 UNC cap). through lists the parts the screw passes, in order from under its head, and into is the part it ends in. The screws' places are given one of two ways: at, an anchor on each screw's axis (a point on the hole's centre line, the anchor's axis along the screw), or holes, a part whose own round holes are the places (for a circuit board, its mounting holes). nut (true, hex, square or lock) says a nut holds the screw where the last part does not; washer puts a plain washer under the head; length gives the length where the name has none; torque gives the tightening torque in N m. A screw across a yoke or a split clamp ends in the part under its head: name that part first in through and again as into ("through": ["fork", "block"], "into": "fork", "nut": true), and place each screw with at, an anchor whose axis points from the head into the part. Along the axis, the part's first stretch of material is the side under the head, and the rest is the far side. Add one with cad add fasten <project>/<assembly> --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2.

Nothing about the holes is declared. Each part is read as drawn: along the screw's axis the mesh is sliced, and the outline round the axis gives the hole's centre, its diameter (across its corners, as it was drawn) and where it starts and stops. From that the check says:

FindingWhat it checks
fasten.holesOne axis runs from under the head through every part: a hole 0.05 mm or more off it fails, with the distance
fasten.slotInto a beam's slot: each screw over a slot's centre line within its hole's play, square to the face and along the beam (see Fastening into a slot, under Beams)
fasten.clearanceEach part passed through has a clearance hole for the thread as drawn on this printer, between the close and the loose figure; it says what the hole measures and what it should be
fasten.endThe far end is a pilot, a hole to tap, a thread drawn to print, an insert's hole or a nut's seat of this thread (a pocket on the far face, or a slot across the screw partway along it, as v.fixings.nutTrap cuts), or a clearance hole with nut; into a motor, one of its own threaded mounting holes
fasten.lengthThe length chosen where none is given: the shortest sold length that fits the stack as measured (into a motor, the longest that stops short of the end of its thread). A given length is checked for reaching the far end, bottoming out in a blind hole (1 mm is kept at the tip) and standing more than a diameter proud
fasten.engagementThe thread engaged at the far end against the rule for what it is in: the thread's pilot_depth or the engagement rule for the project's material, an insert's length, a nut's height; into a motor, its own thread's depth, and at least one diameter (engagement.steel, as motor.mount holds it). A short one names the length or the depth that would do
fasten.seatThe head (or its washer) has a flat seat as wide as itself and square to the screw, read under the head from the part; a countersunk head has a countersink of its angle. It says the force and torque the seat takes on the project's material (and, for a screw in a thread in plastic, the less torque that clamps with half what the thread is estimated to strip at), and with torque holds the pressure against the material's strength and names the washer that would bring it within
fasten.torqueA printed bolt given a torque: the clamp it is turned to (T = K d F with steel's nut factor, an estimate for a printed thread) held against what the bolt breaks at, about twice over (fixings.load_margin); a turn that would break it fails, naming the most to turn it to
fasten.accessA key or driver reaches the head along its axis, in the build pose: a cylinder as wide as the key across its corners, as long as its long arm (both from the hexkey set, ISO 2936; a hexagon head's socket adds hexkey.socket_wall, an estimate), clear of every other part. A part over the head that goes on after the screw passes, with the step it goes on at: cad order puts it after. One that must be there first (it comes earlier in the order, it is one of the joined parts, or it is no step at all) fails by name with how far over the head it is; where a ball-end key tilted up to hexkey.ball_end_tilt (25°) clears it, it warns instead
fasten.loadWith loads or a motor's torque on the joint: what it holds up (the parts left with no other way to the first item, their masses, the loads hung on them, under the assembly's gravity, and the torque of a motor among them), shared between the screws as a group (screwGroup of @rulecad/fixings: shear by distance from the centroid, pull by a plane through it). The screw that takes the most is held against its proof load, the thread it is in against stripping, and the clamp against slipping, at its preload (screwLoad); the margin is how many times the load it holds (for the thread, how many times the preload and the pull together), and under 2 it warns. With no torque, it says the torque that leaves the thread twice the preload and the pull, within half what the seat takes, so never more than half what the thread is estimated to strip at, and cad order tightens to that. It names the estimates it rests on (the nut factor, a plastic's shear strength, the friction)

Every finding has at (under the head) and between (head to tip), so the viewer points at the screw. The screws, nuts, washers and inserts are placed as reference parts from @rulecad/fixings: faint in previews, lifted along their own axes by --explode, checked for overlap with everything but what they are threaded into, moving with the part they sit in through every pose, and carried in links. cad list counts them and cad order names them on the step. A fasten holds its parts as a fit with "fastens": true does and lines their holes up as a holes fit does; both older forms still work, and an assembly with no fasten checks as before.

From the older forms. A holes fit and a fit with "fastens": true between the same two items said apart what one fasten says, and neither knew the screw. cad check names the pair in a note (fasten.suggest) with the entry to paste: { "screw": "M2 cap", "through": ["pcb.board"], "into": "case.body", "holes": "pcb.board" }. The screw is read from the fit's fastener (M2x6), else from a thread set the holes fit's depth names (m2.insert_length), else from the board's holes as drawn: the largest metric thread narrower than the narrowest hole. cad add fasten <project>/<assembly> --from-fits writes it in their place: the holes fit goes, the fit that fastens keeps its gap range (min, max) with fastens, fastener and count taken off, or goes too where it had no range. --screw "M2x8 countersunk" gives another screw. Screws driven from below ("direction": "up") are left for you to write.

cad list counts every fixing (fasten.count): each screw, nut, washer and insert a fasten placed (a component's too), a motor's mounting screws where a fit that fastens holds it (as many as its holes, at the length its mount works out for the plate as drawn, taken to a length sold), and a fit that names its fastener by hand (pins, a clip: anything that is not a screw, since a screw is a fasten's, which knows its length). They are summed by name, which is the thread, length and head (12 × M3x8 cap), each with its mass (an estimate from its outline, from @rulecad/fixings) and the line's, and rounded up to whole packs of packs.pack (10, an estimate: set your own in rules/packs.json) with the spares said. --json gives each line as { fastener, qty, kind, thread, length, head, grams, mass, packs, buy, spare, from }, the totals add fixingsGrams to the machine's mass, and the build page's list shows the same.

Pins, magnets and printed bolts

Two parts held with no steel screw are a fit with "fastens": true whose fastener names what holds them, in a form the schema defines, so it is found, checked and counted as a screw is. Each is sized by @rulecad/fixings, which draws its hole or pocket from the printer's rules:

{ "a": "lid", "b": "box", "fastens": true, "fastener": { "pin": "snap pin 4x6", "count": 2, "pull": 5 } }
{ "a": "lid", "b": "box", "fastens": true, "fastener": { "pin": "dowel 3x12", "count": 2, "fit": "press", "load": 30 } }
{ "a": "lid", "b": "box", "fastens": true, "fastener": { "magnet": "disc magnet 8x3", "count": 2, "load": 10 } }

cad list lists pins (printed, cut or bought) and magnets (bought) with their grams, and printed bolts among the printed parts; cad order names each on its step. A fastener given as text ("fastener": "push pin") is listed as written, unchecked. The fits these rest on (x1c.snap_clearance, pin_press, pin_slip, magnet_press, magnet_glue, magnet_crush, and a plastic's strength_z) are estimates until the holds coupon measures them: examples/bench/projects/benchmarks/MEASURE.md, rows 40 to 47, and cad measured benchmarks/fixings-test x1c.pin_press=<figure>, which refuses a figure no fit of its kind can be.

Joints and poses

Things that move (a lid, a hinged screen, a drawer, a ball head) are one assembly with joints, not one assembly per position. An object names its anchors in its .json, as expressions over its own variables: a point, with an axis.

"anchors": { "pivot": { "at": ["width / 2", 0, "height"], "axis": [1, 0, 0] } }

A joint ties an anchor on its child item to one on its parent item. At value 0 the two anchors lie together, and the joint's value moves the child from there. A joint's child has no at or rotate: the joint places it.

"joints": [
  { "id": "lid", "type": "revolute", "parent": "case.pivot", "child": "lid.pivot", "min": -180, "max": 0, "label": "Lid" },
  { "id": "lid_r", "type": "revolute", "parent": "case.pivot_r", "child": "stay.pivot", "follow": "lid" }
],
"poses": { "shut": { "lid": 0 }, "open": { "lid": -110 } }
TypeValuesFor
fixednonea part bolted on in a set place
revoluteanglehinges, pivots
prismaticdistancestraight rails, drawers
cylindrical[angle, distance]a pin that turns and slides in a slot
ball[x, y, z] anglesball joints; "cone": 30 limits how far the child's axis may tip
pathdistancecurved rails: "path": [[x, y, z], …], a polyline in the parent anchor's frame, the child's axis along it

Angles are in degrees about the anchor's z axis (its axis); distances are in mm along it. A ball turns about x, then y, then z, as rotate does.

Motors

An item can be a motor instead of a printed object: { "id": "drive", "motor": { "model": "nema17", "drives": "elbow" }, "at": […], "rotate": […] }. It comes from @rulecad/motors, is bought and not printed (a reference, in the assembly but never on a plate), and its anchors (shaft, tip, face, horn, hole1 …) work in joints like any other. set changes a figure ({ "holding_torque": { "value": 0.5, "kind": "measured", "source": "…" } }), speed is the motor's speed (rpm), margin how many times over the torque must be (2 by default), duty the share of the time it runs.

Beams

A frame is beams and the joins between them, every beam a profile from a rule set and every join declared, so its drilling, screws and stiffness follow. The frames guide walks one from a spec sheet to a checked box; this section is the reference. In commands:

CommandWhat it does
cad rules draft profile <name>, cad rules check <name>, cad rules draw <name>A profile from its spec sheet, checked and drawn (Models from elsewhere, above)
cad measure <beam.stl> --profile <name> (or a DXF)A profile from the maker's model or a DXF of its section
cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0A beam placed by its ends
cad add join <project>/<assembly> --kind blind --a y1.a --b x1.back@120Two beams joined (Joins, below)
cad new <project>/<assembly> --assembly --frame box --inside 300,300,350 --profile 2020-misumi-hfs5A generated frame, expanded and checked as it is made (A frame from a size, below)
cad set, cad move, cad removeA frame's fields, a beam moved by its ends, a beam taken out (refused, naming them, while joins use it) (Projects and assemblies, by command, above)
cad frame <project>/<assembly>A generated frame's beams and joins (--expand writes them out; --size chooses the lightest profiles)
cad check <project>/<assembly>The joins, screws and nuts, then the frame solved: frame.deflection, frame.stress, frame.buckling, frame.rack, frame.frequency, frame.square, frame.heat, beam.printable; --sweep slides each guide through its travel
cad list, cad beams (--jigs), cad order, cad plates, cad kitThe cut list and what to buy, a sheet per beam and the jigs, the build from bars to a square frame, the printed parts on plates, and all of it in one folder (Building it, below)
cad measured <project>/<assembly> frame.square.<bay>=<mm>A squared bay's diagonal difference, measured; the joint rig's and the beam coupon's figures the same way

Guides (rails, V-wheels, rods, a printed slider, a lead screw) put motion on a beam: Guides, below.

An item can be a beam, a length of an aluminium extrusion, a tube or a bar from @rulecad/frames:

{ "id": "x1", "beam": { "profile": "2020-misumi-hfs5", "length": 300 }, "from": [0, 0, 0], "to": [300, 0, 0], "roll": 0 }

Every beam has addresses, taken wherever an anchor is: an item's at, a joint's parent or child, a loop, a fit's a or b, a fit's access, and a load's at.

AddressWhere
x1.a, x1.bThe middle of each end, its z out of the end
x1.a.1, x1.b.2A bore in an end
x1.top, x1.top.2A face's first and second place (a slot, or the face where it is closed), at the middle of the beam
x1.top@120, x1.top@-20, x1.top@50%120 mm from end a, 20 mm from end b, half way along
x1.top.2@120The second slot of a face that has more than one

A face's anchor has its z out of the face and its x along the beam toward b. An item placed at an address ({ "id": "plate", "object": "plate", "at": "x1.top@50%" }) puts its own origin there, its z out of the face and its x along the beam, turned by its rotate in that frame; it moves with the beam. A distance past either end is refused with the beam's length: "top@320" is past the end of profile-2020-misumi-hfs5 x 300: it is 300 mm long. In a fit, an address stands for the faces near it, as item@anchor does ("within", 10 mm by default).

Joins. "joins" says how beams are held to each other. Each names an end of one beam (a), a place on another (b: a face with a distance where a's end meets it, or an end for a splice, a mitre or a corner) and its kind:

"joins": [{ "kind": "blind", "a": "y1.a", "b": "x1.back@120" }]

The frame solved. cad check solves an assembly that has joins (or a "frame") as a frame of beam elements (@rulecad/fea/frame) and reports six findings:

FigureFormulaSource
Sag limit with nothing tighterspan / 360International Building Code, Table 1604.3, floor members under live load (as reproduced in 780 CMR 1604.3)
Beam stress\|N\| / A + \|My\| / Wy + \|Mz\| / WzBeam theory; the section moduli from the profile's rule set
A beam in compressionP = π² E I / L² (both ends pinned)Euler's column; Roark's Formulas for Stress and Strain, 7th ed., table 15.1, case 1a
A printed fitting's momentdesign load × its distance from the corner × its marginThe fitting's own finite-element margin at its design load, scaled linearly
The solveTimoshenko beam elements, end springs condensed out@rulecad/fea/frame (its README lists its sources)
Sway limit with nothing tighterheight / 400ASCE/SEI 7-22, Commentary to Appendix C, CC.2.2: drift limits in common use are 1/600 to 1/400 of the height
Racking stiffnesspush / mean sway of the top cornersDefinition; each change solved in the model, not estimated
A panel's bar along its diagonal d (bay a by h, sheet t)G t d² / (a h), in series with d² n k_c / (4 (a + h)²) for n clips of k_c eachShear of a plate, γ = τ / G; the clips by their strain energy under a shear flow F / a round the edges
A sheet's GE / 2(1 + ν): acrylic 3300 MPa, ν 0.37Evonik PLEXIGLAS GS technical information (polycarbonate and aluminium: typical figures, marked community)
A move's frequency1 / t, t = speed / accelA working figure (frame.ramp); the lowest mode wanted at twice it
A stepper's full-step raterpm / 60 × 360 / step angleThe motor's step angle and its working speed (workingSpeed)
A beam fixed at both ends, mass M at its middle (the check of the modal solve)f = (1/2π) √(192 E I / (L³ (M + 0.375 m)))Blevins, Formulas for Natural Frequency and Mode Shape (1979), table 8-8
A beam fixed at both ends, load P at its middle (the check of a guide's sag in the error budget)P L³ / (192 E I)Roark's Formulas for Stress and Strain, table 8.1, case 1d
A bay's diagonal difference to accept (frame.square)Σ t × span / d over the beams that set the opening, plus Σ s × span / d over its joins; root-sum-square beside itThe derivative of d = √(w² + h²) with a side, ∂d/∂w = w / d; stacked as an arm's error budget stacks its joints
A join's play s (frame.square)0.1 to 0.3 mm by kind; end-tap 0.25 mmJOIN_PLAY in @rulecad/frames, estimates; end-tap is half ISO 273's medium clearance for M5 (5.5 mm)
A beam's twist at the tooltwist per metre × length × π / 180 × the tool's distance from the beam's axisThe profile's twist_per_metre (MISUMI's JIS special grade figure for its 2020 HFS5)
A frame's growth (frame.heat)α L ΔT, α = 23.4e-6 /K6063 aluminium (Wikipedia's table; suppliers' 6063-T5 sheets 23.4 to 23.5 µm/m °C), a community figure where the alloy's set gives none
A printed beam's creep limit0.15 × its strength for its poseWaseem et al. (2020), Polymers 12, 2962: printed PLA held at 0.3 of its strength broke in 1.2 to 2.3 hours; half that share an estimate
A printed beam's sag as it creepsthe frame solved with its modulus × 0.5An estimate (PRINTED_DEFAULTS.creep_modulus), until a sustained load on the beam coupon measures it
The beam coupon's sag, between two bars L apartF L³ / (48 E I)Roark's Formulas for Stress and Strain, table 8.1, case 1e (simply supported, load at the middle)
The beam coupon's modulus and strengthE × sag predicted / sag measured; stress of its own weight + stress per kg × kg at breakThe solve is linear in E and in the load
A printed fitting's softeningthe plastic's heat deflection temperature, ISO 75 at 0.45 MPa, warned within 10 °CThe plastic's set (pla.softening 57 °C, petg.softening 69 °C, Bambu's data sheets); the 10 °C an estimate

A worked check: a 2020 shelf frame, legs 400 mm, a 600 mm front beam joined blind to the legs 390 mm up, 5 kg at its middle, sags 0.215 mm by hand with the joins rigid (a beam whose ends turn with the corners the legs and the side beams' twist hold) and 0.310 mm with the blind joins' estimated 1.5 N·m/mrad springs; the solve gives the same to three figures (packages/cad/test/frame-checks.test.mjs, "frame checks: a shelf frame").

Two more: a 2020 gantry beam, 600 mm, fixed at both ends, with 2.01 kg carried at its middle, rings first at 74.2 Hz; the formula above gives 74.2 Hz (192 E I / L³ = 461.5 N/mm, M + 0.375 m = 2.1225 kg). An open 2020 cube, 420 mm square and 400 mm tall, two rings of four beams joined blind to its legs, racks at about 63 N/mm under a push at its top; one diagonal brace makes it about 2.6 times stiffer (the bay across from it still racks, and the rings twist), a brace in both bays that way about 240 times ("frame checks: an open cube racks").

Fastening into a slot. A fasten whose into is a slot on a beam ends in a slot nut under the slot's lips:

"fasten": [{ "screw": "M4 button", "through": ["plate"], "into": "x1.top", "holes": "plate.body", "nut": "drop-in" }]

A frame from a size

A frame can be asked for by what it must hold, at the top of an assembly, in place of its beams:

"frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind", "feet": "levelling" }

Before anything else is worked out, it expands into beam items placed by their ends, joins between them, a fitting on every end no join covers, and any panels and braces asked for: everything after (the joins' operations and screws, the cut list, the frame checks, the build page) sees a hand-drawn frame. cad check says what it made (frame.generated: the kind, the inside and outside, the beams by length, the joins and the ends).

cad frame <project>/<assembly> prints what it expands into; --expand writes the expansion into the assembly (its "frame" keeps only how it is solved), to edit by hand from there; --json gives either as data. @rulecad/frames has the generators on their own: box, portal, table, gantry, shelf and frameModel(kind, o).

What a generated box checks to, joined three ways in MISUMI's, Bosch's and item's 2020, 3030 and 4040 (each taken or refused as above): blind checks clean wherever it is taken. end-tap takes each ring's beams along y one width above its beams across x, so no two screws cross inside an upright. Its screw passes a clearance hole drilled across the upright (ISO 273's medium series for the end thread), through the slot on both sides, and where that hole is wider than the slot's opening it would break the lips (beam.op warns twice a join). So the generator takes end-tap only where the hole fits: MISUMI's 2020 (M5, 5.5 mm in a 6 mm opening) and OpenBuilds' 2020 (5.5 mm in 6.25 mm), both clean. It refuses it by name, with both figures and what to use instead, in item's 2020 (5.5 in 5), Bosch's 2020 (M6, 6.6 in 6), item's 3030 (6.6 in 6.2), MISUMI's and Bosch's 3030 and item's 4040 (M8, 9 in 8), and MISUMI's and Bosch's 4040 (M12, 13.5 in 10); no smaller thread cuts in those end bores. bracket with a printed fitting checks clean or warns only frame.rack, the frame's sway. Bosch's 2020 and 4040 L sections also warn beam.mass: their drawn outlines leave out hollows the sheet's mass counts, and the frame is weighed by the sheet's figure.

The lightest profiles

"frame": { "size": { ... } } chooses, for each group of beams that must match, the lightest profile from a list that meets the frame's own limits, by @rulecad/fea/frame's sizing on the frame the checks solve (every pose, the joins' springs, the loads and mounted items):

"frame": { "kind": "table", "inside": [800, 500, 700], "profile": "2020-misumi-hfs5", "join": "blind",
  "size": { "profiles": ["1010-makerbeam", "1515-openbeam", "2020-misumi-hfs5", "2040-misumi-hfs5", "3030-misumi-hfs6", "4040-misumi-hfs8"] } },
"loads": [{ "mass": 30, "at": "x1.top@50%" }, { "mass": 30, "at": "x2.top@50%" }, { "mass": 10, "at": "y1.top@50%" }, { "mass": 10, "at": "y2.top@50%" }]

cad check gives frame.size: each group's profile, its mass, the limit that set it and how many times inside that limit it stands. cad frame <project>/<assembly> --size prints the table:

sized: 3.348 kg of grouped beams (drawn 2.74 kg), 14 designs solved (every design ranked by mass)
group | profile | kg | set by | margin
z1, z2, z3, z4 | 2020-misumi-hfs5 | 1.44 | a join: with 1515-openbeam, blind join of x1.a to z1.back@710 does not go together (an M5 screw (2040-misumi-hfs5's bore) does not pass 1515-openbeam's 3.2 mm slot opening) | 7.29x
x1, x2 | 2040-misumi-hfs5 turned (drawn 2020-misumi-hfs5) | 1.408 | deflection: with 2020-misumi-hfs5, the sag at x1@400 breaks its limit 1.96 times over | 2.56x
y1, y2 | 2020-misumi-hfs5 | 0.5 | a join: with 1515-openbeam, blind join of y1.a to z1.top@710 does not go together (an M3 button head, 5.7 mm across, pulls through 2020-misumi-hfs5's 6 mm slot opening) | 3.33x

"Set by" is the limit the group's next lighter profile breaks, the other groups as chosen: what stops it being any lighter, or the join it would not make. A group already at the lightest in the list says so. With "limits": { "deflection": 6 } the long rails drop to 2020 and the grouped beams to 2.74 kg. Without the joins held to fit, the legs and short rails came out 1515 OpenBeam, whose M3 ends and 3.2 mm slots take neither the 2040 rails' M5 screws nor a 2020 leg's slot.

--write writes the profiles into the assembly: each grouped beam's profile, a quarter roll where it was turned, and its printed end fittings drawn for it. A generated frame is written out expanded, as --expand does, since a generator takes one profile; its rings keep their outer faces (a table's top stays level with its legs' tops). A beam's end that butts against a face moves with that face as the other beam changes size, and a blind or end-tap join at an end that now has two bores (a 2040) becomes a join a bore. A drawn beam whose new depth would stand past the end of the beam it meets (a rail flush with its legs' tops, now a 2060) moves along that beam by as much, so its face there stays where it was, if the move fits at its other end too; where it does not, nothing is written and the refusal names the join and the beam. Otherwise beams keep their lines. Check the written frame: its join checks hold every screw, nut and length, where the sizing held each join's screw and head to its slot.

What it rests on: the joins' springs are as drawn (an estimate until the joint rig measures them) and do not change with the profile; the sizing solves the drawn layout, with each beam's line where it is drawn, so a figure on the written frame differs a little (the table in HFS5, its 2040 rails lowered 10 mm to keep its top level, sags 0.87 mm at a long rail's middle as sized and 0.83 mm as written). With 512 designs or fewer every one is ranked by mass and the first that meets the limits is the lightest; with more, the search goes by steps and lands near the lightest. Racking (frame.rack) is not a sizing limit: it is a bay's to brace, not a beam's to thicken.

WhatFormulaSource
A design's massthe sum over grouped beams of length × the profile's mass per metreThe profile's set (the maker's sheet)
Sag limit (default)span / 360FRAME_CHECK.sag: IBC Table 1604.3
Stressmargin × (abs(N)/A + abs(My)/Wy + abs(Mz)/Wz) ≤ strength, worst of springs and rigid@rulecad/fea/frame; Roark's, chapter 8
Euler load of a grouped beamπ² E I / (K L)² ≥ margin × N, I the lesser second moment, K 1Roark's, table 15.1, case 1a
Frequency floor (with a task)2 × speed / accel Hzframe.frequency: a move ramping in t seconds shakes the frame at about 1/t
What set a groupthe limit with the largest use, over 1, when the group takes its next lighter profileThis package

Building it

Once an assembly is checked, these say how to make it. They all read the assembly itself, so they can't disagree with it.

Every screw is reached in this order: what stands over a screw (fasten.access, or a fit's access) goes on after the step that drives it. Where a side built flat would break that, the side is built on the frame instead; where no build does, it is refused with the screw and what stands over it. It ends with the tightening of each kind of join (blind (16 joins, M5x12 button with a 3 mm hex key): 3.68 N m). A slide-in nut in a stretch of slot that joins close at both ends (frame.nut) is shut in by whichever of the two joins is made second, in any order: the build is refused, naming the slot, the nuts, the two joins, and the nut that goes in through the opening (frame/box: x1's top slot: 2 slide-in nuts (...) for plate would be shut in between the blind join of x1.a to p1.back@30 and the blind join of x1.b to p2.front@30: ...: give "nut": "drop-in"), and cad order exits 1. --json adds frame: { steps: [{ n, kind, text, lines, items, joins, shown, now, dir }], sides, notFlat, bays, torques, stuck }, kind one of cut, drill, side, join, load, square, mount; shown is what is in view at that step (the side on the bench, or the frame so far) and now what goes on in it. --preview draws each step that shows something, numbered as the build is. The build page shows the same as "Building the frame", its one sequence of steps (each a button that shows that step in the viewer), with the torques and the diagonals as tables.

Panels and doors. An item with "panel" is a sheet cut to the bay of four beams it closes:

{ "id": "front", "panel": { "sheet": "acrylic", "thickness": 3, "bay": ["x1", "z2", "x2", "z1"], "out": [0, -1, 0] } }

Services on a frame. A bought board or supply with "mount" sits on a printed mount at an address on a beam's slotted face, its holes read from its own rule set (@rulecad/frames' README, Services):

{ "id": "psu", "bought": "supply-24v", "variant": "LRS-50-24", "mount": { "on": "rail.top@-90" } }

Guides. "guides" puts linear motion on a beam: a miniature rail screwed down on a slotted face and its carriages (@rulecad/frames' README, Guides):

"guides": [{ "kind": "rail", "rail": "rail-mgn12", "carriage": "MGN12H", "on": "x1.top", "from": 50, "length": 300 }]

A carriage on V-wheels runs on a V-slot beam's own tracks, and a printed slider in or over a slot:

"guides": [{ "kind": "wheels", "wheel": "v-wheel-solid", "wheels": 4, "on": "x1.top", "from": 50, "length": 400 },
           { "kind": "slider", "mode": "over", "size": 40, "on": "x2.top.1", "from": 100, "length": 200 }]

Two smooth rods carry a printed carriage on linear bearings, and a lead screw drives it from a motor; an endstop homes it. Each is placed by an address: the rods' holders at the ends of the stretch on the face, the motor plate before it, the switch's mount where its address says:

"guides": [{ "kind": "rods", "on": "x1.top", "from": 60, "length": 101, "endstop": { "at": "x1.front@82" } },
           { "kind": "screw", "guide": "g1", "screw": "t8-screw", "motor": { "model": "28byj48", "microsteps": 1 } }]

A timing belt drives a rail's one carriage: a pulley on a motor at the beam's end a, a toothed idler past the rail's end, both belt ends in a printed clamp on the carriage. The belt guide names the rail guide and the motor, and places the rest by addresses (examples/bench axes/x-belt is one, written by the edit commands):

"guides": [{ "kind": "rail", "rail": "rail-mgn12", "carriage": "MGN12H", "on": "x1.top", "from": 30, "length": 300 },
           { "kind": "belt", "guide": "g1", "motor": { "model": "nema17", "microsteps": 16, "current": 1.2 }, "accel": 3000 }]

Optimised parts

cad optimise finds the stiffest layout of a flat part: where to put a fixed amount of material so the part bends least under its loads (topology optimisation, by @rulecad/topopt). A problem is a file in the project's problems/, with numbers as expressions like an object's (schema: schemas/problem.schema.json):

{
  "title": "A lever",
  "uses": ["m5", "x1c"],
  "material": "pla",
  "thickness": 6, "cell": 1, "volume": 0.5, "filter": 2.5,
  "space": { "at": [60, 0], "size": [140, 40] },
  "keep": [{ "at": [0, 0], "r": 6 }, { "at": [120, 0], "r": 5 }],
  "avoid": [{ "at": [0, 0], "r": "m5.clearance / 2" }, { "at": [120, 0], "r": 2.3 }],
  "supports": [{ "at": [0, 0], "r": "m5.clearance / 2" }],
  "loads": [{ "at": [120, 0], "r": 2.3, "force": [0, -20], "case": "down" }]
}

cad optimise <project>/<problem> runs it, reports how far each load case moves its load and the stiffness that gives, and draws the layout in .preview/. The result is kept, keyed by everything it's made from, so it's only worked out again when something it depends on changes. cad why <project>/<object>.<problem variable> names what that is: the problem file, its rule sets and values, the parts and anchors it reads (and the assembly, joints and sweeps), where its filter came from, and the file the result is kept in.

A 3D result with a build direction is made printable before it's drawn: built up layer by layer from the bed, every cell that nothing holds up (an icicle, a loose bit, a sheet hanging under an edge: whatever the optimiser's smooth overhang filter let through) is emptied, with whatever rested on it; a bridge may run out half the printer's span, in the optimiser's filter and in the cleaning alike, so a flat underside can open into holes that wide. Kept regions always stay, and the optimiser is made to hold them up: a kept cell with nothing under it costs it as much as the whole part's compliance. If there wasn't material enough to stand a kept region on, cad optimise says how much of it is left hanging. Then the drawn surface is tipped back to the printer's overhang limit and any tip left hanging in mid-air is lifted, and only the pieces that touch a support, a load or a kept region are kept (a few grey cells away from the rest can close into a stray bit). cad optimise says how many cells it emptied and pieces it dropped, and cad check tests the part for one piece and nothing starting in mid-air.

cad optimise <project>/<problem> --watch [port] runs it afresh and serves a live view at http://127.0.0.1:8090/: the densities as they change (a 3D part as a surface you can turn, and from three sides), a chart of its compliance and how much it still changes, with a scrubber to look back at any earlier step, its run time and time left, the machine it runs on, and a button that stops the run. It shows the end for ten minutes after the run finishes. It listens on this computer only. To watch from elsewhere, reach it through a private network such as Tailscale.

Every run is kept to watch again. cad optimise writes .preview/<project>/<problem>-run.html: the same page, reading its steps from the file, so it opens with no server and can be sent to someone. Drag the slider or the chart to any step. cad preview <project>/problems/<problem> (or the file's path) draws the result and writes that page. A result made without its steps recorded (by building a design that reads it) shows its end and each step's compliance; cad preview <project>/problems/<problem> --fresh runs it again to record the steps, and --watch shows the run live. A 3D run shows its three views; the turning surface needs the live view.

A design uses it through a variable of type problem, which picks a problem by name:

"problem": { "type": "problem", "value": "lever", "choice": ["lever", "lever:both", "none"] }
export function main (v) {
  return extrudeLinear({ height: v.thickness }, v.shapes.optimisedOutline(v.problems[v.problem]))
}

A variant that sets the problem to none builds without optimising (v.problems then lacks it): a test rig drawn on a plain base, or the parts a problem's regions name ({ "part": "body:regions.mounts" }), which must not need the problem they feed.

optimisedOutline gives the outline as a 2D shape, its keep regions added and avoid regions cut exactly, so bolt holes come out true.

Solid parts (3D)

A problem whose regions have a z is solid. It has no thickness, and takes more kinds of region:

Supports and loads can be any region; a force has x, y and z. "overhang": "+z" keeps only material that prints without supports standing that way up (a variable holding "+z" or "none" works too, so a variant can switch it).

A part made another way says so in place of overhang (one process to a problem; two are refused by name):

Any problem can give "feature", the thinnest member it makes, mm: for a printed part "x1c.wall_min", the printer's two lines (0.84 mm). Where a cell is as wide, every member already is, and cad optimise says the grid holds it; up to three cells across, members narrower go as it optimises; wider is refused with the cells that would hold it.

Any of them can also be "symmetry": { "mirror": "y" } (mirrored across the grid's middle planes; "turns": 2 or 4 about "axis" for half or quarter turns) or "extrude": "x" (one section all along x, a part cut from a bar). A mirror or turn that would swap the side the part is made from for its opposite is refused by name (a mould in two halves parted at the middle may be mirrored across its draw). With a process or a tie, cad optimise warns when more than a tenth of the design is grey (neither empty nor solid): the outline drawn is then a guess. A 2D section milled or cast across its own plane often comes out so; give the problem in 3D or make it from another side.

cad optimise draws the result's four views in .preview/. A design builds the result with v.shapes.optimisedSolid(v.problems[v.problem], { ops: v.ops }), which adds the keep regions and cuts the avoid regions exactly. The surface is a big mesh, so set the object's "engine": "manifold". With "overhang" set, the surface is also kept within the printer's overhang limit: faces smoothing tipped past it are tipped back. An analysis of a solid part voxelises it on the problem's grid.

The surface is drawn with many small triangles, and cad optimise thins them by default: the surface stays within 0.1 mm of where it was drawn (a quarter of an X1C's print line), closed, with no more overhang and no new tips, and cad optimise says how many triangles it had and has. On the bracket bench's printable result that takes 75,592 triangles to 21,124 and 27.808 cm³ to 27.806 cm³ (35.04 g of PLA at 1.26 g/cm³ either way, 0.003 g apart), a quarter of the size in a file or a link. "outline": { "reduce": 0.05 } keeps the surface closer (31,154 triangles on the bracket), and "outline": { "reduce": false } keeps every triangle it was drawn with.

A part prints in one orientation and is loaded in another. Draw it as it prints, and turn it back for its analysis: "rotate" (degrees about x, then y, then z, as JSCAD's rotate) then "move" (mm) put it in the problem's frame. Both take expressions, so a variant can lie the part down:

"analysis": [{ "problem": "bracket", "rotate": ["0 - 90 * side", 0, 0], "move": [0, "0 - side * bench.bracket_h / 2", 0] }]

Grids in 3D are solved by multigrid, with the solver's products shared over the machine's cores. A 16 × 16 × 40 grid (about 10,000 cubes) takes a second or two a step, a 32 × 32 × 40 one (41,000 cubes) about five seconds on an eight-core laptop and a 40 × 40 × 48 one (77,000 cubes) about thirteen, so a whole optimisation of a few hundred steps takes from a few minutes to an hour. Finer cells cost more than their number: each step's solve takes longer to settle too. The result is kept, so it's worked out once.

Analysis

Any flat part, optimised or not, can be checked under a problem's supports and loads. An object's analysis names the problem, and optionally a limit:

"analysis": [{ "problem": "lever", "max_deflection": 0.5, "volume": "target", "tolerance": 0.01 }]

cad check then reports, for each load case, how far the part moves its load, its stiffness (N/mm) and its peak stress against the material's strength, and the part's volume and weight. With max_deflection a case that moves further fails; with volume a part whose volume is further than tolerance (a share) from it fails. A picture goes in .preview/. A twist (forces that add to nothing, such as four round a rim) has no direction to move along, so it's reported as the angle the part turns through, in degrees, under its moment (N·m), and its torsional stiffness (N·m a degree).

On the problem's own cells the analysis is quick and coarse. A solid part's cubes are filled by the share of each the part takes up, so a wall between cell centres still counts, but thin walls on big cubes still come out too stiff when they bend. To check a final shape, give the analysis a smaller cell:

"analysis": [{ "problem": "bracket", "cell": 0.8, "min_safety": 3 }]

The part is then analysed on those cells and again on cells a quarter bigger. For each load case, cad check reports:

A report goes in .preview/ (<object>-report-<problem>.md, and .json), with what the analysis doesn't cover. A solid's analysis is kept in .cache/analysis/, so it runs once.

Safety-critical parts. A problem with "critical": true (a pedal, a lever, a bracket that holds people) marks every part analysed under it as unverified, until a test or an independent analysis is recorded in the object:

"verification": [{ "kind": "test", "date": "2026-11-02", "by": "J. Smith", "summary": "20 N straight down, three prints: 0.21 mm, 95 N/mm", "source": "results.json" }]

The analysis is a design aid, not engineering sign-off: anything that could hurt someone if it failed needs testing.

Boards

A circuit board is an object whose .json says "engine": "pcb". Its main(v) returns a tscircuit board (circuits as code, from npm) built with v.pcb (@rulecad/pcb: npm install @rulecad/pcb in the workspace); the build runs it into Circuit JSON, and the bare board, drilled, becomes a part, so previews, links, cad show and fit assemblies work as for printed parts. The copper (tracks, pads, vias) is drawn in the 2D views, not in 3D.

npx cad check keyboard/macropad-pcb     # tscircuit's design checks, JLCPCB's limits, the matrix
npx cad preview keyboard/macropad-pcb   # the board from above (copper, silkscreen) and in 3D
npx cad export keyboard/macropad-pcb    # <name>-fab.zip for JLCPCB, KiCad files, the matrix

Speed

Fit checks find closest gaps through a grid of triangles (nearest cubes first), and remember overlap volumes between placed parts in .cache/overlaps.json, keyed by each part's build and placement: the staggered keyboards' checks take about 10 s, and a re-check after an edit measures only what the edit moved. The build cache keeps its 800 most recently used builds, keyed by what a build is made from: the design's code, its values resolved, its parts' names and roles, the rule sets and the tool's own code; a rule's words, a label or the version change nothing it builds, so they don't start one. A lamina mechanism's slow stages (its physics, a flooded frame's probe) are kept apart in .cache/stages/, keyed by their own inputs, so a build that changes only what comes after them (a strap, a check) takes minutes rather than the twenty a launcher's physics takes; the design's sandbox reads them and hands back what it made for the tool to write. CAD_NO_CACHE=1 computes everything afresh (and keeps it).

Assemblies: values from other parts

(An object can also read another object directly, outside any assembly: see "Other objects' numbers" under Variables. That suits a case built around one board; from suits values that only mean something where items meet.) An item's from sets inputs from other items' values, in the assembly's names: "from": { "usb_y": "board.pcb.pico_y" }. Every item is built before any is placed, so positions can refer to items listed after them (the board placed under the case's top while the case is built from the board's Pico position). "place": false builds an item only for its values: the PCB build's print plates (staggered-pcb-case, staggered-pcb-plate) take the board's numbers without the board being on the bed. In assemblies a board counts as a reference: checked, drawn faint, never in a print file.

Mechanisms printed flat

A design whose main returns v.flexures.lamina({ … }) (see @rulecad/flexures, Lamina mechanisms) is a mechanism drawn in one plane and printed on its side. cad check adds its own findings to the print checks: that it prints free (nothing within the printer's gap of what it isn't joined to), that every step of its sequence is clear, that nothing jams, that its catches hold, and that every flexure has a hard stop before its strain limit. cad animate <project>/<object> writes the sequence, start to finish, as an animated SVG in .preview/: the frame drawn once, the moving bodies in blue and the flexures in orange, drawn bent, holding a moment at each state. Under it, each driven step's force against its travel, with a marker that follows the frames; a mechanism that fires adds the shot in slow motion. The printer's print_gap is the gap the checks hold it to.

Parts printed in place

An object with "printInPlace": true is printed as one, its parts in the pose they're drawn in, and they move apart once freed with a turn by hand (a gearbox printed whole: @rulecad/gears' compoundPlanetary({ printInPlace: true }) draws its teeth for it). Its parts are named (return { housing, sun, planet_a, output }), and cad check adds three checks to the print checks:

The gaps need manifold-3d in the workspace ("engine": "manifold" objects have it already). To move the parts in an assembly, draw each as an object of its own from the same numbers (the bench's shoulder-pip-* objects share a module and read pip's variables) and name them in the assembly's "printInPlace": [items]: they came off the bed together, so the assembly order never takes them apart from each other. cad order fits them as one step and cad list gives them one printed row, the one print's grams and minutes.

An assembly with a gait (EXAMPLES chapter 14) plays too: cad animate <project>/<assembly> writes the cycle as an animated SVG in .preview/ (a side view of the legs and a plan of the feet and what they stand on) and its data as JSON. The model page plays the same cycle in its Motion panel. cad machine <project>/<assembly> on such an assembly describes it as a legged machine, an axis for each motor's shaft in the order its controller's slots are wired, and cad plot <project>/<assembly> with no drawing writes the gait as a step file for the streamer: --cycles of it (3) from a pose (--pose, by default the one shown) and back, every axis in each block, slowed where a motor cannot keep to the gait's period (--period to set it) and where a joint turns back, with a picture of each axis through the run in .preview/. A motor wired to a slot out of the streamer's order (X, Y, Z on a CNC shield; S0 to S7 on a Mega 2560) fails by name. The machine's controller is the bought board the streamer runs on: a cnc-shield-v3 (an Uno, three axes, and the default) or an arduino-mega-2560 (eight axes, the quadruped's). A motor on a driver of its own reaches its slot through its wire to the driver's breakout and the breakout's signal wire on to the Mega.

An assembly with a motor, or with gears that follow a joint, plays its drive: cad animate <project>/<assembly> writes <assembly>-drive.svg, the gears cut across their shafts through their teeth (up to three cuts side by side, a compound planetary's two rings each in its own), each part turning and moving as it does, the part with the load picked out. It turns the drive until the slowest part has moved about 60° (one to six turns; --turns n to choose). Each part's outline is drawn once and moved, so a gearbox stays a few hundred kilobytes.

Checks

Z is up and the bed is z = 0: a design is built the way it prints.