Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

feat(cli,core,lang,wasm): add translucent/emissive materials, non-GLB --scene exports, and CLI multi-part ergonomics

wrong-nebula355e97e881c7
diff --git a/AGENTS.md b/AGENTS.md
index 6040568..cedc183 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -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))
@@ -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.
diff --git a/SKILL.md b/SKILL.md
index fa0fc29..3ef0b65 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -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
@@ -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.
---
@@ -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`
---
@@ -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
diff --git a/bin/forma-mcp.mjs b/bin/forma-mcp.mjs
index 979d937..0a7ad24 100755
--- a/bin/forma-mcp.mjs
+++ b/bin/forma-mcp.mjs
@@ -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];
}
diff --git a/bin/forma.mjs b/bin/forma.mjs
index 44b643a..0e66de1 100755
--- a/bin/forma.mjs
+++ b/bin/forma.mjs
@@ -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` +
@@ -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;
@@ -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") {
@@ -177,15 +200,21 @@ async function main() {
}
const obs = session.eval(src, { dialect, strict });
+ const totalParts = Object.keys(obs.parts ?? {}).length;
+ const wroteAny = Boolean(outPath || renderPath || drawPath);
+ if (!exportScene && wroteAny && totalParts > 1) {
+ process.stderr.write(
+ `NOTE: scene has ${totalParts} parts, but exported/rendered only the last part because --scene was not set. Pass --scene to export/render all ${totalParts} parts 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);
@@ -204,10 +233,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);
diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rs
index b6ac599..32ee11e 100644
--- a/crates/forma-cli/src/main.rs
+++ b/crates/forma-cli/src/main.rs
@@ -23,22 +23,36 @@ fn print_help() {
"forma {VERSION} — pure-Rust headless 3D polyhedral modeling engine for AI agents\n\
\n\
USAGE:\n\
- forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--no-fs] [--allow-import-dir DIR] [--critique] [--raw-box] [--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 lint [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--no-fs] [--allow-import-dir DIR] [--raw-box] [--json] [file|-]\n\
+ forma eval [--scene] [--out FILE] [--render PNG] [--view VIEW] [--size 512] [--draw SVG] [--unit UNIT] [--strict|--no-strict] [--no-fs] [--allow-import-dir DIR] [--critique] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n\
+ forma lint [--unit UNIT] [--strict|--no-strict] [--no-fs] [--allow-import-dir DIR] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n\
forma render [--scene] [--no-fs] [--allow-import-dir DIR] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n\
forma draw [--scene] [--no-fs] [--allow-import-dir DIR] --out blueprint.svg [file|-]\n\
- forma spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n\
+ forma spec [--dialect pipe|compact] [--topic deform|curves|uv|remesh|scene] [--gbnf]\n\
forma version | --version | -V\n\
forma --help\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 eval --scene --out scene.glb --render preview.png scene.forma\n\
+ forma spec --topic deform # also: curves, uv, remesh, scene\n\
+ \n\
EXIT CODES:\n\
0 Success\n\
1 Script, I/O, or export error\n\
2 Invalid CLI usage or flag\n\
- 3 Strict manifold/invariant check failed\n\
- \n\
- Reads modeling commands from file or stdin, runs automatic topological invariant checks,\n\
- emits compact spatial/topological diagnostics to stdout, and exports deterministically."
+ 3 Strict manifold/invariant check failed"
);
}
@@ -307,6 +321,14 @@ fn main() {
match eval_script(&mut scene, dialect, &src) {
Ok(obs) => {
+ let total_parts = scene.part_names().len();
+ let wrote_any = out_path.is_some() || render_path.is_some() || draw_path.is_some();
+ if !export_scene && wrote_any && total_parts > 1 {
+ let last = scene.last_part_name().unwrap_or("last");
+ eprintln!(
+ "NOTE: scene has {total_parts} parts, but exported/rendered only the last part ('{last}') because --scene was not set. Pass --scene to export/render all {total_parts} parts together."
+ );
+ }
if let Some(ref out) = out_path {
if export_scene {
if let Err(e) = scene.export_scene_path(out) {
diff --git a/crates/forma-cli/tests/scene_materials_cli.rs b/crates/forma-cli/tests/scene_materials_cli.rs
new file mode 100644
index 0000000..9b93672
--- /dev/null
+++ b/crates/forma-cli/tests/scene_materials_cli.rs
@@ -0,0 +1,273 @@
+use forma_core::export::write_glb_bytes;
+use forma_core::import::read_glb_bytes;
+use forma_core::Scene;
+use forma_lang::{eval_script, spec_topic, Dialect, SPEC_PIPE};
+use std::io::Write;
+use std::process::{Command, Stdio};
+
+fn parse_glb_json(glb: &[u8]) -> serde_json::Value {
+ assert!(glb.len() >= 20, "GLB too short");
+ assert_eq!(&glb[0..4], b"glTF");
+ let json_len = u32::from_le_bytes([glb[12], glb[13], glb[14], glb[15]]) as usize;
+ assert_eq!(&glb[16..20], b"JSON");
+ serde_json::from_slice(&glb[20..20 + json_len]).expect("valid GLB JSON chunk")
+}
+
+fn srgb_to_linear_ref(c: f32) -> f32 {
+ if c <= 0.04045 {
+ c / 12.92
+ } else {
+ ((c + 0.055) / 1.055).powf(2.4)
+ }
+}
+
+#[test]
+fn test_material_srgb_linear_roundtrip_and_translucency_emissive_glb() {
+ let script = r#"
+ roof = box(4, 3, 0.2, z0=2.0)
+ | mat("slate_roof", color=(0.20, 0.22, 0.25), roughness=0.7)
+ steam = sphere(0.4, at=(0, 0, 1.0))
+ | mat("steam", color=(0.95, 0.96, 1.0), alpha=0.25, roughness=0.9, double_sided=true)
+ water = box(2, 2, 0.3, at=(0, 0, 0.15))
+ | mat("onsen_water", color=(0.35, 0.68, 0.78, 0.85), roughness=0.1, transmission=0.85, ior=1.33)
+ lantern = box(0.3, 0.3, 0.4, at=(2.5, 0, 0.8))
+ | mat("shoji_glow", color=(0.95, 0.88, 0.72), emissive=(1.0, 0.75, 0.40), emissive_strength=2.5)
+ mist = sphere(0.25, at=(0.5, 0, 1.5)) | color(1.0, 1.0, 1.0, 0.35)
+ "#;
+
+ let mut scene = Scene::new();
+ let obs = eval_script(&mut scene, Dialect::Pipe, script).expect("eval material scene");
+ assert!(obs.ok, "{}", obs.text);
+
+ // 1. Default metallic is 0.0 (dielectric) when omitted
+ let roof = scene.get_part("roof").unwrap();
+ assert_eq!(roof.materials.len(), 1);
+ assert!((roof.materials[0].metallic - 0.0).abs() < 1e-6);
+ assert!((roof.materials[0].color[0] - 0.20).abs() < 1e-6);
+
+ // 2. Single-mesh GLB converts sRGB -> linear and round-trips back to sRGB
+ let roof_glb = write_glb_bytes(roof, true).unwrap();
+ let roof_json = parse_glb_json(&roof_glb);
+ let bcf = roof_json["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"]
+ .as_array()
+ .unwrap();
+ assert!(
+ (bcf[0].as_f64().unwrap() as f32 - srgb_to_linear_ref(0.20)).abs() < 1e-5,
+ "baseColorFactor[0] must be linearized: got {:?}",
+ bcf[0]
+ );
+ assert!(roof_json["materials"][0].get("alphaMode").is_none());
+
+ let imported_roof = read_glb_bytes(&roof_glb).unwrap();
+ assert!((imported_roof.materials[0].color[0] - 0.20).abs() < 1e-4);
+ assert!((imported_roof.materials[0].color[1] - 0.22).abs() < 1e-4);
+ assert!((imported_roof.materials[0].color[2] - 0.25).abs() < 1e-4);
+ assert!((imported_roof.materials[0].color[3] - 1.0).abs() < 1e-4);
+
+ // 3. Multi-node scene GLB emits alphaMode=BLEND, doubleSided, emissive, transmission, ior, and extensionsUsed
+ let scene_glb = scene.export_scene_glb_bytes(true).unwrap();
+ let scene_json = parse_glb_json(&scene_glb);
+ let mats = scene_json["materials"].as_array().unwrap();
+ let find_mat = |name: &str| {
+ mats.iter()
+ .find(|m| m["name"].as_str() == Some(name))
+ .unwrap_or_else(|| panic!("missing material '{name}' in {mats:?}"))
+ };
+
+ let steam_m = find_mat("steam");
+ assert_eq!(steam_m["alphaMode"].as_str(), Some("BLEND"));
+ assert_eq!(steam_m["doubleSided"].as_bool(), Some(true));
+ assert!(
+ (steam_m["pbrMetallicRoughness"]["baseColorFactor"][3].as_f64().unwrap() - 0.25).abs() < 1e-5
+ );
+
+ let water_m = find_mat("onsen_water");
+ assert_eq!(water_m["alphaMode"].as_str(), Some("BLEND"));
+ assert!(
+ (water_m["extensions"]["KHR_materials_transmission"]["transmissionFactor"]
+ .as_f64()
+ .unwrap()
+ - 0.85)
+ .abs()
+ < 1e-5
+ );
+ assert!(
+ (water_m["extensions"]["KHR_materials_ior"]["ior"].as_f64().unwrap() - 1.33).abs() < 1e-5
+ );
+
+ let lantern_m = find_mat("shoji_glow");
+ let em = lantern_m["emissiveFactor"].as_array().unwrap();
+ assert!((em[1].as_f64().unwrap() as f32 - srgb_to_linear_ref(0.75)).abs() < 1e-5);
+ assert!(
+ (lantern_m["extensions"]["KHR_materials_emissive_strength"]["emissiveStrength"]
+ .as_f64()
+ .unwrap()
+ - 2.5)
+ .abs()
+ < 1e-5
+ );
+
+ let exts_used: Vec<&str> = scene_json["extensionsUsed"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter_map(|v| v.as_str())
+ .collect();
+ assert!(exts_used.contains(&"KHR_materials_transmission"));
+ assert!(exts_used.contains(&"KHR_materials_ior"));
+ assert!(exts_used.contains(&"KHR_materials_emissive_strength"));
+
+ // 4. Round-trip import of steam, water, lantern materials preserves all fields
+ let steam_glb = write_glb_bytes(scene.get_part("steam").unwrap(), true).unwrap();
+ let imp_steam = read_glb_bytes(&steam_glb).unwrap();
+ assert!((imp_steam.materials[0].color[3] - 0.25).abs() < 1e-4);
+ assert!(imp_steam.materials[0].double_sided);
+
+ let water_glb = write_glb_bytes(scene.get_part("water").unwrap(), true).unwrap();
+ let imp_water = read_glb_bytes(&water_glb).unwrap();
+ assert!((imp_water.materials[0].transmission - 0.85).abs() < 1e-4);
+ assert!((imp_water.materials[0].ior - 1.33).abs() < 1e-4);
+
+ let lantern_glb = write_glb_bytes(scene.get_part("lantern").unwrap(), true).unwrap();
+ let imp_lantern = read_glb_bytes(&lantern_glb).unwrap();
+ assert!((imp_lantern.materials[0].emissive[1] - 0.75).abs() < 1e-4);
+ assert!((imp_lantern.materials[0].emissive_strength - 2.5).abs() < 1e-4);
+
+ // 5. color(r,g,b,a) shorthand sets alpha & metallic=0
+ let mist = scene.get_part("mist").unwrap();
+ assert!((mist.materials[0].color[3] - 0.35).abs() < 1e-6);
+ assert!((mist.materials[0].metallic - 0.0).abs() < 1e-6);
+
+ // 6. Software renderer handles translucent + emissive scene cleanly
+ let png = scene.render_preview_scene_bytes(256).unwrap();
+ assert!(png.len() > 1000 && &png[0..8] == b"\x89PNG\r\n\x1a\n");
+}
+
+#[test]
+fn test_non_glb_multi_part_scene_exports() {
+ let script = r#"
+ units("mm")
+ base = box(40, 40, 5, z0=0)
+ pillar = cyl(4, 20, segs=16, at=(0, 0, 15))
+ cap = box(12, 12, 4, z0=25)
+ "#;
+ let mut scene = Scene::new();
+ let obs = eval_script(&mut scene, Dialect::Pipe, script).expect("eval multi-part scene");
+ assert!(obs.ok, "{}", obs.text);
+
+ // 1. OBJ multi-object export preserves named parts with `o <name>`
+ let obj_bytes = scene.export_scene_bytes("obj").unwrap();
+ let obj_text = String::from_utf8(obj_bytes).unwrap();
+ assert!(obj_text.contains("o base\n"), "OBJ missing base group");
+ assert!(obj_text.contains("o pillar\n"), "OBJ missing pillar group");
+ assert!(obj_text.contains("o cap\n"), "OBJ missing cap group");
+
+ // 2. 3MF multi-object export emits separate <object> & <item> entries + millimeter unit
+ let threemf_bytes = scene.export_scene_bytes("3mf").unwrap();
+ let threemf_text = String::from_utf8_lossy(&threemf_bytes);
+ assert!(threemf_text.contains(r#"unit="millimeter""#));
+ assert!(threemf_text.contains(r#"name="base""#));
+ assert!(threemf_text.contains(r#"name="pillar""#));
+ assert!(threemf_text.contains(r#"name="cap""#));
+ assert!(threemf_text.contains(r#"<item objectid="3"/>"#));
+
+ // 3. Binary STL combines all 3 parts (triangle count > single part)
+ let single_stl = scene
+ .export_mesh_bytes(scene.get_part("base").unwrap(), "stl")
+ .unwrap();
+ let scene_stl = scene.export_scene_bytes("stl").unwrap();
+ let single_tris =
+ u32::from_le_bytes([single_stl[80], single_stl[81], single_stl[82], single_stl[83]]);
+ let scene_tris =
+ u32::from_le_bytes([scene_stl[80], scene_stl[81], scene_stl[82], scene_stl[83]]);
+ assert!(
+ scene_tris > single_tris * 3,
+ "scene STL must contain all parts: scene_tris={scene_tris}, single_tris={single_tris}"
+ );
+
+ // 4. STEP multi-solid export contains 3 MANIFOLD_SOLID_BREP solids in forma_scene
+ let step_bytes = scene.export_scene_bytes("step").unwrap();
+ let step_text = String::from_utf8(step_bytes).unwrap();
+ assert!(step_text.contains("SI_UNIT(.MILLI.,.METRE.)"));
+ assert!(step_text.contains("MANIFOLD_SOLID_BREP('base'"));
+ assert!(step_text.contains("MANIFOLD_SOLID_BREP('pillar'"));
+ assert!(step_text.contains("MANIFOLD_SOLID_BREP('cap'"));
+ assert!(step_text.contains("ADVANCED_BREP_SHAPE_REPRESENTATION('forma_scene'"));
+}
+
+#[test]
+fn test_native_cli_multipart_scene_ergonomics_and_spec() {
+ assert!(SPEC_PIPE.contains("--scene"), "SPEC_PIPE must mention CLI --scene");
+ assert!(SPEC_PIPE.contains("alpha="), "SPEC_PIPE must document alpha=");
+ assert!(SPEC_PIPE.contains("emissive="), "SPEC_PIPE must document emissive=");
+ assert!(SPEC_PIPE.contains("transmission="), "SPEC_PIPE must document transmission=");
+ let scene_spec = spec_topic("scene").unwrap();
+ assert!(scene_spec.contains("--scene"));
+ assert!(scene_spec.contains(".obj"));
+ assert!(scene_spec.contains(".3mf"));
+ assert!(scene_spec.contains(".step"));
+
+ let bin = env!("CARGO_BIN_EXE_forma");
+ let help = Command::new(bin).arg("--help").output().expect("forma --help");
+ assert!(help.status.success());
+ let help_text = String::from_utf8_lossy(&help.stdout);
+ assert!(help_text.contains("KEY OPTIONS:") && help_text.contains("--scene"));
+
+ let dir = std::env::temp_dir().join(format!("forma_cli_scene_test_{}", std::process::id()));
+ let _ = std::fs::create_dir_all(&dir);
+ let script = r#"
+ floor = box(4, 4, 0.2, z0=0) | mat("wood", color=(0.24, 0.16, 0.10))
+ steam = sphere(0.5, at=(0, 0, 1.2)) | mat("steam", color=(1, 1, 1), alpha=0.25)
+ "#;
+
+ // 1. Omitting --scene on a multi-part export emits a clear NOTE on stderr
+ let single_glb = dir.join("single.glb");
+ let mut child = Command::new(bin)
+ .args(["eval", "--out", single_glb.to_str().unwrap()])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("spawn forma");
+ child.stdin.as_mut().unwrap().write_all(script.as_bytes()).unwrap();
+ let out = child.wait_with_output().unwrap();
+ assert!(out.status.success());
+ let stderr = String::from_utf8_lossy(&out.stderr);
+ assert!(
+ stderr.contains("NOTE:") && stderr.contains("--scene"),
+ "expected --scene hint on stderr, got: {stderr}"
+ );
+
+ // 2. Passing --scene with .obj + --render exports all parts silently (no NOTE)
+ let scene_obj = dir.join("scene.obj");
+ let scene_png = dir.join("scene.png");
+ let mut child2 = Command::new(bin)
+ .args([
+ "eval",
+ "--scene",
+ "--out",
+ scene_obj.to_str().unwrap(),
+ "--render",
+ scene_png.to_str().unwrap(),
+ "--view",
+ "iso",
+ ])
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped())
+ .spawn()
+ .expect("spawn forma --scene");
+ child2.stdin.as_mut().unwrap().write_all(script.as_bytes()).unwrap();
+ let out2 = child2.wait_with_output().unwrap();
+ assert!(out2.status.success(), "stderr={}", String::from_utf8_lossy(&out2.stderr));
+ assert!(
+ String::from_utf8_lossy(&out2.stderr).trim().is_empty(),
+ "unexpected stderr with --scene: {}",
+ String::from_utf8_lossy(&out2.stderr)
+ );
+ let obj_text = std::fs::read_to_string(&scene_obj).unwrap();
+ assert!(obj_text.contains("o floor") && obj_text.contains("o steam"));
+ assert!(std::fs::metadata(&scene_png).unwrap().len() > 500);
+
+ let _ = std::fs::remove_dir_all(&dir);
+}
diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rs
index 5bc6303..c2a55e0 100644
--- a/crates/forma-core/src/export.rs
+++ b/crates/forma-core/src/export.rs
@@ -2,8 +2,9 @@
//! 3MF (.3mf), faceted STEP (.step/.stp), and Blender (.blend via optional Blender CLI bridge).
use crate::math::Vec3;
-use crate::mesh::PolyMesh;
+use crate::mesh::{Material, PolyMesh};
use crate::units::Unit;
+use std::collections::BTreeSet;
use std::fs::File;
use std::io::{BufWriter, Write};
use std::path::Path;
@@ -52,6 +53,80 @@ pub(crate) fn linear_rgba_to_srgb(rgba: [f32; 4]) -> [f32; 4] {
]
}
+/// Build a spec-compliant glTF 2.0 material JSON object from a Forma `Material`.
+/// Converts sRGB `color[0..3]` and `emissive[0..3]` to linear RGB per glTF 2.0,
+/// emits `alphaMode: "BLEND"` whenever `color[3] < 1.0`, and records any used KHR
+/// material extensions (`KHR_materials_transmission`, `KHR_materials_ior`,
+/// `KHR_materials_emissive_strength`) in `used_extensions`.
+fn build_gltf_material(
+ mat: &Material,
+ used_extensions: &mut BTreeSet<&'static str>,
+) -> serde_json::Value {
+ let base_color = srgb_rgba_to_linear(mat.color);
+ let mut obj = serde_json::json!({
+ "name": mat.name,
+ "pbrMetallicRoughness": {
+ "baseColorFactor": base_color,
+ "metallicFactor": mat.metallic.clamp(0.0, 1.0),
+ "roughnessFactor": mat.roughness.clamp(0.0, 1.0)
+ }
+ });
+ if mat.is_alpha_blended() {
+ obj["alphaMode"] = serde_json::json!("BLEND");
+ }
+ if mat.double_sided {
+ obj["doubleSided"] = serde_json::json!(true);
+ }
+ let mut mat_exts = serde_json::Map::new();
+ if mat.has_emissive() {
+ let em = [
+ srgb_to_linear(mat.emissive[0]),
+ srgb_to_linear(mat.emissive[1]),
+ srgb_to_linear(mat.emissive[2]),
+ ];
+ obj["emissiveFactor"] = serde_json::json!(em);
+ if (mat.emissive_strength - 1.0).abs() > 1e-4 {
+ used_extensions.insert("KHR_materials_emissive_strength");
+ mat_exts.insert(
+ "KHR_materials_emissive_strength".into(),
+ serde_json::json!({ "emissiveStrength": mat.emissive_strength.max(0.0) }),
+ );
+ }
+ }
+ let trans = mat.transmission.clamp(0.0, 1.0);
+ if trans > 1e-4 {
+ used_extensions.insert("KHR_materials_transmission");
+ mat_exts.insert(
+ "KHR_materials_transmission".into(),
+ serde_json::json!({ "transmissionFactor": trans }),
+ );
+ }
+ let ior = mat.ior.clamp(1.0, 3.0);
+ if (ior - 1.5).abs() > 1e-4 {
+ used_extensions.insert("KHR_materials_ior");
+ mat_exts.insert("KHR_materials_ior".into(), serde_json::json!({ "ior": ior }));
+ }
+ if !mat_exts.is_empty() {
+ obj["extensions"] = serde_json::Value::Object(mat_exts);
+ }
+ obj
+}
+
+fn gltf_material_dedup_key(mat: &Material) -> String {
+ format!(
+ "{}:{:?}:{}:{}:{:?}:{}:{}:{}:{}",
+ mat.name,
+ mat.color,
+ mat.metallic,
+ mat.roughness,
+ mat.emissive,
+ mat.emissive_strength,
+ mat.transmission,
+ mat.ior,
+ mat.double_sided,
+ )
+}
+
/// Compute deterministic triplanar box UV coordinates for vertex `p` on a face with normal `n`.
#[inline]
fn triplanar_uv(p: Vec3, n: Vec3) -> [f32; 2] {
@@ -396,33 +471,31 @@ pub fn write_glb_bytes_with_unit(mesh: &PolyMesh, yup: bool, unit: Unit) -> Resu
}
}
+ let mut used_extensions: BTreeSet<&'static str> = BTreeSet::new();
let mats_json = if has_mats {
- let mut s = String::from(r#","materials":["#);
- for (i, mat) in mesh.materials.iter().enumerate() {
- if i > 0 {
- s.push(',');
- }
- let name_json = serde_json::to_string(&mat.name).unwrap_or_else(|_| "\"mat\"".to_string());
- let lin = srgb_rgba_to_linear(mat.color);
- s.push_str(&format!(
- r#"{{"name":{},"pbrMetallicRoughness":{{"baseColorFactor":[{},{},{},{}],"metallicFactor":{},"roughnessFactor":{}}}}}"#,
- name_json,
- lin[0], lin[1], lin[2], lin[3],
- mat.metallic, mat.roughness
- ));
- }
- s.push(']');
- s
+ let mats: Vec<serde_json::Value> = mesh
+ .materials
+ .iter()
+ .map(|mat| build_gltf_material(mat, &mut used_extensions))
+ .collect();
+ format!(r#","materials":{}"#, serde_json::Value::Array(mats))
} else {
String::new()
};
+ let exts_json = if used_extensions.is_empty() {
+ String::new()
+ } else {
+ let list: Vec<&str> = used_extensions.into_iter().collect();
+ format!(r#","extensionsUsed":{}"#, serde_json::json!(list))
+ };
let yup_flag = if yup { "true" } else { "false" };
let mut json_bytes = format!(
- r#"{{"asset":{{"version":"2.0","generator":"forma-core 0.4","extras":{{"forma_yup":{}}}}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0,"name":"forma_mesh"}}],"meshes":[{{"name":"forma_mesh","primitives":[{}]}}]{},"buffers":[{{"byteLength":{}}}],"bufferViews":[{}],"accessors":[{}]}}"#,
+ r#"{{"asset":{{"version":"2.0","generator":"forma-core 0.4","extras":{{"forma_yup":{}}}}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0,"name":"forma_mesh"}}],"meshes":[{{"name":"forma_mesh","primitives":[{}]}}]{}{},"buffers":[{{"byteLength":{}}}],"bufferViews":[{}],"accessors":[{}]}}"#,
yup_flag,
prims_json,
mats_json,
+ exts_json,
bin.len(),
bviews_json,
accs_json,
@@ -478,6 +551,7 @@ pub fn write_scene_glb_bytes_with_unit(
let mut accessors: Vec<serde_json::Value> = Vec::new();
let mut gltf_materials: Vec<serde_json::Value> = Vec::new();
let mut mat_dedup: HashMap<String, usize> = HashMap::new();
+ let mut used_extensions: BTreeSet<&'static str> = BTreeSet::new();
let mut gltf_meshes: Vec<serde_json::Value> = Vec::new();
let mut mesh_ptr_map: HashMap<usize, usize> = HashMap::new();
let mut gltf_nodes: Vec<serde_json::Value> = Vec::new();
@@ -544,18 +618,10 @@ pub fn write_scene_glb_bytes_with_unit(
});
if has_mats {
let mat = &mesh.materials[p.gid];
- let key = format!("{}:{:?}:{}:{}", mat.name, mat.color, mat.metallic, mat.roughness);
+ let key = gltf_material_dedup_key(mat);
let mslot = *mat_dedup.entry(key).or_insert_with(|| {
let idx = gltf_materials.len();
- let lin = srgb_rgba_to_linear(mat.color);
- gltf_materials.push(serde_json::json!({
- "name": mat.name,
- "pbrMetallicRoughness": {
- "baseColorFactor": lin,
- "metallicFactor": mat.metallic,
- "roughnessFactor": mat.roughness
- }
- }));
+ gltf_materials.push(build_gltf_material(mat, &mut used_extensions));
idx
});
prim["material"] = serde_json::json!(mslot);
@@ -595,6 +661,10 @@ pub fn write_scene_glb_bytes_with_unit(
if !gltf_materials.is_empty() {
root["materials"] = serde_json::json!(gltf_materials);
}
+ if !used_extensions.is_empty() {
+ let list: Vec<&str> = used_extensions.into_iter().collect();
+ root["extensionsUsed"] = serde_json::json!(list);
+ }
let mut json_bytes = root.to_string().into_bytes();
while json_bytes.len() % 4 != 0 { json_bytes.push(b' '); }
@@ -646,6 +716,44 @@ pub fn write_obj_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
Ok(out)
}
+/// Export a multi-object named scene to Wavefront `.obj` bytes with `o <name>` object groups.
+pub fn write_scene_obj_bytes(parts: &[(&str, &PolyMesh)]) -> Result<Vec<u8>, String> {
+ if parts.is_empty() {
+ return Err("cannot export empty scene to OBJ".into());
+ }
+ let total_v: usize = parts.iter().map(|(_, m)| m.verts.len()).sum();
+ let total_f: usize = parts.iter().map(|(_, m)| m.faces.len()).sum();
+ if total_v == 0 || total_f == 0 {
+ return Err("scene had no non-empty meshes to export".into());
+ }
+ let mut out = Vec::with_capacity(total_v * 32 + total_f * 20 + parts.len() * 24);
+ writeln!(out, "# Exported by forma-core 0.4 (multi-object scene)").map_err(|e| e.to_string())?;
+ let mut v_offset = 0usize;
+ for &(name, mesh) in parts {
+ if mesh.verts.is_empty() || mesh.faces.is_empty() {
+ continue;
+ }
+ let clean_name: String = name
+ .chars()
+ .map(|c| if c.is_whitespace() { '_' } else { c })
+ .collect();
+ writeln!(out, "o {}", if clean_name.is_empty() { "part" } else { &clean_name })
+ .map_err(|e| e.to_string())?;
+ for v in &mesh.verts {
+ writeln!(out, "v {:.6} {:.6} {:.6}", v.x, v.y, v.z).map_err(|e| e.to_string())?;
+ }
+ for face in &mesh.faces {
+ write!(out, "f").map_err(|e| e.to_string())?;
+ for &vi in &face.verts {
+ write!(out, " {}", v_offset + vi + 1).map_err(|e| e.to_string())?;
+ }
+ writeln!(out).map_err(|e| e.to_string())?;
+ }
+ v_offset += mesh.verts.len();
+ }
+ Ok(out)
+}
+
pub fn write_obj(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
let bytes = write_obj_bytes(mesh)?;
let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;
@@ -697,13 +805,23 @@ pub fn write_3mf_bytes(mesh: &PolyMesh) -> Result<Vec<u8>, String> {
write_3mf_bytes_with_unit(mesh, Unit::Meter)
}
-/// Export a PolyMesh to 3MF bytes (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
-/// Vertices are written in model units and `model/@unit` declares `unit`, so slicers and CAD
-/// tools interpret the coordinates at the right physical size.
-pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
- if mesh.faces.is_empty() || mesh.verts.is_empty() {
- return Err("cannot export empty mesh to 3MF".into());
+fn xml_escape_attr(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ for ch in s.chars() {
+ match ch {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&apos;"),
+ c if c.is_control() => out.push(' '),
+ c => out.push(c),
+ }
}
+ out
+}
+
+fn package_3mf_zip(model: &str) -> Vec<u8> {
let content_types = concat!(
r#"<?xml version="1.0" encoding="UTF-8"?>"#,
r#"<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">"#,
@@ -717,24 +835,6 @@ pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>,
r#"<Relationship Target="/3D/3dmodel.model" Id="rel0" Type="http://schemas.microsoft.com/3dmanufacturing/2013/01/3dmodel"/>"#,
r#"</Relationships>"#
);
- let mut model = String::with_capacity(mesh.verts.len() * 48 + mesh.faces.len() * 40 + 512);
- model.push_str(&format!(
- r#"<?xml version="1.0" encoding="UTF-8"?><model unit="{}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources><object id="1" type="model"><mesh><vertices>"#,
- unit.threemf_name()
- ));
- for v in &mesh.verts {
- model.push_str(&format!(r#"<vertex x="{:.6}" y="{:.6}" z="{:.6}"/>"#, v.x, v.y, v.z));
- }
- model.push_str("</vertices><triangles>");
- for fi in 0..mesh.faces.len() {
- for [a, b, c] in mesh.triangulate_face(fi) {
- model.push_str(&format!(r#"<triangle v1="{a}" v2="{b}" v3="{c}"/>"#));
- }
- }
- model.push_str(
- r#"</triangles></mesh></object></resources><build><item objectid="1"/></build></model>"#,
- );
-
let files: [(&str, &[u8]); 3] = [
("[Content_Types].xml", content_types.as_bytes()),
("_rels/.rels", rels.as_bytes()),
@@ -748,7 +848,6 @@ pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>,
let crc = zip_crc32(data);
let len = data.len() as u32;
let nb = name.as_bytes();
- // Local file header (stored, method=0)
zip.extend_from_slice(&0x0403_4B50u32.to_le_bytes());
zip.extend_from_slice(&20u16.to_le_bytes());
zip.extend_from_slice(&0u16.to_le_bytes());
@@ -763,7 +862,6 @@ pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>,
zip.extend_from_slice(nb);
zip.extend_from_slice(data);
- // Central directory header
central.extend_from_slice(&0x0201_4B50u32.to_le_bytes());
central.extend_from_slice(&20u16.to_le_bytes());
central.extend_from_slice(&20u16.to_le_bytes());
@@ -786,7 +884,6 @@ pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>,
let cd_off = zip.len() as u32;
let cd_len = central.len() as u32;
zip.extend_from_slice(&central);
- // End of central directory
zip.extend_from_slice(&0x0605_4B50u32.to_le_bytes());
zip.extend_from_slice(&0u16.to_le_bytes());
zip.extend_from_slice(&0u16.to_le_bytes());
@@ -795,7 +892,78 @@ pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>,
zip.extend_from_slice(&cd_len.to_le_bytes());
zip.extend_from_slice(&cd_off.to_le_bytes());
zip.extend_from_slice(&0u16.to_le_bytes());
- Ok(zip)
+ zip
+}
+
+/// Export a PolyMesh to 3MF bytes (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
+/// Vertices are written in model units and `model/@unit` declares `unit`, so slicers and CAD
+/// tools interpret the coordinates at the right physical size.
+pub fn write_3mf_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
+ if mesh.faces.is_empty() || mesh.verts.is_empty() {
+ return Err("cannot export empty mesh to 3MF".into());
+ }
+ let mut model = String::with_capacity(mesh.verts.len() * 48 + mesh.faces.len() * 40 + 512);
+ model.push_str(&format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?><model unit="{}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources><object id="1" type="model"><mesh><vertices>"#,
+ unit.threemf_name()
+ ));
+ for v in &mesh.verts {
+ model.push_str(&format!(r#"<vertex x="{:.6}" y="{:.6}" z="{:.6}"/>"#, v.x, v.y, v.z));
+ }
+ model.push_str("</vertices><triangles>");
+ for fi in 0..mesh.faces.len() {
+ for [a, b, c] in mesh.triangulate_face(fi) {
+ model.push_str(&format!(r#"<triangle v1="{a}" v2="{b}" v3="{c}"/>"#));
+ }
+ }
+ model.push_str(
+ r#"</triangles></mesh></object></resources><build><item objectid="1"/></build></model>"#,
+ );
+ Ok(package_3mf_zip(&model))
+}
+
+/// Export a multi-object named scene to 3MF bytes with separate named `<object>` entries.
+pub fn write_scene_3mf_bytes_with_unit(parts: &[(&str, &PolyMesh)], unit: Unit) -> Result<Vec<u8>, String> {
+ let non_empty: Vec<(&str, &PolyMesh)> = parts
+ .iter()
+ .copied()
+ .filter(|(_, m)| !m.verts.is_empty() && !m.faces.is_empty())
+ .collect();
+ if non_empty.is_empty() {
+ return Err("cannot export empty scene to 3MF".into());
+ }
+ let est_v: usize = non_empty.iter().map(|(_, m)| m.verts.len()).sum();
+ let est_f: usize = non_empty.iter().map(|(_, m)| m.faces.len()).sum();
+ let mut model = String::with_capacity(est_v * 48 + est_f * 40 + 512 + non_empty.len() * 128);
+ model.push_str(&format!(
+ r#"<?xml version="1.0" encoding="UTF-8"?><model unit="{}" xml:lang="en-US" xmlns="http://schemas.microsoft.com/3dmanufacturing/core/2015/02"><resources>"#,
+ unit.threemf_name()
+ ));
+ let mut ids: Vec<usize> = Vec::with_capacity(non_empty.len());
+ for (idx, &(name, mesh)) in non_empty.iter().enumerate() {
+ let oid = idx + 1;
+ ids.push(oid);
+ model.push_str(&format!(
+ r#"<object id="{oid}" name="{}" type="model"><mesh><vertices>"#,
+ xml_escape_attr(name)
+ ));
+ for v in &mesh.verts {
+ model.push_str(&format!(r#"<vertex x="{:.6}" y="{:.6}" z="{:.6}"/>"#, v.x, v.y, v.z));
+ }
+ model.push_str("</vertices><triangles>");
+ for fi in 0..mesh.faces.len() {
+ for [a, b, c] in mesh.triangulate_face(fi) {
+ model.push_str(&format!(r#"<triangle v1="{a}" v2="{b}" v3="{c}"/>"#));
+ }
+ }
+ model.push_str("</triangles></mesh></object>");
+ }
+ model.push_str("</resources><build>");
+ for oid in ids {
+ model.push_str(&format!(r#"<item objectid="{oid}"/>"#));
+ }
+ model.push_str("</build></model>");
+ Ok(package_3mf_zip(&model))
}
/// Export a PolyMesh to 3MF (3D Manufacturing Format: pure-Rust OPC ZIP + XML, zero crates).
@@ -853,48 +1021,27 @@ fn step_length_unit_entities(unit: Unit) -> String {
}
}
-/// Export a PolyMesh to faceted STEP (AP214). Coordinates are written in model units and the
-/// geometric context declares `unit` as its length unit. The 1e-6 m distance accuracy is
-/// converted into model units so it stays physically constant.
-pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
- if mesh.faces.is_empty() || mesh.verts.is_empty() {
- return Err("cannot export empty mesh to STEP".into());
- }
- let mut s = String::with_capacity(mesh.verts.len() * 120 + mesh.faces.len() * 480 + 2048);
- s.push_str(
- "ISO-10303-21;\n\
- HEADER;\n\
- FILE_DESCRIPTION(('Forma Pure-Rust Faceted Manifold Solid (Planar Faces)'),'2;1');\n\
- FILE_NAME('forma_part.step','2026-12-03T00:00:00',('forma'),('forma-core 0.4'),'forma-core','forma','');\n\
- FILE_SCHEMA(('AUTOMOTIVE_DESIGN { 1 0 10303 214 1 1 1 1 }'));\n\
- ENDSEC;\n\
- DATA;\n\
- #1=APPLICATION_CONTEXT('automotive design');\n\
- #2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1);\n\
- #3=PRODUCT_CONTEXT('',#1,'mechanical');\n\
- #4=PRODUCT('forma_part','forma_part','',(#3));\n\
- #5=PRODUCT_DEFINITION_FORMATION('','',#4);\n\
- #6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design');\n\
- #7=PRODUCT_DEFINITION('design','',#5,#6);\n\
- #8=PRODUCT_DEFINITION_SHAPE('','',#7);\n",
- );
- s.push_str(&step_length_unit_entities(unit));
- s.push_str(&format!(
- "#10=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n\
- #11=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT());\n\
- #12=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({:.6E}),#9,'distance_accuracy_value','');\n\
- #13=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))GLOBAL_UNIT_ASSIGNED_CONTEXT((#9,#10,#11))REPRESENTATION_CONTEXT('Context3D','3D Context'));\n",
- 1e-6 / unit.meters_per_unit()
- ));
+fn step_escape_str(s: &str) -> String {
+ s.chars()
+ .map(|c| if c == '\'' || c.is_control() { '_' } else { c })
+ .collect()
+}
- let mut next_id = 20usize;
+fn append_step_solid(
+ mesh: &PolyMesh,
+ solid_name: &str,
+ s: &mut String,
+ next_id: &mut usize,
+) -> Option<usize> {
let mut alloc = || {
- let id = next_id;
- next_id += 1;
+ let id = *next_id;
+ *next_id += 1;
id
};
+ if mesh.verts.is_empty() || mesh.faces.is_empty() {
+ return None;
+ }
- // 1. Vertices -> CARTESIAN_POINT + VERTEX_POINT
let mut vp_ids = Vec::with_capacity(mesh.verts.len());
let mut cp_ids = Vec::with_capacity(mesh.verts.len());
for v in &mesh.verts {
@@ -906,7 +1053,6 @@ pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>
vp_ids.push(vpid);
}
- // Expand non-planar n-gons into planar triangles so every STEP ADVANCED_FACE lies on a true plane.
let mut planar_faces: Vec<Vec<usize>> = Vec::with_capacity(mesh.faces.len());
for (fi, f) in mesh.faces.iter().enumerate() {
let n = f.verts.len();
@@ -932,7 +1078,6 @@ pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>
}
}
- // 2. Deduplicated undirected edges -> LINE + EDGE_CURVE (oriented min_v -> max_v)
let mut edge_map: std::collections::BTreeMap<(usize, usize), usize> = std::collections::BTreeMap::new();
for fv in &planar_faces {
let n = fv.len();
@@ -966,7 +1111,6 @@ pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>
}
}
- // 3. Faces -> PLANE + EDGE_LOOP + FACE_OUTER_BOUND + ADVANCED_FACE
let mut face_ids = Vec::with_capacity(planar_faces.len());
for fv in &planar_faces {
let n = fv.len();
@@ -1029,19 +1173,92 @@ pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>
face_ids.push(af_id);
}
+ if face_ids.is_empty() {
+ return None;
+ }
let sh_id = alloc();
let msb_id = alloc();
- let rep_id = alloc();
- let sdr_id = alloc();
let f_list: Vec<String> = face_ids.iter().map(|id| format!("#{id}")).collect();
s.push_str(&format!("#{sh_id}=CLOSED_SHELL('',({}));\n", f_list.join(",")));
- s.push_str(&format!("#{msb_id}=MANIFOLD_SOLID_BREP('forma_solid',#{sh_id});\n"));
- s.push_str(&format!("#{rep_id}=ADVANCED_BREP_SHAPE_REPRESENTATION('forma_part',(#{msb_id}),#13);\n"));
+ s.push_str(&format!(
+ "#{msb_id}=MANIFOLD_SOLID_BREP('{}',#{sh_id});\n",
+ step_escape_str(solid_name)
+ ));
+ Some(msb_id)
+}
+
+/// Export a multi-solid faceted STEP (AP214) scene declaring `unit`.
+pub fn write_scene_step_bytes_with_unit(parts: &[(&str, &PolyMesh)], unit: Unit) -> Result<Vec<u8>, String> {
+ let non_empty: Vec<(&str, &PolyMesh)> = parts
+ .iter()
+ .copied()
+ .filter(|(_, m)| !m.verts.is_empty() && !m.faces.is_empty())
+ .collect();
+ if non_empty.is_empty() {
+ return Err("cannot export empty scene to STEP".into());
+ }
+ let est_v: usize = non_empty.iter().map(|(_, m)| m.verts.len()).sum();
+ let est_f: usize = non_empty.iter().map(|(_, m)| m.faces.len()).sum();
+ let rep_name = if non_empty.len() == 1 { "forma_part" } else { "forma_scene" };
+ let mut s = String::with_capacity(est_v * 120 + est_f * 480 + 2048);
+ s.push_str(&format!(
+ "ISO-10303-21;\n\
+ HEADER;\n\
+ FILE_DESCRIPTION(('Forma Pure-Rust Faceted Manifold Solid (Planar Faces)'),'2;1');\n\
+ FILE_NAME('{rep_name}.step','2026-12-03T00:00:00',('forma'),('forma-core 0.4'),'forma-core','forma','');\n\
+ FILE_SCHEMA(('AUTOMOTIVE_DESIGN {{ 1 0 10303 214 1 1 1 1 }}'));\n\
+ ENDSEC;\n\
+ DATA;\n\
+ #1=APPLICATION_CONTEXT('automotive design');\n\
+ #2=APPLICATION_PROTOCOL_DEFINITION('international standard','automotive_design',2000,#1);\n\
+ #3=PRODUCT_CONTEXT('',#1,'mechanical');\n\
+ #4=PRODUCT('{rep_name}','{rep_name}','',(#3));\n\
+ #5=PRODUCT_DEFINITION_FORMATION('','',#4);\n\
+ #6=PRODUCT_DEFINITION_CONTEXT('part definition',#1,'design');\n\
+ #7=PRODUCT_DEFINITION('design','',#5,#6);\n\
+ #8=PRODUCT_DEFINITION_SHAPE('','',#7);\n"
+ ));
+ s.push_str(&step_length_unit_entities(unit));
+ s.push_str(&format!(
+ "#10=(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.));\n\
+ #11=(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT());\n\
+ #12=UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE({:.6E}),#9,'distance_accuracy_value','');\n\
+ #13=(GEOMETRIC_REPRESENTATION_CONTEXT(3)GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#12))GLOBAL_UNIT_ASSIGNED_CONTEXT((#9,#10,#11))REPRESENTATION_CONTEXT('Context3D','3D Context'));\n",
+ 1e-6 / unit.meters_per_unit()
+ ));
+
+ let mut next_id = 20usize;
+ let mut msb_ids = Vec::with_capacity(non_empty.len());
+ for &(name, mesh) in &non_empty {
+ if let Some(id) = append_step_solid(mesh, name, &mut s, &mut next_id) {
+ msb_ids.push(id);
+ }
+ }
+ if msb_ids.is_empty() {
+ return Err("cannot export empty scene to STEP".into());
+ }
+ let rep_id = next_id;
+ let sdr_id = next_id + 1;
+ let msb_list: Vec<String> = msb_ids.iter().map(|id| format!("#{id}")).collect();
+ s.push_str(&format!(
+ "#{rep_id}=ADVANCED_BREP_SHAPE_REPRESENTATION('{rep_name}',({}),#13);\n",
+ msb_list.join(",")
+ ));
s.push_str(&format!("#{sdr_id}=SHAPE_DEFINITION_REPRESENTATION(#8,#{rep_id});\n"));
s.push_str("ENDSEC;\nEND-ISO-10303-21;\n");
Ok(s.into_bytes())
}
+/// Export a PolyMesh to faceted STEP (AP214). Coordinates are written in model units and the
+/// geometric context declares `unit` as its length unit. The 1e-6 m distance accuracy is
+/// converted into model units so it stays physically constant.
+pub fn write_step_bytes_with_unit(mesh: &PolyMesh, unit: Unit) -> Result<Vec<u8>, String> {
+ if mesh.faces.is_empty() || mesh.verts.is_empty() {
+ return Err("cannot export empty mesh to STEP".into());
+ }
+ write_scene_step_bytes_with_unit(&[("forma_solid", mesh)], unit)
+}
+
/// Export a PolyMesh to faceted ISO 10303-21 STEP (AP214) planar-face manifold solid (`.step` / `.stp`).
pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {
write_step_with_unit(mesh, path, Unit::Meter)
diff --git a/crates/forma-core/src/import.rs b/crates/forma-core/src/import.rs
index 46b6980..16fb2aa 100644
--- a/crates/forma-core/src/import.rs
+++ b/crates/forma-core/src/import.rs
@@ -492,11 +492,51 @@ pub fn read_glb_bytes_with_opts(bytes: &[u8], yup_override: Option<bool>) -> Res
])
})
.unwrap_or([0.72, 0.75, 0.80, 1.0]);
- let metallic = pbr.and_then(|p| p.get("metallicFactor")).and_then(|v| v.as_f64()).unwrap_or(0.1) as f32;
+ let metallic = pbr.and_then(|p| p.get("metallicFactor")).and_then(|v| v.as_f64()).unwrap_or(0.0) as f32;
let roughness = pbr.and_then(|p| p.get("roughnessFactor")).and_then(|v| v.as_f64()).unwrap_or(0.5) as f32;
+ let emissive = mval
+ .get("emissiveFactor")
+ .and_then(|v| v.as_array())
+ .filter(|a| a.len() >= 3)
+ .map(|a| [
+ crate::export::linear_to_srgb(a[0].as_f64().unwrap_or(0.0) as f32),
+ crate::export::linear_to_srgb(a[1].as_f64().unwrap_or(0.0) as f32),
+ crate::export::linear_to_srgb(a[2].as_f64().unwrap_or(0.0) as f32),
+ ])
+ .unwrap_or([0.0, 0.0, 0.0]);
+ let exts = mval.get("extensions");
+ let emissive_strength = exts
+ .and_then(|e| e.get("KHR_materials_emissive_strength"))
+ .and_then(|e| e.get("emissiveStrength"))
+ .and_then(|v| v.as_f64())
+ .unwrap_or(1.0) as f32;
+ let transmission = exts
+ .and_then(|e| e.get("KHR_materials_transmission"))
+ .and_then(|e| e.get("transmissionFactor"))
+ .and_then(|v| v.as_f64())
+ .unwrap_or(0.0) as f32;
+ let ior = exts
+ .and_then(|e| e.get("KHR_materials_ior"))
+ .and_then(|e| e.get("ior"))
+ .and_then(|v| v.as_f64())
+ .unwrap_or(1.5) as f32;
+ let double_sided = mval
+ .get("doubleSided")
+ .and_then(|v| v.as_bool())
+ .unwrap_or(false);
let name = mval.get("name").and_then(|v| v.as_str()).unwrap_or("imported_mat").to_string();
let slot = out.materials.len() as u16;
- out.materials.push(Material { name, color: col, metallic, roughness });
+ out.materials.push(Material {
+ name,
+ color: col,
+ metallic,
+ roughness,
+ emissive,
+ emissive_strength,
+ transmission,
+ ior,
+ double_sided,
+ });
mat_map.insert(mi, slot);
Some(slot)
});
diff --git a/crates/forma-core/src/mesh.rs b/crates/forma-core/src/mesh.rs
index dd3db38..fc58591 100644
--- a/crates/forma-core/src/mesh.rs
+++ b/crates/forma-core/src/mesh.rs
@@ -8,12 +8,39 @@ use std::collections::{BTreeMap, HashMap};
pub type LineageId = u64;
+#[inline]
+fn default_emissive_strength() -> f32 {
+ 1.0
+}
+
+#[inline]
+fn default_ior() -> f32 {
+ 1.5
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Material {
pub name: String,
+ /// Display sRGB `[r, g, b]` plus linear `alpha` in `0.0..=1.0`.
+ /// Converted to linear RGB on glTF 2.0 `baseColorFactor` export.
pub color: [f32; 4],
pub metallic: f32,
pub roughness: f32,
+ /// Display sRGB emissive color `[r, g, b]` in `0.0..=1.0` (all zeros = non-emissive).
+ #[serde(default)]
+ pub emissive: [f32; 3],
+ /// Emissive intensity multiplier (`>= 0.0`, default `1.0`; emits `KHR_materials_emissive_strength` when `!= 1.0`).
+ #[serde(default = "default_emissive_strength")]
+ pub emissive_strength: f32,
+ /// Optical transmission factor `0.0..=1.0` (`KHR_materials_transmission`) for glass/water.
+ #[serde(default)]
+ pub transmission: f32,
+ /// Index of refraction (`1.0..=3.0`, default `1.5`; emits `KHR_materials_ior` when `!= 1.5`).
+ #[serde(default = "default_ior")]
+ pub ior: f32,
+ /// Render both sides of faces (emits glTF `doubleSided: true`).
+ #[serde(default)]
+ pub double_sided: bool,
}
impl Default for Material {
@@ -21,12 +48,32 @@ impl Default for Material {
Self {
name: "default".into(),
color: [0.78, 0.80, 0.84, 1.0],
- metallic: 0.1,
+ metallic: 0.0,
roughness: 0.55,
+ emissive: [0.0, 0.0, 0.0],
+ emissive_strength: 1.0,
+ transmission: 0.0,
+ ior: 1.5,
+ double_sided: false,
}
}
}
+impl Material {
+ /// True when the material uses alpha blending (`color[3] < 1.0`).
+ #[inline]
+ pub fn is_alpha_blended(&self) -> bool {
+ self.color[3] < 1.0 - 1e-4
+ }
+
+ /// True when any emissive channel is non-zero with positive strength.
+ #[inline]
+ pub fn has_emissive(&self) -> bool {
+ self.emissive_strength > 1e-4
+ && (self.emissive[0] > 1e-6 || self.emissive[1] > 1e-6 || self.emissive[2] > 1e-6)
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Face {
pub verts: SmallVec<[usize; 4]>,
diff --git a/crates/forma-core/src/render.rs b/crates/forma-core/src/render.rs
index 3423179..9aa969e 100644
--- a/crates/forma-core/src/render.rs
+++ b/crates/forma-core/src/render.rs
@@ -169,6 +169,101 @@ impl Framebuffer {
}
}
+ /// Alpha-blended triangle rasterizer tested against opaque `zbuf` without writing depth.
+ fn raster_tri_blend(
+ &mut self,
+ p0: [f32; 3],
+ p1: [f32; 3],
+ p2: [f32; 3],
+ color: [u8; 3],
+ alpha: f32,
+ vp: (i32, i32, i32, i32),
+ ) {
+ let a = alpha.clamp(0.0, 1.0);
+ if a <= 1e-4 {
+ return;
+ }
+ let inv_a = 1.0 - a;
+ let area = (p1[0] - p0[0]) * (p2[1] - p0[1]) - (p2[0] - p0[0]) * (p1[1] - p0[1]);
+ let abs_area = area.abs();
+ if abs_area < 1e-4 {
+ return;
+ }
+
+ let min_x = p0[0].min(p1[0]).min(p2[0]).floor() as i32;
+ let max_x = p0[0].max(p1[0]).max(p2[0]).ceil() as i32;
+ let min_y = p0[1].min(p1[1]).min(p2[1]).floor() as i32;
+ let max_y = p0[1].max(p1[1]).max(p2[1]).ceil() as i32;
+
+ let x0 = min_x.max(vp.0);
+ let x1 = max_x.min(vp.2 - 1);
+ let y0 = min_y.max(vp.1);
+ let y1 = max_y.min(vp.3 - 1);
+ if x0 > x1 || y0 > y1 {
+ return;
+ }
+
+ let sign = area.signum();
+ let inv_area_s = 1.0 / abs_area;
+
+ let e0_dx = (p1[1] - p2[1]) * sign;
+ let e0_dy = (p2[0] - p1[0]) * sign;
+ let e1_dx = (p2[1] - p0[1]) * sign;
+ let e1_dy = (p0[0] - p2[0]) * sign;
+ let e2_dx = (p0[1] - p1[1]) * sign;
+ let e2_dy = (p1[0] - p0[0]) * sign;
+
+ let z0_s = p0[2];
+ let dz_dw1 = (p1[2] - p0[2]) * inv_area_s;
+ let dz_dw2 = (p2[2] - p0[2]) * inv_area_s;
+ let dz_dx = e1_dx * dz_dw1 + e2_dx * dz_dw2;
+ let dz_dy = e1_dy * dz_dw1 + e2_dy * dz_dw2;
+
+ let px0 = x0 as f32 + 0.5;
+ let py0 = y0 as f32 + 0.5;
+ let mut w0_row = ((p1[0] - px0) * (p2[1] - py0) - (p2[0] - px0) * (p1[1] - py0)) * sign;
+ let mut w1_row = ((p2[0] - px0) * (p0[1] - py0) - (p0[0] - px0) * (p2[1] - py0)) * sign;
+ let mut w2_row = ((p0[0] - px0) * (p1[1] - py0) - (p1[0] - px0) * (p0[1] - py0)) * sign;
+ let mut z_row = z0_s + w1_row * dz_dw1 + w2_row * dz_dw2;
+
+ let sr = color[0] as f32 * a;
+ let sg = color[1] as f32 * a;
+ let sb = color[2] as f32 * a;
+ let x0u = x0 as usize;
+ let x1u = x1 as usize;
+ for y in y0..=y1 {
+ let row = y as usize * self.w;
+ let z_slice = &self.zbuf[row + x0u..=row + x1u];
+ let rgb_slice = &mut self.rgb[(row + x0u) * 3..(row + x1u + 1) * 3];
+ let mut w0 = w0_row;
+ let mut w1 = w1_row;
+ let mut w2 = w2_row;
+ let mut z = z_row;
+ let mut entered = false;
+ for (dx, &zslot) in z_slice.iter().enumerate() {
+ if w0 >= -1e-4 && w1 >= -1e-4 && w2 >= -1e-4 {
+ entered = true;
+ if z < zslot {
+ let ci = dx * 3;
+ rgb_slice[ci] = (sr + rgb_slice[ci] as f32 * inv_a).clamp(0.0, 255.0) as u8;
+ rgb_slice[ci + 1] = (sg + rgb_slice[ci + 1] as f32 * inv_a).clamp(0.0, 255.0) as u8;
+ rgb_slice[ci + 2] = (sb + rgb_slice[ci + 2] as f32 * inv_a).clamp(0.0, 255.0) as u8;
+ }
+ } else if entered {
+ break;
+ }
+ w0 += e0_dx;
+ w1 += e1_dx;
+ w2 += e2_dx;
+ z += dz_dx;
+ }
+ w0_row += e0_dy;
+ w1_row += e1_dy;
+ w2_row += e2_dy;
+ z_row += dz_dy;
+ }
+ }
+
fn draw_line_z(
&mut self,
p0: [f32; 3],
@@ -287,32 +382,65 @@ fn render_views_to_png(
let size = size.clamp(128, 2048);
let half = size / 2;
- // Pre-extract indexed triangles with normals & base colors (avoids re-projecting shared verts per face)
- let mut tris: Vec<([usize; 3], Vec3, [f32; 3])> = Vec::with_capacity(mesh.faces.len() * 2);
+ struct RenderTri {
+ verts: [usize; 3],
+ face_n: Vec3,
+ base: [f32; 3],
+ emissive: [f32; 3],
+ alpha: f32,
+ double_sided: bool,
+ }
+
+ // Pre-extract indexed triangles with normals & material colors (avoids re-projecting shared verts per face)
+ let mut tris: Vec<RenderTri> = Vec::with_capacity(mesh.faces.len() * 2);
let mut face_normals: Vec<Vec3> = Vec::with_capacity(mesh.faces.len());
let mut edge_runs: Vec<(u64, u32)> = Vec::with_capacity(mesh.faces.len() * 4);
for (fi, f) in mesh.faces.iter().enumerate() {
let n = mesh.face_normal(fi);
face_normals.push(n);
+ let (base_rgb, emissive_rgb, alpha, double_sided) =
+ if let Some(mat) = mesh.materials.get(f.mat_id as usize) {
+ let raw_a = mat.color[3].clamp(0.0, 1.0);
+ let trans = mat.transmission.clamp(0.0, 1.0);
+ let eff_a = if trans > 1e-4 && raw_a >= 0.995 {
+ (1.0 - 0.72 * trans).clamp(0.12, 0.95)
+ } else {
+ raw_a
+ };
+ let em_s = mat.emissive_strength.max(0.0);
+ (
+ [mat.color[0], mat.color[1], mat.color[2]],
+ [mat.emissive[0] * em_s, mat.emissive[1] * em_s, mat.emissive[2] * em_s],
+ eff_a,
+ mat.double_sided,
+ )
+ } else {
+ ([0.66, 0.75, 0.86], [0.0, 0.0, 0.0], 1.0, false)
+ };
+ let is_trans = alpha < 0.995;
let nv_f = f.verts.len();
- for i in 0..nv_f {
- let u = f.verts[i];
- let v = f.verts[(i + 1) % nv_f];
- if u != v {
- let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
- edge_runs.push(((lo << 32) | hi, fi as u32));
+ if !is_trans {
+ for i in 0..nv_f {
+ let u = f.verts[i];
+ let v = f.verts[(i + 1) % nv_f];
+ if u != v {
+ let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
+ edge_runs.push(((lo << 32) | hi, fi as u32));
+ }
}
}
if n.len_sq() <= 1e-18 {
continue;
}
- let base_rgb = if let Some(mat) = mesh.materials.get(f.mat_id as usize) {
- [mat.color[0], mat.color[1], mat.color[2]]
- } else {
- [0.66, 0.75, 0.86]
- };
for tri in mesh.triangulate_face(fi) {
- tris.push((tri, n, base_rgb));
+ tris.push(RenderTri {
+ verts: tri,
+ face_n: n,
+ base: base_rgb,
+ emissive: emissive_rgb,
+ alpha,
+ double_sided,
+ });
}
}
@@ -383,24 +511,34 @@ fn render_views_to_png(
((cy + half_v).ceil() as i32 + 2).min(vp.3),
);
- for (ti, n, base) in &tris {
- // Backface cull on outward-wound solids (cam.fwd points into scene, so front normals have dot < 0)
- if n.dot(cam.fwd) > 0.05 {
+ let mut translucent_indices: Vec<(f32, usize)> = Vec::new();
+ for (ti, t) in tris.iter().enumerate() {
+ let back_facing = t.face_n.dot(cam.fwd) > 0.05;
+ if back_facing && !t.double_sided {
+ continue;
+ }
+ let p0 = proj_verts[t.verts[0]];
+ let p1 = proj_verts[t.verts[1]];
+ let p2 = proj_verts[t.verts[2]];
+ if t.alpha < 0.995 {
+ let avg_z = (p0[2] + p1[2] + p2[2]) * (1.0 / 3.0);
+ translucent_indices.push((avg_z, ti));
continue;
}
+ let n = if back_facing { -t.face_n } else { t.face_n };
let ndotk = n.dot(key_dir).abs();
let ndotf = n.dot(fill_dir).max(0.0);
let hemi = 0.5 + 0.5 * n.z;
let lum = (0.24 + 0.16 * hemi + 0.52 * ndotk + 0.18 * ndotf) as f32;
let col = [
- (base[0] * lum * 255.0).clamp(0.0, 255.0) as u8,
- (base[1] * lum * 255.0).clamp(0.0, 255.0) as u8,
- (base[2] * lum * 255.0).clamp(0.0, 255.0) as u8,
+ ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0) as u8,
+ ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0) as u8,
+ ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0) as u8,
];
- fb.raster_tri(proj_verts[ti[0]], proj_verts[ti[1]], proj_verts[ti[2]], col, *vp);
+ fb.raster_tri(p0, p1, p2, col, *vp);
}
- // Crisp dark feature edges
+ // Crisp dark feature edges on opaque geometry
for &(a, b) in &feature_edges {
fb.draw_line_z(proj_verts[a], proj_verts[b], [32, 42, 58], *vp);
}
@@ -408,6 +546,35 @@ fn render_views_to_png(
// Fast branchless 3x3 depth-discontinuity silhouette & screen-space cavity AO pass
apply_ssao_and_silhouettes(&mut fb, ssao_vp);
+ // Back-to-front alpha-blended translucent pass (tested against opaque zbuf)
+ if !translucent_indices.is_empty() {
+ translucent_indices.sort_unstable_by(|a, b| {
+ b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal)
+ });
+ for &(_, ti) in &translucent_indices {
+ let t = &tris[ti];
+ let back_facing = t.face_n.dot(cam.fwd) > 0.05;
+ let n = if back_facing { -t.face_n } else { t.face_n };
+ let ndotk = n.dot(key_dir).abs();
+ let ndotf = n.dot(fill_dir).max(0.0);
+ let hemi = 0.5 + 0.5 * n.z;
+ let lum = (0.28 + 0.16 * hemi + 0.48 * ndotk + 0.18 * ndotf) as f32;
+ let col = [
+ ((t.base[0] * lum + t.emissive[0]) * 255.0).clamp(0.0, 255.0) as u8,
+ ((t.base[1] * lum + t.emissive[1]) * 255.0).clamp(0.0, 255.0) as u8,
+ ((t.base[2] * lum + t.emissive[2]) * 255.0).clamp(0.0, 255.0) as u8,
+ ];
+ fb.raster_tri_blend(
+ proj_verts[t.verts[0]],
+ proj_verts[t.verts[1]],
+ proj_verts[t.verts[2]],
+ col,
+ t.alpha,
+ *vp,
+ );
+ }
+ }
+
fb.draw_label(vp.0 + 8, vp.1 + 8, label);
}
diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs
index c2e51bf..297c6a4 100644
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@ -416,7 +416,53 @@ impl Scene {
crate::export::write_scene_glb_bytes_with_unit(&nodes, yup, self.unit).map_err(SceneError::OpFailed)
}
- /// Export all named scene parts as a multi-node `.glb` or `.blend` scene file.
+ /// Collect every named scene part for multi-object export.
+ fn collect_scene_meshes(&self) -> Result<Vec<(&str, &PolyMesh)>, SceneError> {
+ if self.parts.is_empty() {
+ return Err(SceneError::EmptyScene);
+ }
+ Ok(self
+ .parts
+ .iter()
+ .map(|(name, entry)| (name.as_str(), entry.mesh.as_ref()))
+ .collect())
+ }
+
+ /// Export ALL named scene parts to in-memory bytes by extension
+ /// (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`, `png`, `svg`).
+ pub fn export_scene_bytes(&self, ext: &str) -> Result<Vec<u8>, SceneError> {
+ match ext.trim_start_matches('.').to_lowercase().as_str() {
+ "glb" => self.export_scene_glb_bytes(true),
+ "obj" => {
+ let refs = self.collect_scene_meshes()?;
+ crate::export::write_scene_obj_bytes(&refs).map_err(SceneError::OpFailed)
+ }
+ "3mf" => {
+ let refs = self.collect_scene_meshes()?;
+ crate::export::write_scene_3mf_bytes_with_unit(&refs, self.unit)
+ .map_err(SceneError::OpFailed)
+ }
+ "stl" => {
+ let merged = self.merged_scene_mesh()?;
+ crate::export::write_stl_binary_bytes(&merged).map_err(SceneError::OpFailed)
+ }
+ "step" | "stp" => {
+ let refs = self.collect_scene_meshes()?;
+ crate::export::write_scene_step_bytes_with_unit(&refs, self.unit)
+ .map_err(SceneError::OpFailed)
+ }
+ "png" => self.render_preview_scene_bytes(512),
+ "svg" => self
+ .export_blueprint_svg_scene_string()
+ .map(String::into_bytes),
+ other => Err(SceneError::OpFailed(format!(
+ "unsupported scene export extension '.{other}' (supported: .glb, .obj, .stl, .3mf, .step, .blend, .png, .svg)"
+ ))),
+ }
+ }
+
+ /// Export all named scene parts as a multi-part scene file
+ /// (`.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.stp`, `.png`, `.svg`).
#[cfg(not(target_arch = "wasm32"))]
pub fn export_scene_path(&self, path: &Path) -> Result<usize, SceneError> {
let ext = path
@@ -424,20 +470,21 @@ impl Scene {
.and_then(|s| s.to_str())
.map(|s| s.to_lowercase())
.unwrap_or_default();
- let bytes = self.export_scene_glb_bytes(true)?;
match ext.as_str() {
- "glb" => {
- std::fs::write(path, &bytes).map_err(|e| SceneError::OpFailed(e.to_string()))?;
- Ok(bytes.len())
- }
"blend" => {
+ let bytes = self.export_scene_glb_bytes(true)?;
crate::export::write_blend_from_glb_bytes(&bytes, path)
.map_err(SceneError::OpFailed)?;
let len = std::fs::metadata(path).map(|m| m.len() as usize).unwrap_or(0);
Ok(len)
}
+ "glb" | "obj" | "3mf" | "stl" | "step" | "stp" | "png" | "svg" => {
+ let bytes = self.export_scene_bytes(&ext)?;
+ std::fs::write(path, &bytes).map_err(|e| SceneError::OpFailed(e.to_string()))?;
+ Ok(bytes.len())
+ }
_ => Err(SceneError::OpFailed(format!(
- "multi-node scene export requires .glb or .blend (got '.{ext}')"
+ "unsupported scene export extension '.{ext}' (supported: .glb, .blend, .obj, .3mf, .stl, .step, .png, .svg)"
))),
}
}
diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rs
index 3817134..8d4e09a 100644
--- a/crates/forma-core/tests/kernel_tests.rs
+++ b/crates/forma-core/tests/kernel_tests.rs
@@ -293,6 +293,7 @@ fn test_pbr_materials_spatial_queries_and_headless_png_renderer() {
color: [0.72, 0.76, 0.82, 1.0],
metallic: 0.9,
roughness: 0.25,
+ ..Default::default()
},
None,
);
@@ -1062,6 +1063,7 @@ fn test_snapshot_restores_last_modified_and_mesh_materials() {
color: [1.0, 0.0, 0.0, 1.0],
metallic: 0.0,
roughness: 0.5,
+ ..Default::default()
},
None,
);
@@ -1167,6 +1169,7 @@ fn test_issue_82_glb_base_color_srgb_to_linear_roundtrip() {
color: srgb,
metallic: 0.2,
roughness: 0.7,
+ ..Default::default()
},
None,
);
diff --git a/crates/forma-core/tests/mcp_ergonomics.rs b/crates/forma-core/tests/mcp_ergonomics.rs
index 1fa50c1..b0ead07 100644
--- a/crates/forma-core/tests/mcp_ergonomics.rs
+++ b/crates/forma-core/tests/mcp_ergonomics.rs
@@ -162,6 +162,7 @@ fn make_two_colored_parts_scene() -> Scene {
color: [0.95, 0.12, 0.12, 1.0],
metallic: 0.1,
roughness: 0.5,
+ ..Default::default()
},
None,
);
@@ -175,6 +176,7 @@ fn make_two_colored_parts_scene() -> Scene {
color: [0.12, 0.90, 0.18, 1.0],
metallic: 0.1,
roughness: 0.5,
+ ..Default::default()
},
None,
);
diff --git a/crates/forma-core/tests/regression_fixes.rs b/crates/forma-core/tests/regression_fixes.rs
index c5e4fdc..4bfed69 100644
--- a/crates/forma-core/tests/regression_fixes.rs
+++ b/crates/forma-core/tests/regression_fixes.rs
@@ -80,6 +80,7 @@ fn test_glb_unconditional_welding_per_prim_compaction_and_u16_indices() {
color: [0.92, 0.28, 0.08, 1.0],
metallic: 0.2,
roughness: 0.3,
+ ..Default::default()
},
None,
);
@@ -91,6 +92,7 @@ fn test_glb_unconditional_welding_per_prim_compaction_and_u16_indices() {
color: [0.58, 0.62, 0.67, 1.0],
metallic: 0.85,
roughness: 0.35,
+ ..Default::default()
},
None,
);
diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs
index 78d9b62..f1c789f 100644
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@ -69,7 +69,7 @@ pub const SPEC_PIPE_GBNF: &str = include_str!("../../../grammar/forma_pipe.gbnf"
/// Concise reference for Forma-Pipe (~485 o200k tokens).
/// Keeps core MCP tool schemas strictly under 800 tokens; advanced topics load on demand via `spec_topic`.
pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up, watertight, default m; scalars persist):
-name = expr | op (multi-line |; _tmp local; del("name"); def f(a=1)=expr; [e for i in range(n)]; math +-*/ sqrt sin cos tan asin acos atan atan2 abs pi; last exports, export scene=true for .glb/.png/.svg).
+name = expr | op (multi-line |; _tmp local; del("name"); def f(a=1)=expr; [e for i in range(n)]; math +-*/ sqrt sin cos tan asin acos atan atan2 abs pi; last exports; pass --scene (CLI) or scene=true (MCP) to export/render ALL parts).
Prims (at=(x,y,z)|[...], z0=Z, rot=(rx,ry,rz)):
box(sx,sy,sz) cyl(r,h,segs=32,axis=z) [6:k*60deg] cone(r0,r1,h) sphere(r) torus(R,r) pipe(ro,ri,h)
revolve([(r,z),...],segs=32) extrude2d([(x,y),...],z0,z1,holes=) loft([(z,[(x,y),...]),...]) gear(z,m=,h=,bore=)
@@ -78,7 +78,7 @@ Ops (| or op(m,...); add/cut take at=):
add(b,at=) cut(b,at=) intersect(b) mirror(x|y|z) array(n,step) radial(n,r=,axis=z) shell(t,open_top=true) subsurf(levels=1,crease=false)
bevel(edges,w,segs=1) [vertical|top_rim|bottom_rim|outer_rim|sharp|all] extrude(faces,d) inset(faces,amt,depth=0) [top|bottom|sides|all]
move(x,y,z) rot(rx,ry,rz) scale(sx,sy,sz) align(x|y|z,min|center|max,val) on(base) align_z0(z)
-mat(name,color=(r,g,b),metallic=,roughness=) color(r,g,b) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z)
+mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z)
Topics: deform|curves|uv|remesh|scene"#;
/// Progressive on-demand domain specs (loaded only when requested).
@@ -112,9 +112,11 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
),
"scene" => Ok(
"Forma-Pipe // Multi-Object Scene Graph & Previews:\n\
- - Pass `scene: true` to MCP `export` (or `--scene` in `forma eval`) for:\n\
- - `.glb` / `.blend`: export all named parts as separate scene nodes with shared mesh instancing.\n\
- - `.png` / `.svg`: render or draw all named scene parts together with their materials (no need to boolean-merge a dummy assembly).\n\
+ - Pass `scene: true` to MCP `export` (or `--scene` in `forma eval` / `forma render` / `forma draw`) to export ALL named parts together:\n\
+ - `.glb` / `.blend`: separate scene nodes with shared mesh instancing.\n\
+ - `.obj` / `.3mf` / `.step` / `.stl`: multi-object `o <name>` OBJ, multi-`<object>` 3MF, multi-solid STEP, or combined STL.\n\
+ - `.png` / `.svg`: render or draw all named scene parts together with their materials (never boolean-merge a dummy assembly just to export or preview).\n\
+ - Without `--scene` / `scene: true`, only the last-modified part exports.\n\
- Prefix temporary/helper meshes with `_` (e.g. `_cut = ...`) so they stay local and do not appear in `scene.parts` or `scene: true` exports; remove an existing named part with `del(\"name\")`."
),
other => Err(format!("unknown spec topic '{other}' (valid: deform, curves, uv, remesh, scene)")),
diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs
index 7902859..c57d757 100644
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@ -212,6 +212,23 @@ impl Val {
_ => Err(format!("{ctx}: expected 3-tuple (x, y, z)")),
}
}
+ fn as_rgba(&self, ctx: &str) -> Result<[f32; 4], String> {
+ match self {
+ Val::List(v) if v.len() == 3 => Ok([
+ v[0].as_num(ctx)? as f32,
+ v[1].as_num(ctx)? as f32,
+ v[2].as_num(ctx)? as f32,
+ 1.0,
+ ]),
+ Val::List(v) if v.len() == 4 => Ok([
+ v[0].as_num(ctx)? as f32,
+ v[1].as_num(ctx)? as f32,
+ v[2].as_num(ctx)? as f32,
+ v[3].as_num(ctx)? as f32,
+ ]),
+ _ => Err(format!("{ctx}: expected RGB (r, g, b) or RGBA (r, g, b, a) tuple")),
+ }
+ }
fn as_vec3_list(&self, ctx: &str) -> Result<Vec<Vec3>, String> {
match self {
Val::List(v) if v.len() == 3 && matches!(v[0], Val::Num(_)) => {
@@ -378,11 +395,12 @@ fn max_pipe_positional(op_name: &str) -> Option<usize> {
"bevel" => 3,
"shell" | "extrude" | "subsurf" | "subdiv" => 2,
"inset" => 3,
- "move" | "translate" | "rot" | "rotate" | "scale" | "color" => 3,
+ "move" | "translate" | "rot" | "rotate" | "scale" => 3,
+ "color" => 4,
"align_z0" => 1,
"align" => 3,
"on" | "place_on" => 2,
- "mat" | "material" => 4,
+ "mat" | "material" => 5,
"mirror" => 2,
"pattern_linear" | "array" | "pattern_radial" | "radial" => 3,
"decimate" | "lod" | "remesh" => 1,
@@ -510,10 +528,28 @@ fn allowed_pipe_kwargs(op_name: &str) -> Option<&'static [&'static str]> {
"extrude" => &["faces", "dist", "d"],
"inset" => &["faces", "amt", "amount", "depth"],
"subsurf" | "subdiv" => &["levels", "level", "n", "crease"],
- "move" | "translate" | "rot" | "rotate" | "scale" | "align_z0" | "color" | "flat" => &[],
+ "move" | "translate" | "rot" | "rotate" | "scale" | "align_z0" | "flat" => &[],
+ "color" => &["alpha", "opacity", "a", "faces", "tag"],
"align" => &["axis", "mode", "val", "to"],
"on" | "place_on" => &["base", "gap"],
- "mat" | "material" => &["name", "color", "metallic", "m", "roughness", "r", "faces", "tag"],
+ "mat" | "material" => &[
+ "name",
+ "color",
+ "metallic",
+ "m",
+ "roughness",
+ "r",
+ "alpha",
+ "opacity",
+ "a",
+ "emissive",
+ "emissive_strength",
+ "transmission",
+ "ior",
+ "double_sided",
+ "faces",
+ "tag",
+ ],
"mirror" => &["axis", "union"],
"pattern_linear" | "array" => &["count", "n", "step", "union"],
"pattern_radial" | "radial" => &["count", "n", "r", "radius", "axis", "union"],
@@ -1931,40 +1967,100 @@ impl<'a> Parser<'a> {
}
"mat" | "material" => {
let mname = kw.get("name").or_else(|| pos.first()).map(|v| v.as_str(&ctx)).transpose()?.unwrap_or("mat").to_string();
- let col_v = if let Some(cv) = kw.get("color").or_else(|| pos.get(1)) {
- cv.as_vec3(&ctx)?
+ let mut rgba = if let Some(cv) = kw.get("color").or_else(|| pos.get(1)) {
+ cv.as_rgba(&ctx)?
} else {
- Vec3::new(0.78, 0.80, 0.84)
+ [0.78, 0.80, 0.84, 1.0]
};
- let metallic = kw.get("metallic").or_else(|| kw.get("m")).or_else(|| pos.get(2)).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.1) as f32;
+ let metallic = kw.get("metallic").or_else(|| kw.get("m")).or_else(|| pos.get(2)).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.0) as f32;
let roughness = kw.get("roughness").or_else(|| kw.get("r")).or_else(|| pos.get(3)).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.5) as f32;
+ if let Some(av) = kw.get("alpha").or_else(|| kw.get("opacity")).or_else(|| kw.get("a")).or_else(|| pos.get(4)) {
+ rgba[3] = av.as_num(&ctx)? as f32;
+ }
+ rgba = [
+ rgba[0].clamp(0.0, 1.0),
+ rgba[1].clamp(0.0, 1.0),
+ rgba[2].clamp(0.0, 1.0),
+ rgba[3].clamp(0.0, 1.0),
+ ];
+ let emissive = if let Some(ev) = kw.get("emissive") {
+ let v = ev.as_vec3(&ctx)?;
+ [
+ (v.x as f32).clamp(0.0, 1.0),
+ (v.y as f32).clamp(0.0, 1.0),
+ (v.z as f32).clamp(0.0, 1.0),
+ ]
+ } else {
+ [0.0, 0.0, 0.0]
+ };
+ let emissive_strength = kw
+ .get("emissive_strength")
+ .map(|v| v.as_num(&ctx))
+ .transpose()?
+ .unwrap_or(1.0) as f32;
+ let transmission = kw
+ .get("transmission")
+ .map(|v| v.as_num(&ctx))
+ .transpose()?
+ .unwrap_or(0.0) as f32;
+ let ior = kw
+ .get("ior")
+ .map(|v| v.as_num(&ctx))
+ .transpose()?
+ .unwrap_or(1.5) as f32;
+ let double_sided = kw
+ .get("double_sided")
+ .map(|v| v.as_bool(&ctx))
+ .transpose()?
+ .unwrap_or(false);
let tag_filter = kw.get("faces").or_else(|| kw.get("tag")).map(|v| v.as_str(&ctx)).transpose()?;
let mat = forma_core::Material {
name: mname,
- color: [col_v.x as f32, col_v.y as f32, col_v.z as f32, 1.0],
+ color: rgba,
metallic: metallic.clamp(0.0, 1.0),
roughness: roughness.clamp(0.0, 1.0),
+ emissive,
+ emissive_strength: emissive_strength.max(0.0),
+ transmission: transmission.clamp(0.0, 1.0),
+ ior: ior.clamp(1.0, 3.0),
+ double_sided,
};
mesh.assign_material(mat, tag_filter);
Ok(mesh)
}
"color" => {
- let col_v = if pos.len() == 1 {
- pos[0].as_vec3(&ctx)?
+ let mut rgba = if pos.len() == 1 {
+ pos[0].as_rgba(&ctx)?
} else {
- Vec3::new(
- pos.first().ok_or(format!("{ctx}: missing r"))?.as_num(&ctx)?,
- pos.get(1).ok_or(format!("{ctx}: missing g"))?.as_num(&ctx)?,
- pos.get(2).ok_or(format!("{ctx}: missing b"))?.as_num(&ctx)?,
- )
+ let r = pos.first().ok_or(format!("{ctx}: missing r"))?.as_num(&ctx)? as f32;
+ let g = pos.get(1).ok_or(format!("{ctx}: missing g"))?.as_num(&ctx)? as f32;
+ let b = pos.get(2).ok_or(format!("{ctx}: missing b"))?.as_num(&ctx)? as f32;
+ let a = pos.get(3).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(1.0) as f32;
+ [r, g, b, a]
+ };
+ if let Some(av) = kw.get("alpha").or_else(|| kw.get("opacity")).or_else(|| kw.get("a")) {
+ rgba[3] = av.as_num(&ctx)? as f32;
+ }
+ rgba = [
+ rgba[0].clamp(0.0, 1.0),
+ rgba[1].clamp(0.0, 1.0),
+ rgba[2].clamp(0.0, 1.0),
+ rgba[3].clamp(0.0, 1.0),
+ ];
+ let tag_filter = kw.get("faces").or_else(|| kw.get("tag")).map(|v| v.as_str(&ctx)).transpose()?;
+ let name = if rgba[3] < 1.0 - 1e-4 {
+ format!("rgba_{:.2}_{:.2}_{:.2}_{:.2}", rgba[0], rgba[1], rgba[2], rgba[3])
+ } else {
+ format!("rgb_{:.2}_{:.2}_{:.2}", rgba[0], rgba[1], rgba[2])
};
let mat = forma_core::Material {
- name: format!("rgb_{:.2}_{:.2}_{:.2}", col_v.x, col_v.y, col_v.z),
- color: [col_v.x as f32, col_v.y as f32, col_v.z as f32, 1.0],
- metallic: 0.1,
+ name,
+ color: rgba,
+ metallic: 0.0,
roughness: 0.5,
+ ..Default::default()
};
- mesh.assign_material(mat, None);
+ mesh.assign_material(mat, tag_filter);
Ok(mesh)
}
"mirror" => {
diff --git a/crates/forma-lang/tests/audit_regressions.rs b/crates/forma-lang/tests/audit_regressions.rs
index 626da07..2abbaec 100644
--- a/crates/forma-lang/tests/audit_regressions.rs
+++ b/crates/forma-lang/tests/audit_regressions.rs
@@ -138,6 +138,7 @@ fn flip_winding_extrude_invariants_and_glb_json_escaping() {
color: [0.8, 0.2, 0.2, 1.0],
metallic: 0.1,
roughness: 0.5,
+ ..Default::default()
},
None,
);
@@ -257,6 +258,7 @@ fn inset_and_bevel_preserve_materials_and_weld_syncs_uvs() {
color: [0.8, 0.45, 0.25, 1.0],
metallic: 0.9,
roughness: 0.3,
+ ..Default::default()
},
None,
);
diff --git a/crates/forma-print/src/export_3mf.rs b/crates/forma-print/src/export_3mf.rs
index 4d84a04..96c0bef 100644
--- a/crates/forma-print/src/export_3mf.rs
+++ b/crates/forma-print/src/export_3mf.rs
@@ -1889,6 +1889,7 @@ pub(crate) mod tests {
color: [0.8, 0.2, 0.2, 1.0],
metallic: 0.0,
roughness: 0.5,
+ ..Default::default()
},
None,
);
@@ -1898,6 +1899,7 @@ pub(crate) mod tests {
color: [0.2, 0.8, 0.3, 1.0],
metallic: 0.0,
roughness: 0.5,
+ ..Default::default()
},
Some("top"),
);
diff --git a/crates/forma-print/src/heatmap.rs b/crates/forma-print/src/heatmap.rs
index f441c7d..2fe672f 100644
--- a/crates/forma-print/src/heatmap.rs
+++ b/crates/forma-print/src/heatmap.rs
@@ -66,6 +66,7 @@ impl HeatmapPalette {
color: Self::color_for(sev),
metallic: 0.05,
roughness: 0.65,
+ ..Default::default()
})
.collect()
}
@@ -198,6 +199,7 @@ mod tests {
color: [0.1, 0.2, 0.3, 1.0],
metallic: 0.9,
roughness: 0.1,
+ ..Default::default()
},
None,
);
diff --git a/crates/forma-print/src/orient.rs b/crates/forma-print/src/orient.rs
index 79a4144..cc9c676 100644
--- a/crates/forma-print/src/orient.rs
+++ b/crates/forma-print/src/orient.rs
@@ -1125,12 +1125,14 @@ mod tests {
color: [0.9, 0.2, 0.2, 1.0],
metallic: 0.0,
roughness: 0.5,
+ ..Default::default()
});
let mat_b = m.add_material(forma_core::Material {
name: "right_blue".into(),
color: [0.2, 0.4, 0.9, 1.0],
metallic: 0.0,
roughness: 0.5,
+ ..Default::default()
});
// Rings at x = -20 (0..4), x = 0 (4..8), x = +20 (8..12)
diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rs
index 3eb6f2a..b779285 100644
--- a/crates/forma-wasm/src/lib.rs
+++ b/crates/forma-wasm/src/lib.rs
@@ -397,6 +397,37 @@ pub extern "C" fn forma_session_export_scene(id: u32) -> u32 {
})
}
+/// Export all named scene parts in the requested format (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`, `png`, `svg`).
+#[no_mangle]
+pub extern "C" fn forma_session_export_scene_format(
+ id: u32,
+ ext_ptr: *const u8,
+ ext_len: usize,
+) -> u32 {
+ let ext = match unsafe { read_utf8(ext_ptr, ext_len) } {
+ Ok(s) => s.trim().trim_start_matches('.').to_lowercase(),
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get_mut(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ let is_png = ext == "png";
+ match scene.export_scene_bytes(&ext) {
+ Ok(bytes) => {
+ if is_png {
+ scene.mark_rendered();
+ } else {
+ scene.mark_exported();
+ }
+ s.set_ok_bytes(bytes)
+ }
+ Err(e) => s.set_err(e.to_string()),
+ }
+ })
+}
+
/// Render a named view (`quad|front|back|right|left|top|iso`) of a part directly to PNG bytes.
#[no_mangle]
pub extern "C" fn forma_session_export_png_view(
diff --git a/docs/reference/cli.md b/docs/reference/cli.md
index 6bba5e5..ff6c6dc 100644
--- a/docs/reference/cli.md
+++ b/docs/reference/cli.md
@@ -10,8 +10,9 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo
| Subcommand | Native `forma` | WASM `forma-3d` | Description |
| --- | --- | --- | --- |
| `eval` | Yes | Yes | Evaluate a script from a file path or stdin (`-` or omitted), print observation, and optionally export mesh, PNG, or SVG. |
-| `render` | Yes | Yes | Evaluate a script and render a software PNG preview (`--out preview.png` required). |
-| `draw` | Yes | Yes | Evaluate a script and generate a 3-view orthographic SVG blueprint (`--out blueprint.svg` required). |
+| `lint` | Yes | Yes | Evaluate a script and run deterministic Layer A craftsmanship lint + pairwise assembly contact graph. |
+| `render` | Yes | Yes | Evaluate a script and render a software PNG preview (`--out preview.png` required; pass `--scene` for all parts). |
+| `draw` | Yes | Yes | Evaluate a script and generate a 3-view orthographic SVG blueprint (`--out blueprint.svg` required; pass `--scene` for all parts). |
| `spec` | Yes | Yes | Print the compiled `Forma-Pipe` or `Forma-DSL` specification, a progressive `--topic` spec, or the `--gbnf` grammar. |
| `mcp` | Separate binary (`forma-mcp`) | Yes (`forma-3d mcp` / `forma-3d-mcp`) | Start the stdio JSON-RPC 2.0 MCP server. |
| `version` / `--version` / `-V` | Yes | Yes | Print the CLI version string (`forma 0.4.4`). |
@@ -25,8 +26,9 @@ Forma ships two command-line executables backed by the same `forma-lang` and `fo
| `--unit`, `-u <m\|cm\|mm\|um\|in\|ft>` | `m` | Yes | Yes | Set initial scene model unit before evaluating script. |
| `--strict` | Enabled | Yes | Yes | Enforce watertightness, zero non-manifold edges, finite vertices, and non-degenerate volume. |
| `--no-strict` | Disabled | Yes | Yes | Disable strict invariant rejection and exit code `3`. |
+| `--critique` | Disabled | Yes | Yes | Append deterministic craftsmanship lint & assembly contact diagnostics. |
| `--json` | Disabled | Yes | Yes | Print full `Observation` JSON to stdout instead of compact text. |
-| `--scene` | Disabled | Yes | Yes | Export/render/draw all named parts together (`.glb`, `.blend`, `.png`, `.svg`) instead of only the last assigned part. |
+| `--scene` | Disabled | Yes | Yes | Export/render/draw ALL named parts together (`.glb`/`.blend` nodes, multi-object `.obj`/`.3mf`, multi-solid `.step`, combined `.stl`, and full-scene `.png`/`.svg`). Without `--scene`, only the last-modified part exports (a stderr `NOTE:` warns when `parts > 1`). |
| `--out`, `-o <path>` | None | Yes | Yes | Export mesh (`.glb`, `.obj`, `.stl`, `.3mf`, `.step`, `.blend` via Blender bridge). |
| `--render <path.png>` | None | Yes | Yes | Render PNG preview alongside `eval`. |
| `--view <view>` | `quad` | Yes | Yes | Camera view for `--render` / `render`: `quad`, `front`, `back`, `right`, `left`, `top`, `iso`. |
diff --git a/docs/reference/language-and-formats.md b/docs/reference/language-and-formats.md
index e552824..0477c6e 100644
--- a/docs/reference/language-and-formats.md
+++ b/docs/reference/language-and-formats.md
@@ -6,7 +6,7 @@ Authoritative specification for Forma's two modeling dialects, semantic selector
- **Axes**: Right-handed Z-up internally. `glTF` (`.glb`) export automatically converts to Y-up (`[x, z, -y]`).
- **Default unit**: `1.0` equals one meter (`Unit::Meter`) unless overridden by `units("...")`, `--unit`, JS `{ unit }`, or HTTP `unit`.
-- **Export target**: The last assigned or modified part exports by default unless a specific `part` or multi-part `scene` export/render (`scene: true` / `--scene` for `.glb`, `.blend`, `.png`, or `.svg`) is requested.
+- **Export target**: The last assigned or modified part exports by default unless a specific `part` or multi-part `scene` export/render (`scene: true` / `--scene` for `.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, or `.svg`) is requested.
- **Variables & scope**: Scalar variables persist across stateful `eval` calls (such as MCP sessions) and roll back with `tx`. Mesh variables prefixed with `_` (for example `_tmp = ...`) stay local to the script and do not pollute `scene.parts` or `scene: true` exports. Use `del("name")` to delete a named part from `scene.parts`.
- **Transactional rollback**: Every `eval_script` call pushes an undo snapshot before execution and restores geometry, scalar variables, and `Scene.unit` if any statement fails or violates strict invariants.
@@ -45,7 +45,7 @@ Authoritative specification for Forma's two modeling dialects, semantic selector
| Patterns and symmetry | `mirror(x\|y\|z)`, `array(n, step)` / `pattern_linear(n, step)`, `radial(n, r=, axis=z)` / `pattern_radial(n, r=, axis=z)` |
| Topology modifiers | `shell(t, open_top=true)`, `subsurf(levels=1, crease=false)`, `bevel(edges, w, segs=1)`, `extrude(faces, d)`, `inset(faces, amt, depth=0)` |
| Transforms and placement | `move(x, y, z)`, `rot(rx, ry, rz)`, `scale(sx, sy, sz)`, `align(x\|y\|z, min\|center\|max, val)`, `on(base, gap=0)`, `align_z0(z)` |
-| Materials | `mat(name, color=(r, g, b), metallic=0.1, roughness=0.5, faces=)`, `color(r, g, b)` |
+| Materials | `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=)` (display sRGB converted to linear RGB in glTF `.glb` export) |
| Queries, state, and units | `clearance(a, b)`, `section(part, z)`, `units("m\|cm\|mm\|um\|in\|ft")`, `checkpoint(tag)`, `rollback(tag)`, `undo()`, `del(name)` |
## Semantic selectors
@@ -65,7 +65,7 @@ Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `GET
| `curves` | `curves` | `bezier([(x,y,z), ...], segs=24)`, `nurbs([(x,y,z), ...], degree=3, segs=32, weights=)`, `extrude2d(outer, z0, z1, holes=...)`, `sweep(profile2d, path3d, scale_end=1.0, twist=0.0, closed=false)` |
| `uv` | `uv`, `normals` | `smooth(angle=35, weighted=true)`, `flat()`, `unwrap(angle=45, margin=0.01)`, `decimate(ratio=0.5, faces=)` |
| `remesh` | `remesh` | `remesh(voxel_size=0.0)` (`0` = auto `diag/28`), `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)`, `load("path.glb\|obj\|stl", yup=)` |
-| `scene` | `scene` | Multi-object scene graph export & rendering (`--scene` in CLI, `scene: true` in MCP `export` for `.glb`, `.blend`, `.png`, and `.svg`, `exportSceneBytes()` in JS/TS); `_`-prefixed locals and `del("name")`. |
+| `scene` | `scene` | Multi-object scene graph export & rendering (`--scene` in CLI, `scene: true` in MCP `export` for `.glb`, `.blend`, `.obj`, `.3mf`, `.stl`, `.step`, `.png`, and `.svg`, `exportSceneBytes(format)` in JS/TS); `_`-prefixed locals and `del("name")`. |
## Invariant metrics (`MeshInvariants`)
@@ -95,11 +95,11 @@ Query via `forma spec --topic <name>`, `npx forma-3d spec --topic <name>`, `GET
| Format | Extension | Direction | Unit handling | Axis / notes |
| --- | --- | --- | --- | --- |
-| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, PBR materials, optional `TEXCOORD_0` UVs (via `unwrap()`); supports multi-node `--scene` / `scene: true`. |
-| STEP AP214 | `.step`, `.stp` | Export | Declares model unit in header | Faceted B-Rep solid for CAD interoperability. |
-| 3D Manufacturing Format | `.3mf` | Export | Declares `model/@unit` | Ready for modern 3D-printing slicers. |
-| Binary STL | `.stl` | Import + Export | Raw model units (format has no unit field) | Triangulated mesh. |
-| Wavefront OBJ | `.obj` | Import + Export | Raw model units (format has no unit field) | Polygons/triangles. |
+| Binary glTF 2.0 | `.glb` | Import + Export | Scaled to meters (`meters_per_unit()`) | Y-up conversion, sRGB→linear PBR materials (`alphaMode: "BLEND"`, `doubleSided`, `emissiveFactor`, `KHR_materials_transmission`, `KHR_materials_ior`, `KHR_materials_emissive_strength`), optional `TEXCOORD_0` UVs (via `unwrap()`); supports multi-node `--scene` / `scene: true`. |
+| STEP AP214 | `.step`, `.stp` | Export | Declares model unit in header | Faceted B-Rep solid for CAD interoperability; supports multi-solid `--scene` / `scene: true`. |
+| 3D Manufacturing Format | `.3mf` | Export | Declares `model/@unit` | Ready for modern 3D-printing slicers; supports multi-object `--scene` / `scene: true`. |
+| Binary STL | `.stl` | Import + Export | Raw model units (format has no unit field) | Triangulated mesh; supports combined `--scene` / `scene: true`. |
+| Wavefront OBJ | `.obj` | Import + Export | Raw model units (format has no unit field) | Polygons/triangles; supports multi-object `o <name>` `--scene` / `scene: true`. |
| PNG preview | `.png` | Export | Scale-invariant framed view | Pure-Rust software rasterizer (4-view `quad` default; single views on native CLI); supports `--scene` / `scene: true` to render all named parts together with materials. |
| SVG blueprint | `.svg` | Export | Dimensioned in model units | 3-view orthographic engineering drawing; supports `--scene` / `scene: true` for multi-part scenes. |
| Blender file | `.blend` | Export (CLI & MCP) | Scaled to meters via glTF bridge | Invokes local Blender (`BLENDER_BIN` or `blender` on `PATH`); supports `--scene` / `scene: true`. |
diff --git a/lib/edge.mjs b/lib/edge.mjs
index c4b0377..fdf800b 100644
--- a/lib/edge.mjs
+++ b/lib/edge.mjs
@@ -274,11 +274,21 @@ export class FormaSession {
);
}
- /** Export all named scene parts as a multi-node glTF 2.0 (.glb) scene graph. */
- exportSceneBytes() {
+ /** Export all named scene parts as bytes (`.glb` default; also `.obj`, `.3mf`, `.stl`, `.step`, `.svg`, `.png`). */
+ exportSceneBytes(format = "glb") {
this._checkOpen();
- this._engine._run(() => this._engine.exports.forma_session_export_scene(this._id));
- return this._engine._readResultBytes();
+ const ext = String(format ?? "glb").replace(/^\./, "").toLowerCase();
+ if (ext === "glb" || !this._engine.exports.forma_session_export_scene_format) {
+ if (ext !== "glb") {
+ throw new Error(`multi-part scene export for '.${ext}' requires updated WASM binary`);
+ }
+ this._engine._run(() => this._engine.exports.forma_session_export_scene(this._id));
+ return this._engine._readResultBytes();
+ }
+ return this._engine._withUtf8(ext, (ep, el) => {
+ this._engine.exports.forma_session_export_scene_format(this._id, ep, el);
+ return this._engine._readResultBytes();
+ });
}
/** Render a studio PNG preview (`quad|front|back|right|left|top|iso`) of all named scene parts combined. */
@@ -526,8 +536,7 @@ export async function exportMesh(code, format = "glb", opts = {}) {
const ext = String(format ?? "glb").replace(/^\./, "").toLowerCase();
if (ext === "png") return s.exportScenePngBytes(opts.size ?? 512, opts.view ?? "quad");
if (ext === "svg") return encoder.encode(s.exportSceneSvg());
- if (ext === "glb") return s.exportSceneBytes();
- throw new Error(`scene export requires .glb, .png, or .svg (got '.${ext}')`);
+ return s.exportSceneBytes(ext);
}
return s.exportBytes(format, opts);
} finally {
diff --git a/lib/index.d.ts b/lib/index.d.ts
index 6b2fadc..2e45f08 100644
--- a/lib/index.d.ts
+++ b/lib/index.d.ts
@@ -147,8 +147,8 @@ export class FormaSession {
tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string;
/** Export a part to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, or `.png` bytes. */
exportBytes(format: FormaExportFormat, opts?: { part?: string; size?: number; view?: FormaRenderView | string }): Uint8Array;
- /** Export all named parts as a multi-node binary glTF 2.0 (`.glb`) scene graph. */
- exportSceneBytes(): Uint8Array;
+ /** Export all named scene parts as bytes (`.glb` default; also `.obj`, `.3mf`, `.stl`, `.step`, `.svg`, `.png`). */
+ exportSceneBytes(format?: FormaExportFormat): Uint8Array;
/** Render a studio PNG preview (`quad|front|back|right|left|top|iso`) of all named scene parts combined. */
exportScenePngBytes(size?: number, view?: FormaView | string): Uint8Array;
/** Render a named view (`quad|front|back|right|left|top|iso`) PNG for a part or the full scene. */
diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjs
index cb22541..fedee29 100644
--- a/tests/npm_smoke.mjs
+++ b/tests/npm_smoke.mjs
@@ -166,6 +166,52 @@ section(flange, 0.0)
const mmSvgText = readFileSync(mmSvg, "utf-8");
assert.ok(mmSvgText.includes("100.000 mm") && mmSvgText.includes("mm^3"), "SVG labels reflect --unit mm");
+ // Multi-part CLI --scene parity (.glb/.obj/.3mf/.stl/.step + --render --view iso + --draw) and single-part NOTE
+ const multiCode = `
+ base = box(3, 3, 0.4, z0=0) | mat("wood", color=(0.25, 0.16, 0.10))
+ steam = sphere(0.5, at=(0, 0, 1.2)) | mat("steam", color=(1, 1, 1), alpha=0.3, double_sided=true)
+ `;
+ const noSceneGlb = join(tmp, "no-scene.glb");
+ const noSceneRun = await new Promise((resolve, reject) => {
+ const child = spawn(process.execPath, [cli, "eval", "--out", noSceneGlb], {
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ let out = "";
+ let err = "";
+ child.stdout.on("data", (d) => (out += d.toString()));
+ child.stderr.on("data", (d) => (err += d.toString()));
+ child.on("error", reject);
+ child.on("close", (code) => resolve({ code, out, err }));
+ child.stdin.write(multiCode);
+ child.stdin.end();
+ });
+ assert.equal(noSceneRun.code, 0, noSceneRun.err);
+ assert.ok(noSceneRun.err.includes("--scene"), `expected --scene hint on stderr, got: ${noSceneRun.err}`);
+
+ const multiSceneObj = join(tmp, "multi-scene.obj");
+ const multiScene3mf = join(tmp, "multi-scene.3mf");
+ const multiSceneStl = join(tmp, "multi-scene.stl");
+ const multiSceneStep = join(tmp, "multi-scene.step");
+ const multiSceneIsoPng = join(tmp, "multi-scene-iso.png");
+ const multiSceneSvg = join(tmp, "multi-scene.svg");
+ execFileSync(
+ process.execPath,
+ [cli, "eval", "--scene", "--out", multiSceneObj, "--render", multiSceneIsoPng, "--view", "iso", "--draw", multiSceneSvg],
+ { input: multiCode, encoding: "utf-8" }
+ );
+ const sceneObjText = readFileSync(multiSceneObj, "utf-8");
+ assert.ok(sceneObjText.includes("o base") && sceneObjText.includes("o steam"), "CLI --scene .obj exports all parts");
+ assert.ok(statSync(multiSceneIsoPng).size > 500 && statSync(multiSceneSvg).size > 500);
+ for (const p of [multiScene3mf, multiSceneStl, multiSceneStep]) {
+ execFileSync(process.execPath, [cli, "eval", "--scene", "--out", p], {
+ input: multiCode,
+ encoding: "utf-8",
+ });
+ assert.ok(statSync(p).size > 200, `CLI --scene export empty: ${p}`);
+ }
+ const helpText = execFileSync(process.execPath, [cli, "--help"], { encoding: "utf-8" });
+ assert.ok(helpText.includes("KEY OPTIONS:") && helpText.includes("--scene"), "CLI --help explains --scene");
+
// Unknown CLI flags exit with status 2 (usage error)
let badFlagCode = 0;
try {
diff --git a/wasm/forma.wasm b/wasm/forma.wasm
index 2c858cd..df479f9 100755
Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ