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: add gear primitive, def macros, list comprehensions, trig, and MCP scene ergonomics

wrong-nebuladae0109d698c
diff --git a/bin/forma-mcp.mjs b/bin/forma-mcp.mjs
index c387ac9..126d112 100755
--- a/bin/forma-mcp.mjs
+++ b/bin/forma-mcp.mjs
@@ -1,22 +1,26 @@
#!/usr/bin/env node
/**
- * forma-3d-mcp — Thin, minimal-schema stdio JSON-RPC 2.0 MCP server (4 tools, 789 o200k tokens).
+ * forma-3d-mcp — Minimal-schema stdio JSON-RPC 2.0 MCP server (4 tools, 721 o200k tokens).
* Powered by Forma's bundled pure-Rust WebAssembly engine (zero external dependencies).
*/
-import { createInterface } from "node:readline";
-import { writeFile } from "node:fs/promises";
+import { readFileSync } from "node:fs";
+import { stat, writeFile } from "node:fs/promises";
import { extname } from "node:path";
import { performance } from "node:perf_hooks";
+import { createInterface } from "node:readline";
import { loadForma } from "../lib/index.mjs";
+import { writeBlendFromGlbBytes } from "./blend-bridge.mjs";
-const VERSION = "0.4.2";
+const VERSION = JSON.parse(
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8")
+).version;
function buildToolsSchema(specPipe) {
return [
{
name: "eval",
- description: `Run transactional Forma-Pipe code (auto-rollback on error); returns compact bbox/vol/manifold diff.\n${specPipe}`,
+ description: `Run transactional Forma-Pipe code; returns bbox/vol/manifold diff.\n${specPipe}`,
inputSchema: {
type: "object",
properties: {
@@ -28,7 +32,7 @@ function buildToolsSchema(specPipe) {
},
{
name: "inspect",
- description: "Scene invariants/tags, or domain spec if topic set.",
+ description: "Scene invariants/tags, or topic spec if topic set.",
inputSchema: {
type: "object",
properties: {
@@ -38,7 +42,7 @@ function buildToolsSchema(specPipe) {
},
{
name: "tx",
- description: "CoW snapshot control: checkpoint|rollback|undo|reset.",
+ description: "CoW snapshot: checkpoint|rollback|undo|reset.",
inputSchema: {
type: "object",
properties: {
@@ -50,7 +54,7 @@ function buildToolsSchema(specPipe) {
},
{
name: "export",
- description: "Export to .glb/.step/.3mf/.stl/.obj/.svg or 2x2 studio preview .png.",
+ description: "Export .glb/.step/.3mf/.stl/.obj/.svg/.blend or 4-view .png.",
inputSchema: {
type: "object",
properties: {
@@ -71,12 +75,9 @@ async function handleToolCall(engine, session, name, args) {
if (typeof args?.code !== "string") {
return [true, "ERR: missing 'code' string"];
}
- const t0 = performance.now();
const strict = args.strict === undefined ? true : Boolean(args.strict);
const obs = session.eval(args.code, { strict });
- const ms = performance.now() - t0;
- const text = obs.text.replace("[0.00ms]", `[${ms.toFixed(2)}ms]`);
- return [false, text];
+ return [false, obs.text];
}
if (name === "inspect") {
if (typeof args?.topic === "string" && args.topic.trim().length > 0) {
@@ -96,18 +97,54 @@ async function handleToolCall(engine, session, name, args) {
return [true, "ERR: missing 'path'"];
}
const p = args.path;
+ const ext = extname(p).replace(/^\./, "").toLowerCase();
if (args.scene === true) {
+ const partsCount = Object.keys(session.inspect().parts ?? {}).length;
+ const size = Number.isInteger(args.size) ? args.size : 512;
+ if (ext === "png") {
+ const t0 = performance.now();
+ const bytes = session.exportScenePngBytes(size);
+ await writeFile(p, bytes);
+ const ms = performance.now() - t0;
+ return [
+ false,
+ `OK rendered ${size}x${size} scene quad preview '${p}' (parts=${partsCount}) [${ms.toFixed(2)}ms]`,
+ ];
+ }
+ if (ext === "svg") {
+ const t0 = performance.now();
+ const svg = session.exportSceneSvg();
+ await writeFile(p, svg, "utf-8");
+ const ms = performance.now() - t0;
+ return [
+ false,
+ `OK drew scene engineering blueprint '${p}' (parts=${partsCount}) [${ms.toFixed(2)}ms]`,
+ ];
+ }
+ if (ext === "blend") {
+ await writeBlendFromGlbBytes(session.exportSceneBytes(), p);
+ const byteLen = (await stat(p)).size;
+ return [false, `OK exported multi-node scene '${p}' (${byteLen} bytes, parts=${partsCount})`];
+ }
+ if (ext !== "glb") {
+ return [
+ true,
+ `ERR: multi-node scene export requires .glb, .blend, .png, or .svg (got '.${ext}')`,
+ ];
+ }
const bytes = session.exportSceneBytes();
await writeFile(p, bytes);
- const partsCount = Object.keys(session.inspect().parts ?? {}).length;
return [false, `OK exported multi-node scene '${p}' (${bytes.length} bytes, parts=${partsCount})`];
}
const part = typeof args.part === "string" ? args.part : "";
- const ext = extname(p).replace(/^\./, "").toLowerCase();
const size = Number.isInteger(args.size) ? args.size : 512;
const t0 = performance.now();
- const bytes = session.exportBytes(ext, { part, size });
- await writeFile(p, bytes);
+ if (ext === "blend") {
+ await writeBlendFromGlbBytes(session.exportBytes("glb", { part }), p);
+ } else {
+ const bytes = session.exportBytes(ext, { part, size });
+ await writeFile(p, bytes);
+ }
const ms = performance.now() - t0;
if (ext === "png") {
return [false, `OK rendered ${size}x${size} quad preview '${p}' [${ms.toFixed(2)}ms]`];
@@ -118,7 +155,7 @@ async function handleToolCall(engine, session, name, args) {
const inv = session.invariants(part);
return [
false,
- `OK exported '${p}' V=${inv.verts} F=${inv.faces} WT=${inv.watertight} NM=${inv.non_manifold_edges} vol=${Number(inv.volume).toFixed(3)}`,
+ `OK exported '${p}' V=${inv.verts} F=${inv.faces} WT=${inv.watertight ? "ok" : "BAD"} NM=${inv.non_manifold_edges} vol=${Number(inv.volume).toFixed(3)}`,
];
}
return [true, `ERR: unknown tool '${name}'`];
diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rs
index 59cc8cb..9fe2554 100644
--- a/crates/forma-cli/src/main.rs
+++ b/crates/forma-cli/src/main.rs
@@ -1,67 +1,43 @@
-//! forma: Unix-composable headless 3D modeling CLI for LLM agents.
+//! forma: Unix-composable headless 3D modeling CLI for AI agents.
//!
//! Usage:
-//! forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict] [--json] [--out FILE] [SCRIPT_FILE | -]
-//! forma spec [--dialect pipe|compact]
-//! forma version
+//! forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--json] [--scene] [--out FILE] [--render PNG] [--draw SVG] [file|-]
+//! forma render [--scene] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]
+//! forma draw [--scene] --out blueprint.svg [file|-]
+//! forma spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]
+//! forma version | --version | -V
use forma_core::{Scene, Unit};
use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
use std::io::{self, Read};
use std::path::PathBuf;
-use std::process::{self, Command};
+use std::process;
+
+const VERSION: &str = env!("CARGO_PKG_VERSION");
fn print_help() {
println!(
- "forma 0.4.2 — ultra-fast, headless, watertight, LLM-native 3D modeling engine\n\
+ "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] [--json] [--scene] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--view quad|front|back|right|left|top|iso] [--draw blueprint.svg] [file|-]\n\
- forma render [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n\
- forma draw --out blueprint.svg [file|-]\n\
+ forma 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 render [--scene] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n\
+ forma draw [--scene] --out blueprint.svg [file|-]\n\
forma spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]\n\
+ forma version | --version | -V\n\
forma --help\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."
);
}
-fn export_with_blend_bridge(scene: &Scene, out: &PathBuf) -> Result<(), String> {
- let ext = out
- .extension()
- .and_then(|s| s.to_str())
- .map(|s| s.to_lowercase())
- .unwrap_or_default();
- if ext == "blend" {
- let tmp_glb = out.with_extension("tmp_forma.glb");
- scene.export(&tmp_glb, None).map_err(|e| e.to_string())?;
- let blender = std::env::var("BLENDER_BIN")
- .unwrap_or_else(|_| "/Applications/Blender.app/Contents/MacOS/Blender".into());
- let py = format!(
- "import bpy; bpy.ops.wm.read_factory_settings(use_empty=True); \
- bpy.ops.import_scene.gltf(filepath={:?}); \
- bpy.ops.wm.save_as_mainfile(filepath={:?})",
- tmp_glb.to_string_lossy(),
- out.to_string_lossy()
- );
- let status = Command::new(&blender)
- .args(["--background", "--factory-startup", "--python-expr", &py])
- .output()
- .map_err(|e| format!("failed to invoke blender bridge ({blender}): {e}"))?;
- let _ = std::fs::remove_file(&tmp_glb);
- if !status.status.success() {
- return Err(format!(
- "blender .blend bridge failed: {}",
- String::from_utf8_lossy(&status.stderr)
- ));
- }
- Ok(())
- } else {
- scene.export(out, None).map(|_| ()).map_err(|e| e.to_string())
- }
-}
-
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if args.is_empty() || args[0] == "-h" || args[0] == "--help" || args[0] == "help" {
@@ -71,7 +47,7 @@ fn main() {
match args[0].as_str() {
"version" | "--version" | "-V" => {
- println!("forma 0.4.2");
+ println!("forma {VERSION}");
return;
}
"spec" => {
@@ -80,23 +56,42 @@ fn main() {
let mut topic: Option<String> = None;
let mut i = 1;
while i < args.len() {
- if (args[i] == "--dialect" || args[i] == "-d") && i + 1 < args.len() {
- dialect = Dialect::parse_name(&args[i + 1]).unwrap_or_else(|e| {
- eprintln!("ERR: {e}");
+ match args[i].as_str() {
+ "--dialect" | "-d" => {
+ if i + 1 >= args.len() {
+ eprintln!("ERR: --dialect requires value (pipe|compact)");
+ process::exit(2);
+ }
+ dialect = Dialect::parse_name(&args[i + 1]).unwrap_or_else(|e| {
+ eprintln!("ERR: {e}");
+ process::exit(2);
+ });
+ i += 2;
+ }
+ "--topic" | "-t" => {
+ if i + 1 >= args.len() {
+ eprintln!("ERR: --topic requires value (deform|curves|uv|remesh|scene)");
+ process::exit(2);
+ }
+ topic = Some(args[i + 1].clone());
+ i += 2;
+ }
+ "--gbnf" => {
+ gbnf = true;
+ i += 1;
+ }
+ arg if arg.starts_with('-') => {
+ eprintln!("ERR: unknown flag '{arg}' for `forma spec`. Run `forma --help`.");
process::exit(2);
- });
- i += 2;
- } else if (args[i] == "--topic" || args[i] == "-t") && i + 1 < args.len() {
- topic = Some(args[i + 1].clone());
- i += 2;
- } else if args[i] == "--gbnf" {
- gbnf = true;
- i += 1;
- } else if !args[i].starts_with('-') && topic.is_none() {
- topic = Some(args[i].clone());
- i += 1;
- } else {
- i += 1;
+ }
+ arg if topic.is_none() => {
+ topic = Some(arg.to_string());
+ i += 1;
+ }
+ arg => {
+ eprintln!("ERR: unexpected argument '{arg}' for `forma spec`. Run `forma --help`.");
+ process::exit(2);
+ }
}
}
if let Some(t) = topic {
@@ -231,13 +226,30 @@ fn main() {
export_scene = true;
i += 1;
}
+ arg if arg.starts_with('-') && arg != "-" => {
+ eprintln!("ERR: unknown flag '{arg}'. Run `forma --help`.");
+ process::exit(2);
+ }
arg => {
+ if in_file.is_some() {
+ eprintln!("ERR: unexpected extra input file '{arg}' (only one script file is accepted)");
+ process::exit(2);
+ }
in_file = Some(arg.to_string());
i += 1;
}
}
}
+ if is_render_cmd && render_path.is_none() {
+ eprintln!("ERR: `forma render` requires `--out preview.png`");
+ process::exit(2);
+ }
+ if is_draw_cmd && draw_path.is_none() {
+ eprintln!("ERR: `forma draw` requires `--out blueprint.svg`");
+ process::exit(2);
+ }
+
let src = match in_file.as_deref() {
None | Some("-") => {
let mut buf = String::new();
@@ -266,31 +278,33 @@ fn main() {
Ok(obs) => {
if let Some(ref out) = out_path {
if export_scene {
- match scene.export_scene_glb_bytes(true) {
- Ok(bytes) => {
- if let Err(e) = std::fs::write(out, bytes) {
- eprintln!("ERR: scene export failed: {e}");
- process::exit(1);
- }
- }
- Err(e) => {
- eprintln!("ERR: scene export failed: {e}");
- process::exit(1);
- }
+ if let Err(e) = scene.export_scene_path(out) {
+ eprintln!("ERR: scene export failed: {e}");
+ process::exit(1);
}
- } else if let Err(e) = export_with_blend_bridge(&scene, out) {
+ } else if let Err(e) = scene.export(out, None) {
eprintln!("ERR: export failed: {e}");
process::exit(1);
}
}
if let Some(ref png) = render_path {
- if let Err(e) = scene.render_preview_view(png, None, render_size, &render_view) {
+ let res = if export_scene {
+ scene.render_preview_scene_view(png, render_size, &render_view)
+ } else {
+ scene.render_preview_view(png, None, render_size, &render_view)
+ };
+ if let Err(e) = res {
eprintln!("ERR: render failed: {e}");
process::exit(1);
}
}
if let Some(ref svg) = draw_path {
- if let Err(e) = scene.export_blueprint_svg(svg, None) {
+ let res = if export_scene {
+ scene.export_blueprint_svg_scene(svg)
+ } else {
+ scene.export_blueprint_svg(svg, None)
+ };
+ if let Err(e) = res {
eprintln!("ERR: draw failed: {e}");
process::exit(1);
}
diff --git a/crates/forma-core/src/primitives.rs b/crates/forma-core/src/primitives.rs
index 744e4b4..48224e1 100644
--- a/crates/forma-core/src/primitives.rs
+++ b/crates/forma-core/src/primitives.rs
@@ -877,8 +877,8 @@ pub fn make_text_3d(text: &str, height: f64, depth: f64, op_id: u32) -> Result<P
let x_off = -0.5 * total_w;
let y_off = -0.5 * height;
- // Emit merged horizontal pixel runs as clean, disjoint watertight bars (with tiny 2% gap between rows
- // OR clean manifold voxel boundary mesh so zero non-manifold shared edges ever form!)
+ // Emit merged horizontal pixel runs as disjoint watertight bars with a 4% inter-row gap
+ // so adjacent rows never share non-manifold edges.
let mut out = PolyMesh::new();
let gap = cell * 0.04;
for (ci, &ch) in chars.iter().enumerate() {
@@ -912,6 +912,163 @@ pub fn make_text_3d(text: &str, height: f64, depth: f64, op_id: u32) -> Result<P
Ok(out)
}
+/// Watertight involute-approximated metric spur gear aligned with Z, centered at origin
+/// (`z in [-height/2, +height/2]`), with tooth 0 centered on the +X axis (angle 0).
+///
+/// Two meshing gears of the same `module` with tooth counts `z1` and `z2` placed at center
+/// distance `module * (z1 + z2) / 2` (with gear 2 rotated by `180 / z2` deg for even `z2`)
+/// mesh cleanly with positive clearance.
+pub fn make_gear(
+ teeth: usize,
+ module: f64,
+ height: f64,
+ pressure_angle_deg: f64,
+ bore: f64,
+ op_id: u32,
+) -> Result<PolyMesh, String> {
+ if !(4..=200).contains(&teeth) {
+ return Err(format!("gear: teeth must be in 4..=200 (got {teeth})"));
+ }
+ if !module.is_finite() || module <= 1e-6 {
+ return Err(format!("gear: module must be finite and > 0 (got {module})"));
+ }
+ if !height.is_finite() || height <= 1e-6 {
+ return Err(format!("gear: height must be finite and > 0 (got {height})"));
+ }
+ if !pressure_angle_deg.is_finite() || !(5.0..=45.0).contains(&pressure_angle_deg) {
+ return Err(format!(
+ "gear: pressure_angle must be in 5..=45 degrees (got {pressure_angle_deg})"
+ ));
+ }
+ if !bore.is_finite() || bore < 0.0 {
+ return Err(format!("gear: bore radius must be finite and >= 0 (got {bore})"));
+ }
+
+ let z = teeth as f64;
+ let rp = module * z * 0.5;
+ let addendum = module;
+ let dedendum = 1.25 * module;
+ let ra = rp + addendum;
+ let rf = (rp - dedendum).max(0.1 * rp);
+ let alpha = pressure_angle_deg.to_radians();
+ let rb = rp * alpha.cos();
+
+ if bore > 0.0 && bore >= rf - 1e-4 {
+ return Err(format!(
+ "gear: bore radius ({bore:.4}) must be smaller than root radius ({rf:.4})"
+ ));
+ }
+
+ let inv_p = alpha.tan() - alpha;
+ // Standard circumferential backlash per gear (~0.04 * module) ensures meshing teeth clear cleanly.
+ let backlash_half_ang = (0.04 * module) / (2.0 * rp);
+ let half_tooth_ang = (PI / (2.0 * z)) - backlash_half_ang;
+ let half_pitch = PI / z;
+ let max_half_ang = half_pitch * 0.92;
+ let min_tip_ang = (half_pitch * 0.06).min(0.01);
+
+ let inv_at_r = |r: f64| -> f64 {
+ if r <= rb {
+ 0.0
+ } else {
+ let phi = (rb / r).clamp(-1.0, 1.0).acos();
+ phi.tan() - phi
+ }
+ };
+ let raw_half_ang = |r: f64| -> f64 { half_tooth_ang + inv_p - inv_at_r(r) };
+
+ let r_start = rb.max(rf);
+ // Truncate tip radius if flanks would otherwise cross (extreme low-tooth / high-pressure-angle gears).
+ let r_tip = if raw_half_ang(ra) >= min_tip_ang {
+ ra
+ } else {
+ let mut lo = r_start;
+ let mut hi = ra;
+ for _ in 0..24 {
+ let mid = 0.5 * (lo + hi);
+ if raw_half_ang(mid) >= min_tip_ang {
+ lo = mid;
+ } else {
+ hi = mid;
+ }
+ }
+ lo
+ };
+
+ let has_root_step = rf < rb - 1e-6 * module;
+ let n_flank: usize = if teeth <= 64 { 4 } else { 3 };
+ let mut flank_samples: Vec<(f64, f64)> = Vec::with_capacity(n_flank);
+ for j in 0..n_flank {
+ let t = (j as f64) / ((n_flank - 1) as f64);
+ let r = r_start + t * (r_tip - r_start);
+ let ang = raw_half_ang(r).clamp(min_tip_ang, max_half_ang);
+ flank_samples.push((r, ang));
+ }
+ let root_ang = flank_samples[0].1;
+ let tip_ang = flank_samples[n_flank - 1].1;
+ // Only emit arc midpoints when arc curvature clearly exceeds self-intersection plane_eps (1e-7 * scale).
+ let emit_valley_mid = (half_pitch - root_ang) > 0.015;
+ let emit_tip_mid = tip_ang > 0.015;
+ let pts_per_tooth = (if emit_valley_mid { 1 } else { 0 })
+ + (if has_root_step { 2 } else { 0 })
+ + 2 * n_flank
+ + (if emit_tip_mid { 1 } else { 0 });
+ let mut profile: Vec<(f64, f64)> = Vec::with_capacity(teeth * pts_per_tooth);
+
+ for k in 0..teeth {
+ let theta_c = 2.0 * PI * (k as f64) / z;
+ // Valley midpoint on root circle (when wide enough to avoid near-collinear slivers)
+ if emit_valley_mid {
+ let (sv, cv) = (theta_c - half_pitch).sin_cos();
+ profile.push((rf * cv, rf * sv));
+ }
+
+ // Lower root corner (when root circle lies below base circle)
+ if has_root_step {
+ let (sr, cr) = (theta_c - root_ang).sin_cos();
+ profile.push((rf * cr, rf * sr));
+ }
+
+ // Lower involute flank (from r_start up to r_tip)
+ for &(r, ang) in &flank_samples {
+ let (s, c) = (theta_c - ang).sin_cos();
+ profile.push((r * c, r * s));
+ }
+
+ // Tip midpoint (places tooth 0 tip cleanly at (r_tip, 0) on +X when arc is wide enough)
+ if emit_tip_mid {
+ let (st, ct) = theta_c.sin_cos();
+ profile.push((r_tip * ct, r_tip * st));
+ }
+
+ // Upper involute flank (from r_tip down to r_start)
+ for &(r, ang) in flank_samples.iter().rev() {
+ let (s, c) = (theta_c + ang).sin_cos();
+ profile.push((r * c, r * s));
+ }
+
+ // Upper root corner
+ if has_root_step {
+ let (sr, cr) = (theta_c + root_ang).sin_cos();
+ profile.push((rf * cr, rf * sr));
+ }
+ }
+
+ let hz = height * 0.5;
+ if bore > 0.0 {
+ let bore_segs = 32usize;
+ let mut hole = Vec::with_capacity(bore_segs);
+ for i in 0..bore_segs {
+ let a = 2.0 * PI * (i as f64) / (bore_segs as f64);
+ let (s, c) = a.sin_cos();
+ hole.push((bore * c, bore * s));
+ }
+ crate::curves::make_extrude_2d_with_holes(&profile, &[hole], -hz, hz, op_id)
+ } else {
+ make_extrude_2d(&profile, -hz, hz, op_id)
+ }
+}
+
fn rodrigues(v: Vec3, axis: Vec3, angle: f64) -> Vec3 {
let (s, c) = angle.sin_cos();
v * c + axis.cross(v) * s + axis * (axis.dot(v) * (1.0 - c))
diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs
index 40b7245..a9584ee 100644
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@ -35,6 +35,7 @@ pub enum SceneError {
#[derive(Debug, Clone)]
struct SceneSnapshot {
parts: BTreeMap<String, Arc<PolyMesh>>,
+ scalars: BTreeMap<String, f64>,
last_modified: Option<String>,
op_counter: u32,
unit: Unit,
@@ -53,6 +54,7 @@ pub struct Observation {
#[derive(Debug, Clone)]
pub struct Scene {
parts: BTreeMap<String, Arc<PolyMesh>>,
+ scalars: BTreeMap<String, f64>,
last_modified: Option<String>,
snapshots: BTreeMap<String, SceneSnapshot>,
undo_stack: Vec<SceneSnapshot>,
@@ -78,6 +80,7 @@ impl Scene {
pub fn new() -> Self {
Self {
parts: BTreeMap::new(),
+ scalars: BTreeMap::new(),
last_modified: None,
snapshots: BTreeMap::new(),
undo_stack: Vec::new(),
@@ -93,6 +96,26 @@ impl Scene {
}
}
+ /// Persist a scalar variable on the scene (participates in transactional checkpoints, rollbacks, and undo).
+ pub fn set_scalar(&mut self, name: impl Into<String>, val: f64) {
+ self.scalars.insert(name.into(), val);
+ }
+
+ /// Look up a persisted scalar variable on the scene.
+ pub fn get_scalar(&self, name: &str) -> Option<f64> {
+ self.scalars.get(name).copied()
+ }
+
+ /// Borrow all persisted scalar variables on the scene.
+ pub fn scalars(&self) -> &BTreeMap<String, f64> {
+ &self.scalars
+ }
+
+ /// Remove all persisted scalar variables from the scene.
+ pub fn clear_scalars(&mut self) {
+ self.scalars.clear();
+ }
+
/// Attach an in-memory binary asset (e.g. `.glb`, `.obj`, `.stl`) for zero-disk `load("name")` in servers/WASM.
pub fn insert_asset(&mut self, name: impl Into<String>, bytes: Vec<u8>) {
if self.assets.len() >= 32 {
@@ -169,10 +192,43 @@ impl Scene {
crate::render::render_view_png(&mesh, path, size, view).map_err(SceneError::OpFailed)
}
+ /// Render a 2x2 studio quad preview PNG of ALL named parts in the scene combined.
+ pub fn render_preview_scene(&self, path: &Path, size: usize) -> Result<(), SceneError> {
+ let mesh = self.merged_scene_mesh()?;
+ crate::render::render_quad_png(&mesh, path, size).map_err(SceneError::OpFailed)
+ }
+
+ /// Render a named view (`quad|front|back|right|left|top|iso`) of ALL named parts in the scene combined.
+ pub fn render_preview_scene_view(&self, path: &Path, size: usize, view: &str) -> Result<(), SceneError> {
+ let mesh = self.merged_scene_mesh()?;
+ crate::render::render_view_png(&mesh, path, size, view).map_err(SceneError::OpFailed)
+ }
+
+ /// Render a 2x2 studio quad preview PNG of ALL named parts in the scene directly to in-memory bytes.
+ pub fn render_preview_scene_bytes(&self, size: usize) -> Result<Vec<u8>, SceneError> {
+ let mesh = self.merged_scene_mesh()?;
+ crate::render::render_quad_png_bytes(&mesh, size).map_err(SceneError::OpFailed)
+ }
+
pub fn export_blueprint_svg(&self, path: &Path, part_opt: Option<&str>) -> Result<(), SceneError> {
let mesh = self.merged_mesh(part_opt)?;
let title = part_opt.or_else(|| self.last_part_name()).unwrap_or("forma_part");
- crate::render::write_blueprint_svg(&mesh, title, path).map_err(SceneError::OpFailed)
+ crate::render::write_blueprint_svg_with_unit(&mesh, title, path, self.unit)
+ .map_err(SceneError::OpFailed)
+ }
+
+ /// Export a 1200x900 engineering SVG blueprint of ALL named parts in the scene combined.
+ pub fn export_blueprint_svg_scene(&self, path: &Path) -> Result<(), SceneError> {
+ let mesh = self.merged_scene_mesh()?;
+ crate::render::write_blueprint_svg_with_unit(&mesh, "forma_scene", path, self.unit)
+ .map_err(SceneError::OpFailed)
+ }
+
+ /// Render a 1200x900 engineering SVG blueprint of ALL named parts in the scene as a String.
+ pub fn export_blueprint_svg_scene_string(&self) -> Result<String, SceneError> {
+ let mesh = self.merged_scene_mesh()?;
+ crate::render::render_blueprint_svg_string_with_unit(&mesh, "forma_scene", self.unit)
+ .map_err(SceneError::OpFailed)
}
/// Export `mesh` (typically from [`Scene::merged_mesh`]) to in-memory bytes by extension,
@@ -191,6 +247,32 @@ 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.
+ #[cfg(not(target_arch = "wasm32"))]
+ pub fn export_scene_path(&self, path: &Path) -> Result<usize, SceneError> {
+ let ext = path
+ .extension()
+ .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" => {
+ 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)
+ }
+ _ => Err(SceneError::OpFailed(format!(
+ "multi-node scene export requires .glb or .blend (got '.{ext}')"
+ ))),
+ }
+ }
+
pub fn part_names(&self) -> Vec<String> {
self.parts.keys().cloned().collect()
}
@@ -212,6 +294,7 @@ impl Scene {
pub fn push_undo(&mut self) {
self.undo_stack.push(SceneSnapshot {
parts: self.parts.clone(),
+ scalars: self.scalars.clone(),
last_modified: self.last_modified.clone(),
op_counter: self.op_counter,
unit: self.unit,
@@ -231,6 +314,7 @@ impl Scene {
name.to_string(),
SceneSnapshot {
parts: self.parts.clone(),
+ scalars: self.scalars.clone(),
last_modified: self.last_modified.clone(),
op_counter: self.op_counter,
unit: self.unit,
@@ -246,6 +330,7 @@ impl Scene {
.ok_or_else(|| SceneError::UnknownCheckpoint(name.to_string()))?;
self.push_undo();
self.parts = snap.parts;
+ self.scalars = snap.scalars;
self.last_modified = snap.last_modified;
self.op_counter = snap.op_counter;
self.unit = snap.unit;
@@ -255,6 +340,7 @@ impl Scene {
pub fn undo(&mut self) -> Result<(), SceneError> {
let snap = self.undo_stack.pop().ok_or(SceneError::NothingToUndo)?;
self.parts = snap.parts;
+ self.scalars = snap.scalars;
self.last_modified = snap.last_modified;
self.op_counter = snap.op_counter;
self.unit = snap.unit;
@@ -351,6 +437,7 @@ impl Scene {
}
}
self.last_modified = Some(name.clone());
+ self.scalars.remove(&name);
self.parts.insert(name, Arc::new(mesh));
Ok(inv)
}
@@ -585,14 +672,8 @@ impl Scene {
self.set_part(target, res)
}
- /// Return the requested part, or the last modified part (avoiding exporting leaked temp operands).
- pub fn merged_mesh(&self, part_opt: Option<&str>) -> Result<PolyMesh, SceneError> {
- if let Some(p) = part_opt {
- return Ok((**self.get_part(p)?).clone());
- }
- if let Some(last) = self.last_part_name() {
- return Ok((**self.parts.get(last).unwrap()).clone());
- }
+ /// Combine ALL named scene parts into a single `PolyMesh`, preserving every part's materials and colors.
+ pub fn merged_scene_mesh(&self) -> Result<PolyMesh, SceneError> {
if self.parts.is_empty() {
return Err(SceneError::EmptyScene);
}
@@ -604,6 +685,17 @@ impl Scene {
Ok(out)
}
+ /// Return the requested part, or the last modified part (avoiding exporting leaked temp operands).
+ pub fn merged_mesh(&self, part_opt: Option<&str>) -> Result<PolyMesh, SceneError> {
+ if let Some(p) = part_opt {
+ return Ok((**self.get_part(p)?).clone());
+ }
+ if let Some(last) = self.last_part_name() {
+ return Ok((**self.parts.get(last).unwrap()).clone());
+ }
+ self.merged_scene_mesh()
+ }
+
pub fn export(&self, path: &Path, part_opt: Option<&str>) -> Result<MeshInvariants, SceneError> {
let mesh = self.merged_mesh(part_opt)?;
export_mesh_with_unit(&mesh, path, self.unit).map_err(SceneError::OpFailed)?;
diff --git a/crates/forma-core/tests/mcp_ergonomics.rs b/crates/forma-core/tests/mcp_ergonomics.rs
new file mode 100644
index 0000000..427a9ae
--- /dev/null
+++ b/crates/forma-core/tests/mcp_ergonomics.rs
@@ -0,0 +1,336 @@
+use forma_core::math::Vec3;
+use forma_core::{Material, Scene, SceneError};
+
+/// Minimal RFC 1951 fixed-Huffman + PNG Sub-filter RGB decoder matching `forma_core::render`.
+fn decode_png_rgb(png: &[u8]) -> (u32, u32, Vec<u8>) {
+ assert!(png.len() > 33, "PNG too short");
+ assert_eq!(&png[0..8], &[137, 80, 78, 71, 13, 10, 26, 10], "invalid PNG signature");
+
+ let mut pos = 8usize;
+ let mut width = 0u32;
+ let mut height = 0u32;
+ let mut idat = Vec::new();
+ let mut saw_iend = false;
+
+ while pos + 12 <= png.len() {
+ let len = u32::from_be_bytes(png[pos..pos + 4].try_into().unwrap()) as usize;
+ let tag = &png[pos + 4..pos + 8];
+ let data = &png[pos + 8..pos + 8 + len];
+ pos += 12 + len;
+ match tag {
+ b"IHDR" => {
+ assert_eq!(len, 13);
+ width = u32::from_be_bytes(data[0..4].try_into().unwrap());
+ height = u32::from_be_bytes(data[4..8].try_into().unwrap());
+ assert_eq!(data[8], 8, "expected 8-bit depth");
+ assert_eq!(data[9], 2, "expected truecolor RGB");
+ }
+ b"IDAT" => idat.extend_from_slice(data),
+ b"IEND" => {
+ saw_iend = true;
+ break;
+ }
+ _ => {}
+ }
+ }
+ assert!(saw_iend, "missing IEND chunk");
+ assert!(width > 0 && height > 0, "invalid PNG dimensions");
+ assert!(idat.len() >= 6, "IDAT zlib stream too short");
+ assert_eq!(idat[0], 0x78);
+
+ // Bit reader over deflate payload (skip 2-byte zlib header, leave 4-byte adler32)
+ struct BitReader<'a> {
+ data: &'a [u8],
+ bit_pos: usize,
+ }
+ impl<'a> BitReader<'a> {
+ fn read_bit(&mut self) -> u32 {
+ let byte = self.data[self.bit_pos / 8];
+ let bit = (byte >> (self.bit_pos % 8)) & 1;
+ self.bit_pos += 1;
+ bit as u32
+ }
+ fn read_bits_lsb(&mut self, n: u8) -> u32 {
+ let mut v = 0u32;
+ for i in 0..n {
+ v |= self.read_bit() << i;
+ }
+ v
+ }
+ fn read_bits_msb(&mut self, n: u8) -> u32 {
+ let mut v = 0u32;
+ for _ in 0..n {
+ v = (v << 1) | self.read_bit();
+ }
+ v
+ }
+ fn read_fixed_lit(&mut self) -> u16 {
+ let c7 = self.read_bits_msb(7);
+ if c7 <= 0b001_0111 {
+ return (256 + c7) as u16;
+ }
+ let c8 = (c7 << 1) | self.read_bit();
+ if (0x30..=0xBF).contains(&c8) {
+ return (c8 - 0x30) as u16;
+ }
+ if (0xC0..=0xC7).contains(&c8) {
+ return (280 + (c8 - 0xC0)) as u16;
+ }
+ let c9 = (c8 << 1) | self.read_bit();
+ assert!((0x190..=0x1FF).contains(&c9), "invalid fixed Huffman code {c9:#x}");
+ (144 + (c9 - 0x190)) as u16
+ }
+ }
+
+ const LEN_BASE: [usize; 29] = [
+ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99,
+ 115, 131, 163, 195, 227, 258,
+ ];
+ const LEN_EXTRA: [u8; 29] = [
+ 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
+ ];
+ const DIST_BASE: [usize; 30] = [
+ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025,
+ 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
+ ];
+ const DIST_EXTRA: [u8; 30] = [
+ 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12,
+ 12, 13, 13,
+ ];
+
+ let mut br = BitReader {
+ data: &idat[2..idat.len() - 4],
+ bit_pos: 0,
+ };
+ let mut raw = Vec::with_capacity((height as usize) * (1 + width as usize * 3));
+ loop {
+ let bfinal = br.read_bit();
+ let btype = br.read_bits_lsb(2);
+ assert_eq!(btype, 1, "expected fixed Huffman deflate block");
+ loop {
+ let sym = br.read_fixed_lit();
+ if sym < 256 {
+ raw.push(sym as u8);
+ } else if sym == 256 {
+ break;
+ } else {
+ let li = (sym - 257) as usize;
+ let length = LEN_BASE[li] + br.read_bits_lsb(LEN_EXTRA[li]) as usize;
+ let di = br.read_bits_msb(5) as usize;
+ let dist = DIST_BASE[di] + br.read_bits_lsb(DIST_EXTRA[di]) as usize;
+ for _ in 0..length {
+ let b = raw[raw.len() - dist];
+ raw.push(b);
+ }
+ }
+ }
+ if bfinal == 1 {
+ break;
+ }
+ }
+
+ let row_bytes = width as usize * 3;
+ let stride = 1 + row_bytes;
+ assert_eq!(raw.len(), height as usize * stride, "unexpected decoded scanline byte count");
+
+ let mut rgb = vec![0u8; height as usize * row_bytes];
+ for y in 0..height as usize {
+ let filter = raw[y * stride];
+ let src = &raw[y * stride + 1..y * stride + stride];
+ let dst = &mut rgb[y * row_bytes..(y + 1) * row_bytes];
+ match filter {
+ 0 => dst.copy_from_slice(src),
+ 1 => {
+ for x in 0..row_bytes {
+ let left = if x >= 3 { dst[x - 3] } else { 0 };
+ dst[x] = src[x].wrapping_add(left);
+ }
+ }
+ other => panic!("unexpected PNG filter type {other}"),
+ }
+ }
+ (width, height, rgb)
+}
+
+fn make_two_colored_parts_scene() -> Scene {
+ let mut scene = Scene::new();
+ scene.add_box("part_red", 2.0, 2.0, 2.0, Vec3::new(-3.0, 0.0, 0.0)).unwrap();
+ let mut red_mesh = (**scene.get_part("part_red").unwrap()).clone();
+ red_mesh.assign_material(
+ Material {
+ name: "red".into(),
+ color: [0.95, 0.12, 0.12, 1.0],
+ metallic: 0.1,
+ roughness: 0.5,
+ },
+ None,
+ );
+ scene.set_part("part_red", red_mesh).unwrap();
+
+ scene.add_box("part_green", 2.0, 2.0, 2.0, Vec3::new(3.0, 0.0, 0.0)).unwrap();
+ let mut green_mesh = (**scene.get_part("part_green").unwrap()).clone();
+ green_mesh.assign_material(
+ Material {
+ name: "green".into(),
+ color: [0.12, 0.90, 0.18, 1.0],
+ metallic: 0.1,
+ roughness: 0.5,
+ },
+ None,
+ );
+ scene.set_part("part_green", green_mesh).unwrap();
+ scene
+}
+
+#[test]
+fn scalar_persistence_and_transactional_restore() {
+ let mut scene = Scene::new();
+ assert!(scene.scalars().is_empty());
+ assert_eq!(scene.get_scalar("r"), None);
+
+ scene.set_scalar("r", 12.5);
+ scene.set_scalar("teeth", 24.0);
+ assert_eq!(scene.get_scalar("r"), Some(12.5));
+ assert_eq!(scene.get_scalar("teeth"), Some(24.0));
+ assert_eq!(scene.scalars().len(), 2);
+
+ // Checkpoint saves scalars alongside scene geometry
+ scene.checkpoint("v1");
+
+ // Mutate, add, and overwrite scalars after checkpoint
+ scene.set_scalar("r", 99.0);
+ scene.set_scalar("pitch", 2.0);
+ assert_eq!(scene.get_scalar("r"), Some(99.0));
+ assert_eq!(scene.get_scalar("pitch"), Some(2.0));
+
+ // Rollback restores exact scalar map from checkpoint
+ scene.rollback("v1").unwrap();
+ assert_eq!(scene.get_scalar("r"), Some(12.5));
+ assert_eq!(scene.get_scalar("teeth"), Some(24.0));
+ assert_eq!(scene.get_scalar("pitch"), None);
+ assert_eq!(scene.scalars().len(), 2);
+
+ // Undo after rollback restores pre-rollback scalar state
+ scene.undo().unwrap();
+ assert_eq!(scene.get_scalar("r"), Some(99.0));
+ assert_eq!(scene.get_scalar("pitch"), Some(2.0));
+
+ // push_undo + clear_scalars + undo restores scalars
+ scene.push_undo();
+ scene.clear_scalars();
+ assert!(scene.scalars().is_empty());
+ assert_eq!(scene.get_scalar("r"), None);
+
+ scene.undo().unwrap();
+ assert_eq!(scene.get_scalar("r"), Some(99.0));
+ assert_eq!(scene.get_scalar("teeth"), Some(24.0));
+ assert_eq!(scene.get_scalar("pitch"), Some(2.0));
+}
+
+#[test]
+fn merged_scene_mesh_preserves_materials_and_bbox() {
+ let empty = Scene::new();
+ assert!(matches!(empty.merged_scene_mesh(), Err(SceneError::EmptyScene)));
+
+ let scene = make_two_colored_parts_scene();
+
+ // Default single-part merged_mesh(None) only returns last modified part ("part_green")
+ let last_only = scene.merged_mesh(None).unwrap();
+ let last_bb = last_only.aabb();
+ assert!((last_bb.min.x - 2.0).abs() < 1e-6);
+ assert!((last_bb.max.x - 4.0).abs() < 1e-6);
+
+ // merged_scene_mesh() combines both parts and preserves both materials
+ let merged = scene.merged_scene_mesh().unwrap();
+ let bb = merged.aabb();
+ assert!((bb.min.x - (-4.0)).abs() < 1e-6, "min.x={}", bb.min.x);
+ assert!((bb.max.x - 4.0).abs() < 1e-6, "max.x={}", bb.max.x);
+ assert!((bb.min.y - (-1.0)).abs() < 1e-6);
+ assert!((bb.max.y - 1.0).abs() < 1e-6);
+ assert!((bb.min.z - (-1.0)).abs() < 1e-6);
+ assert!((bb.max.z - 1.0).abs() < 1e-6);
+
+ assert_eq!(merged.materials.len(), 2, "expected 2 distinct materials");
+ let red_id = merged.materials.iter().position(|m| m.name == "red").expect("red material missing") as u16;
+ let green_id = merged.materials.iter().position(|m| m.name == "green").expect("green material missing") as u16;
+ assert_ne!(red_id, green_id);
+
+ let red_faces = merged.faces.iter().filter(|f| f.mat_id == red_id).count();
+ let green_faces = merged.faces.iter().filter(|f| f.mat_id == green_id).count();
+ assert_eq!(red_faces, 6);
+ assert_eq!(green_faces, 6);
+}
+
+#[test]
+fn render_preview_scene_and_bytes_contain_both_part_colors() {
+ let scene = make_two_colored_parts_scene();
+
+ // In-memory bytes API
+ let png_bytes = scene.render_preview_scene_bytes(256).unwrap();
+ let (w, h, rgb) = decode_png_rgb(&png_bytes);
+ assert_eq!((w, h), (256, 256));
+
+ let mut red_pixels = 0usize;
+ let mut green_pixels = 0usize;
+ for px in rgb.chunks_exact(3) {
+ let (r, g, b) = (px[0] as i32, px[1] as i32, px[2] as i32);
+ if r - g > 60 && r - b > 60 {
+ red_pixels += 1;
+ }
+ if g - r > 60 && g - b > 60 {
+ green_pixels += 1;
+ }
+ }
+ assert!(
+ red_pixels > 50,
+ "expected red pixels from part_red in scene render, got {red_pixels}"
+ );
+ assert!(
+ green_pixels > 50,
+ "expected green pixels from part_green in scene render, got {green_pixels}"
+ );
+
+ // File output API writes a valid PNG containing both colors
+ let tmp_path = std::env::temp_dir().join(format!(
+ "forma_mcp_ergonomics_scene_{}.png",
+ std::process::id()
+ ));
+ scene.render_preview_scene(&tmp_path, 256).unwrap();
+ let disk_bytes = std::fs::read(&tmp_path).unwrap();
+ let _ = std::fs::remove_file(&tmp_path);
+ let (dw, dh, drgb) = decode_png_rgb(&disk_bytes);
+ assert_eq!((dw, dh), (256, 256));
+ let disk_red = drgb
+ .chunks_exact(3)
+ .filter(|px| px[0] as i32 - px[1] as i32 > 60 && px[0] as i32 - px[2] as i32 > 60)
+ .count();
+ let disk_green = drgb
+ .chunks_exact(3)
+ .filter(|px| px[1] as i32 - px[0] as i32 > 60 && px[1] as i32 - px[2] as i32 > 60)
+ .count();
+ assert!(disk_red > 50, "expected red pixels in disk PNG, got {disk_red}");
+ assert!(disk_green > 50, "expected green pixels in disk PNG, got {disk_green}");
+}
+
+#[test]
+fn export_blueprint_svg_scene_spans_all_parts() {
+ let scene = make_two_colored_parts_scene();
+ let svg = scene.export_blueprint_svg_scene_string().unwrap();
+ assert!(svg.starts_with("<svg "), "invalid SVG header");
+ assert!(svg.trim_end().ends_with("</svg>"), "missing SVG closing tag");
+ assert!(svg.contains("forma_scene"), "expected scene title in blueprint");
+ assert!(svg.contains("SIZE: 8.000 x 2.000 x 2.000 m"), "expected combined bbox in blueprint");
+ assert!(svg.contains("VOL: 16.0000 m^3"), "expected combined volume in blueprint");
+
+ let tmp_svg = std::env::temp_dir().join(format!(
+ "forma_mcp_ergonomics_scene_{}.svg",
+ std::process::id()
+ ));
+ scene.export_blueprint_svg_scene(&tmp_svg).unwrap();
+ let disk_svg = std::fs::read_to_string(&tmp_svg).unwrap();
+ let _ = std::fs::remove_file(&tmp_svg);
+ assert!(disk_svg.starts_with("<svg "), "invalid disk SVG header");
+ assert!(disk_svg.contains("forma_scene"), "expected scene title in disk SVG");
+ assert!(disk_svg.contains("SIZE: 8.000 x 2.000 x 2.000 m"), "expected combined bbox in disk SVG");
+ assert_eq!(disk_svg.len(), svg.len());
+}
diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs
index 4259c36..4095552 100644
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@ -1,9 +1,9 @@
-//! forma-lang: Dual notation parsers/evaluators for empirical LLM ablation.
+//! forma-lang: Parsers and transactional evaluators for Forma's modeling languages.
//!
-//! - Candidate A (`pipeline` / Forma-Pipe): In-distribution declarative/pipeline dialect
+//! - `pipeline` (`Forma-Pipe`, default): Declarative pipe notation
//! (`name = prim(...) | op(...)`) with named keyword arguments and semantic selectors.
-//! - Candidate B (`compact` / Forma-DSL): Compact EBNF-specified positional line-oriented DSL
-//! (`box f 4 2 .4` / `sub f cyl .5 1 @ ...`).
+//! - `compact` (`Forma-DSL`): Positional line-oriented notation
+//! (`new f box 4 2 .4` / `sub f cyl .5 1 @ ...`).
pub mod compact;
pub mod pipeline;
@@ -68,24 +68,22 @@ pub fn eval_script(scene: &mut Scene, dialect: Dialect, src: &str) -> Result<Obs
/// Formal GBNF grammar for zero-syntax-error constrained decoding (llama.cpp / XGrammar / vLLM).
pub const SPEC_PIPE_GBNF: &str = include_str!("../../../grammar/forma_pipe.gbnf");
-/// Concise system prompt spec for Candidate A (Forma-Pipe), ~355 o200k tokens.
-/// Keeps core MCP schema strictly <800 tokens; advanced Tier-1 domains load on-demand via `spec_topic`.
-pub const SPEC_PIPE: &str = r#"Forma-Pipe (Z-up, unit-agnostic numbers, default meters, watertight 3D):
-`name = expr | op | op` (multi-line `|`, math `+ - * / sqrt sin cos pi`, last assigned part exports).
-Primitives (`at=(x,y,z)` or `[(x,y,z),...]`; `z0=Z` sets bottom):
-- `box(sx,sy,sz, at=, z0=)` | `cyl(r,h, segs=32, axis=z, at=, z0=)` (`segs=6`: verts k*60deg)
-- `cone(r0,r1,h)` | `sphere(r)` | `torus(R,r)` | `revolve([(r,z),...], segs=32)` (auto-closes r=0)
-- `arc_tube(center=(x,y,z), rx=, rz=, start=-90, end=90, r=0.08)` | `tube([(x,y,z),...], r=0.08)`
-- `extrude2d([(x,y),...], z0, z1, holes=)` | `pipe(ro,ri,h)` | `loft([(z,[(x,y),...]),...])` | `thread(r0,r1,pitch,turns)`
-Ops (`|` or `op(m,...)`; `add`/`cut` take `at=(x,y,z)` or `[...]`):
-- `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)`
-- `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=0.1, roughness=0.5)` | `color(r,g,b)` | `clearance(a,b)` | `section(p,z)`
-- `units("mm")` (m|cm|mm|um|in|ft): declare the unit your numbers are in; .3mf/.step carry it, .glb is scaled to metres
-More: `inspect(topic="deform|curves|uv|remesh|scene")`"#;
-
-/// Progressive on-demand Tier-1 domain specs (paid 0 tokens unless requested!).
+/// 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).
+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=)
+arc_tube(center=,rx=,rz=,start=-90,end=90,r=) tube([(x,y,z),...],r=) thread(r0,r1,pitch,turns) text3d("T",height=,depth=)
+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)
+Topics: deform|curves|uv|remesh|scene"#;
+
+/// Progressive on-demand domain specs (loaded only when requested).
pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
match topic.trim().to_lowercase().as_str() {
"deform" => Ok(
@@ -93,7 +91,7 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
- `solidify(t, offset=-1.0, open_top=false)` — true vertex-normal offset shell (safe on concave/curved shapes)\n\
- `deform(\"bend\"|\"twist\"|\"taper\", axis=x|y|z, angle=45, factor=0.5, subdivs=0)` — auto-subdivides & deforms\n\
- `deform(\"curve\", path=[(x,y,z),...], axis=x|y|z)` — parallel-transport curve warp (accepts `bezier()`/`nurbs()`)\n\
- - `deform(\"lattice\", corners=[8 Vec3 points])` — trilinear 3D FFD cage"
+ - `deform(\"lattice\", corners=[8 Vec3 points in (x,y,z) bit order: 000,100,010,110,001,101,011,111])` — trilinear 3D FFD cage"
),
"curves" => Ok(
"Forma-Pipe // Curves & Sketch Holes:\n\
@@ -110,19 +108,22 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
),
"remesh" => Ok(
"Forma-Pipe // Remesh, Bisect & Import:\n\
- - `remesh(voxel_size=0.08)` — pure-Rust Surface Nets voxel remesh (heals dirty/multi-shell meshes to watertight)\n\
+ - `remesh(voxel_size=0.0)` — Surface Nets voxel remesh (0 = auto diag/28; heals dirty/multi-shell meshes to watertight)\n\
- `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)` — exact watertight half-space plane cut + planar cap\n\
- `load(\"path.glb|obj|stl\")` — import external 3D asset (or uploaded key in forma-server)"
),
"scene" => Ok(
- "Forma-Pipe // Multi-Object glTF Scene Graph:\n\
- - Pass `scene: true` to MCP `export` or `--scene` to `forma eval --out scene.glb` to export all named parts as separate glTF 2.0 nodes with shared Arc<PolyMesh> instancing."
+ "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\
+ - 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)")),
}
}
-/// Concise system prompt spec + EBNF for Candidate B (Forma-DSL), ~330 o200k tokens.
+/// Concise reference and EBNF for Forma-DSL (compact positional notation).
pub const SPEC_COMPACT: &str = r#"Forma-DSL (Z-up, default meters, watertight 3D line DSL; last modified part exports):
EBNF:
stmt := 'new' ID prim | ('add'|'sub'|'int') ID (ID|prim) ['@' x y z (',' x y z)*] | mod | tx
@@ -141,7 +142,7 @@ mod tests {
use super::*;
#[test]
- fn test_issue_2_unknown_kwargs_and_clamp_warnings() {
+ fn test_unknown_kwargs_and_clamp_warnings() {
let mut s = Scene::new();
s.strict_manifold = true;
// Unknown kwarg rejected
@@ -196,7 +197,7 @@ mod tests {
let mut s = Scene::new();
let obs = eval_script(&mut s, Dialect::Pipe, "p = box(1, 1, 1)").unwrap();
assert_eq!(s.unit, forma_core::Unit::Meter);
- assert!(!obs.text.contains("unit="), "metre scenes keep the legacy observation text");
+ assert!(!obs.text.contains("unit="), "default metre scenes omit the unit= suffix");
let err = eval_script(&mut s, Dialect::Pipe, "units(\"parsec\")").unwrap_err();
assert!(err.contains("unknown unit 'parsec'"), "err={err}");
@@ -209,7 +210,7 @@ mod tests {
}
#[test]
- fn test_issue_35_fallback_bevel_segs_warning() {
+ fn test_fallback_bevel_segs_warning() {
let mut s = Scene::new();
s.strict_manifold = true;
let obs = eval_script(&mut s, Dialect::Pipe, "a = box(2, 2, 2) | bevel(all, 0.3, segs=4)").unwrap();
diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs
index 29a1402..bcba169 100644
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@ -1,4 +1,4 @@
-//! Candidate A (Forma-Pipe): In-distribution declarative/pipeline modeling dialect.
+//! Forma-Pipe: Declarative pipeline modeling dialect (`name = prim(...) | op(...)`).
//!
//! Grammar overview:
//! stmt := ID '=' expr | expr
@@ -34,6 +34,29 @@ enum Tok {
Eof,
}
+impl Tok {
+ fn describe(&self) -> String {
+ match self {
+ Tok::Ident(s) => format!("identifier '{s}'"),
+ Tok::Num(v) => format!("number '{v}'"),
+ Tok::Str(s) => format!("string \"{s}\""),
+ Tok::LParen => "'('".into(),
+ Tok::RParen => "')'".into(),
+ Tok::LBracket => "'['".into(),
+ Tok::RBracket => "']'".into(),
+ Tok::Comma => "','".into(),
+ Tok::Eq => "'='".into(),
+ Tok::Pipe => "'|'".into(),
+ Tok::Plus => "'+'".into(),
+ Tok::Minus => "'-'".into(),
+ Tok::Star => "'*'".into(),
+ Tok::Slash => "'/'".into(),
+ Tok::Newline => "end of line".into(),
+ Tok::Eof => "end of input".into(),
+ }
+ }
+}
+
fn tokenize(src: &str) -> Result<Vec<(Tok, usize)>, String> {
let mut out = Vec::new();
let chars: Vec<char> = src.chars().collect();
@@ -222,9 +245,12 @@ impl Val {
const MAX_PARSE_DEPTH: usize = 128;
const MAX_BATCH_POINTS: usize = 512;
+const MAX_COMP_ITERS: usize = 512;
+const MAX_TOTAL_COMP_STEPS: usize = 8192;
+const MAX_MACRO_DEPTH: usize = 16;
+const MAX_MACRO_CALLS: usize = 2048;
-/// Count-like arguments (segs, levels, n, degree) must be whole and non-negative: a fraction or a
-/// negative used to be truncated to something else without a word.
+/// Count-like arguments (segs, levels, n, degree) must be whole non-negative integers.
fn whole_count(v: f64, ctx: &str) -> Result<usize, String> {
if v.is_finite() && v >= 0.0 && v.fract() == 0.0 && v <= 1.0e9 {
Ok(v as usize)
@@ -233,6 +259,15 @@ fn whole_count(v: f64, ctx: &str) -> Result<usize, String> {
}
}
+/// Whole signed integer helper for `range(start, stop, step)` bounds.
+fn whole_int(v: f64, ctx: &str) -> Result<i64, String> {
+ if v.is_finite() && v.fract() == 0.0 && v.abs() <= 1.0e9 {
+ Ok(v as i64)
+ } else {
+ Err(format!("{ctx}: range bounds/step must be finite whole integers (got {v})"))
+ }
+}
+
fn check_finite(v: f64, ctx: &str) -> Result<f64, String> {
if v.is_finite() {
Ok(v)
@@ -297,10 +332,11 @@ fn warn_if_clamped(scene: &mut Scene, op: &str, param: &str, requested: usize, l
}
}
-/// Most positional arguments each function reads. More than this used to be dropped silently.
+/// Maximum number of positional arguments each function accepts.
fn max_call_positional(name: &str) -> Option<usize> {
Some(match name {
- "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad" => 1,
+ "sqrt" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "abs" | "deg" | "rad" => 1,
+ "atan2" => 2,
"bezier" => 2,
"nurbs" | "bspline" => 3,
"clearance" | "section" => 2,
@@ -320,6 +356,7 @@ fn max_call_positional(name: &str) -> Option<usize> {
"thread" | "helix" => 5,
"sweep" => 2,
"text3d" | "text" => 3,
+ "gear" => 5,
"load" | "import" => 2,
_ => return None,
})
@@ -361,9 +398,9 @@ fn check_positional_count(n: usize, max: Option<usize>, allowed_kw: Option<&[&st
const CALL_NAMES: &[&str] = &[
"box", "cyl", "cylinder", "prism", "cone", "frustum", "sphere", "torus", "revolve", "arc_tube", "tube", "extrude2d",
- "pipe", "hollow_cyl", "loft", "thread", "helix", "sweep", "text3d", "text", "load", "import", "bezier", "nurbs",
- "bspline", "clearance", "section", "checkpoint", "rollback", "undo", "units", "del", "remove", "sqrt", "sin",
- "cos", "asin", "acos", "abs", "deg", "rad",
+ "pipe", "hollow_cyl", "loft", "thread", "helix", "sweep", "text3d", "text", "gear", "load", "import", "bezier", "nurbs",
+ "bspline", "clearance", "section", "checkpoint", "rollback", "undo", "units", "unit", "del", "remove", "sqrt", "sin",
+ "cos", "tan", "asin", "acos", "atan", "atan2", "abs", "deg", "rad",
];
const PIPE_OP_NAMES: &[&str] = &[
@@ -384,13 +421,23 @@ fn unknown_name_hint(name: &str, known: &[&str]) -> String {
format!("{suggestion}; accepted: {}", known.join(", "))
}
+fn is_builtin_name(name: &str) -> bool {
+ CALL_NAMES.contains(&name)
+ || PIPE_OP_NAMES.contains(&name)
+ || matches!(
+ name,
+ "def" | "for" | "in" | "range" | "true" | "True" | "false" | "False" | "pi" | "PI"
+ )
+}
+
fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> {
Some(match name {
- "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad" => &["x"],
+ "sqrt" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "abs" | "deg" | "rad" => &["x"],
+ "atan2" => &["y", "x"],
"bezier" => &["points", "pts", "segs", "segments"],
"nurbs" | "bspline" => &["points", "pts", "degree", "deg", "segs", "segments", "weights"],
"clearance" => &["a", "b"],
- "section" => &["part", "z"],
+ "section" => &["part", "p", "z"],
"checkpoint" | "rollback" | "del" | "remove" => &["name", "tag"],
"units" | "unit" => &["name", "unit"],
"undo" => &[],
@@ -405,9 +452,10 @@ fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> {
"extrude2d" => &["points", "pts", "z0", "z1", "holes", "rot", "rotate", "at", "center"],
"pipe" | "hollow_cyl" => &["r_out", "ro", "outer", "r", "r_in", "ri", "inner", "h", "height", "len", "length", "segs", "segments", "axis", "rot", "rotate", "at", "center", "z0"],
"loft" => &["sections", "profiles", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
- "thread" | "helix" => &["r_minor", "r_min", "r_in", "r", "r_major", "r_maj", "r_out", "pitch", "p", "turns", "n", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
+ "thread" | "helix" => &["r_minor", "r_min", "r_in", "r0", "r", "r_major", "r_maj", "r_out", "r1", "pitch", "p", "turns", "n", "segs", "segments", "rot", "rotate", "at", "center", "z0"],
"sweep" => &["profile", "path", "closed", "scale_end", "taper", "twist", "twist_deg", "rot", "rotate", "at", "center", "z0"],
"text3d" | "text" => &["text", "size", "h", "height", "depth", "d", "t", "rot", "rotate", "at", "center", "z0"],
+ "gear" => &["teeth", "z", "n", "module", "m", "h", "height", "pressure_angle", "pa", "bore", "bore_r", "rot", "rotate", "at", "center", "z0"],
"load" | "import" => &["path", "file", "yup", "rot", "rotate", "at", "center", "z0"],
_ => return None,
})
@@ -439,13 +487,30 @@ fn allowed_pipe_kwargs(op_name: &str) -> Option<&'static [&'static str]> {
})
}
+#[derive(Clone)]
+struct MacroParam {
+ name: String,
+ default_range: Option<(usize, usize)>,
+}
+
+#[derive(Clone)]
+struct MacroDef {
+ params: Vec<MacroParam>,
+ body_start: usize,
+ body_end: usize,
+}
+
struct Parser<'a> {
toks: Vec<(Tok, usize)>,
pos: usize,
depth: usize,
stmts: usize,
+ comp_steps: usize,
+ macro_depth: usize,
+ macro_calls: usize,
scene: &'a mut Scene,
vars: HashMap<String, Val>,
+ macros: HashMap<String, MacroDef>,
}
impl<'a> Parser<'a> {
@@ -477,7 +542,7 @@ impl<'a> Parser<'a> {
self.bump();
Ok(())
} else {
- Err(format!("line {}: expected {:?}, got {:?}", self.line(), expected, self.peek()))
+ Err(format!("line {}: expected {}, got {}", self.line(), expected.describe(), self.peek().describe()))
}
}
@@ -503,14 +568,30 @@ impl<'a> Parser<'a> {
}
fn parse_stmt(&mut self) -> Result<(), String> {
+ // Check `def name(p1, p2=default) = expr`
+ if matches!(self.peek(), Tok::Ident(s) if s == "def")
+ && !matches!(self.toks.get(self.pos + 1).map(|t| &t.0), Some(Tok::Eq))
+ {
+ return self.parse_def_stmt();
+ }
// Check `ID = expr`
if let Tok::Ident(name) = self.peek().clone() {
if self.pos + 1 < self.toks.len() && matches!(self.toks[self.pos + 1].0, Tok::Eq) {
self.bump(); // ident
self.bump(); // '='
let val = self.parse_pipe()?;
- if let Val::Mesh(ref m) = val {
- self.scene.set_part(name.clone(), m.clone()).map_err(|e| e.to_string())?;
+ match val {
+ Val::Mesh(ref m) => {
+ if !name.starts_with('_') {
+ self.scene.set_part(name.clone(), m.clone()).map_err(|e| e.to_string())?;
+ }
+ }
+ Val::Num(n) => {
+ if !name.starts_with('_') && n.is_finite() {
+ self.scene.set_scalar(name.clone(), n);
+ }
+ }
+ _ => {}
}
self.vars.insert(name, val);
return Ok(());
@@ -526,6 +607,127 @@ impl<'a> Parser<'a> {
Ok(())
}
+ fn parse_def_stmt(&mut self) -> Result<(), String> {
+ let def_line = self.line();
+ self.bump(); // 'def'
+ let macro_name = match self.bump() {
+ Tok::Ident(s) => s,
+ other => {
+ return Err(format!(
+ "line {def_line}: expected macro name after 'def', got {}",
+ other.describe()
+ ))
+ }
+ };
+ if is_builtin_name(&macro_name) {
+ return Err(format!("line {def_line}: cannot redefine built-in '{macro_name}'"));
+ }
+ self.expect(&Tok::LParen)?;
+ let mut params: Vec<MacroParam> = Vec::new();
+ let mut seen_default = false;
+ while !matches!(self.peek(), Tok::RParen | Tok::Eof) {
+ let p_line = self.line();
+ let pname = match self.bump() {
+ Tok::Ident(s) => s,
+ other => {
+ return Err(format!(
+ "line {p_line}: expected parameter name in macro '{macro_name}', got {}",
+ other.describe()
+ ))
+ }
+ };
+ if params.iter().any(|p| p.name == pname) {
+ return Err(format!(
+ "line {p_line}: duplicate parameter '{pname}' in macro '{macro_name}'"
+ ));
+ }
+ let default_range = if matches!(self.peek(), Tok::Eq) {
+ self.bump(); // '='
+ let d_start = self.pos;
+ let mut p_depth = 0usize;
+ let mut b_depth = 0usize;
+ while !matches!(self.peek(), Tok::Eof) {
+ if p_depth == 0 && b_depth == 0 && matches!(self.peek(), Tok::Comma | Tok::RParen) {
+ break;
+ }
+ match self.peek() {
+ Tok::LParen => p_depth += 1,
+ Tok::RParen => p_depth = p_depth.saturating_sub(1),
+ Tok::LBracket => b_depth += 1,
+ Tok::RBracket => b_depth = b_depth.saturating_sub(1),
+ _ => {}
+ }
+ self.bump();
+ }
+ let d_end = self.pos;
+ if d_start == d_end {
+ return Err(format!(
+ "line {p_line}: missing default expression for parameter '{pname}' in macro '{macro_name}'"
+ ));
+ }
+ seen_default = true;
+ Some((d_start, d_end))
+ } else {
+ if seen_default {
+ return Err(format!(
+ "line {p_line}: non-default parameter '{pname}' follows default parameter in macro '{macro_name}'"
+ ));
+ }
+ None
+ };
+ params.push(MacroParam {
+ name: pname,
+ default_range,
+ });
+ if matches!(self.peek(), Tok::Comma) {
+ self.bump();
+ } else {
+ break;
+ }
+ }
+ self.expect(&Tok::RParen)?;
+ self.expect(&Tok::Eq)?;
+ let body_start = self.pos;
+ let mut p_depth = 0usize;
+ let mut b_depth = 0usize;
+ while !matches!(self.peek(), Tok::Newline | Tok::Eof) {
+ match self.peek() {
+ Tok::LParen => p_depth += 1,
+ Tok::RParen => {
+ if p_depth == 0 {
+ return Err(format!("line {}: unmatched ')' in macro '{macro_name}'", self.line()));
+ }
+ p_depth -= 1;
+ }
+ Tok::LBracket => b_depth += 1,
+ Tok::RBracket => {
+ if b_depth == 0 {
+ return Err(format!("line {}: unmatched ']' in macro '{macro_name}'", self.line()));
+ }
+ b_depth -= 1;
+ }
+ _ => {}
+ }
+ self.bump();
+ }
+ if p_depth != 0 || b_depth != 0 {
+ return Err(format!("line {def_line}: unclosed delimiter in macro '{macro_name}'"));
+ }
+ let body_end = self.pos;
+ if body_start == body_end {
+ return Err(format!("line {def_line}: macro '{macro_name}' requires a body expression after '='"));
+ }
+ self.macros.insert(
+ macro_name,
+ MacroDef {
+ params,
+ body_start,
+ body_end,
+ },
+ );
+ Ok(())
+ }
+
fn parse_pipe(&mut self) -> Result<Val, String> {
self.enter()?;
let res = (|| {
@@ -618,6 +820,9 @@ impl<'a> Parser<'a> {
}
}
Tok::LBracket => {
+ if let Some(for_pos) = self.find_list_comp_for() {
+ return self.parse_list_comp(self.pos, for_pos, line);
+ }
let mut items = Vec::new();
while !matches!(self.peek(), Tok::RBracket | Tok::Eof) {
items.push(self.parse_pipe()?);
@@ -682,6 +887,224 @@ impl<'a> Parser<'a> {
}
}
+ /// Look ahead from just after `[` for a top-level `for` keyword before any depth-0 `,` or `]`.
+ fn find_list_comp_for(&self) -> Option<usize> {
+ let mut k = self.pos;
+ let mut p_depth = 0usize;
+ let mut b_depth = 0usize;
+ while k < self.toks.len() {
+ match &self.toks[k].0 {
+ Tok::Eof => return None,
+ Tok::LParen => p_depth += 1,
+ Tok::RParen => p_depth = p_depth.saturating_sub(1),
+ Tok::LBracket => b_depth += 1,
+ Tok::RBracket => {
+ if b_depth == 0 && p_depth == 0 {
+ return None;
+ }
+ b_depth = b_depth.saturating_sub(1);
+ }
+ Tok::Comma if p_depth == 0 && b_depth == 0 => return None,
+ Tok::Ident(s) if p_depth == 0 && b_depth == 0 && s == "for" => return Some(k),
+ _ => {}
+ }
+ k += 1;
+ }
+ None
+ }
+
+ fn parse_list_comp(&mut self, body_start: usize, for_pos: usize, line: usize) -> Result<Val, String> {
+ let ctx = format!("line {line}: list comprehension");
+ if body_start == for_pos {
+ return Err(format!("{ctx}: missing expression before 'for'"));
+ }
+ self.pos = for_pos + 1; // past 'for'
+ let var_name = match self.bump() {
+ Tok::Ident(s) if !matches!(s.as_str(), "for" | "in" | "def") => s,
+ other => {
+ return Err(format!(
+ "{ctx}: expected loop variable name after 'for', got {}",
+ other.describe()
+ ))
+ }
+ };
+ match self.bump() {
+ Tok::Ident(ref s) if s == "in" => {}
+ other => return Err(format!("{ctx}: expected 'in' after '{var_name}', got {}", other.describe())),
+ }
+ match self.bump() {
+ Tok::Ident(ref s) if s == "range" => {}
+ other => return Err(format!("{ctx}: expected 'range(...)' after 'in', got {}", other.describe())),
+ }
+ let (r_pos, r_kw) = self.parse_call_args()?;
+ if !r_kw.is_empty() {
+ return Err(format!("{ctx}: range() accepts positional arguments only"));
+ }
+ let (start, stop, step) = match r_pos.len() {
+ 1 => (0i64, whole_int(r_pos[0].as_num(&ctx)?, &ctx)?, 1i64),
+ 2 => (
+ whole_int(r_pos[0].as_num(&ctx)?, &ctx)?,
+ whole_int(r_pos[1].as_num(&ctx)?, &ctx)?,
+ 1i64,
+ ),
+ 3 => (
+ whole_int(r_pos[0].as_num(&ctx)?, &ctx)?,
+ whole_int(r_pos[1].as_num(&ctx)?, &ctx)?,
+ whole_int(r_pos[2].as_num(&ctx)?, &ctx)?,
+ ),
+ n => return Err(format!("{ctx}: range() takes 1 to 3 arguments, got {n}")),
+ };
+ if step == 0 {
+ return Err(format!("{ctx}: range() step must not be 0"));
+ }
+ self.expect(&Tok::RBracket)?;
+ let after_bracket = self.pos;
+
+ let count_i64: i64 = if step > 0 {
+ if stop <= start {
+ 0
+ } else {
+ (stop - start + step - 1) / step
+ }
+ } else if stop >= start {
+ 0
+ } else {
+ (start - stop + (-step) - 1) / (-step)
+ };
+ if count_i64 as usize > MAX_COMP_ITERS {
+ return Err(format!(
+ "{ctx}: range count ({count_i64}) exceeds limit ({MAX_COMP_ITERS})"
+ ));
+ }
+ let count = count_i64 as usize;
+
+ let prev_var = self.vars.get(&var_name).cloned();
+ let eval_res: Result<Vec<Val>, String> = (|| {
+ let mut out = Vec::with_capacity(count);
+ for idx in 0..count {
+ self.comp_steps += 1;
+ if self.comp_steps > MAX_TOTAL_COMP_STEPS {
+ return Err(format!(
+ "{ctx}: total list comprehension iterations exceed limit ({MAX_TOTAL_COMP_STEPS})"
+ ));
+ }
+ let cur_val = start + (idx as i64) * step;
+ self.vars.insert(var_name.clone(), Val::Num(cur_val as f64));
+ self.pos = body_start;
+ let item = self.parse_pipe()?;
+ if self.pos != for_pos {
+ return Err(format!(
+ "line {}: unexpected {} before 'for' in list comprehension",
+ self.line(),
+ self.peek().describe()
+ ));
+ }
+ out.push(item);
+ }
+ Ok(out)
+ })();
+
+ match prev_var {
+ Some(v) => {
+ self.vars.insert(var_name, v);
+ }
+ None => {
+ self.vars.remove(&var_name);
+ }
+ }
+ self.pos = after_bracket;
+ Ok(Val::List(eval_res?))
+ }
+
+ fn eval_macro_call(
+ &mut self,
+ name: &str,
+ mdef: MacroDef,
+ pos: Vec<Val>,
+ kw: HashMap<String, Val>,
+ line: usize,
+ ) -> Result<Val, String> {
+ let ctx = format!("line {line}: {name}()");
+ if self.macro_depth >= MAX_MACRO_DEPTH {
+ return Err(format!("{ctx}: macro call depth exceeds limit ({MAX_MACRO_DEPTH})"));
+ }
+ self.macro_calls += 1;
+ if self.macro_calls > MAX_MACRO_CALLS {
+ return Err(format!("{ctx}: total macro calls exceed limit ({MAX_MACRO_CALLS})"));
+ }
+ if pos.len() > mdef.params.len() {
+ return Err(format!(
+ "{ctx}: takes at most {} positional argument(s), got {}",
+ mdef.params.len(),
+ pos.len()
+ ));
+ }
+ let param_names: Vec<&str> = mdef.params.iter().map(|p| p.name.as_str()).collect();
+ check_allowed_kwargs(&kw, &param_names, &ctx)?;
+ for (i, p) in mdef.params.iter().enumerate() {
+ if i < pos.len() && kw.contains_key(&p.name) {
+ return Err(format!(
+ "{ctx}: parameter '{}' passed both positionally and by keyword",
+ p.name
+ ));
+ }
+ }
+
+ let saved_pos = self.pos;
+ self.macro_depth += 1;
+ let mut shadowed: Vec<(String, Option<Val>)> = Vec::with_capacity(mdef.params.len());
+
+ let result: Result<Val, String> = (|| {
+ for (i, param) in mdef.params.iter().enumerate() {
+ let val = if i < pos.len() {
+ pos[i].clone()
+ } else if let Some(v) = kw.get(&param.name) {
+ v.clone()
+ } else if let Some((d_start, d_end)) = param.default_range {
+ self.pos = d_start;
+ let v = self.parse_pipe()?;
+ if self.pos != d_end {
+ return Err(format!(
+ "line {}: unexpected {} in default value for parameter '{}'",
+ self.line(),
+ self.peek().describe(),
+ param.name
+ ));
+ }
+ v
+ } else {
+ return Err(format!("{ctx}: missing required argument '{}'", param.name));
+ };
+ let old = self.vars.insert(param.name.clone(), val);
+ shadowed.push((param.name.clone(), old));
+ }
+ self.pos = mdef.body_start;
+ let val = self.parse_pipe()?;
+ if self.pos != mdef.body_end {
+ return Err(format!(
+ "line {}: unexpected {} in body of macro '{name}'",
+ self.line(),
+ self.peek().describe()
+ ));
+ }
+ Ok(val)
+ })();
+
+ for (pname, old) in shadowed.into_iter().rev() {
+ match old {
+ Some(v) => {
+ self.vars.insert(pname, v);
+ }
+ None => {
+ self.vars.remove(&pname);
+ }
+ }
+ }
+ self.pos = saved_pos;
+ self.macro_depth = self.macro_depth.saturating_sub(1);
+ result
+ }
+
fn parse_call_args(&mut self) -> Result<(Vec<Val>, HashMap<String, Val>), String> {
self.expect(&Tok::LParen)?;
let mut pos_args = Vec::new();
@@ -716,6 +1139,9 @@ impl<'a> Parser<'a> {
kw: HashMap<String, Val>,
line: usize,
) -> Result<Val, String> {
+ if let Some(mdef) = self.macros.get(name).cloned() {
+ return self.eval_macro_call(name, mdef, pos, kw, line);
+ }
let ctx = format!("line {line}: {name}()");
if let Some(allowed) = allowed_call_kwargs(name) {
check_allowed_kwargs(&kw, allowed, &ctx)?;
@@ -744,8 +1170,15 @@ impl<'a> Parser<'a> {
"sqrt" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.sqrt(), "sqrt")?)),
"sin" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.sin(), "sin")?)),
"cos" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.cos(), "cos")?)),
+ "tan" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.tan(), "tan")?)),
"asin" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.asin(), "asin")?)),
"acos" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.acos(), "acos")?)),
+ "atan" => return Ok(Val::Num(check_finite(get_num(0, "x", None)?.atan(), "atan")?)),
+ "atan2" => {
+ let y = get_num(0, "y", None)?;
+ let x = get_num(1, "x", None)?;
+ return Ok(Val::Num(check_finite(y.atan2(x), "atan2")?));
+ }
"abs" => return Ok(Val::Num(get_num(0, "x", None)?.abs())),
"deg" => return Ok(Val::Num(get_num(0, "x", None)?.to_degrees())),
"rad" => return Ok(Val::Num(get_num(0, "x", None)?.to_radians())),
@@ -779,7 +1212,7 @@ impl<'a> Parser<'a> {
return Ok(Val::Num(rep.min_distance));
}
"section" => {
- let m = pos.first().or_else(|| kw.get("part")).ok_or(format!("{ctx}: missing part"))?.as_mesh(&ctx)?;
+ let m = pos.first().or_else(|| kw.get("part")).or_else(|| kw.get("p")).ok_or(format!("{ctx}: missing part"))?.as_mesh(&ctx)?;
let z = get_num(1, "z", Some(0.0))?;
let rep = forma_core::spatial::section_z(&m, z);
self.scene.push_note(rep.summary("part"));
@@ -805,7 +1238,12 @@ impl<'a> Parser<'a> {
return Ok(Val::Bool(true));
}
"del" | "remove" => {
- let target = pos.first().or_else(|| kw.get("name")).ok_or(format!("{ctx}: missing part name"))?.as_str(&ctx)?;
+ let target = pos
+ .first()
+ .or_else(|| kw.get("name"))
+ .or_else(|| kw.get("tag"))
+ .ok_or(format!("{ctx}: missing part name"))?
+ .as_str(&ctx)?;
self.scene.remove_part(target).map_err(|e| format!("{ctx}: {e}"))?;
return Ok(Val::Bool(true));
}
@@ -1011,8 +1449,8 @@ impl<'a> Parser<'a> {
forma_core::primitives::make_loft(&sections, segs, op_id).map_err(|e| format!("{ctx}: {e}"))?
}
"thread" | "helix" => {
- let r_min = get_num_any(0, &["r_minor", "r_min", "r_in", "r"], None)?;
- let r_maj = get_num_any(1, &["r_major", "r_maj", "r_out"], Some(r_min * 1.15))?;
+ let r_min = get_num_any(0, &["r_minor", "r_min", "r_in", "r0", "r"], None)?;
+ let r_maj = get_num_any(1, &["r_major", "r_maj", "r_out", "r1"], Some(r_min * 1.15))?;
let pitch = get_num_any(2, &["pitch", "p"], Some(r_min * 0.3))?;
let turns = get_num_any(3, &["turns", "n"], Some(4.0))?;
let segs = whole_count(get_num_any(4, &["segs", "segments"], Some(28.0))?, &ctx)?;
@@ -1053,6 +1491,15 @@ impl<'a> Parser<'a> {
forma_core::primitives::make_text_3d(txt, h, d, op_id)
.map_err(|e| format!("{ctx}: {e}"))?
}
+ "gear" => {
+ let teeth = whole_count(get_num_any(0, &["teeth", "z", "n"], None)?, &ctx)?;
+ let module = get_num_any(1, &["module", "m"], Some(1.0))?;
+ let h = get_num_any(2, &["h", "height"], Some(1.0))?;
+ let pa = get_num_any(3, &["pressure_angle", "pa"], Some(20.0))?;
+ let bore = get_num_any(4, &["bore", "bore_r"], Some(0.0))?;
+ forma_core::primitives::make_gear(teeth, module, h, pa, bore, op_id)
+ .map_err(|e| format!("{ctx}: {e}"))?
+ }
"load" | "import" => {
let path_or_key = kw
.get("path")
@@ -1108,11 +1555,13 @@ impl<'a> Parser<'a> {
}
}
}
- if let Some(z0v) = kw.get("z0") {
- let z0 = z0v.as_num(&ctx)?;
- let bb = mesh.aabb();
- if bb.is_valid() {
- mesh.translate(Vec3::new(0.0, 0.0, z0 - bb.min.z));
+ if name != "extrude2d" {
+ if let Some(z0v) = kw.get("z0") {
+ let z0 = z0v.as_num(&ctx)?;
+ let bb = mesh.aabb();
+ if bb.is_valid() {
+ mesh.translate(Vec3::new(0.0, 0.0, z0 - bb.min.z));
+ }
}
}
Ok(Val::Mesh(mesh))
@@ -1447,13 +1896,21 @@ impl<'a> Parser<'a> {
pub fn eval_pipe(scene: &mut Scene, src: &str) -> Result<(), String> {
let toks = tokenize(src)?;
+ let mut vars = HashMap::new();
+ for (k, &v) in scene.scalars() {
+ vars.insert(k.clone(), Val::Num(v));
+ }
let mut p = Parser {
toks,
pos: 0,
depth: 0,
stmts: 0,
+ comp_steps: 0,
+ macro_depth: 0,
+ macro_calls: 0,
scene,
- vars: HashMap::new(),
+ vars,
+ macros: HashMap::new(),
};
p.run()
}
diff --git a/crates/forma-lang/tests/fuzz_expressiveness.rs b/crates/forma-lang/tests/fuzz_expressiveness.rs
new file mode 100644
index 0000000..93ef0e2
--- /dev/null
+++ b/crates/forma-lang/tests/fuzz_expressiveness.rs
@@ -0,0 +1,254 @@
+//! Randomized fuzz and stress tests for Forma-Pipe expressiveness & MCP ergonomics:
+//! - 200 randomized involute spur gears (4..=200 teeth, varied module/height/pressure_angle/bore)
+//! - 50 randomized meshing gear pairs (even/odd combinations) verified collision-free with clearance > 0
+//! - 500 randomized parser/macro/comprehension/scalar-tx/strict-rollback fuzz episodes (zero panics, zero NaNs)
+
+use forma_core::boolean::{check_self_intersections, OverlapCheck, SELF_INTERSECTION_BUDGET};
+use forma_core::spatial::clearance;
+use forma_core::{MeshInvariants, Scene};
+use forma_lang::{eval_script, Dialect};
+
+struct Rng(u64);
+
+impl Rng {
+ fn new(seed: u64) -> Self {
+ Self(seed)
+ }
+ fn next_u64(&mut self) -> u64 {
+ let mut x = self.0;
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ self.0 = x;
+ x
+ }
+ fn range_usize(&mut self, lo: usize, hi_inclusive: usize) -> usize {
+ lo + (self.next_u64() as usize) % (hi_inclusive - lo + 1)
+ }
+ fn range_f64(&mut self, lo: f64, hi: f64) -> f64 {
+ let u = (self.next_u64() >> 11) as f64 / ((1u64 << 53) as f64);
+ lo + u * (hi - lo)
+ }
+}
+
+#[test]
+fn fuzz_200_random_gears_watertight_and_non_self_intersecting() {
+ let mut rng = Rng::new(0x6E4A_F001_CAFE_BEEF);
+ for case in 0..200 {
+ let teeth = match case {
+ 0 => 4,
+ 1 => 5,
+ 2 => 6,
+ 3 => 7,
+ 4 => 199,
+ 5 => 200,
+ _ => rng.range_usize(4, 140),
+ };
+ let module = rng.range_f64(0.05, 15.0);
+ let height = rng.range_f64(0.1, 40.0);
+ let pa = rng.range_f64(5.0, 45.0);
+ let rp = module * (teeth as f64) * 0.5;
+ let rf = (rp - 1.25 * module).max(0.1 * rp);
+ let has_bore = case % 2 == 1 && rf > 0.05;
+ let bore = if has_bore {
+ rng.range_f64(0.05 * rf, 0.85 * rf)
+ } else {
+ 0.0
+ };
+
+ let script = format!(
+ "g = gear({teeth}, module={module:.6}, h={height:.6}, pressure_angle={pa:.4}, bore={bore:.6}, z0=0)"
+ );
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ let obs = eval_script(&mut s, Dialect::Pipe, &script)
+ .unwrap_or_else(|e| panic!("case {case} failed ({script}): {e}"));
+ assert!(obs.ok, "case {case} obs not ok: {}", obs.text);
+
+ let m = s.get_part("g").unwrap();
+ let inv = MeshInvariants::compute(m);
+ assert!(
+ inv.watertight && inv.consistent_winding && inv.non_manifold_edges == 0 && inv.boundary_edges == 0 && inv.nan_verts == 0,
+ "case {case} ({script}) bad invariants: {inv:?}"
+ );
+ let expected_genus = if has_bore { 1 } else { 0 };
+ assert_eq!(inv.genus, expected_genus, "case {case} ({script}) genus mismatch");
+ assert!(inv.signed_volume > 0.0, "case {case} non-positive volume");
+ assert_ne!(
+ check_self_intersections(m, SELF_INTERSECTION_BUDGET),
+ OverlapCheck::Overlap,
+ "case {case} ({script}) self-intersects"
+ );
+ }
+}
+
+#[test]
+fn fuzz_50_random_meshing_gear_pairs_positive_clearance() {
+ let mut rng = Rng::new(0x50A7_7EED_1234_5678);
+ for case in 0..50 {
+ let z1 = rng.range_usize(6, 48);
+ let z2 = rng.range_usize(6, 48);
+ let module = rng.range_f64(0.25, 8.0);
+ let height = rng.range_f64(0.5, 20.0);
+ let pa = rng.range_f64(14.5, 35.0);
+ let rot2 = if z2 % 2 == 0 { 180.0 / (z2 as f64) } else { 0.0 };
+ let cdist = module * ((z1 + z2) as f64) * 0.5;
+
+ let script = format!(
+ "g1 = gear({z1}, m={module:.5}, h={height:.4}, pa={pa:.3}, z0=0)\n\
+ g2 = gear({z2}, m={module:.5}, h={height:.4}, pa={pa:.3}, rot=(0,0,{rot2:.8}), at=({cdist:.6},0,0), z0=0)"
+ );
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ eval_script(&mut s, Dialect::Pipe, &script)
+ .unwrap_or_else(|e| panic!("pair {case} failed ({script}): {e}"));
+ let m1 = s.get_part("g1").unwrap();
+ let m2 = s.get_part("g2").unwrap();
+ let bb1 = m1.aabb();
+ let bb2 = m2.aabb();
+ // Teeth actually interleave in X
+ assert!(
+ bb1.max.x > bb2.min.x + 0.5 * module,
+ "pair {case} (z1={z1}, z2={z2}, m={module}) did not interleave: bb1.max.x={} bb2.min.x={}",
+ bb1.max.x,
+ bb2.min.x
+ );
+ let rep = clearance(m1, m2);
+ assert!(
+ !rep.intersecting && rep.min_distance > 0.0,
+ "pair {case} (z1={z1}, z2={z2}, m={module:.3}, pa={pa:.2}, rot2={rot2:.3}) collided! dist={} inter={}",
+ rep.min_distance,
+ rep.intersecting
+ );
+ }
+}
+
+#[test]
+fn fuzz_500_adversarial_parser_macros_comprehensions_and_scalar_tx() {
+ let mut rng = Rng::new(0xF022_DEAD_C0DE_9999);
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+
+ let tokens = [
+ "def", "for", "in", "range", "(", ")", "[", "]", ",", "=", "|", "+", "-", "*", "/",
+ "box", "cyl", "gear", "extrude2d", "add", "cut", "move", "rot", "tan", "atan", "atan2",
+ "sin", "cos", "pi", "del", "_tmp", "a", "b", "i", "x", "0", "1", "-2", "3.5", "\"a\"",
+ ];
+
+ // 1. 250 completely random token-soup programs: must NEVER panic!
+ for ep in 0..250 {
+ let len = rng.range_usize(1, 22);
+ let mut code = String::new();
+ for _ in 0..len {
+ let tok = tokens[rng.range_usize(0, tokens.len() - 1)];
+ code.push_str(tok);
+ code.push(if rng.range_usize(0, 5) == 0 { '\n' } else { ' ' });
+ }
+ let _ = eval_script(&mut s, Dialect::Pipe, &code);
+ // Every accepted part in scene must remain strictly watertight & NaN-free
+ for name in s.part_names() {
+ assert!(!name.starts_with('_'), "ep {ep}: leaked underscore part '{name}'");
+ let inv = MeshInvariants::compute(s.get_part(&name).unwrap());
+ assert!(
+ inv.watertight && inv.non_manifold_edges == 0 && inv.nan_verts == 0,
+ "ep {ep}: scene corrupted part '{name}': {inv:?}"
+ );
+ }
+ }
+
+ // 2. 250 structured stateful multi-eval episodes exercising persistent scalars, macros,
+ // comprehensions, `_tmp` locals, `del()`, checkpoints, rollbacks, and undo!
+ let mut st = Scene::new();
+ st.strict_manifold = true;
+ eval_script(&mut st, Dialect::Pipe, "base_s = 2.0\nanchor = box(2, 2, 1, z0=0)").unwrap();
+ st.checkpoint("init");
+
+ let mut structured_ok = 0usize;
+ let mut structured_attempts = 0usize;
+ for ep in 0..250 {
+ let kind = ep % 7;
+ let script = match kind {
+ 0 => {
+ let n = rng.range_usize(2, 8);
+ let r = rng.range_f64(1.2, 4.0);
+ format!(
+ "rad = {r:.3}\n\
+ _holes = [({r:.3} * cos(2*pi*i/{n}), {r:.3} * sin(2*pi*i/{n}), 0) for i in range({n})]\n\
+ plate = cyl({:.3}, 1.0, segs=32, z0=0) | cut(cyl(0.25, 2.0, z0=-0.5), at=_holes)",
+ r + 1.0
+ )
+ }
+ 1 => {
+ let w = rng.range_f64(0.8, 3.0);
+ format!(
+ "def boss(r, h=1.2) = cyl(r, h, segs=20, z0=0) | bevel(top_rim, 0.08)\n\
+ _b = boss({:.3})\n\
+ part_m = box({w:.3}, {w:.3}, 0.6, z0=0) | add(_b)",
+ (w * 0.25).max(0.25)
+ )
+ }
+ 2 => {
+ // Intentional strict failure mid-script: scalar mutation MUST roll back!
+ let prev = st.get_scalar("base_s").unwrap_or(2.0);
+ let bad = "base_s = 9999.0\nbroken = box(0, 1, 1)";
+ assert!(eval_script(&mut st, Dialect::Pipe, bad).is_err());
+ assert_eq!(st.get_scalar("base_s"), Some(prev));
+ continue;
+ }
+ 3 => {
+ // Trig + persistent scalar reference
+ let ang = rng.range_f64(-1.2, 1.2);
+ format!(
+ "t_val = abs(tan({ang:.4})) + abs(atan({ang:.4})) + abs(atan2(1, base_s))\n\
+ trig_box = box(1 + t_val * 0.2, 1, 1, z0=0)"
+ )
+ }
+ 4 => {
+ // Meshing pair using persistent scalar
+ let z1 = rng.range_usize(8, 20);
+ let z2 = rng.range_usize(8, 24);
+ let rot2 = if z2 % 2 == 0 { 180.0 / (z2 as f64) } else { 0.0 };
+ format!(
+ "g_a = gear({z1}, m=0.5, h=1.0, z0=0)\n\
+ g_b = gear({z2}, m=0.5, h=1.0, rot=(0,0,{rot2:.6}), at=(0.5*({z1}+{z2})/2, 0, 0), z0=0)"
+ )
+ }
+ 5 => {
+ // Rollback to checkpoint and confirm base_s == 2.0 and anchor exists
+ st.rollback("init").unwrap();
+ assert_eq!(st.get_scalar("base_s"), Some(2.0));
+ assert!(st.get_part("anchor").is_ok());
+ continue;
+ }
+ _ => {
+ // Multi-part scene preview render + SVG blueprint
+ let png = st.render_preview_scene_bytes(128).unwrap();
+ assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
+ let svg = st.export_blueprint_svg_scene_string().unwrap();
+ assert!(svg.contains("<svg"));
+ continue;
+ }
+ };
+ structured_attempts += 1;
+ let res = eval_script(&mut st, Dialect::Pipe, &script);
+ if kind != 0 {
+ // Non-curved-boolean structured scripts (macros, trig, gears) must succeed 100%
+ assert!(res.is_ok(), "structured ep {ep} (kind={kind}) failed ({script}): {res:?}");
+ }
+ if res.is_ok() {
+ structured_ok += 1;
+ }
+ for name in st.part_names() {
+ assert!(!name.starts_with('_'), "ep {ep}: leaked underscore part '{name}'");
+ let inv = MeshInvariants::compute(st.get_part(&name).unwrap());
+ assert!(
+ inv.watertight && inv.non_manifold_edges == 0 && inv.nan_verts == 0,
+ "structured ep {ep}: bad part '{name}': {inv:?}"
+ );
+ }
+ }
+ assert!(
+ structured_ok * 100 >= structured_attempts * 95,
+ "expected >= 95% structured strict pass rate, got {structured_ok}/{structured_attempts}"
+ );
+}
diff --git a/crates/forma-lang/tests/lang_expressiveness.rs b/crates/forma-lang/tests/lang_expressiveness.rs
new file mode 100644
index 0000000..424169f
--- /dev/null
+++ b/crates/forma-lang/tests/lang_expressiveness.rs
@@ -0,0 +1,367 @@
+use forma_core::boolean::has_self_intersections;
+use forma_core::spatial::clearance;
+use forma_core::{MeshInvariants, Scene};
+use forma_lang::{eval_script, Dialect};
+
+fn eval_strict(script: &str) -> (Scene, forma_core::Observation) {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ let obs = eval_script(&mut s, Dialect::Pipe, script)
+ .unwrap_or_else(|e| panic!("script failed:\n{script}\nerr: {e}"));
+ assert!(obs.ok, "expected ok observation, got: {}", obs.text);
+ (s, obs)
+}
+
+#[test]
+fn test_trig_tan_atan_atan2() {
+ // Use box dimensions computed from tan, atan, atan2 to verify exact numeric values.
+ let (s, _) = eval_strict(
+ r#"
+a = tan(pi / 4)
+b = atan(1) / (pi / 4)
+c = atan2(1, -1) / (3 * pi / 4)
+d = atan2(y=1, x=0) / (pi / 2)
+p = box(a, b, c + d)
+"#,
+ );
+ let m = s.get_part("p").unwrap();
+ let sz = m.aabb().size();
+ assert!((sz.x - 1.0).abs() < 1e-6, "tan(pi/4)={}", sz.x);
+ assert!((sz.y - 1.0).abs() < 1e-6, "atan(1)/(pi/4)={}", sz.y);
+ assert!((sz.z - 2.0).abs() < 1e-6, "atan2 sum={}", sz.z);
+
+ // Reject extra positional args and unknown kwargs
+ let mut s2 = Scene::new();
+ assert!(eval_script(&mut s2, Dialect::Pipe, "p = box(tan(1, 2), 1, 1)").is_err());
+ assert!(eval_script(&mut s2, Dialect::Pipe, "p = box(atan2(1, 2, 3), 1, 1)").is_err());
+ assert!(eval_script(&mut s2, Dialect::Pipe, "p = box(atan2(z=1, x=1), 1, 1)").is_err());
+}
+
+#[test]
+fn test_underscore_local_mesh_vars_not_in_scene() {
+ let (s, _) = eval_strict(
+ r#"
+_blank = box(10, 10, 2)
+_bore = cyl(2, 8)
+_boss = cyl(3.5, 4, z0=-1)
+part = _blank | add(_boss) | cut(_bore)
+other = cyl(1, 2, at=(20, 0, 0))
+"#,
+ );
+ let names = s.part_names();
+ assert_eq!(names, vec!["other".to_string(), "part".to_string()]);
+ assert!(s.get_part("_blank").is_err());
+ assert!(s.get_part("_bore").is_err());
+ assert!(s.get_part("_boss").is_err());
+
+ let inv = MeshInvariants::compute(s.get_part("part").unwrap());
+ assert!(inv.watertight && inv.non_manifold_edges == 0 && inv.boundary_edges == 0);
+ assert_eq!(inv.genus, 1);
+}
+
+#[test]
+fn test_list_comprehensions_in_at_and_extrude2d() {
+ // Circular bolt-hole pattern via list comprehension in `at=[...]`
+ let (s, _) = eval_strict(
+ r#"
+n = 6
+r = 12
+flange = cyl(18, 3)
+ | cut(cyl(5, 5))
+ | cut(cyl(1.8, 5), at=[(r * cos(2 * pi * i / n), r * sin(2 * pi * i / n), 0) for i in range(n)])
+"#,
+ );
+ let m = s.get_part("flange").unwrap();
+ let inv = MeshInvariants::compute(m);
+ assert!(inv.watertight && inv.non_manifold_edges == 0 && inv.boundary_edges == 0);
+ assert_eq!(inv.genus, 7, "1 center bore + 6 bolt holes => genus 7");
+
+ // 2D polygon extrusion from list comprehension + 2-arg & 3-arg range + shadowing preservation
+ let (s2, _) = eval_strict(
+ r#"
+i = 7
+pts = [(10 * cos(2 * pi * i / 12), 10 * sin(2 * pi * i / 12)) for i in range(12)]
+poly = extrude2d(pts, 0, 4)
+# Verify outer `i` was NOT overwritten by loop variable `i`
+marker = box(i, 1, 1, at=(25, 0, 0))
+# 2-arg and 3-arg range (including negative step)
+pins = cyl(0.5, 2, at=[(k * 3, 0, 0) for k in range(2, 10, 2)])
+rev_pins = cyl(0.5, 2, at=[(k * 3, 5, 0) for k in range(8, 0, -2)])
+# Regular list literals still work
+reg = extrude2d([(0, 0), (2, 0), (2, 2), (0, 2)], 0, 1)
+"#,
+ );
+ let poly_inv = MeshInvariants::compute(s2.get_part("poly").unwrap());
+ assert!(poly_inv.watertight && poly_inv.non_manifold_edges == 0);
+ assert!((s2.get_part("marker").unwrap().aabb().size().x - 7.0).abs() < 1e-6);
+ assert!(MeshInvariants::compute(s2.get_part("pins").unwrap()).watertight);
+ assert!(MeshInvariants::compute(s2.get_part("rev_pins").unwrap()).watertight);
+ assert!(MeshInvariants::compute(s2.get_part("reg").unwrap()).watertight);
+
+ // Safety limits: >512 iterations, step == 0, non-integer bounds
+ let mut s_err = Scene::new();
+ let err_cap = eval_script(&mut s_err, Dialect::Pipe, "xs = [i for i in range(513)]").unwrap_err();
+ assert!(err_cap.contains("exceeds limit"), "err={err_cap}");
+
+ let err_zero = eval_script(&mut s_err, Dialect::Pipe, "xs = [i for i in range(0, 10, 0)]").unwrap_err();
+ assert!(err_zero.contains("step must not be 0"), "err={err_zero}");
+
+ let err_frac = eval_script(&mut s_err, Dialect::Pipe, "xs = [i for i in range(3.5)]").unwrap_err();
+ assert!(err_frac.contains("whole integers"), "err={err_frac}");
+}
+
+#[test]
+fn test_parametric_def_macros() {
+ let (s, _) = eval_strict(
+ r#"
+outer_x = 42
+
+def ring_pts(n, r, z=0) = [(r * cos(2 * pi * i / n), r * sin(2 * pi * i / n), z) for i in range(n)]
+
+def bolt_flange(outer_r, inner_r=outer_r * 0.3, h=3, n_bolts=6) = cyl(outer_r, h, z0=0)
+ | cut(cyl(inner_r, h + 2, z0=-1))
+ | cut(cyl(outer_r * 0.08, h + 2, z0=-1), at=ring_pts(n_bolts, outer_r * 0.7))
+
+# Positional, keyword, and default arguments
+f1 = bolt_flange(15)
+f2 = bolt_flange(outer_r=12, n_bolts=4, h=5) | move(40, 0, 0)
+check_outer = box(outer_x, 1, 1, at=(0, 30, 0))
+"#,
+ );
+ // Macro parameters must not pollute scene parts
+ let names = s.part_names();
+ assert_eq!(names, vec!["check_outer", "f1", "f2"]);
+
+ let inv1 = MeshInvariants::compute(s.get_part("f1").unwrap());
+ assert!(inv1.watertight && inv1.non_manifold_edges == 0 && inv1.boundary_edges == 0);
+ assert_eq!(inv1.genus, 7, "center bore + 6 bolts");
+
+ let inv2 = MeshInvariants::compute(s.get_part("f2").unwrap());
+ assert!(inv2.watertight && inv2.non_manifold_edges == 0 && inv2.boundary_edges == 0);
+ assert_eq!(inv2.genus, 5, "center bore + 4 bolts");
+ assert!((s.get_part("f2").unwrap().aabb().size().z - 5.0).abs() < 1e-6);
+ assert!((s.get_part("check_outer").unwrap().aabb().size().x - 42.0).abs() < 1e-6);
+
+ // Shadowing restoration: outer param `x` preserved after macro call
+ let (s_sh, _) = eval_strict(
+ r#"
+x = 10
+def double_box(x) = box(x * 2, 1, 1)
+a = double_box(3)
+b = box(x, 1, 1, at=(0, 10, 0))
+"#,
+ );
+ assert!((s_sh.get_part("a").unwrap().aabb().size().x - 6.0).abs() < 1e-6);
+ assert!((s_sh.get_part("b").unwrap().aabb().size().x - 10.0).abs() < 1e-6);
+
+ // Recursion limit rejection (self-recursion and mutual recursion)
+ let mut s_err = Scene::new();
+ let err_rec = eval_script(&mut s_err, Dialect::Pipe, "def inf(n) = inf(n + 1)\nx = inf(0)").unwrap_err();
+ assert!(err_rec.contains("call depth exceeds limit"), "err={err_rec}");
+
+ let err_mut = eval_script(
+ &mut s_err,
+ Dialect::Pipe,
+ "def a(n) = b(n)\ndef b(n) = a(n)\nx = a(1)",
+ )
+ .unwrap_err();
+ assert!(err_mut.contains("call depth exceeds limit"), "err={err_mut}");
+
+ // Disallow redefining built-in names
+ for builtin in ["box", "cut", "gear", "sin", "atan2", "bevel"] {
+ let err = eval_script(&mut s_err, Dialect::Pipe, &format!("def {builtin}(x) = x")).unwrap_err();
+ assert!(err.contains("cannot redefine built-in"), "builtin={builtin}, err={err}");
+ }
+
+ // Reject unknown kwargs, non-default after default, duplicate param
+ let err_kw = eval_script(&mut s_err, Dialect::Pipe, "def f(a=1) = box(a,1,1)\np = f(b=2)").unwrap_err();
+ assert!(err_kw.contains("unknown keyword argument 'b'"), "err={err_kw}");
+
+ let err_ord = eval_script(&mut s_err, Dialect::Pipe, "def f(a=1, b) = box(a,b,1)").unwrap_err();
+ assert!(err_ord.contains("non-default parameter"), "err={err_ord}");
+}
+
+#[test]
+fn test_gear_standalone_bore_and_features() {
+ // 1. Standalone gear without bore
+ let (s1, _) = eval_strict("g = gear(20, module=2.0, h=8.0, z0=0)");
+ let g1 = s1.get_part("g").unwrap();
+ let inv1 = MeshInvariants::compute(g1);
+ assert!(inv1.watertight && inv1.non_manifold_edges == 0 && inv1.boundary_edges == 0);
+ assert_eq!(inv1.genus, 0);
+ assert!(!has_self_intersections(g1));
+ let bb1 = g1.aabb();
+ assert!((bb1.min.z - 0.0).abs() < 1e-6);
+ assert!((bb1.max.z - 8.0).abs() < 1e-6);
+ // Exact outer diameter = m * (z + 2) = 2 * 22 = 44.0
+ assert!((bb1.size().x - 44.0).abs() < 1e-3, "outer diam X={}", bb1.size().x);
+ assert!(g1.faces.iter().any(|f| f.tags.iter().any(|t| t == "top")));
+ assert!(g1.faces.iter().any(|f| f.tags.iter().any(|t| t == "bottom")));
+ assert!(g1.faces.iter().any(|f| f.tags.iter().any(|t| t == "side")));
+
+ // 2. Gear with bore directly
+ let (s2, _) = eval_strict("g = gear(teeth=24, m=2.0, height=10.0, pa=20, bore=6.0)");
+ let g2 = s2.get_part("g").unwrap();
+ let inv2 = MeshInvariants::compute(g2);
+ assert!(inv2.watertight && inv2.non_manifold_edges == 0 && inv2.boundary_edges == 0);
+ assert_eq!(inv2.genus, 1);
+ assert!(!has_self_intersections(g2));
+
+ // 3. Gear with hub + keyway + 6 lightening holes via list comprehension
+ let (s3, _) = eval_strict(
+ r#"
+_hub = cyl(10, 16)
+_keyway = box(4, 3, 20, at=(6.0, 0, 0))
+_bore = cyl(5.5, 20)
+wheel = gear(32, m=2.0, h=10.0)
+ | add(_hub)
+ | cut(_bore)
+ | cut(_keyway)
+ | cut(cyl(3.2, 14), at=[(19 * cos(2 * pi * i / 6), 19 * sin(2 * pi * i / 6), 0) for i in range(6)])
+"#,
+ );
+ assert_eq!(s3.part_names(), vec!["wheel"]);
+ let w = s3.get_part("wheel").unwrap();
+ let inv3 = MeshInvariants::compute(w);
+ assert!(inv3.watertight && inv3.non_manifold_edges == 0 && inv3.boundary_edges == 0);
+ assert_eq!(inv3.genus, 7, "1 keyed central bore + 6 lightening holes => genus 7");
+}
+
+#[test]
+fn test_two_meshing_gears_positive_clearance_and_exact_diameters() {
+ let (s, obs) = eval_strict(
+ r#"
+units("mm")
+m = 2.0
+z1 = 16
+z2 = 32
+center_dist = m * (z1 + z2) / 2
+
+g1 = gear(z1, m=m, h=10, bore=5, z0=0)
+g2 = gear(z2, m=m, h=10, bore=8, rot=(0, 0, 180 / z2), at=(center_dist, 0, 0), z0=0)
+gap = clearance(g1, g2)
+"#,
+ );
+ let m1 = s.get_part("g1").unwrap();
+ let m2 = s.get_part("g2").unwrap();
+ let inv1 = MeshInvariants::compute(m1);
+ let inv2 = MeshInvariants::compute(m2);
+ assert!(inv1.watertight && inv1.non_manifold_edges == 0 && inv1.boundary_edges == 0);
+ assert!(inv2.watertight && inv2.non_manifold_edges == 0 && inv2.boundary_edges == 0);
+ assert_eq!(inv1.genus, 1);
+ assert_eq!(inv2.genus, 1);
+ assert!(!has_self_intersections(m1));
+ assert!(!has_self_intersections(m2));
+
+ // Exact outer diameters: da1 = m*(z1+2) = 36.0, da2 = m*(z2+2) = 68.0
+ // Pitch diameters: dp1 = m*z1 = 32.0, dp2 = m*z2 = 64.0, center distance = 48.0
+ let bb1 = m1.aabb();
+ let bb2 = m2.aabb();
+ assert!((bb1.size().x - 36.0).abs() < 1e-3, "g1 outer diam={}", bb1.size().x);
+ assert!((bb1.min.x + 18.0).abs() < 1e-3 && (bb1.max.x - 18.0).abs() < 1e-3);
+ // g2 is rotated by 180/32 = 5.625 deg; its outer diameter in XY is still ~68.0 (within cos(5.625deg))
+ let expected_d2 = 68.0;
+ assert!(
+ (bb2.size().x - expected_d2 * (5.625_f64.to_radians()).cos()).abs() < 0.25,
+ "g2 bbox X size={}",
+ bb2.size().x
+ );
+ let c1 = (bb1.min.x + bb1.max.x) * 0.5;
+ let c2 = (bb2.min.x + bb2.max.x) * 0.5;
+ assert!(((c2 - c1) - 48.0).abs() < 1e-3, "center distance={}", c2 - c1);
+
+ // Meshing teeth overlap in X bounding box (bb1.max.x = 18 > bb2.min.x ~= 14.16)
+ // YET exact 3D mesh clearance is strictly positive (no collision!).
+ assert!(bb1.max.x > bb2.min.x + 2.0, "gears should actually interleave/mesh in X");
+ let rep = clearance(m1, m2);
+ assert!(
+ rep.min_distance > 0.01 && !rep.intersecting,
+ "expected positive meshing clearance without collision, got dist={} intersecting={} obs={}",
+ rep.min_distance,
+ rep.intersecting,
+ obs.text
+ );
+}
+
+#[test]
+fn test_gear_edge_cases_and_validation() {
+ // Extreme small tooth count + high pressure angle (pointed tooth truncation) stays watertight
+ let (s_ext, _) = eval_strict("g = gear(4, m=2.0, h=5.0, pa=45)");
+ let g_ext = s_ext.get_part("g").unwrap();
+ let inv_ext = MeshInvariants::compute(g_ext);
+ assert!(inv_ext.watertight && inv_ext.non_manifold_edges == 0 && inv_ext.boundary_edges == 0);
+ assert!(!has_self_intersections(g_ext));
+
+ // Max tooth count (200) with bore stays watertight and clean
+ let (s_big, _) = eval_strict("g = gear(200, m=1.0, h=4.0, bore=40.0)");
+ let g_big = s_big.get_part("g").unwrap();
+ let inv_big = MeshInvariants::compute(g_big);
+ assert!(inv_big.watertight && inv_big.non_manifold_edges == 0 && inv_big.boundary_edges == 0);
+ assert_eq!(inv_big.genus, 1);
+
+ // Invalid parameters rejected cleanly
+ let mut s = Scene::new();
+ for bad in [
+ "g = gear(3, m=1, h=1)",
+ "g = gear(201, m=1, h=1)",
+ "g = gear(16, m=0, h=1)",
+ "g = gear(16, m=1, h=0)",
+ "g = gear(16, m=1, h=1, pa=4)",
+ "g = gear(16, m=1, h=1, pa=50)",
+ "g = gear(16, m=2, h=5, bore=13.5)", // root radius is 13.5 -> must fail
+ "g = gear(16, m=2, h=5, bore=-1)",
+ ] {
+ assert!(eval_script(&mut s, Dialect::Pipe, bad).is_err(), "expected error for: {bad}");
+ }
+}
+
+#[test]
+fn test_scalar_persistence_across_eval_and_rollback() {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+
+ // Eval 1: define shared gear parameters (non-`_` scalars persist; `_tmp` stays local)
+ let obs1 = eval_script(
+ &mut s,
+ Dialect::Pipe,
+ r#"
+units("mm")
+m = 2.0
+z1 = 16
+z2 = 32
+h = 10.0
+_local_only = 999.0
+"#,
+ )
+ .unwrap();
+ assert!(obs1.ok);
+ assert_eq!(s.get_scalar("m"), Some(2.0));
+ assert_eq!(s.get_scalar("_local_only"), None);
+
+ // Eval 2: reference scalars from Eval 1 without re-declaring them
+ let obs2 = eval_script(
+ &mut s,
+ Dialect::Pipe,
+ r#"
+center_dist = m * (z1 + z2) / 2
+pinion = gear(z1, m=m, h=h, bore=5, z0=0) | mat("blue", color=(0.3, 0.55, 0.85))
+wheel = gear(z2, m=m, h=h, bore=8, rot=(0, 0, 180 / z2), at=(center_dist, 0, 0), z0=0) | mat("gold", color=(0.82, 0.68, 0.30))
+"#,
+ )
+ .unwrap();
+ assert!(obs2.ok);
+ assert_eq!(s.part_names(), vec!["pinion", "wheel"]);
+ assert_eq!(s.get_scalar("center_dist"), Some(48.0));
+
+ // `_local_only` did NOT leak across evals
+ assert!(eval_script(&mut s, Dialect::Pipe, "x = _local_only").is_err());
+
+ // Failed eval rolls back scalar mutations cleanly
+ assert!(eval_script(&mut s, Dialect::Pipe, "m = 99.0\nbad = box(0, 1, 1)").is_err());
+ assert_eq!(s.get_scalar("m"), Some(2.0));
+
+ // Multi-part scene preview PNG renders both parts cleanly
+ let png = s.render_preview_scene_bytes(256).unwrap();
+ assert!(png.starts_with(b"\x89PNG\r\n\x1a\n"));
+ assert!(png.len() > 2000);
+}
diff --git a/crates/forma-mcp/src/main.rs b/crates/forma-mcp/src/main.rs
index f04269a..3c6c109 100644
--- a/crates/forma-mcp/src/main.rs
+++ b/crates/forma-mcp/src/main.rs
@@ -1,11 +1,10 @@
-//! forma-mcp: Thin, minimal-schema, model-agnostic stdio JSON-RPC MCP server.
+//! forma-mcp: Minimal-schema stdio JSON-RPC 2.0 MCP server (<800 o200k tokens across 4 tools).
//!
-//! Designed specifically for minimal context-window schema tax (<650 tokens total across
-//! all tools!) with 4 composable stateful tools:
-//! 1. `eval` — Execute Forma modeling script (transactional; returns compact ~120-tok state + diff)
-//! 2. `inspect` — Return compact spatial/topological summary + face tags without mutating state
-//! 3. `tx` — Instant copy-on-write snapshot/rollback/undo/reset (`checkpoint`, `rollback`, `undo`, `reset`)
-//! 4. `export` — Export scene or single part to `.glb`, `.obj`, `.stl` (or `.blend` via bridge)
+//! Tools:
+//! 1. `eval` — Execute transactional Forma-Pipe code; returns compact state & spatial diff
+//! 2. `inspect` — Return scene invariants/tags or a domain topic spec without mutating state
+//! 3. `tx` — Copy-on-write snapshot control (`checkpoint`, `rollback`, `undo`, `reset`)
+//! 4. `export` — Export `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, `.blend` (via Blender bridge), or 4-view `.png`
use forma_core::Scene;
use forma_lang::{eval_script, spec_topic, Dialect, SPEC_PIPE};
@@ -29,7 +28,7 @@ fn tools_schema() -> Value {
},
{
"name": "inspect",
- "description": "Scene invariants/tags, or domain spec if topic set.",
+ "description": "Scene invariants/tags, or topic spec if topic set.",
"inputSchema": {
"type": "object",
"properties": {
@@ -51,7 +50,7 @@ fn tools_schema() -> Value {
},
{
"name": "export",
- "description": "Export .glb/.step/.3mf/.stl/.obj/.svg or 4-view .png.",
+ "description": "Export .glb/.step/.3mf/.stl/.obj/.svg/.blend or 4-view .png.",
"inputSchema": {
"type": "object",
"properties": {
@@ -108,7 +107,9 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> (bool, Strin
*scene = Scene::new();
Ok("OK scene reset".into())
}
- _ => Err(format!("unknown tx action '{action}'")),
+ _ => Err(format!(
+ "unknown tx action '{action}' (valid: checkpoint, rollback, undo, reset)"
+ )),
};
match res {
Ok(msg) => (false, msg),
@@ -121,20 +122,53 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> (bool, Strin
};
let part = args.get("part").and_then(|v| v.as_str());
let path = PathBuf::from(p);
- let is_png = path
+ let ext = path
.extension()
.and_then(|s| s.to_str())
- .map_or(false, |s| s.eq_ignore_ascii_case("png"));
+ .map(|s| s.to_lowercase())
+ .unwrap_or_default();
let is_scene = args.get("scene").and_then(|v| v.as_bool()).unwrap_or(false);
if is_scene {
- match scene.export_scene_glb_bytes(true) {
- Ok(bytes) => match std::fs::write(&path, &bytes) {
- Ok(()) => (false, format!("OK exported multi-node scene '{p}' ({} bytes, parts={})", bytes.len(), scene.part_names().len())),
+ if ext == "png" {
+ let sz = args.get("size").and_then(|v| v.as_u64()).unwrap_or(512) as usize;
+ let t0 = std::time::Instant::now();
+ match scene.render_preview_scene(&path, sz) {
+ Ok(()) => (
+ false,
+ format!(
+ "OK rendered {sz}x{sz} scene quad preview '{p}' (parts={}) [{:.2}ms]",
+ scene.part_names().len(),
+ t0.elapsed().as_secs_f64() * 1000.0
+ ),
+ ),
Err(e) => (true, format!("ERR: {e}")),
- },
- Err(e) => (true, format!("ERR: {e}")),
+ }
+ } else if ext == "svg" {
+ let t0 = std::time::Instant::now();
+ match scene.export_blueprint_svg_scene(&path) {
+ Ok(()) => (
+ false,
+ format!(
+ "OK drew scene engineering blueprint '{p}' (parts={}) [{:.2}ms]",
+ scene.part_names().len(),
+ t0.elapsed().as_secs_f64() * 1000.0
+ ),
+ ),
+ Err(e) => (true, format!("ERR: {e}")),
+ }
+ } else {
+ match scene.export_scene_path(&path) {
+ Ok(byte_len) => (
+ false,
+ format!(
+ "OK exported multi-node scene '{p}' ({byte_len} bytes, parts={})",
+ scene.part_names().len()
+ ),
+ ),
+ Err(e) => (true, format!("ERR: {e}")),
+ }
}
- } else if is_png {
+ } else if ext == "png" {
let sz = args.get("size").and_then(|v| v.as_u64()).unwrap_or(512) as usize;
let t0 = std::time::Instant::now();
match scene.render_preview(&path, part, sz) {
@@ -144,13 +178,26 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> (bool, Strin
),
Err(e) => (true, format!("ERR: {e}")),
}
+ } else if ext == "svg" {
+ let t0 = std::time::Instant::now();
+ match scene.export_blueprint_svg(&path, part) {
+ Ok(()) => (
+ false,
+ format!("OK drew engineering blueprint '{p}' [{:.2}ms]", t0.elapsed().as_secs_f64() * 1000.0),
+ ),
+ Err(e) => (true, format!("ERR: {e}")),
+ }
} else {
match scene.export(&path, part) {
Ok(inv) => (
false,
format!(
"OK exported '{p}' V={} F={} WT={} NM={} vol={:.3}",
- inv.verts, inv.faces, inv.watertight, inv.non_manifold_edges, inv.volume
+ inv.verts,
+ inv.faces,
+ if inv.watertight { "ok" } else { "BAD" },
+ inv.non_manifold_edges,
+ inv.volume
),
),
Err(e) => (true, format!("ERR: {e}")),
@@ -203,7 +250,7 @@ fn main() {
"result": {
"protocolVersion": "2024-11-05",
"capabilities": { "tools": {} },
- "serverInfo": { "name": "forma-mcp", "version": "0.4.2" }
+ "serverInfo": { "name": "forma-mcp", "version": env!("CARGO_PKG_VERSION") }
}
}),
"ping" => json!({ "jsonrpc": "2.0", "id": id, "result": {} }),
diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rs
index ea1fd0a..bf22aee 100644
--- a/crates/forma-wasm/src/lib.rs
+++ b/crates/forma-wasm/src/lib.rs
@@ -123,11 +123,34 @@ pub extern "C" fn forma_session_new() -> u32 {
let mut s = st.borrow_mut();
let id = s.next_id;
s.next_id = s.next_id.wrapping_add(1).max(1);
- s.sessions.insert(id, Scene::new());
+ let mut scene = Scene::new();
+ scene.allow_fs_import = false;
+ s.sessions.insert(id, scene);
id
})
}
+/// Set the model unit for a session (`m`, `cm`, `mm`, `um`, `in`, `ft`).
+#[no_mangle]
+pub extern "C" fn forma_session_set_unit(id: u32, unit_ptr: *const u8, unit_len: usize) -> u32 {
+ let unit_str = match unsafe { read_utf8(unit_ptr, unit_len) } {
+ Ok(s) => s,
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ let unit = match forma_core::Unit::parse(&unit_str) {
+ Ok(u) => u,
+ 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}"));
+ };
+ scene.unit = unit;
+ s.set_ok_str(unit.symbol())
+ })
+}
+
#[no_mangle]
pub extern "C" fn forma_session_free(id: u32) {
STATE.with(|st| {
@@ -220,9 +243,12 @@ pub extern "C" fn forma_session_tx(
.map_err(|e| e.to_string()),
"reset" => {
*scene = Scene::new();
+ scene.allow_fs_import = false;
Ok("OK scene reset".into())
}
- other => Err(format!("unknown tx action '{other}'")),
+ other => Err(format!(
+ "unknown tx action '{other}' (valid: checkpoint, rollback, undo, reset)"
+ )),
};
match res {
Ok(msg) => s.set_ok_str(msg),
@@ -267,7 +293,7 @@ pub extern "C" fn forma_session_export(
}
"svg" => {
let title = part_opt.as_deref().unwrap_or("FORMA PART");
- forma_core::render::render_blueprint_svg_string(&mesh, title)
+ forma_core::render::render_blueprint_svg_string_with_unit(&mesh, title, scene.unit)
.map(|svg| svg.into_bytes())
}
other => scene.export_mesh_bytes(&mesh, other),
@@ -294,6 +320,37 @@ pub extern "C" fn forma_session_export_scene(id: u32) -> u32 {
})
}
+/// Render a 2x2 studio quad preview PNG of all named scene parts combined.
+#[no_mangle]
+pub extern "C" fn forma_session_export_scene_png(id: u32, size: u32) -> u32 {
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ let sz = if size == 0 { 512 } else { size as usize };
+ match scene.render_preview_scene_bytes(sz) {
+ Ok(bytes) => s.set_ok_bytes(bytes),
+ Err(e) => s.set_err(e.to_string()),
+ }
+ })
+}
+
+/// Render a 1200x900 dimensioned engineering SVG blueprint of all named scene parts combined.
+#[no_mangle]
+pub extern "C" fn forma_session_export_scene_svg(id: u32) -> u32 {
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ match scene.export_blueprint_svg_scene_string() {
+ Ok(svg) => s.set_ok_str(svg),
+ Err(e) => s.set_err(e.to_string()),
+ }
+ })
+}
+
/// Return JSON invariants for the current (or named) part — useful for MCP `export` summaries.
#[no_mangle]
pub extern "C" fn forma_session_invariants(id: u32, part_ptr: *const u8, part_len: usize) -> u32 {
diff --git a/grammar/forma_pipe.gbnf b/grammar/forma_pipe.gbnf
index 6aa6832..9de35f7 100644
--- a/grammar/forma_pipe.gbnf
+++ b/grammar/forma_pipe.gbnf
@@ -1,10 +1,13 @@
# Formal GBNF (llama.cpp / XGrammar / vLLM) Constrained-Decoding Grammar for Forma-Pipe
# Guarantees 0% syntax errors under grammar-constrained LLM generation.
-root ::= ws (stmt (nl stmt)*)? ws
-stmt ::= ident ws "=" ws expr | expr
-expr ::= add-expr (ws "|" ws pipe-call)*
-pipe-call ::= pipe-op "(" ws arg-list? ws ")"
+root ::= ws-nl (stmt (nl stmt)*)? ws-nl
+stmt ::= def-stmt | ident ws "=" ws expr | expr
+def-stmt ::= "def" [ \t]+ ident ws "(" ws-nl param-list? ws-nl ")" ws "=" ws expr
+param-list ::= param (ws-nl "," ws-nl param)* (ws-nl ",")?
+param ::= ident (ws "=" ws expr)?
+expr ::= add-expr (ws-nl "|" ws pipe-call)*
+pipe-call ::= pipe-op "(" ws-nl arg-list? ws-nl ")"
add-expr ::= mul-expr (ws ("+" | "-") ws mul-expr)*
mul-expr ::= unary-expr (ws ("*" | "/") ws unary-expr)*
@@ -19,20 +22,22 @@ atom ::= call
| bool-lit
| ident
-call ::= func-name "(" ws arg-list? ws ")"
-arg-list ::= arg (ws "," ws arg)* (ws ",")?
-arg ::= (kw-name ws "=" ws)? expr
+call ::= (func-name | ident) "(" ws-nl arg-list? ws-nl ")"
+arg-list ::= arg (ws-nl "," ws-nl arg)* (ws-nl ",")?
+arg ::= ((kw-name | ident) ws "=" ws)? expr
-tuple-or-paren ::= "(" ws (expr (ws "," ws expr)* (ws ",")?)? ws ")"
-list-lit ::= "[" ws (expr (ws "," ws expr)* (ws ",")?)? ws "]"
+tuple-or-paren ::= "(" ws-nl (expr (ws-nl "," ws-nl expr)* (ws-nl ",")?)? ws-nl ")"
+list-lit ::= "[" ws-nl (list-comp | expr (ws-nl "," ws-nl expr)* (ws-nl ",")?)? ws-nl "]"
+list-comp ::= expr [ \t\r\n]+ "for" [ \t\r\n]+ ident [ \t\r\n]+ "in" [ \t\r\n]+ "range" "(" ws-nl range-args ws-nl ")"
+range-args ::= expr (ws-nl "," ws-nl expr (ws-nl "," ws-nl expr)?)?
func-name ::= "box" | "cyl" | "cylinder" | "prism" | "pipe" | "hollow_cyl"
| "cone" | "frustum" | "sphere" | "torus" | "revolve"
| "arc_tube" | "tube" | "extrude2d" | "loft" | "thread" | "helix"
- | "sweep" | "text3d" | "text" | "bezier" | "nurbs" | "bspline"
+ | "sweep" | "text3d" | "text" | "gear" | "bezier" | "nurbs" | "bspline"
| "load" | "import"
- | "clearance" | "section" | "checkpoint" | "rollback" | "undo" | "units" | "del" | "remove"
- | "sqrt" | "sin" | "cos" | "asin" | "acos" | "abs" | "deg" | "rad"
+ | "clearance" | "section" | "checkpoint" | "rollback" | "undo" | "units" | "unit" | "del" | "remove"
+ | "sqrt" | "sin" | "cos" | "tan" | "asin" | "acos" | "atan" | "atan2" | "abs" | "deg" | "rad"
| pipe-op
pipe-op ::= "add" | "union" | "cut" | "sub" | "diff" | "intersect"
@@ -47,11 +52,13 @@ pipe-op ::= "add" | "union" | "cut" | "sub" | "diff" | "intersect"
selector-kw ::= "vertical" | "horizontal" | "top_rim" | "bottom_rim" | "outer_rim"
| "rim" | "sharp" | "boundary" | "all"
| "top" | "bottom" | "front" | "back" | "left" | "right" | "sides" | "side"
- | "min" | "center" | "mid" | "max" | "x" | "y" | "z" | "pi"
+ | "min" | "center" | "mid" | "max" | "x" | "y" | "z" | "pi" | "PI"
-kw-name ::= "sx" | "sy" | "sz" | "r" | "h" | "r0" | "r1" | "R" | "segs" | "segments"
- | "axis" | "at" | "center" | "z0" | "z1" | "rot" | "rotate" | "rx" | "rz"
- | "start" | "end" | "start_deg" | "end_deg" | "profile" | "points" | "pts" | "closed"
+kw-name ::= "sx" | "sy" | "sz" | "x" | "y" | "z" | "a" | "b" | "r" | "h" | "len" | "length"
+ | "r0" | "r1" | "r_bot" | "r_bottom" | "r_top" | "R" | "segs" | "segments" | "sides"
+ | "axis" | "at" | "center" | "z0" | "z1" | "rot" | "rotate" | "rx" | "r_x" | "rz" | "r_z"
+ | "start" | "end" | "start_deg" | "end_deg" | "a0" | "a1" | "tube_r" | "arc_segs"
+ | "profile" | "points" | "pts" | "closed" | "part"
| "edges" | "faces" | "w" | "width" | "t" | "thickness" | "wall" | "open_top"
| "dist" | "d" | "amt" | "amount" | "depth" | "levels" | "level" | "n" | "count"
| "crease" | "union" | "mode" | "val" | "to" | "gap" | "step"
@@ -62,10 +69,12 @@ kw-name ::= "sx" | "sy" | "sz" | "r" | "h" | "r0" | "r1" | "R" | "segs" | "se
| "degree" | "deg" | "weights" | "sections" | "profiles"
| "r_out" | "ro" | "outer" | "r_in" | "ri" | "inner" | "r_minor" | "r_min" | "r_major" | "r_maj"
| "pitch" | "p" | "turns" | "file" | "yup" | "text" | "height" | "radius" | "major" | "minor" | "unit"
+ | "teeth" | "module" | "pressure_angle" | "pa" | "bore" | "bore_r"
-bool-lit ::= "true" | "false"
+bool-lit ::= "true" | "false" | "True" | "False"
ident ::= [a-zA-Z_] [a-zA-Z0-9_]*
number ::= "-"? ([0-9]+ ("." [0-9]+)? | "." [0-9]+) ([eE] [+-]? [0-9]+)?
string ::= "\"" [^"\\\n]* "\"" | "'" [^'\\\n]* "'"
nl ::= ([ \t]* ("#" [^\n]*)? ("\r"? "\n" | ";"))+ [ \t]*
+ws-nl ::= ([ \t\r\n] | "#" [^\n]* "\n")*
ws ::= [ \t]*
diff --git a/lib/edge.mjs b/lib/edge.mjs
index 31ee12a..8a221b8 100644
--- a/lib/edge.mjs
+++ b/lib/edge.mjs
@@ -30,6 +30,23 @@ function evictEngine(engine) {
}
}
+function parseDialectCode(dialect) {
+ const norm = String(dialect ?? "pipe").trim().toLowerCase();
+ if (norm === "pipe" || norm === "forma-pipe" || norm === "a" || norm === "default") {
+ return 0;
+ }
+ if (norm === "compact" || norm === "dsl" || norm === "forma-dsl" || norm === "b") {
+ return 1;
+ }
+ throw new Error(`unknown dialect '${dialect}' (use 'pipe' or 'compact')`);
+}
+
+function nowMs() {
+ return typeof performance !== "undefined" && typeof performance.now === "function"
+ ? performance.now()
+ : Date.now();
+}
+
export class FormaEngine {
constructor(instance, onTrap = null) {
this.exports = instance.exports;
@@ -82,10 +99,10 @@ export class FormaEngine {
return decoder.decode(this._readResultBytes());
}
- /** Return the compact language reference (~355 tokens) or formal GBNF grammar. */
+ /** Return the compact language reference or formal GBNF grammar. */
spec({ dialect = "pipe", gbnf = false } = {}) {
return this._run(() => {
- const d = dialect === "compact" ? 1 : 0;
+ const d = parseDialectCode(dialect);
this.exports.forma_spec(d, gbnf ? 1 : 0);
return this._readResultString();
});
@@ -119,14 +136,33 @@ export class FormaSession {
}
}
+ /** Set the session model unit (`m`, `cm`, `mm`, `um`, `in`, `ft`). */
+ setUnit(unit) {
+ this._checkOpen();
+ return this._engine._withUtf8(String(unit), (up, ul) => {
+ this._engine.exports.forma_session_set_unit(this._id, up, ul);
+ return this._engine._readResultString();
+ });
+ }
+
/** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */
- eval(code, { dialect = "pipe", strict = true } = {}) {
+ eval(code, { dialect = "pipe", strict = true, unit } = {}) {
this._checkOpen();
- const d = dialect === "compact" ? 1 : 0;
+ const d = parseDialectCode(dialect);
+ if (unit != null) {
+ this.setUnit(unit);
+ }
+ const t0 = nowMs();
this._engine._withUtf8(code, (ptr, len) => {
this._engine.exports.forma_session_eval(this._id, ptr, len, d, strict ? 1 : 0);
});
- return JSON.parse(this._engine._readResultString());
+ const obs = JSON.parse(this._engine._readResultString());
+ const ms = nowMs() - t0;
+ obs.elapsed_ms = Number(ms.toFixed(2));
+ if (typeof obs.text === "string") {
+ obs.text = obs.text.replace("[0.00ms]", `[${ms.toFixed(2)}ms]`);
+ }
+ return obs;
}
/** Inspect current scene state without mutating it. */
@@ -165,6 +201,22 @@ export class FormaSession {
return this._engine._readResultBytes();
}
+ /** Render a 4-view studio PNG preview of all named scene parts combined. */
+ exportScenePngBytes(size = 512) {
+ this._checkOpen();
+ this._engine._run(() =>
+ this._engine.exports.forma_session_export_scene_png(this._id, size >>> 0)
+ );
+ return this._engine._readResultBytes();
+ }
+
+ /** Render a 1200x900 engineering SVG blueprint of all named scene parts combined. */
+ exportSceneSvg() {
+ this._checkOpen();
+ this._engine._run(() => this._engine.exports.forma_session_export_scene_svg(this._id));
+ return this._engine._readResultString();
+ }
+
/** Compute MeshInvariants JSON for the current or named part. */
invariants(part = "") {
this._checkOpen();
@@ -315,10 +367,10 @@ export async function loadForma(wasmSource, { fresh = false } = {}) {
if (!fresh) {
if (effectiveSource instanceof WebAssembly.Module) {
moduleEngineCache.set(effectiveSource, loader);
- if (!defaultEnginePromise) {
+ if (wasmSource == null && !defaultEnginePromise) {
defaultEnginePromise = loader;
}
- } else if (wasmSource == null || !defaultEnginePromise) {
+ } else if (wasmSource == null) {
defaultEnginePromise = loader;
}
loader.catch(evict);
@@ -344,6 +396,13 @@ export async function exportMesh(code, format = "glb", opts = {}) {
const s = engine.createSession();
try {
s.eval(code, opts);
+ if (opts.scene) {
+ const ext = String(format ?? "glb").replace(/^\./, "").toLowerCase();
+ if (ext === "png") return s.exportScenePngBytes(opts.size ?? 512);
+ 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.exportBytes(format, opts);
} finally {
s.free();
diff --git a/lib/index.d.ts b/lib/index.d.ts
index 096b34a..d993f94 100644
--- a/lib/index.d.ts
+++ b/lib/index.d.ts
@@ -18,21 +18,40 @@ export type WasmSource =
| string
>;
-export interface FormaObservation {
- ok: boolean;
- elapsed_ms: number;
- text: string;
- parts: Record<string, unknown>;
-}
+export type FormaDialect = "pipe" | "forma-pipe" | "a" | "default" | "compact" | "dsl" | "forma-dsl" | "b";
+export type FormaUnit = "m" | "cm" | "mm" | "um" | "in" | "ft";
+export type FormaExportFormat = "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png";
export interface FormaInvariants {
verts: number;
+ edges: number;
faces: number;
+ tris: number;
watertight: boolean;
non_manifold_edges: number;
boundary_edges: number;
+ euler: number;
genus: number;
+ consistent_winding: boolean;
+ degenerate_faces: number;
+ nan_verts: number;
+ components: number;
+ signed_volume: number;
volume: number;
+ surface_area: number;
+ bbox_min: [number, number, number];
+ bbox_max: [number, number, number];
+ size: [number, number, number];
+ tags: Record<string, number>;
+}
+
+export interface FormaObservation {
+ ok: boolean;
+ elapsed_ms: number;
+ parts: Record<string, FormaInvariants>;
+ diff: string;
+ warnings: string[];
+ text: string;
}
export interface LoadFormaOptions {
@@ -40,21 +59,35 @@ export interface LoadFormaOptions {
fresh?: boolean;
}
-export interface EvalOptions {
- dialect?: "pipe" | "compact";
+export interface SessionEvalOptions {
+ /** Modeling notation: `"pipe"` (default) or `"compact"`. */
+ dialect?: FormaDialect;
+ /** Roll back automatically if strict manifold/invariant checks fail (default `true`). */
strict?: boolean;
+ /** Model unit (`m|cm|mm|um|in|ft`; defaults to current scene unit / `"m"`). */
+ unit?: FormaUnit | string;
+}
+
+export interface EvalOptions extends SessionEvalOptions {
/** Optional WASM module/bytes/Response/URL for edge & browser runtimes. */
wasm?: WasmSource;
}
export interface ExportOptions extends EvalOptions {
+ /** Named part to export (defaults to the last assigned part). */
part?: string;
+ /** Combine/export all named scene parts instead of only the last part (`.glb`, `.png`, `.svg`). */
+ scene?: boolean;
+ /** Render resolution in pixels for PNG exports (default `512`). */
size?: number;
}
-export interface SpecOptions {
- dialect?: "pipe" | "compact";
+export interface EngineSpecOptions {
+ dialect?: FormaDialect;
gbnf?: boolean;
+}
+
+export interface SpecOptions extends EngineSpecOptions {
/** Optional WASM module/bytes/Response/URL for edge & browser runtimes. */
wasm?: WasmSource;
}
@@ -64,34 +97,56 @@ export interface TopicOptions {
wasm?: WasmSource;
}
+/** Stateful transactional modeling session backed by the WASM engine. */
export class FormaSession {
- eval(code: string, opts?: EvalOptions): FormaObservation;
+ /** Set the session model unit (`m`, `cm`, `mm`, `um`, `in`, `ft`). */
+ setUnit(unit: FormaUnit | string): string;
+ /** Evaluate a modeling script transactionally and return invariants + diff. */
+ eval(code: string, opts?: SessionEvalOptions): FormaObservation;
+ /** Inspect current scene invariants without mutating state. */
inspect(): FormaObservation;
+ /** Copy-on-write snapshot control: `checkpoint`, `rollback`, `undo`, or `reset`. */
tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string;
- exportBytes(
- format: "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png",
- opts?: { part?: string; size?: number }
- ): Uint8Array;
+ /** Export a part to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, or 4-view `.png` bytes. */
+ exportBytes(format: FormaExportFormat, opts?: { part?: string; size?: number }): Uint8Array;
+ /** Export all named parts as a multi-node binary glTF 2.0 (`.glb`) scene graph. */
exportSceneBytes(): Uint8Array;
+ /** Render a 4-view studio PNG preview of all named scene parts combined. */
+ exportScenePngBytes(size?: number): Uint8Array;
+ /** Render a 1200x900 dimensioned SVG blueprint of all named scene parts combined. */
+ exportSceneSvg(): string;
+ /** Compute topological & spatial invariants for the current or named part. */
invariants(part?: string): FormaInvariants;
+ /** Release this session's memory from the WASM heap. */
free(): void;
}
+/** Loaded Forma WebAssembly engine instance. */
export class FormaEngine {
constructor(instance: WebAssembly.Instance);
- spec(opts?: SpecOptions): string;
+ /** Return the compact language reference or formal GBNF grammar. */
+ spec(opts?: EngineSpecOptions): string;
+ /** Return an on-demand domain spec (`deform|curves|uv|remesh|scene`). */
specTopic(topic: string): string;
+ /** Create a new stateful modeling session. */
createSession(): FormaSession;
}
+/** Load and instantiate the Forma WASM engine (cached by default). */
export function loadForma(wasmSource?: WasmSource, opts?: LoadFormaOptions): Promise<FormaEngine>;
+/** One-shot helper: evaluate a script and return the parsed Observation. */
export function evalPipe(code: string, opts?: EvalOptions): Promise<FormaObservation>;
+/** One-shot helper: evaluate a script and export binary bytes. */
export function exportMesh(
code: string,
- format?: "glb" | "step" | "stp" | "3mf" | "stl" | "obj" | "svg" | "png",
+ format?: FormaExportFormat,
opts?: ExportOptions
): Promise<Uint8Array>;
-export function renderPng(code: string, size?: number, opts?: EvalOptions): Promise<Uint8Array>;
-export function drawSvg(code: string, opts?: EvalOptions): Promise<string>;
+/** One-shot helper: evaluate a script and render a 4-view studio PNG. */
+export function renderPng(code: string, size?: number, opts?: ExportOptions): Promise<Uint8Array>;
+/** One-shot helper: evaluate a script and render a 1200x900 dimensioned SVG blueprint string. */
+export function drawSvg(code: string, opts?: ExportOptions): Promise<string>;
+/** Return the compact language reference or formal GBNF grammar. */
export function getSpec(opts?: SpecOptions): Promise<string>;
+/** Return an on-demand domain spec (`deform|curves|uv|remesh|scene`). */
export function getSpecTopic(topic: string, opts?: TopicOptions): Promise<string>;
diff --git a/wasm/forma.wasm b/wasm/forma.wasm
index 091302e..c77bac2 100755
Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ