Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,13 @@ Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.)
If your agent already has a shell tool, you don't even need MCP—pipe scripts directly into `forma`:

```bash
# 1. Read the compact zero-shot language spec (~485 o200k tokens)
# 1. Read the compact zero-shot language spec (~485 o200k tokens) and optional topics
forma spec
forma spec --topic deform # also: curves, uv, remesh, scene

# 2. Build, verify watertightness + zero-overhead critique, export CAD/mesh, and render a 4-view preview in ~15 ms
forma eval --strict --critique --out part.glb --render preview.png --draw blueprint.svg <<'EOF'
# (Add --scene for multi-part scripts so ALL named parts export/render together!)
forma eval --strict --critique --scene --out part.glb --render preview.png --draw blueprint.svg <<'EOF'
flange = box(4, 2, 0.4)
| mat("steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
| cut(cyl(0.5, 1))
Expand Down Expand Up @@ -95,4 +97,5 @@ forma spec --gbnf > forma_pipe.gbnf
- **Multi-hole patterns:** Pass `at=[(x1,y1,z1), ...]` or a list comprehension `at=[(r*cos(2*pi*i/n), r*sin(2*pi*i/n), 0) for i in range(n)]` in a single `| cut(...)` or `| add(...)` call—Forma automatically batches pairwise-disjoint booleans in one pass.
- **Meshing spur gears:** `gear(z, module=m, h=h, bore=...)` places tooth 0 on `+X`; position a mating gear at center distance `m * (z1 + z2) / 2` and rotate it around Z by `180 / z2` degrees when `z2` is even (`0` degrees when `z2` is odd).
- **Sharp revolved/mechanical subsurf:** Use `subsurf(1, crease=true)` if you want smooth curvature without shrinking sharp rims.
- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, PBR materials + LSCM/triplanar UVs; pass `scene: true` for multi-part scenes), faceted `.step` (watertight planar-face ISO 10303-21 solid; no analytic cylinders/NURBS) for reference/assembly import into SolidWorks/Fusion 360/FreeCAD, `.3mf`/`.stl` for 3D printing (model in mm? start the script with `units("mm")` so `.3mf`/`.step` declare millimetres; `.stl`/`.obj` have no unit field and keep model units), `.svg` for dimensioned blueprints (supports `scene: true`), and `.blend` via Blender bridge.
- **Multi-part scenes & translucency:** Always pass `--scene` (CLI) or `scene: true` (MCP) when exporting/rendering scripts with multiple named parts — never boolean-merge separate objects just to export them together (`--scene` supports `.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, `.svg`). For steam, glass, water, or lamps, use `mat(..., color=(r,g,b[,a]), alpha=, transmission=, ior=, emissive=(r,g,b), emissive_strength=, double_sided=)` (colors are display sRGB and automatically converted to linear RGB in `.glb`).
- **Exporting for downstream tools:** Use `.glb` for web/Blender/Three.js (glTF 2.0 Y-up, sRGB→linear PBR materials + `alphaMode: "BLEND"` + `KHR_materials_transmission`/`emissive_strength` + LSCM/triplanar UVs; pass `--scene` / `scene: true` for multi-part scenes), faceted `.step` (watertight planar-face ISO 10303-21 solid; supports multi-solid `--scene`), `.3mf`/`.stl` for 3D printing (model in mm? start the script with `units("mm")` so `.3mf`/`.step` declare millimetres; `.3mf` supports multi-object `--scene`; `.stl`/`.obj` have no unit field and keep model units; `.obj` supports multi-object `o <name>` `--scene`), `.svg` for dimensioned blueprints (supports `--scene` / `scene: true`), and `.blend` via Blender bridge.
26 changes: 19 additions & 7 deletions SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,16 @@ Exposed tools (4 tools, 900 `o200k` tokens total, Native = WASM parity; optional
### Option B — CLI (single-shot Unix pipes)
Use either the compiled native binary (`forma`) or the cross-platform npm CLI (`npx -y forma-3d`):
```bash
forma spec # Print ~485-token language reference
forma spec # Print ~485-token core language reference
forma spec --topic deform # Load advanced topic: deform | curves | uv | remesh | scene
forma spec --gbnf # Print GBNF grammar for constrained decoding
forma lint --json script.forma # Deterministic Layer A lint + contact graph

# Multi-part export/render: ALWAYS pass --scene to include ALL named parts!
# (Omitting --scene exports ONLY the last-modified part.)
forma eval --strict --critique --scene \
--out scene.glb \
--render preview.png \
--out scene.glb \ # .glb, .blend, .obj, .3mf, .stl, or .step
--render preview.png \ # --view quad|front|back|right|left|top|iso
--draw blueprint.svg <<'EOF'
...Forma-Pipe script...
EOF
Expand All @@ -50,8 +54,8 @@ Minimize round-trips and output tokens by treating `Forma-Pipe` as a parametric
1. **Batch the whole part or assembly into 1–2 `eval` calls.** Define shared parameters as scalars (which persist across MCP `eval` calls), reuse geometry with `def name(p1, p2=default) = expr` macros and `[expr for i in range(n)]` comprehensions, and prefix temporary cutters/helpers with `_` (`_tmp = ...`) so they stay local and never pollute `scene.parts` or `scene: true` exports.
2. **Set coordinates (Z-up) and unit upfront.** Numbers default to meters; for mm/in parts, start with `units("mm")` (or `forma eval --unit mm`) so `.3mf`/`.step` open at the right size (`.glb` scales to metres; `.stl`/`.obj` keep model units). Primitives center at `(0, 0, 0)` unless placed with `at=(x,y,z)` or `z0=Z` (`z0=` overrides Z if both are given).
3. **Skip routine checkpoints.** `eval` with `strict: true` (default) already auto-rolls back on any error or watertightness failure (`WT!=ok`, `NM>0`). Only call `tx(action="checkpoint", tag="...")` before genuinely risky or exploratory edits you may want to discard even if they succeed.
4. **Verify from the returned diff, then preview once.** Check `WT=ok NM=0`, `bbox`/`size`, `vol`, `genus`, and geometric queries (`clearance(a, b)`, `section(part, z)`) directly in the `eval` output. Call `export({ path: "preview.png", scene: true })` once at the end (or when debugging complex spatial fit) instead of re-rendering after every edit — `scene: true` renders all named parts together with their materials, so never boolean-merge a dummy assembly just to preview.
5. **Clean up & export.** Remove unwanted parts with `del("name")`, then export `.glb`/`.blend` (with `scene: true` for multi-part assemblies), `.step`, `.3mf`, `.stl`, `.obj`, or `.svg`.
4. **Verify from the returned diff, then preview once.** Check `WT=ok NM=0`, `bbox`/`size`, `vol`, `genus`, and geometric queries (`clearance(a, b)`, `section(part, z)`) directly in the `eval` output. Preview the full assembly with `export({ path: "preview.png", scene: true })` (MCP) or `forma eval --scene --render preview.png ...` (CLI) — **never boolean-merge (`add`) separate scene parts just to export or preview them together**; `--scene` / `scene: true` exports all named parts with their materials intact.
5. **Clean up & export.** Remove unwanted parts with `del("name")`, then export with `--scene` (CLI) or `scene: true` (MCP) for multi-part assemblies (`.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, `.svg`). Without `--scene` / `scene: true`, only the last-modified part exports.

---

Expand Down Expand Up @@ -98,10 +102,18 @@ Minimize round-trips and output tokens by treating `Forma-Pipe` as a parametric
- `move(x, y, z)` | `rot(rx, ry, rz)` (degrees) | `scale(sx, sy, sz)`
- `on(base)` (rests cleanly on top of `base`) | `align(x|y|z, min|center|max, val)` | `align_z0(z)`
- **Materials, State & Spatial Queries:**
- `mat("name", color=(r,g,b), metallic=0.1, roughness=0.5)` | `color(r,g,b)`
- `mat("name", color=(r,g,b[,a]), metallic=0.0, roughness=0.5, alpha=1.0, emissive=(r,g,b), emissive_strength=1.0, transmission=0.0, ior=1.5, double_sided=false, faces=)` | `color(r,g,b[,a], alpha=)`
- Colors are display **sRGB** (`0..1`) and automatically converted to linear RGB in glTF `.glb` export (matching Forma's PNG preview).
- Use `alpha=0.25` (or `opacity=0.25` / 4-tuple `color=(1,1,1,0.25)`) for translucent steam/smoke/tinted glass (`alphaMode: "BLEND"` in `.glb`), `transmission=0.85, ior=1.33` for refractive water/glass (`KHR_materials_transmission`), and `emissive=(1.0, 0.78, 0.45), emissive_strength=2.0` for glowing lamps/shoji/screens.
- `del("name")` — remove a named part from the scene.
- `section(part, z)` — returns 2D cross-section loop count & area at plane `Z`.
- `clearance(a, b)` — returns exact minimum 3D distance between parts `a` and `b`.
- **Advanced Topics (load via `forma spec --topic <name>` or MCP `inspect({ topic })`):**
- `deform`: `solidify(t, offset=-1.0, open_top=false)`, `deform("bend"|"twist"|"taper"|"curve"|"lattice", ...)`
- `curves`: `bezier([...])`, `nurbs([...])`, `sweep(profile2d, path3d, scale_end=, twist=)`
- `uv`: `smooth(angle=35)`, `flat()`, `unwrap()`, `decimate(ratio=)`
- `remesh`: `remesh(voxel_size=)`, `bisect(normal=, offset=)`
- `scene`: multi-part `--scene` / `scene: true` exports across `.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, `.svg`

---

Expand All @@ -127,7 +139,7 @@ wheel = gear(z2, module=m, h=h, bore=4, z0=0)
| move(cd, 0, 0)
| mat("brass", color=(0.82, 0.66, 0.28), metallic=0.88, roughness=0.28)
```
Then render both gears together in one call: `export({ path: "gears.png", scene: true })` (and `export({ path: "gears.glb", scene: true })`). `_hole` stays local and does not appear in the exported scene.
Then render/export both gears together in one call — MCP: `export({ paths: ["gears.png", "gears.glb"], scene: true })`, or CLI: `forma eval --scene --out gears.glb --render gears.png gears.forma`. `_hole` stays local and does not appear in the exported scene.

### Brushed-Steel 5-Hole Mounting Flange
```forma
Expand Down
9 changes: 2 additions & 7 deletions bin/forma-mcp.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -168,16 +168,11 @@ async function exportSinglePath(session, p, { part, isScene, size, view }) {
];
}
if (ext === "blend") {
await writeBlendFromGlbBytes(session.exportSceneBytes(), p);
await writeBlendFromGlbBytes(session.exportSceneBytes("glb"), p);
const byteLen = (await stat(p)).size;
return [`OK exported multi-node scene '${p}' (${byteLen} bytes, parts=${partsCount})`, null];
}
if (ext !== "glb") {
throw new Error(
`multi-node scene export requires .glb, .blend, .png, or .svg (got '.${ext}')`
);
}
const bytes = session.exportSceneBytes();
const bytes = session.exportSceneBytes(ext);
await writeFile(p, bytes);
return [`OK exported multi-node scene '${p}' (${bytes.length} bytes, parts=${partsCount})`, null];
}
Expand Down
62 changes: 53 additions & 9 deletions bin/forma.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,28 @@ function printHelp() {
process.stdout.write(
`forma ${VERSION} (WASM) — pure-Rust headless 3D polyhedral modeling engine for AI agents\n\n` +
`USAGE:\n` +
` forma-3d eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--size 512] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n` +
` forma-3d eval [--scene] [--out FILE] [--render PNG] [--view VIEW] [--size 512] [--draw SVG] [--unit UNIT] [--strict|--no-strict] [--critique] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n` +
` forma-3d lint [--unit UNIT] [--strict|--no-strict] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n` +
` forma-3d render [--scene] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n` +
` forma-3d draw [--scene] --out blueprint.svg [file|-]\n` +
` forma-3d spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n` +
` forma-3d spec [--dialect pipe|compact] [--topic deform|curves|uv|remesh|scene] [--gbnf]\n` +
` forma-3d mcp\n` +
` forma-3d version | --version | -V\n\n` +
`KEY OPTIONS:\n` +
` --scene Export/render/draw ALL named parts together\n` +
` (default without --scene exports ONLY the last-modified part)\n` +
` --out, -o FILE Export mesh (.glb, .obj, .stl, .3mf, .step, .blend)\n` +
` --render PNG Render studio preview PNG (combine with --scene for full assembly)\n` +
` --view VIEW Preview angle: quad|front|back|right|left|top|iso (default: quad)\n` +
` --size PX Preview PNG size in pixels (default: 512)\n` +
` --draw SVG Emit 3-view orthographic blueprint SVG (combine with --scene for full assembly)\n` +
` --unit, -u UNIT Model unit: m|cm|mm|um|in|ft (default: m)\n` +
` --strict/--no-strict Enforce watertight manifold geometry (default: --strict)\n` +
` --critique Run deterministic craftsmanship lint & assembly contact checks\n` +
` --json Emit machine-readable JSON observation to stdout\n\n` +
`EXAMPLES:\n` +
` forma-3d eval --scene --out scene.glb --render preview.png scene.forma\n` +
` forma-3d spec --topic deform # also: curves, uv, remesh, scene\n\n` +
`EXIT CODES:\n` +
` 0 Success\n` +
` 1 Script, I/O, or export error\n` +
Expand Down Expand Up @@ -101,13 +117,16 @@ async function main() {
}
}

if (cmd !== "eval" && cmd !== "render" && cmd !== "draw") {
if (cmd !== "eval" && cmd !== "lint" && cmd !== "render" && cmd !== "draw") {
usageErr(`unknown subcommand '${cmd}'. Run 'forma-3d --help'.`);
}

const isLintCmd = cmd === "lint";
let dialect = "pipe";
let unit = null;
let strict = true;
let critique = isLintCmd;
let includeRawBox = false;
let asJson = false;
let exportScene = false;
let outPath = null;
Expand Down Expand Up @@ -145,6 +164,10 @@ async function main() {
strict = true;
} else if (a === "--no-strict") {
strict = false;
} else if (a === "--critique") {
critique = true;
} else if (a === "--raw-box") {
includeRawBox = true;
} else if (a === "--json") {
asJson = true;
} else if (a === "--scene") {
Expand Down Expand Up @@ -177,15 +200,23 @@ async function main() {
}
const obs = session.eval(src, { dialect, strict });

const partCount = Object.keys(obs.parts ?? {}).length;
const instMatch = /\binsts=(\d+)/.exec(obs.text ?? "");
const totalObjs = partCount + (instMatch ? Number.parseInt(instMatch[1], 10) : 0);
const wroteAny = Boolean(outPath || renderPath || drawPath);
if (!exportScene && wroteAny && totalObjs > 1) {
process.stderr.write(
`NOTE: scene has ${totalObjs} objects, but exported/rendered only the last part because --scene was not set. Pass --scene to export/render all ${totalObjs} objects together.\n`
);
}

if (outPath) {
const ext = extname(outPath).replace(/^\./, "").toLowerCase();
if (exportScene) {
if (ext === "blend") {
await writeBlendFromGlbBytes(session.exportSceneBytes(), outPath);
} else if (ext === "glb") {
await writeFile(outPath, session.exportSceneBytes());
await writeBlendFromGlbBytes(session.exportSceneBytes("glb"), outPath);
} else {
throw new Error(`multi-node scene export requires .glb or .blend (got '.${ext}')`);
await writeFile(outPath, session.exportSceneBytes(ext));
}
} else if (ext === "blend") {
await writeBlendFromGlbBytes(session.exportBytes("glb"), outPath);
Expand All @@ -204,10 +235,23 @@ async function main() {
await writeFile(drawPath, svgData);
}

if (asJson) {
process.stdout.write(JSON.stringify(obs) + "\n");
const lintRep = critique ? session.lint({ includeRawBox }) : null;
if (isLintCmd) {
if (asJson) {
process.stdout.write(JSON.stringify(lintRep) + "\n");
} else {
process.stdout.write((lintRep.text ?? "") + "\n");
}
} else if (asJson) {
const payload = lintRep ? { ...obs, lint: lintRep } : obs;
process.stdout.write(JSON.stringify(payload) + "\n");
} else {
process.stdout.write(obs.text + "\n");
if (lintRep && lintRep.critique_text) {
process.stdout.write(lintRep.critique_text + "\n");
} else if (lintRep && lintRep.issues?.length > 0 && lintRep.text) {
process.stdout.write(lintRep.text + "\n");
}
}
if (strict && !obs.ok) {
process.exit(3);
Expand Down
Loading
Loading