A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
fix: harden strict mode, pattern defaults, GLB Y-up/Z-up axes, and statement limit (Fixes #1)
wrong-nebula8166c1d17d6d
diff --git a/bin/forma-mcp.mjs b/bin/forma-mcp.mjsindex c0dc600..4dcd399 100755--- a/bin/forma-mcp.mjs+++ b/bin/forma-mcp.mjs@@ -66,7 +66,8 @@ async function handleToolCall(session, name, args) {return [true, "ERR: missing 'code' string"];}const t0 = performance.now();- const obs = session.eval(args.code, { strict: Boolean(args.strict) });+ 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];diff --git a/bin/forma.mjs b/bin/forma.mjsindex 5fa66d5..448b6c7 100755--- a/bin/forma.mjs+++ b/bin/forma.mjs@@ -72,7 +72,7 @@ async function main() {}let dialect = "pipe";- let strict = false;+ let strict = true;let asJson = false;let outPath = null;let renderPath = null;@@ -97,6 +97,8 @@ async function main() {renderSize = Number.parseInt(args[++i], 10) || 512;} else if (a === "--strict") {strict = true;+ } else if (a === "--no-strict") {+ strict = false;} else if (a === "--json") {asJson = true;} else {diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rsindex 8f91c19..f4b14d7 100644--- a/crates/forma-cli/src/main.rs+++ b/crates/forma-cli/src/main.rs@@ -16,7 +16,7 @@ fn print_help() {"forma 0.4.0 — ultra-fast, headless, watertight, LLM-native 3D modeling engine\n\\n\USAGE:\n\- forma eval [--dialect pipe|compact] [--strict] [--json] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--draw blueprint.svg] [file|-]\n\+ forma eval [--dialect pipe|compact] [--strict|--no-strict] [--json] [--out path.(glb|obj|stl|3mf|step|blend)] [--render preview.png] [--draw blueprint.svg] [file|-]\n\forma render [--size 512] --out preview.png [file|-]\n\forma draw --out blueprint.svg [file|-]\n\forma spec [--dialect pipe|compact] [--gbnf]\n\@@ -130,7 +130,7 @@ fn main() {let is_render_cmd = args[0] == "render";let is_draw_cmd = args[0] == "draw";let mut dialect = Dialect::Pipe;- let mut strict = false;+ let mut strict = true;let mut as_json = false;let mut export_scene = false;let mut out_path: Option<PathBuf> = None;@@ -195,6 +195,10 @@ fn main() {strict = true;i += 1;}+ "--no-strict" => {+ strict = false;+ i += 1;+ }"--json" => {as_json = true;i += 1;@@ -235,7 +239,7 @@ fn main() {Ok(obs) => {if let Some(ref out) = out_path {if export_scene {- match scene.export_scene_glb_bytes(false) {+ match scene.export_scene_glb_bytes(true) {Ok(bytes) => {if let Err(e) = std::fs::write(out, bytes) {eprintln!("ERR: scene export failed: {e}");diff --git a/crates/forma-core/src/boolean.rs b/crates/forma-core/src/boolean.rsindex c9842cb..47596f7 100644--- a/crates/forma-core/src/boolean.rs+++ b/crates/forma-core/src/boolean.rs@@ -1,19 +1,23 @@-//! Ultra-fast, zero-HashMap, BVH-localized exact-plane CSG boolean engine.+//! Ultra-fast, zero-HashMap, tolerance-guided BVH-localized CSG boolean engine+//! with deterministic repair pipeline and perturbation retry.//!//! Algorithm (inspired by Zhou et al. 2016 "Mesh Arrangements for Solid Geometry"):-//! 1. Build lightweight flat binary AABB-BVHs over triangles of A and B (~20-50 us).-//! 2. Partition A into A_hit (triangles whose AABB overlaps at least one triangle of B)+//! 1. Normalize operands into a shared unit cube around their combined AABB center so all+//! floating-point tolerances stay scale-invariant across arbitrary part dimensions.+//! 2. Build lightweight flat binary AABB-BVHs over triangles of A and B (~20-50 us).+//! 3. Partition A into A_hit (triangles whose AABB overlaps at least one triangle of B)//! and A_far (guaranteed non-intersecting!). Do the same for B -> B_hit, B_far.-//! 3. Classify A_far against solid B (and B_far against solid A) in O(log N) per triangle-//! using BVH-accelerated exact Generalized Winding Number (no splitting ever!).-//! 4. Subdivide ONLY each triangle `ta` in A_hit against ONLY the ~2-8 triangles `tb` of B+//! 4. Classify A_far against solid B (and B_far against solid A) in O(log N) per triangle+//! using BVH-accelerated ray-parity / Generalized Winding Number (no splitting ever!).+//! 5. Subdivide ONLY each triangle `ta` in A_hit against ONLY the ~2-8 triangles `tb` of B//! that actually overlap `ta`'s AABB (and vice versa for B_hit) using stack-inline//! `SmallVec<[Vec3; 8]>` polygons — zero global BSP fragmentation, zero String clones!-//! 5. Classify each tiny subdivided fragment via BVH winding number (with exact coplanar+//! 6. Classify each tiny subdivided fragment via BVH winding number (with coplanar//! normal tie-breaking when a fragment lies on a face of the opposing mesh).-//! 6. Sort-based spatial vertex welding + deterministic opposing-tri cancellation +-//! spatial-grid T-junction elimination + folded-flap pruning.-//! 7. Deterministic Simulation-of-Simplicity perturbation fallback if exact grazing seams survive.+//! 7. Sort-based spatial vertex welding + deterministic opposing-tri cancellation ++//! spatial-grid T-junction elimination + seam snapping + folded-flap pruning.+//! 8. Deterministic perturbation retry (2 nudged `(shift, scale)` attempts) on grazing curved seams,+//! un-normalizing the final mesh back to world coordinates.use crate::math::{Aabb, Vec3};use crate::mesh::{edge_key, Face, LineageId, PolyMesh};@@ -1566,7 +1570,8 @@ fn prune_folded_flaps(mesh: &mut PolyMesh) {}}-/// Execute a guaranteed-manifold, BVH-localized CSG boolean operation between two closed solids.+/// Execute a scale-invariant, tolerance-guided BVH-localized CSG boolean operation+/// between two closed solids, with post-assembly manifold repair and perturbation retries.pub fn boolean_op(a: &PolyMesh,b: &PolyMesh,@@ -1576,7 +1581,28 @@ pub fn boolean_op() -> Result<PolyMesh, String> {let bb_a = a.aabb();let bb_b = b.aabb();- if !bb_a.overlaps(&bb_b, 1e-5) {+ if !bb_a.is_valid() || !bb_b.is_valid() {+ return Ok(match op {+ BoolOp::Union => {+ if bb_a.is_valid() {+ a.clone()+ } else {+ b.clone()+ }+ }+ BoolOp::Difference => a.clone(),+ BoolOp::Intersect => PolyMesh::new(),+ });+ }++ let cmin = bb_a.min.min(bb_b.min);+ let cmax = bb_a.max.max(bb_b.max);+ let center = (cmin + cmax) * 0.5;+ let ext = cmax - cmin;+ let scale = ext.x.max(ext.y).max(ext.z).max(1e-9);+ let rel_eps = 1e-5 * scale;++ if !bb_a.overlaps(&bb_b, rel_eps) {return Ok(match op {BoolOp::Union => {let mut out = a.clone();@@ -1588,13 +1614,44 @@ pub fn boolean_op(});}+ // Normalize both operands to a unit cube around their combined AABB center whenever+ // the geometry is far from unit scale or far from the origin, keeping all boolean+ // tolerances scale-invariant while avoiding unnecessary floating-point churn at unit scale.+ let needs_norm = scale < 0.25 || scale > 8.0 || center.len() > 1e3;+ let (an_buf, bn_buf);+ let (a_ref, b_ref): (&PolyMesh, &PolyMesh) = if needs_norm {+ let inv_scale = 1.0 / scale;+ let mut an = a.clone();+ for v in &mut an.verts {+ *v = (*v - center) * inv_scale;+ }+ let mut bn = b.clone();+ for v in &mut bn.verts {+ *v = (*v - center) * inv_scale;+ }+ an_buf = an;+ bn_buf = bn;+ (&an_buf, &bn_buf)+ } else {+ (a, b)+ };++ let unnormalize = |mut m: PolyMesh| -> PolyMesh {+ if needs_norm {+ for v in &mut m.verts {+ *v = *v * scale + center;+ }+ }+ m+ };+let tag_str = b_name.map(|n| format!("bool:{n}"));- let (res, bad0) = run_bvh_csg(a, b, op, tag_str.as_deref(), op_id);+ let (res, bad0) = run_bvh_csg(a_ref, b_ref, op, tag_str.as_deref(), op_id);if bad0 == 0 && !res.faces.is_empty() {- return Ok(res);+ return Ok(unnormalize(res));}- // Simulation-of-Simplicity deterministic retry on grazing curved seams+ // Deterministic perturbation retry on grazing curved seamslet perturbations = [(Vec3::new(1.37e-5, -2.11e-5, 1.73e-5), 1.0 + 1.9e-5),(Vec3::new(-2.91e-5, 1.63e-5, -1.49e-5), 1.0 - 2.3e-5),@@ -1603,14 +1660,14 @@ pub fn boolean_op(let mut best_bad = bad0;for (shift, sc) in perturbations {- let mut bp = b.clone();+ let mut bp = b_ref.clone();let c = bp.aabb().center();for v in &mut bp.verts {*v = c + (*v - c) * sc + shift;}- let (cand, bad) = run_bvh_csg(a, &bp, op, tag_str.as_deref(), op_id);+ let (cand, bad) = run_bvh_csg(a_ref, &bp, op, tag_str.as_deref(), op_id);if bad == 0 && !cand.faces.is_empty() {- return Ok(cand);+ return Ok(unnormalize(cand));}if bad < best_bad {best_bad = bad;@@ -1618,7 +1675,7 @@ pub fn boolean_op(}}- Ok(best)+ Ok(unnormalize(best))}/// Batch boolean of `a` with multiple tool meshes.@@ -1669,3 +1726,301 @@ pub fn boolean_batch(}Ok(acc)}++#[inline]+fn clip_poly_2d_halfplane(+ poly: &[(f64, f64)],+ a: (f64, f64),+ b: (f64, f64),+) -> SmallVec<[(f64, f64); 8]> {+ let mut out: SmallVec<[(f64, f64); 8]> = SmallVec::new();+ let n = poly.len();+ if n == 0 {+ return out;+ }+ let dx = b.0 - a.0;+ let dy = b.1 - a.1;+ let side = |p: (f64, f64)| -> f64 { dx * (p.1 - a.1) - dy * (p.0 - a.0) };+ let mut prev = poly[n - 1];+ let mut prev_s = side(prev);+ for &curr in poly {+ let curr_s = side(curr);+ let prev_in = prev_s >= 0.0;+ let curr_in = curr_s >= 0.0;+ if curr_in {+ if !prev_in {+ let denom = prev_s - curr_s;+ if denom.abs() > 1e-18 {+ let t = prev_s / denom;+ out.push((prev.0 + (curr.0 - prev.0) * t, prev.1 + (curr.1 - prev.1) * t));+ }+ }+ out.push(curr);+ } else if prev_in {+ let denom = prev_s - curr_s;+ if denom.abs() > 1e-18 {+ let t = prev_s / denom;+ out.push((prev.0 + (curr.0 - prev.0) * t, prev.1 + (curr.1 - prev.1) * t));+ }+ }+ prev = curr;+ prev_s = curr_s;+ }+ out+}++fn coplanar_tris_overlap_area(a: &[Vec3; 3], b: &[Vec3; 3], n: Vec3) -> f64 {+ let drop_axis = if n.x.abs() >= n.y.abs() && n.x.abs() >= n.z.abs() {+ 0+ } else if n.y.abs() >= n.z.abs() {+ 1+ } else {+ 2+ };+ let proj = |p: Vec3| -> (f64, f64) {+ match drop_axis {+ 0 => (p.y, p.z),+ 1 => (p.z, p.x),+ _ => (p.x, p.y),+ }+ };+ let mut pa = [proj(a[0]), proj(a[1]), proj(a[2])];+ let mut pb = [proj(b[0]), proj(b[1]), proj(b[2])];+ let cross2 = |p0: (f64, f64), p1: (f64, f64), p2: (f64, f64)| -> f64 {+ (p1.0 - p0.0) * (p2.1 - p0.1) - (p1.1 - p0.1) * (p2.0 - p0.0)+ };+ if cross2(pa[0], pa[1], pa[2]) < 0.0 {+ pa.swap(1, 2);+ }+ if cross2(pb[0], pb[1], pb[2]) < 0.0 {+ pb.swap(1, 2);+ }+ let mut poly: SmallVec<[(f64, f64); 8]> = SmallVec::from_slice(&pa);+ for i in 0..3 {+ poly = clip_poly_2d_halfplane(&poly, pb[i], pb[(i + 1) % 3]);+ if poly.len() < 3 {+ return 0.0;+ }+ }+ let mut area2 = 0.0;+ for i in 0..poly.len() {+ let p0 = poly[i];+ let p1 = poly[(i + 1) % poly.len()];+ area2 += p0.0 * p1.1 - p1.0 * p0.1;+ }+ 0.5 * area2.abs()+}++fn tri_plane_overlap_interval(tri: &[Vec3; 3], dists: [f64; 3], line_dir: Vec3, eps: f64) -> Option<(f64, f64)> {+ let mut tmin = f64::INFINITY;+ let mut tmax = f64::NEG_INFINITY;+ let mut count = 0usize;+ for k in 0..3 {+ if dists[k].abs() <= eps {+ let t = tri[k].dot(line_dir);+ tmin = tmin.min(t);+ tmax = tmax.max(t);+ count += 1;+ }+ let kn = (k + 1) % 3;+ if (dists[k] > eps && dists[kn] < -eps) || (dists[k] < -eps && dists[kn] > eps) {+ let frac = dists[k] / (dists[k] - dists[kn]);+ let p = tri[k] + (tri[kn] - tri[k]) * frac;+ let t = p.dot(line_dir);+ tmin = tmin.min(t);+ tmax = tmax.max(t);+ count += 1;+ }+ }+ if count > 0 {+ Some((tmin, tmax))+ } else {+ None+ }+}++fn tris_overlap_3d(a: &Tri, b: &Tri, scale: f64) -> bool {+ let plane_eps = 1e-7 * scale.max(1e-9);+ let da = [+ b.normal.dot(a.v[0]) - b.w,+ b.normal.dot(a.v[1]) - b.w,+ b.normal.dot(a.v[2]) - b.w,+ ];+ if (da[0] > plane_eps && da[1] > plane_eps && da[2] > plane_eps)+ || (da[0] < -plane_eps && da[1] < -plane_eps && da[2] < -plane_eps)+ {+ return false;+ }+ let db = [+ a.normal.dot(b.v[0]) - a.w,+ a.normal.dot(b.v[1]) - a.w,+ a.normal.dot(b.v[2]) - a.w,+ ];+ if (db[0] > plane_eps && db[1] > plane_eps && db[2] > plane_eps)+ || (db[0] < -plane_eps && db[1] < -plane_eps && db[2] < -plane_eps)+ {+ return false;+ }+ let line_dir = a.normal.cross(b.normal);+ if line_dir.len_sq() < 1e-10 {+ let area = coplanar_tris_overlap_area(&a.v, &b.v, a.normal);+ let area_eps = 1e-10 * scale * scale;+ return area > area_eps;+ }+ let d = line_dir.normalized();+ let Some((ta0, ta1)) = tri_plane_overlap_interval(&a.v, da, d, plane_eps) else {+ return false;+ };+ let Some((tb0, tb1)) = tri_plane_overlap_interval(&b.v, db, d, plane_eps) else {+ return false;+ };+ ta0.max(tb0) < ta1.min(tb1) - 1e-7 * scale.max(1e-9)+}++/// Fast per-component AABB + BVH inter-shell overlap check for multi-component meshes.+/// Zero cost for single-component meshes; cleanly permits valid negative-volume inner cavities+/// (e.g. closed `shell(..., open_top=false)`) whose triangles do not intersect the outer shell.+pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {+ let n_faces = mesh.faces.len();+ if n_faces < 2 {+ return false;+ }++ // 1. Sort-based face-edge Union-Find to partition connected shell components+ let mut edges: Vec<(u32, u32, u32)> = Vec::with_capacity(n_faces * 4);+ for (fi, f) in mesh.faces.iter().enumerate() {+ let n = f.verts.len();+ let fi32 = fi as u32;+ for i in 0..n {+ let u = f.verts[i];+ let v = f.verts[(i + 1) % n];+ if u != v {+ let (a, b) = if u < v { (u as u32, v as u32) } else { (v as u32, u as u32) };+ edges.push((a, b, fi32));+ }+ }+ }+ edges.sort_unstable_by_key(|&(a, b, _)| ((a as u64) << 32) | (b as u64));++ let mut parent: Vec<u32> = (0..n_faces as u32).collect();+ let find = |parent: &mut [u32], mut x: u32| -> u32 {+ while parent[x as usize] != x {+ let gp = parent[parent[x as usize] as usize];+ parent[x as usize] = gp;+ x = gp;+ }+ x+ };+ let mut i = 0;+ let m = edges.len();+ while i < m {+ let (u, v, f0) = edges[i];+ let mut j = i + 1;+ while j < m && edges[j].0 == u && edges[j].1 == v {+ let ra = find(&mut parent, f0);+ let rb = find(&mut parent, edges[j].2);+ if ra != rb {+ parent[rb as usize] = ra;+ }+ j += 1;+ }+ i = j;+ }++ let mut root_to_cid = vec![u32::MAX; n_faces];+ let mut comp_faces: Vec<Vec<usize>> = Vec::new();+ for fi in 0..n_faces {+ let r = find(&mut parent, fi as u32) as usize;+ if root_to_cid[r] == u32::MAX {+ root_to_cid[r] = comp_faces.len() as u32;+ comp_faces.push(Vec::new());+ }+ comp_faces[root_to_cid[r] as usize].push(fi);+ }++ let nc = comp_faces.len();+ if nc <= 1 {+ return false;+ }++ // 2. Per-component AABB and signed volume (fast O(N) pass)+ let mut comp_bbs: Vec<Aabb> = Vec::with_capacity(nc);+ let mut comp_vols: Vec<f64> = Vec::with_capacity(nc);+ let mut global_bb = Aabb::empty();+ for c_faces in &comp_faces {+ let mut bb = Aabb::empty();+ let mut vol6 = 0.0;+ for &fi in c_faces {+ for &vi in &mesh.faces[fi].verts {+ bb.include(mesh.verts[vi]);+ }+ for [a, b, c] in mesh.triangulate_face(fi) {+ vol6 += mesh.verts[a].dot(mesh.verts[b].cross(mesh.verts[c]));+ }+ }+ global_bb.min = global_bb.min.min(bb.min);+ global_bb.max = global_bb.max.max(bb.max);+ comp_bbs.push(bb);+ comp_vols.push(vol6 / 6.0);+ }++ let mesh_scale = global_bb.size().x.max(global_bb.size().y).max(global_bb.size().z).max(1e-9);+ let aabb_eps = 1e-6 * mesh_scale;++ // 3. Lazy per-component triangle + BVH build ONLY for components with an AABB overlap+ let mut comp_data: Vec<Option<(Vec<Tri>, TriBvh)>> = (0..nc).map(|_| None).collect();+ let ensure_comp = |cid: usize, comp_data: &mut [Option<(Vec<Tri>, TriBvh)>]| {+ if comp_data[cid].is_some() {+ return;+ }+ let mut tris = Vec::with_capacity(comp_faces[cid].len() * 2);+ for &fi in &comp_faces[cid] {+ for [a, b, c] in mesh.triangulate_face(fi) {+ if let Some(t) = Tri::from_verts(mesh.verts[a], mesh.verts[b], mesh.verts[c], 0, 0, 0) {+ tris.push(t);+ }+ }+ }+ let bvh = TriBvh::build(&tris);+ comp_data[cid] = Some((tris, bvh));+ };++ let mut hits: Vec<u32> = Vec::with_capacity(32);+ for ci in 0..nc {+ for cj in (ci + 1)..nc {+ if !comp_bbs[ci].overlaps(&comp_bbs[cj], aabb_eps) {+ continue;+ }+ ensure_comp(ci, &mut comp_data);+ ensure_comp(cj, &mut comp_data);+ let (tris_i, bvh_i) = comp_data[ci].as_ref().unwrap();+ let (tris_j, bvh_j) = comp_data[cj].as_ref().unwrap();++ // Check triangle-triangle crossing or coplanar face overlap+ for ta in tris_i {+ bvh_j.query_aabb(&ta.aabb, aabb_eps, &mut hits);+ for &tb_idx in &hits {+ if tris_overlap_3d(ta, &tris_j[tb_idx as usize], mesh_scale) {+ return true;+ }+ }+ }++ // Check solid-inside-solid full containment (skip valid negative-volume inner cavities!)+ if comp_vols[ci] > 1e-12 && comp_vols[cj] > 1e-12 {+ if let Some(t0) = tris_i.first() {+ if bvh_j.point_inside(tris_j, t0.centroid) {+ return true;+ }+ }+ if let Some(t0) = tris_j.first() {+ if bvh_i.point_inside(tris_i, t0.centroid) {+ return true;+ }+ }+ }+ }+ }++ false+}diff --git a/crates/forma-core/src/export.rs b/crates/forma-core/src/export.rsindex bc4c83e..e3e0f47 100644--- a/crates/forma-core/src/export.rs+++ b/crates/forma-core/src/export.rs@@ -202,8 +202,10 @@ pub fn write_glb_bytes(mesh: &PolyMesh, yup: bool) -> Result<Vec<u8>, String> {String::new()};+ let yup_flag = if yup { "true" } else { "false" };let mut json_bytes = format!(- r#"{{"asset":{{"version":"2.0","generator":"forma-core 0.2"}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0,"name":"forma_mesh"}}],"meshes":[{{"name":"forma_mesh","primitives":[{}]}}]{},"buffers":[{{"byteLength":{}}}],"bufferViews":[{}],"accessors":[{}]}}"#,+ r#"{{"asset":{{"version":"2.0","generator":"forma-core 0.4","extras":{{"forma_yup":{}}}}},"scene":0,"scenes":[{{"nodes":[0]}}],"nodes":[{{"mesh":0,"name":"forma_mesh"}}],"meshes":[{{"name":"forma_mesh","primitives":[{}]}}]{},"buffers":[{{"byteLength":{}}}],"bufferViews":[{}],"accessors":[{}]}}"#,+ yup_flag,prims_json,mats_json,bin.len(),@@ -375,7 +377,7 @@ pub fn write_scene_glb_bytes(let node_indices: Vec<usize> = (0..gltf_nodes.len()).collect();let mut root = serde_json::json!({- "asset": {"version": "2.0", "generator": "forma-core 0.4"},+ "asset": {"version": "2.0", "generator": "forma-core 0.4", "extras": {"forma_yup": yup}},"scene": 0,"scenes": [{"nodes": node_indices}],"nodes": gltf_nodes,@@ -405,9 +407,9 @@ pub fn write_scene_glb_bytes(Ok(out)}-/// Export a PolyMesh to binary glTF 2.0 (.glb) with flat hard-surface normals,-/// automatic triplanar `TEXCOORD_0` UVs, and optional per-face PBR `materials`.-/// Note: `yup = false` preserves exact Z-up coordinates (matching Blender's `export_yup=False`).+/// Export a PolyMesh to binary glTF 2.0 (.glb) with flat/smooth normals,+/// automatic triplanar or unwrapped `TEXCOORD_0` UVs, and optional per-face PBR `materials`.+/// Note: `yup = true` emits glTF 2.0 spec-compliant Y-up coordinates (`(x,y,z) -> (x,z,-y)`).pub fn write_glb(mesh: &PolyMesh, path: &Path, yup: bool) -> Result<(), String> {let bytes = write_glb_bytes(mesh, yup)?;let f = File::create(path).map_err(|e| format!("create {}: {e}", path.display()))?;@@ -745,7 +747,7 @@ pub fn write_step(mesh: &PolyMesh, path: &Path) -> Result<(), String> {/// Export by extension string (`glb`, `obj`, `stl`, `3mf`, `step`, `stp`) into memory bytes.pub fn export_mesh_bytes(mesh: &PolyMesh, ext: &str) -> Result<Vec<u8>, String> {match ext.trim_start_matches('.').to_lowercase().as_str() {- "glb" => write_glb_bytes(mesh, false),+ "glb" => write_glb_bytes(mesh, true),"obj" => write_obj_bytes(mesh),"stl" => write_stl_binary_bytes(mesh),"3mf" => write_3mf_bytes(mesh),@@ -764,7 +766,7 @@ pub fn export_mesh(mesh: &PolyMesh, path: &Path) -> Result<(), String> {.map(|s| s.to_lowercase()).unwrap_or_default();match ext.as_str() {- "glb" => write_glb(mesh, path, false),+ "glb" => write_glb(mesh, path, true),"obj" => write_obj(mesh, path),"stl" => write_stl_binary(mesh, path),"3mf" => write_3mf(mesh, path),diff --git a/crates/forma-core/src/import.rs b/crates/forma-core/src/import.rsindex 886df48..d17a4a8 100644--- a/crates/forma-core/src/import.rs+++ b/crates/forma-core/src/import.rs@@ -11,6 +11,13 @@ use std::path::Path;const MAX_IMPORT_BYTES: usize = 32 * 1024 * 1024;const MAX_IMPORT_FACES: usize = 200_000;+fn ensure_outward_winding_if_closed(mesh: &mut PolyMesh) {+ let inv = crate::invariants::MeshInvariants::compute(mesh);+ if inv.boundary_edges == 0 && inv.signed_volume < 0.0 {+ mesh.flip_winding();+ }+}+fn weld_key(v: Vec3) -> (i64, i64, i64) {((v.x * 1e5).round() as i64,@@ -86,7 +93,7 @@ pub fn read_obj_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {if mesh.faces.is_empty() {return Err("OBJ contained no valid faces".into());}- mesh.ensure_outward_winding();+ ensure_outward_winding_if_closed(&mut mesh);Ok(mesh)}@@ -122,7 +129,7 @@ pub fn read_stl_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {if mesh.faces.is_empty() {return Err("binary STL contained no valid triangles".into());}- mesh.ensure_outward_winding();+ ensure_outward_winding_if_closed(&mut mesh);return Ok(mesh);}}@@ -159,7 +166,7 @@ pub fn read_stl_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {if mesh.faces.is_empty() {return Err("STL contained no valid triangles".into());}- mesh.ensure_outward_winding();+ ensure_outward_winding_if_closed(&mut mesh);Ok(mesh)}@@ -190,6 +197,12 @@ fn mat4_transform_pt(m: &[[f64; 4]; 4], p: Vec3) -> Vec3 {)}+fn mat4_det3(m: &[[f64; 4]; 4]) -> f64 {+ m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1])+ - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])+ + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])+}+fn node_local_matrix(node: &Value) -> [[f64; 4]; 4] {if let Some(arr) = node.get("matrix").and_then(|v| v.as_array()) {if arr.len() == 16 {@@ -221,7 +234,12 @@ fn node_local_matrix(node: &Value) -> [[f64; 4]; 4] {.filter(|a| a.len() == 4).map(|a| [a[0].as_f64().unwrap_or(0.0), a[1].as_f64().unwrap_or(0.0), a[2].as_f64().unwrap_or(0.0), a[3].as_f64().unwrap_or(1.0)]).unwrap_or([0.0, 0.0, 0.0, 1.0]);- let (qx, qy, qz, qw) = (q[0], q[1], q[2], q[3]);+ let qlen = (q[0] * q[0] + q[1] * q[1] + q[2] * q[2] + q[3] * q[3]).sqrt();+ let (qx, qy, qz, qw) = if qlen > 1e-12 {+ (q[0] / qlen, q[1] / qlen, q[2] / qlen, q[3] / qlen)+ } else {+ (0.0, 0.0, 0.0, 1.0)+ };let r00 = 1.0 - 2.0 * (qy * qy + qz * qz);let r01 = 2.0 * (qx * qy - qz * qw);let r02 = 2.0 * (qx * qz + qy * qw);@@ -240,7 +258,14 @@ fn node_local_matrix(node: &Value) -> [[f64; 4]; 4] {}/// Import a glTF 2.0 binary `.glb` mesh from bytes (positions, triangle indices, node transforms, PBR materials).+/// By default (`yup_override = None`), converts glTF 2.0 Y-up coordinates into Forma's Z-up convention+/// `(x, y, z) -> (x, -z, y)`, while auto-detecting legacy `forma-core 0.2`/`0.4` Z-up exports.pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {+ read_glb_bytes_with_opts(bytes, None)+}++/// Import a glTF 2.0 binary `.glb` mesh from bytes with an optional explicit `yup` axis override.+pub fn read_glb_bytes_with_opts(bytes: &[u8], yup_override: Option<bool>) -> Result<PolyMesh, String> {if bytes.len() < 20 {return Err("GLB too short".into());}@@ -277,30 +302,69 @@ pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {let bin = bin_slice.ok_or("GLB missing BIN chunk")?;let gltf: Value = serde_json::from_slice(json_bytes).map_err(|e| format!("GLB JSON parse: {e}"))?;+ // Determine whether to convert glTF Y-up -> Forma Z-up: (x, y, z) -> (x, -z, y).+ // Standard glTF 2.0 is strictly Y-up; legacy forma-core 0.2/0.4 GLBs without `asset.extras.forma_yup`+ // were emitted Z-up and are preserved transparently for backwards compatibility.+ let convert_yup = if let Some(explicit) = yup_override {+ explicit+ } else if let Some(flag) = gltf+ .get("asset")+ .and_then(|a| a.get("extras"))+ .and_then(|e| e.get("forma_yup"))+ .and_then(|v| v.as_bool())+ {+ flag+ } else {+ let gen = gltf+ .get("asset")+ .and_then(|a| a.get("generator"))+ .and_then(|v| v.as_str())+ .unwrap_or("");+ !(gen.starts_with("forma-core 0.2") || gen.starts_with("forma-core 0.4"))+ };+let accessors = gltf.get("accessors").and_then(|v| v.as_array()).ok_or("GLB missing accessors")?;let buffer_views = gltf.get("bufferViews").and_then(|v| v.as_array()).ok_or("GLB missing bufferViews")?;let meshes_arr = gltf.get("meshes").and_then(|v| v.as_array()).ok_or("GLB missing meshes")?;let mats_arr = gltf.get("materials").and_then(|v| v.as_array());- // Build node world transforms -> (mesh_idx, world_matrix)+ // Build node world transforms -> (mesh_idx, world_matrix) starting from active scene rootslet mut mesh_instances: Vec<(usize, [[f64; 4]; 4])> = Vec::new();if let Some(nodes) = gltf.get("nodes").and_then(|v| v.as_array()) {- let mut has_parent = vec![false; nodes.len()];- for n in nodes {- if let Some(ch) = n.get("children").and_then(|v| v.as_array()) {- for c in ch {- if let Some(ci) = c.as_u64().map(|x| x as usize) {- if ci < has_parent.len() {- has_parent[ci] = true;- }+ let mut stack: Vec<(usize, [[f64; 4]; 4], usize)> = Vec::new();+ let active_scene_idx = gltf.get("scene").and_then(|v| v.as_u64()).unwrap_or(0) as usize;+ if let Some(root_nodes) = gltf+ .get("scenes")+ .and_then(|v| v.as_array())+ .and_then(|arr| arr.get(active_scene_idx).or_else(|| arr.first()))+ .and_then(|sc| sc.get("nodes"))+ .and_then(|v| v.as_array())+ {+ for rn in root_nodes.iter().rev() {+ if let Some(ri) = rn.as_u64().map(|x| x as usize) {+ if ri < nodes.len() {+ stack.push((ri, mat4_identity(), 0));}}}}- let mut stack: Vec<(usize, [[f64; 4]; 4], usize)> = Vec::new();- for (i, &hp) in has_parent.iter().enumerate() {- if !hp {- stack.push((i, mat4_identity(), 0));+ if stack.is_empty() {+ let mut has_parent = vec![false; nodes.len()];+ for n in nodes {+ if let Some(ch) = n.get("children").and_then(|v| v.as_array()) {+ for c in ch {+ if let Some(ci) = c.as_u64().map(|x| x as usize) {+ if ci < has_parent.len() {+ has_parent[ci] = true;+ }+ }+ }+ }+ }+ for (i, &hp) in has_parent.iter().enumerate() {+ if !hp {+ stack.push((i, mat4_identity(), 0));+ }}}while let Some((ni, parent_m, depth)) = stack.pop() {@@ -334,6 +398,7 @@ pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {for (mesh_idx, world_m) in mesh_instances {let Some(mobj) = meshes_arr.get(mesh_idx) else { continue };let Some(prims) = mobj.get("primitives").and_then(|v| v.as_array()) else { continue };+ let flip_winding = mat4_det3(&world_m) < 0.0;for prim in prims {// Mode defaults to 4 (TRIANGLES)let mode = prim.get("mode").and_then(|v| v.as_u64()).unwrap_or(4);@@ -363,7 +428,12 @@ pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {if !x.is_finite() || !y.is_finite() || !z.is_finite() {return Err("GLB contains non-finite vertex".into());}- let wp = mat4_transform_pt(&world_m, Vec3::new(x, y, z));+ let wp_raw = mat4_transform_pt(&world_m, Vec3::new(x, y, z));+ let wp = if convert_yup {+ Vec3::new(wp_raw.x, -wp_raw.z, wp_raw.y)+ } else {+ wp_raw+ };let vi = *weld.entry(weld_key(wp)).or_insert_with(|| out.add_vert(wp));local_v.push(vi);}@@ -441,7 +511,12 @@ pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {return Err(format!("GLB exceeds max face budget ({MAX_IMPORT_FACES})"));}if tri[0] != tri[1] && tri[1] != tri[2] && tri[2] != tri[0] {- let fi = out.add_face(SmallVec::from_slice(tri), 0, Some("imported"));+ let ordered = if flip_winding {+ [tri[0], tri[2], tri[1]]+ } else {+ [tri[0], tri[1], tri[2]]+ };+ let fi = out.add_face(SmallVec::from_slice(&ordered), 0, Some("imported"));if let Some(slot) = mat_slot {out.faces[fi].mat_id = slot;}@@ -453,26 +528,36 @@ pub fn read_glb_bytes(bytes: &[u8]) -> Result<PolyMesh, String> {if out.faces.is_empty() {return Err("GLB contained no triangle meshes".into());}- out.ensure_outward_winding();+ ensure_outward_winding_if_closed(&mut out);Ok(out)}-/// Import mesh bytes by format extension (`glb`, `obj`, `stl`).-pub fn import_mesh_bytes(bytes: &[u8], ext: &str) -> Result<PolyMesh, String> {+/// Import mesh bytes by format extension (`glb`, `obj`, `stl`) with optional `yup` override for `.glb`.+pub fn import_mesh_bytes_with_opts(bytes: &[u8], ext: &str, yup: Option<bool>) -> Result<PolyMesh, String> {match ext.trim_start_matches('.').to_lowercase().as_str() {- "glb" => read_glb_bytes(bytes),+ "glb" => read_glb_bytes_with_opts(bytes, yup),"obj" => read_obj_bytes(bytes),"stl" => read_stl_bytes(bytes),other => Err(format!("unsupported import extension '.{other}' (supported: .glb, .obj, .stl)")),}}-/// Import mesh file from disk by extension (`.glb`, `.obj`, `.stl`).-pub fn import_mesh(path: &Path) -> Result<PolyMesh, String> {+/// Import mesh bytes by format extension (`glb`, `obj`, `stl`).+pub fn import_mesh_bytes(bytes: &[u8], ext: &str) -> Result<PolyMesh, String> {+ import_mesh_bytes_with_opts(bytes, ext, None)+}++/// Import mesh file from disk by extension (`.glb`, `.obj`, `.stl`) with optional `yup` override for `.glb`.+pub fn import_mesh_with_opts(path: &Path, yup: Option<bool>) -> Result<PolyMesh, String> {let ext = path.extension().and_then(|s| s.to_str()).unwrap_or("");let bytes = std::fs::read(path).map_err(|e| format!("read {}: {e}", path.display()))?;- import_mesh_bytes(&bytes, ext)+ import_mesh_bytes_with_opts(&bytes, ext, yup)+}++/// Import mesh file from disk by extension (`.glb`, `.obj`, `.stl`).+pub fn import_mesh(path: &Path) -> Result<PolyMesh, String> {+ import_mesh_with_opts(path, None)}diff --git a/crates/forma-core/src/invariants.rs b/crates/forma-core/src/invariants.rsindex 78b2105..56daa08 100644--- a/crates/forma-core/src/invariants.rs+++ b/crates/forma-core/src/invariants.rs@@ -155,7 +155,8 @@ impl MeshInvariants {let euler = (verts as i64) - (edges as i64) + (faces as i64);let signed_volume = vol6 / 6.0;- let watertight = faces > 0 && boundary_edges == 0 && non_manifold_edges == 0 && nan_verts == 0;+ let watertight =+ faces > 0 && boundary_edges == 0 && non_manifold_edges == 0 && nan_verts == 0 && consistent_winding;let genus = if watertight {((2 * (components as i64) - euler) / 2).max(0)} else {@@ -191,7 +192,11 @@ impl MeshInvariants {}pub fn is_valid_solid(&self) -> bool {- self.watertight && self.consistent_winding && self.nan_verts == 0 && self.signed_volume > 0.0+ self.watertight+ && self.consistent_winding+ && self.non_manifold_edges == 0+ && self.nan_verts == 0+ && self.signed_volume > 1e-12}pub fn summary_line(&self, name: &str) -> String {diff --git a/crates/forma-core/src/ops.rs b/crates/forma-core/src/ops.rsindex c097486..b7dcd54 100644--- a/crates/forma-core/src/ops.rs+++ b/crates/forma-core/src/ops.rs@@ -950,7 +950,8 @@ pub fn mirror_mesh(mesh: &PolyMesh, axis: char, union_with_orig: bool, op_id: u3}}-/// Repeat a mesh linearly (or union all instances).+/// Repeat a mesh linearly (defaulting to union for overlapping instances; pairwise-disjoint+/// instances use an O(1) AABB fast-path with zero CSG overhead).pub fn array_linear(mesh: &PolyMesh,count: usize,@@ -966,45 +967,72 @@ pub fn array_linear(return Err(format!("array count {count} exceeds limit ({max_cnt})"));}let mut acc = mesh.clone();+ let mut inst_bbs: Vec<crate::math::Aabb> = Vec::with_capacity(count);+ inst_bbs.push(mesh.aabb());for i in 1..count {let mut inst = mesh.clone();inst.translate(step * (i as f64));- if union_all {+ let ibb = inst.aabb();+ if union_all && inst_bbs.iter().any(|b| b.overlaps(&ibb, 1e-5)) {acc = boolean_op(&acc, &inst, BoolOp::Union, None, op_id)?;} else {acc.append_mesh(&inst);}+ inst_bbs.push(ibb);}Ok(acc)}-/// Repeat a mesh radially around the Z axis.-pub fn array_radial(+/// Repeat a mesh radially around the Z axis, optionally offset radially by `radius` along +X before rotating.+/// Pairwise-disjoint instances use an O(1) AABB fast-path with zero CSG overhead.+pub fn array_radial_with_radius(mesh: &PolyMesh,count: usize,+ radius: f64,union_all: bool,op_id: u32,) -> Result<PolyMesh, String> {if count == 0 {return Err("radial array count must be >= 1".into());}+ if !radius.is_finite() {+ return Err("radial array radius must be finite".into());+ }let max_cnt = if union_all { 32 } else { 64 };if count > max_cnt {return Err(format!("radial array count {count} exceeds limit ({max_cnt})"));}- let mut acc = mesh.clone();+ let mut base = mesh.clone();+ if radius.abs() > 1e-12 {+ base.translate(Vec3::new(radius, 0.0, 0.0));+ }+ let mut acc = base.clone();+ let mut inst_bbs: Vec<crate::math::Aabb> = Vec::with_capacity(count);+ inst_bbs.push(base.aabb());for i in 1..count {- let mut inst = mesh.clone();+ let mut inst = base.clone();inst.rotate_deg(0.0, 0.0, 360.0 * (i as f64) / (count as f64));- if union_all {+ let ibb = inst.aabb();+ if union_all && inst_bbs.iter().any(|b| b.overlaps(&ibb, 1e-5)) {acc = boolean_op(&acc, &inst, BoolOp::Union, None, op_id)?;} else {acc.append_mesh(&inst);}+ inst_bbs.push(ibb);}Ok(acc)}+/// Repeat a mesh radially around the Z axis (zero radial offset).+pub fn array_radial(+ mesh: &PolyMesh,+ count: usize,+ union_all: bool,+ op_id: u32,+) -> Result<PolyMesh, String> {+ array_radial_with_radius(mesh, count, 0.0, union_all, op_id)+}+/// Topology-preserving Quadric Error Metric (QEM) mesh decimation with Edelsbrunner Link-Condition./// Reduces face count toward `target_ratio` (in `(0.05..=1.0]`) or `target_faces` while keeping/// watertight manifold solids watertight (`NM=0`) and preventing normal flips.diff --git a/crates/forma-core/src/primitives.rs b/crates/forma-core/src/primitives.rsindex 14d1e08..df3097e 100644--- a/crates/forma-core/src/primitives.rs+++ b/crates/forma-core/src/primitives.rs@@ -8,6 +8,9 @@ use std::f64::consts::PI;/// Axis-aligned box centered at the origin with dimensions (sx, sy, sz).pub fn make_box(sx: f64, sy: f64, sz: f64, op_id: u32) -> PolyMesh {+ if !sx.is_finite() || !sy.is_finite() || !sz.is_finite() || sx <= 1e-9 || sy <= 1e-9 || sz <= 1e-9 {+ return PolyMesh::new();+ }let hx = sx * 0.5;let hy = sy * 0.5;let hz = sz * 0.5;@@ -43,7 +46,14 @@ pub fn make_cone(r_bot: f64, r_top: f64, height: f64, segs: usize, op_id: u32) -let hz = height * 0.5;let mut m = PolyMesh::new();- if r_top <= 1e-9 && r_bot <= 1e-9 {+ if !height.is_finite()+ || height <= 1e-9+ || !r_bot.is_finite()+ || !r_top.is_finite()+ || r_bot < 0.0+ || r_top < 0.0+ || (r_top <= 1e-9 && r_bot <= 1e-9)+ {return m;}@@ -104,6 +114,9 @@ pub fn make_cone(r_bot: f64, r_top: f64, height: f64, segs: usize, op_id: u32) -/// UV sphere centered at origin.pub fn make_sphere(radius: f64, u_segs: usize, v_segs: usize, op_id: u32) -> PolyMesh {+ if !radius.is_finite() || radius <= 1e-9 {+ return PolyMesh::new();+ }let u_segs = u_segs.clamp(4, 36);let v_segs = v_segs.clamp(3, 18);let mut m = PolyMesh::new();@@ -148,6 +161,9 @@ pub fn make_sphere(radius: f64, u_segs: usize, v_segs: usize, op_id: u32) -> Pol/// Torus centered at origin lying in the XY plane.pub fn make_torus(major_r: f64, minor_r: f64, major_segs: usize, minor_segs: usize, op_id: u32) -> PolyMesh {+ if !major_r.is_finite() || !minor_r.is_finite() || major_r <= 1e-9 || minor_r <= 1e-9 {+ return PolyMesh::new();+ }let major_segs = major_segs.clamp(6, 48);let minor_segs = minor_segs.clamp(4, 32);let mut m = PolyMesh::new();@@ -264,6 +280,9 @@ pub fn make_revolve(profile: &[(f64, f64)], segs: usize, op_id: u32) -> Result<P/// Sweep a circular tube along a 3D polyline using twist-free parallel transport frames.pub fn make_tube(points: &[Vec3], radius: f64, ring_segs: usize, closed: bool, op_id: u32) -> Result<PolyMesh, String> {+ if !radius.is_finite() || radius <= 1e-9 {+ return Err(format!("tube requires radius > 0 (got {radius})"));+ }if points.len() < 2 {return Err("tube requires at least 2 path points".into());}@@ -361,6 +380,15 @@ pub fn make_arc_tube(ring_segs: usize,op_id: u32,) -> Result<PolyMesh, String> {+ if !tube_r.is_finite() || tube_r <= 1e-9 {+ return Err(format!("arc_tube requires r > 0 (got {tube_r})"));+ }+ if !rx.is_finite() || !rz.is_finite() || (rx.abs() <= 1e-9 && rz.abs() <= 1e-9) {+ return Err(format!("arc_tube requires non-zero rx or rz (got rx={rx}, rz={rz})"));+ }+ if !(end_deg - start_deg).is_finite() || (end_deg - start_deg).abs() <= 1e-6 {+ return Err("arc_tube requires non-zero angular span".into());+ }let arc_segs = arc_segs.clamp(4, 64);let mut pts = Vec::with_capacity(arc_segs + 1);for i in 0..=arc_segs {@@ -375,6 +403,9 @@ pub fn make_extrude_2d(pts_2d: &[(f64, f64)], z0: f64, z1: f64, op_id: u32) -> Rif pts_2d.len() < 3 {return Err("extrude_2d requires at least 3 2D points".into());}+ if !z0.is_finite() || !z1.is_finite() || (z1 - z0).abs() <= 1e-9 {+ return Err(format!("extrude_2d requires |z1 - z0| > 0 (got z0={z0}, z1={z1})"));+ }// Ensure CCW winding in XYlet mut area2 = 0.0;let n = pts_2d.len();@@ -383,6 +414,9 @@ pub fn make_extrude_2d(pts_2d: &[(f64, f64)], z0: f64, z1: f64, op_id: u32) -> Rlet (x1, y1) = pts_2d[(i + 1) % n];area2 += x0 * y1 - x1 * y0;}+ if !area2.is_finite() || area2.abs() <= 1e-12 {+ return Err("extrude_2d requires non-degenerate 2D polygon with positive area".into());+ }let pts: Vec<(f64, f64)> = if area2 < 0.0 {pts_2d.iter().rev().copied().collect()} else {diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rsindex 0c6be28..c9b584f 100644--- a/crates/forma-core/src/scene.rs+++ b/crates/forma-core/src/scene.rs@@ -57,6 +57,7 @@ pub struct Scene {pub strict_manifold: bool,pub allow_fs_import: bool,pub max_faces_per_part: usize,+ pub max_statements: usize,pub assets: BTreeMap<String, Vec<u8>>,pub query_notes: Vec<String>,}@@ -78,6 +79,7 @@ impl Scene {strict_manifold: false,allow_fs_import: true,max_faces_per_part: 200_000,+ max_statements: 4_096,assets: BTreeMap::new(),query_notes: Vec::new(),}@@ -93,21 +95,27 @@ impl Scene {self.assets.insert(name.into(), bytes);}- /// Load a mesh from attached in-memory assets or (if `allow_fs_import`) from disk.- pub fn load_asset_mesh(&self, path_or_key: &str) -> Result<PolyMesh, String> {+ /// Load a mesh from attached in-memory assets or (if `allow_fs_import`) from disk,+ /// with an optional explicit `yup` override for `.glb` imports.+ pub fn load_asset_mesh_with_opts(&self, path_or_key: &str, yup: Option<bool>) -> Result<PolyMesh, String> {if let Some(bytes) = self.assets.get(path_or_key) {let ext = Path::new(path_or_key).extension().and_then(|s| s.to_str()).unwrap_or("glb");- return crate::import::import_mesh_bytes(bytes, ext);+ return crate::import::import_mesh_bytes_with_opts(bytes, ext, yup);}if !self.allow_fs_import {return Err(format!("filesystem import disabled in sandboxed mode; upload '{path_or_key}' in request assets"));}- crate::import::import_mesh(Path::new(path_or_key))+ crate::import::import_mesh_with_opts(Path::new(path_or_key), yup)+ }++ /// Load a mesh from attached in-memory assets or (if `allow_fs_import`) from disk.+ pub fn load_asset_mesh(&self, path_or_key: &str) -> Result<PolyMesh, String> {+ self.load_asset_mesh_with_opts(path_or_key, None)}pub fn push_note(&mut self, note: impl Into<String>) {@@ -226,16 +234,40 @@ impl Scene {self.max_faces_per_part)));}- mesh.ensure_outward_winding();- let inv = MeshInvariants::compute(&mesh);- if self.strict_manifold && (!inv.watertight || inv.non_manifold_edges > 0) {- return Err(SceneError::InvariantViolation {- part: name,- reason: format!(- "non-manifold result (WT={}, NM={}, B={})",- inv.watertight, inv.non_manifold_edges, inv.boundary_edges- ),- });+ let mut inv = MeshInvariants::compute(&mesh);+ if inv.boundary_edges == 0 && inv.signed_volume < 0.0 {+ mesh.flip_winding();+ inv = MeshInvariants::compute(&mesh);+ }+ if self.strict_manifold {+ if !inv.watertight || !inv.consistent_winding || inv.non_manifold_edges > 0 || inv.nan_verts > 0 {+ return Err(SceneError::InvariantViolation {+ part: name,+ reason: format!(+ "non-manifold result (WT={}, CW={}, NM={}, B={}, NaN={})",+ inv.watertight,+ inv.consistent_winding,+ inv.non_manifold_edges,+ inv.boundary_edges,+ inv.nan_verts+ ),+ });+ }+ if inv.signed_volume <= 1e-12 || inv.volume <= 1e-12 {+ return Err(SceneError::InvariantViolation {+ part: name,+ reason: format!("zero or negative volume solid (vol={:.3e})", inv.signed_volume),+ });+ }+ if inv.components > 1 && crate::boolean::has_overlapping_components(&mesh) {+ return Err(SceneError::InvariantViolation {+ part: name,+ reason: format!(+ "overlapping/self-intersecting multi-shell mesh ({} components overlap; use union=true or separate instances)",+ inv.components+ ),+ });+ }}self.last_modified = Some(name.clone());self.parts.insert(name, Arc::new(mesh));@@ -256,6 +288,11 @@ impl Scene {// --- High-level modeling commands ---pub fn add_box(&mut self, name: &str, sx: f64, sy: f64, sz: f64, at: Vec3) -> Result<MeshInvariants, SceneError> {+ if !sx.is_finite() || !sy.is_finite() || !sz.is_finite() || sx <= 1e-9 || sy <= 1e-9 || sz <= 1e-9 {+ return Err(SceneError::OpFailed(format!(+ "box requires positive dimensions (sx={sx}, sy={sy}, sz={sz})"+ )));+ }let op = self.next_op();let mut m = primitives::make_box(sx, sy, sz, op);m.translate(at);@@ -263,6 +300,11 @@ impl Scene {}pub fn add_cyl(&mut self, name: &str, r: f64, h: f64, segs: usize, at: Vec3, axis: char) -> Result<MeshInvariants, SceneError> {+ if !r.is_finite() || !h.is_finite() || r <= 1e-9 || h <= 1e-9 {+ return Err(SceneError::OpFailed(format!(+ "cyl requires positive radius and height (r={r}, h={h})"+ )));+ }let op = self.next_op();let mut m = primitives::make_cylinder(r, h, segs, op);match axis.to_ascii_lowercase() {@@ -275,6 +317,11 @@ impl Scene {}pub fn add_cone(&mut self, name: &str, r_bot: f64, r_top: f64, h: f64, segs: usize, at: Vec3, axis: char) -> Result<MeshInvariants, SceneError> {+ if !h.is_finite() || h <= 1e-9 || !r_bot.is_finite() || !r_top.is_finite() || r_bot < 0.0 || r_top < 0.0 || r_bot.max(r_top) <= 1e-9 {+ return Err(SceneError::OpFailed(format!(+ "cone requires positive height and at least one positive radius (r0={r_bot}, r1={r_top}, h={h})"+ )));+ }let op = self.next_op();let mut m = primitives::make_cone(r_bot, r_top, h, segs, op);match axis.to_ascii_lowercase() {@@ -287,6 +334,9 @@ impl Scene {}pub fn add_sphere(&mut self, name: &str, r: f64, u: usize, v: usize, at: Vec3) -> Result<MeshInvariants, SceneError> {+ if !r.is_finite() || r <= 1e-9 {+ return Err(SceneError::OpFailed(format!("sphere requires positive radius (r={r})")));+ }let op = self.next_op();let mut m = primitives::make_sphere(r, u, v, op);m.translate(at);@@ -294,6 +344,11 @@ impl Scene {}pub fn add_torus(&mut self, name: &str, major: f64, minor: f64, maj_s: usize, min_s: usize, at: Vec3) -> Result<MeshInvariants, SceneError> {+ if !major.is_finite() || !minor.is_finite() || major <= 1e-9 || minor <= 1e-9 {+ return Err(SceneError::OpFailed(format!(+ "torus requires positive major and minor radii (R={major}, r={minor})"+ )));+ }let op = self.next_op();let mut m = primitives::make_torus(major, minor, maj_s, min_s, op);m.translate(at);@@ -385,6 +440,14 @@ impl Scene {}pub fn transform(&mut self, target: &str, translate: Vec3, rotate_deg: Vec3, scale: Vec3) -> Result<MeshInvariants, SceneError> {+ if !scale.x.is_finite() || !scale.y.is_finite() || !scale.z.is_finite()+ || scale.x.abs() <= 1e-9 || scale.y.abs() <= 1e-9 || scale.z.abs() <= 1e-9+ {+ return Err(SceneError::OpFailed(format!(+ "scale requires non-zero finite axes (sx={}, sy={}, sz={})",+ scale.x, scale.y, scale.z+ )));+ }let mut m = (**self.get_part(target)?).clone();if (scale.x - 1.0).abs() > 1e-12 || (scale.y - 1.0).abs() > 1e-12 || (scale.z - 1.0).abs() > 1e-12 {m.scale(scale);@@ -470,11 +533,11 @@ impl Scene {let mut all_manifold = true;for (name, mesh) in &self.parts {let inv = MeshInvariants::compute(mesh);- if !inv.watertight || inv.non_manifold_edges > 0 || inv.nan_verts > 0 {+ if !inv.watertight || !inv.consistent_winding || inv.non_manifold_edges > 0 || inv.nan_verts > 0 || inv.volume <= 1e-12 {all_manifold = false;warnings.push(format!(- "part '{name}' non-manifold (WT={} NM={} B={})",- inv.watertight, inv.non_manifold_edges, inv.boundary_edges+ "part '{name}' invalid solid (WT={} CW={} NM={} B={} vol={:.3e})",+ inv.watertight, inv.consistent_winding, inv.non_manifold_edges, inv.boundary_edges, inv.volume));}if inv.degenerate_faces > 0 {diff --git a/crates/forma-core/tests/kernel_tests.rs b/crates/forma-core/tests/kernel_tests.rsindex 2ee5604..d34a88b 100644--- a/crates/forma-core/tests/kernel_tests.rs+++ b/crates/forma-core/tests/kernel_tests.rs@@ -411,3 +411,186 @@ fn test_v04_step_blueprint_svg_sweep_and_text3d() {let svg_txt = std::fs::read_to_string(&svg_path).unwrap();assert!(svg_txt.starts_with("<svg ") && svg_txt.contains("PART: L_RAIL") && svg_txt.contains("WATERTIGHT"));}++#[test]+fn test_issue_1_strict_patterns_zero_vol_and_scale_invariant_csg() {+ // 1. Overlapping linear pattern: union=true merges cleanly; union=false rejected under strict+ let mut s = Scene::new();+ s.strict_manifold = true;+ s.add_box("b", 1.0, 1.0, 1.0, Vec3::ZERO).unwrap();+ let inv_u = s.array_linear("b", 3, Vec3::new(0.5, 0.0, 0.0), true).unwrap();+ assert!(inv_u.is_valid_solid() && inv_u.components == 1);+ assert!((inv_u.volume - 2.0).abs() < 1e-4, "expected vol=2.0 got {}", inv_u.volume);++ let mut s2 = Scene::new();+ s2.strict_manifold = true;+ s2.add_box("b", 1.0, 1.0, 1.0, Vec3::ZERO).unwrap();+ assert!(+ s2.array_linear("b", 3, Vec3::new(0.5, 0.0, 0.0), false).is_err(),+ "overlapping multi-shell linear pattern with union=false must fail strict mode"+ );++ // Disjoint linear pattern passes strict via O(1) AABB fast-path+ let inv_d = s2.array_linear("b", 3, Vec3::new(2.0, 0.0, 0.0), true).unwrap();+ assert!(inv_d.is_valid_solid() && inv_d.components == 3 && (inv_d.volume - 3.0).abs() < 1e-4);++ // 2. Radial pattern: r=0 overlapping vs r=2.0 disjoint+ let cyl = forma_core::primitives::make_cylinder(1.0, 0.2, 16, 1);+ let rad_u = forma_core::ops::array_radial_with_radius(&cyl, 6, 0.0, true, 2).unwrap();+ let mut sr = Scene::new();+ sr.strict_manifold = true;+ let inv_ru = sr.set_part("ru", rad_u).unwrap();+ assert!(inv_ru.is_valid_solid() && inv_ru.components == 1);++ let rad_bad = forma_core::ops::array_radial_with_radius(&cyl, 6, 0.0, false, 3).unwrap();+ assert!(+ sr.set_part("rb", rad_bad).is_err(),+ "overlapping radial pattern with union=false must fail strict mode"+ );++ let small_cyl = forma_core::primitives::make_cylinder(0.25, 0.5, 16, 4);+ let rad_disjoint = forma_core::ops::array_radial_with_radius(&small_cyl, 6, 2.0, true, 5).unwrap();+ let inv_rd = sr.set_part("rd", rad_disjoint).unwrap();+ assert!(inv_rd.is_valid_solid() && inv_rd.components == 6);++ // 3. Zero/negative dimensions and zero-scale rejected+ let mut sv = Scene::new();+ sv.strict_manifold = true;+ assert!(sv.add_box("z0", 0.0, 1.0, 1.0, Vec3::ZERO).is_err());+ assert!(sv.add_cyl("z1", 1.0, 0.0, 16, Vec3::ZERO, 'z').is_err());+ assert!(sv.add_cone("z2", 0.0, 0.0, 1.0, 16, Vec3::ZERO, 'z').is_err());+ assert!(sv.add_sphere("z3", 0.0, 16, 8, Vec3::ZERO).is_err());+ assert!(sv.add_torus("z4", 1.0, 0.0, 16, 8, Vec3::ZERO).is_err());+ assert!(forma_core::primitives::make_extrude_2d(&[(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], 0.0, 0.0, 1).is_err());+ sv.add_box("ok", 1.0, 1.0, 1.0, Vec3::ZERO).unwrap();+ assert!(sv.transform("ok", Vec3::ZERO, Vec3::ZERO, Vec3::new(0.0, 1.0, 1.0)).is_err());++ // 4. Inconsistent winding rejected by watertight & strict mode+ let mut bad_wind = forma_core::primitives::make_box(1.0, 1.0, 1.0, 10);+ bad_wind.faces[0].verts.reverse();+ let bw_inv = MeshInvariants::compute(&bad_wind);+ assert!(!bw_inv.consistent_winding && !bw_inv.watertight);+ assert!(sv.set_part("bw", bad_wind).is_err());++ // 5. Closed hollow shell (2 components: positive outer + negative inner void) MUST pass strict+ let mut sh = Scene::new();+ sh.strict_manifold = true;+ sh.add_box("hollow", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();+ let sh_inv = sh.shell("hollow", 0.2, false).unwrap();+ assert!(sh_inv.is_valid_solid() && sh_inv.components == 2);+ assert!((sh_inv.volume - (8.0 - 1.6_f64.powi(3))).abs() < 1e-3);++ // 6. Scale-invariant boolean_op at 1e-3 (mm) and 1e+3 (km) scales+ for scale in [1e-3_f64, 1e+3_f64] {+ let mut sc = Scene::new();+ sc.strict_manifold = true;+ sc.add_box("plate", 4.0 * scale, 2.0 * scale, 0.4 * scale, Vec3::ZERO).unwrap();+ sc.add_cyl("hole", 0.5 * scale, 1.0 * scale, 24, Vec3::ZERO, 'z').unwrap();+ let inv = sc.boolean_parts("plate", "hole", BoolOp::Difference, false).unwrap();+ assert!(inv.is_valid_solid(), "scale={scale} boolean failed: {inv:?}");+ let exp_vol = (4.0 * 2.0 - std::f64::consts::PI * 0.25) * 0.4 * scale.powi(3);+ let rel_err = (inv.volume - exp_vol).abs() / exp_vol;+ assert!(rel_err < 0.02, "scale={scale} vol err={rel_err:.4}");+ }+}++#[test]+fn test_glb_yup_roundtrip_legacy_compat_and_import_fixes() {+ use forma_core::export::{export_mesh_bytes, write_glb_bytes};+ use forma_core::import::{read_glb_bytes, read_glb_bytes_with_opts, read_obj_bytes};++ // 1. Asymmetric box at asymmetric offset: Forma Z-up -> GLB Y-up -> Forma Z-up exact round-trip+ let mut orig = forma_core::primitives::make_box(4.0, 2.0, 1.0, 1);+ orig.translate(Vec3::new(0.5, -1.0, 3.0));+ let orig_bb = orig.aabb();++ let glb_yup = export_mesh_bytes(&orig, "glb").unwrap();+ // Verify GLB header JSON stamps forma_yup:true and stores Y-up coordinates (height 1.0 along glTF Y)+ let jlen = u32::from_le_bytes([glb_yup[12], glb_yup[13], glb_yup[14], glb_yup[15]]) as usize;+ let gltf: serde_json::Value = serde_json::from_slice(&glb_yup[20..20 + jlen]).unwrap();+ assert_eq!(gltf["asset"]["extras"]["forma_yup"].as_bool(), Some(true));+ let acc_min = gltf["accessors"][0]["min"].as_array().unwrap();+ let acc_max = gltf["accessors"][0]["max"].as_array().unwrap();+ let gltf_dy = acc_max[1].as_f64().unwrap() - acc_min[1].as_f64().unwrap();+ let gltf_dz = acc_max[2].as_f64().unwrap() - acc_min[2].as_f64().unwrap();+ assert!((gltf_dy - 1.0).abs() < 1e-4, "glTF Y extent should be Forma Z=1.0, got {gltf_dy}");+ assert!((gltf_dz - 2.0).abs() < 1e-4, "glTF Z extent should be Forma Y=2.0, got {gltf_dz}");++ // Round-trip back into Forma Z-up+ let rt = read_glb_bytes(&glb_yup).unwrap();+ let rt_inv = MeshInvariants::compute(&rt);+ assert!(rt_inv.is_valid_solid(), "round-tripped GLB must be valid solid: {rt_inv:?}");+ let rt_bb = rt.aabb();+ assert!((rt_bb.min - orig_bb.min).len() < 1e-4, "min mismatch: {:?} vs {:?}", rt_bb.min, orig_bb.min);+ assert!((rt_bb.max - orig_bb.max).len() < 1e-4, "max mismatch: {:?} vs {:?}", rt_bb.max, orig_bb.max);++ // 2. Explicit yup=false export stamps forma_yup:false and round-trips without rotating+ let glb_zup = write_glb_bytes(&orig, false).unwrap();+ let rt_zup = read_glb_bytes(&glb_zup).unwrap();+ assert!((rt_zup.aabb().min - orig_bb.min).len() < 1e-4);+ assert!((rt_zup.aabb().max - orig_bb.max).len() < 1e-4);++ // Legacy forma-core 0.2 GLB (without extras.forma_yup) stays Z-up by default+ let mut legacy_json = gltf.clone();+ legacy_json["asset"] = serde_json::json!({"version": "2.0", "generator": "forma-core 0.2"});+ let glb_raw_z = write_glb_bytes(&orig, false).unwrap();+ let ljlen = u32::from_le_bytes([glb_raw_z[12], glb_raw_z[13], glb_raw_z[14], glb_raw_z[15]]) as usize;+ let bin_part = &glb_raw_z[20 + ljlen..];+ let mut legacy_gltf: serde_json::Value = serde_json::from_slice(&glb_raw_z[20..20 + ljlen]).unwrap();+ legacy_gltf["asset"] = serde_json::json!({"version": "2.0", "generator": "forma-core 0.2"});+ let mut ljb = legacy_gltf.to_string().into_bytes();+ while ljb.len() % 4 != 0 {+ ljb.push(b' ');+ }+ let ltot = 12 + 8 + ljb.len() + bin_part.len();+ let mut legacy_glb = Vec::with_capacity(ltot);+ legacy_glb.extend_from_slice(&0x46546C67u32.to_le_bytes());+ legacy_glb.extend_from_slice(&2u32.to_le_bytes());+ legacy_glb.extend_from_slice(&(ltot as u32).to_le_bytes());+ legacy_glb.extend_from_slice(&(ljb.len() as u32).to_le_bytes());+ legacy_glb.extend_from_slice(&0x4E4F534Au32.to_le_bytes());+ legacy_glb.extend_from_slice(&ljb);+ legacy_glb.extend_from_slice(bin_part);+ let rt_legacy = read_glb_bytes(&legacy_glb).unwrap();+ assert!((rt_legacy.aabb().size() - orig_bb.size()).len() < 1e-4);++ // Explicit override yup=true rotates Z-up data+ let forced = read_glb_bytes_with_opts(&glb_zup, Some(true)).unwrap();+ assert!((forced.aabb().size().z - 2.0).abs() < 1e-4);++ // 3. Mirrored node (negative determinant scale=[-1,1,1]) + inactive scene node filtering+ let mut mir_gltf: serde_json::Value = serde_json::from_slice(&glb_yup[20..20 + jlen]).unwrap();+ mir_gltf["nodes"] = serde_json::json!([+ {"mesh": 0, "scale": [-1.0, 1.0, 1.0]},+ {"mesh": 0, "translation": [100.0, 0.0, 0.0]}+ ]);+ mir_gltf["scene"] = serde_json::json!(0);+ mir_gltf["scenes"] = serde_json::json!([+ {"nodes": [0]},+ {"nodes": [1]}+ ]);+ let mut mjb = mir_gltf.to_string().into_bytes();+ while mjb.len() % 4 != 0 {+ mjb.push(b' ');+ }+ let mbin = &glb_yup[20 + jlen..];+ let mtot = 12 + 8 + mjb.len() + mbin.len();+ let mut mir_glb = Vec::with_capacity(mtot);+ mir_glb.extend_from_slice(&0x46546C67u32.to_le_bytes());+ mir_glb.extend_from_slice(&2u32.to_le_bytes());+ mir_glb.extend_from_slice(&(mtot as u32).to_le_bytes());+ mir_glb.extend_from_slice(&(mjb.len() as u32).to_le_bytes());+ mir_glb.extend_from_slice(&0x4E4F534Au32.to_le_bytes());+ mir_glb.extend_from_slice(&mjb);+ mir_glb.extend_from_slice(mbin);+ let mir_mesh = read_glb_bytes(&mir_glb).unwrap();+ let mir_inv = MeshInvariants::compute(&mir_mesh);+ assert!(mir_inv.is_valid_solid(), "mirrored node must preserve outward winding: {mir_inv:?}");+ assert_eq!(mir_inv.components, 1, "inactive scene 1 node must not be imported");++ // 4. Open mesh must NOT be inverted by ensure_outward_winding_if_closed+ let open_obj = b"v 0 0 -10\nv 1 0 -10\nv 1 1 -10\nv 0 1 -10\nf 1 2 3 4\n";+ let open_mesh = read_obj_bytes(open_obj).unwrap();+ let n = open_mesh.face_normal(0);+ assert!(n.z > 0.99, "open quad +Z normal must not be inverted at negative Z, got {n:?}");+}diff --git a/crates/forma-lang/src/compact.rs b/crates/forma-lang/src/compact.rsindex be28157..990b314 100644--- a/crates/forma-lang/src/compact.rs+++ b/crates/forma-lang/src/compact.rs@@ -73,6 +73,9 @@ fn parse_prim(let sy = parse_f(tokens[idx + 1], line)?;let sz = parse_f(tokens[idx + 2], line)?;idx += 3;+ if !sx.is_finite() || !sy.is_finite() || !sz.is_finite() || sx <= 1e-9 || sy <= 1e-9 || sz <= 1e-9 {+ return Err(format!("line {line}: box requires positive dimensions (sx={sx}, sy={sy}, sz={sz})"));+ }forma_core::primitives::make_box(sx, sy, sz, op_id)}"cyl" => {@@ -82,6 +85,9 @@ fn parse_prim(let r = parse_f(tokens[idx], line)?;let h = parse_f(tokens[idx + 1], line)?;idx += 2;+ if !r.is_finite() || !h.is_finite() || r <= 1e-9 || h <= 1e-9 {+ return Err(format!("line {line}: cyl requires positive radius and height (r={r}, h={h})"));+ }let mut segs = 32usize;if idx < tokens.len() && !is_opt_kw(tokens[idx]) && !is_axis_tok(tokens[idx]) {segs = parse_f(tokens[idx], line)? as usize;@@ -101,6 +107,9 @@ fn parse_prim(let r1 = parse_f(tokens[idx + 1], line)?;let h = parse_f(tokens[idx + 2], line)?;idx += 3;+ if !h.is_finite() || h <= 1e-9 || !r0.is_finite() || !r1.is_finite() || r0 < 0.0 || r1 < 0.0 || r0.max(r1) <= 1e-9 {+ return Err(format!("line {line}: cone requires positive height and at least one positive radius"));+ }let mut segs = 32usize;if idx < tokens.len() && !is_opt_kw(tokens[idx]) && !is_axis_tok(tokens[idx]) {segs = parse_f(tokens[idx], line)? as usize;@@ -118,6 +127,9 @@ fn parse_prim(}let r = parse_f(tokens[idx], line)?;idx += 1;+ if !r.is_finite() || r <= 1e-9 {+ return Err(format!("line {line}: sphere requires positive radius (r={r})"));+ }let mut segs = 32usize;if idx < tokens.len() && !is_opt_kw(tokens[idx]) {segs = parse_f(tokens[idx], line)? as usize;@@ -132,6 +144,9 @@ fn parse_prim(let maj = parse_f(tokens[idx], line)?;let min = parse_f(tokens[idx + 1], line)?;idx += 2;+ if !maj.is_finite() || !min.is_finite() || maj <= 1e-9 || min <= 1e-9 {+ return Err(format!("line {line}: torus requires positive major and minor radii"));+ }forma_core::primitives::make_torus(maj, min, 32, 16, op_id)}"rev" => {@@ -284,12 +299,17 @@ fn is_prim_kw(tok: &str) -> bool {}pub fn eval_compact(scene: &mut Scene, src: &str) -> Result<(), String> {+ let mut stmts = 0usize;for (li, raw_line) in src.lines().enumerate() {let line = li + 1;let stripped = raw_line.split('#').next().unwrap_or("").trim();if stripped.is_empty() {continue;}+ stmts += 1;+ if scene.max_statements > 0 && stmts > scene.max_statements {+ return Err(format!("script exceeds maximum statement limit ({})", scene.max_statements));+ }// Normalize commas around '@' while keeping `r,z` pairs intactlet normalized = stripped.replace(" ,", ",").replace(", ", " , ");let tokens: Vec<&str> = normalized.split_whitespace().collect();diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rsindex 0b7eea6..6ede451 100644--- a/crates/forma-lang/src/pipeline.rs+++ b/crates/forma-lang/src/pipeline.rs@@ -220,9 +220,8 @@ impl Val {}}-const MAX_PARSE_DEPTH: usize = 64;-const MAX_STATEMENTS: usize = 256;-const MAX_BATCH_POINTS: usize = 64;+const MAX_PARSE_DEPTH: usize = 128;+const MAX_BATCH_POINTS: usize = 512;fn check_finite(v: f64, ctx: &str) -> Result<f64, String> {if v.is_finite() {@@ -283,8 +282,9 @@ impl<'a> Parser<'a> {break;}self.stmts += 1;- if self.stmts > MAX_STATEMENTS {- return Err(format!("script exceeds maximum statement limit ({MAX_STATEMENTS})"));+ let max_stmts = self.scene.max_statements;+ if max_stmts > 0 && self.stmts > max_stmts {+ return Err(format!("script exceeds maximum statement limit ({max_stmts})"));}self.parse_stmt()?;while matches!(self.peek(), Tok::Newline) {@@ -613,11 +613,17 @@ impl<'a> Parser<'a> {let sx = get_num_any(0, &["sx", "x", "w", "width"], None)?;let sy = get_num_any(1, &["sy", "y", "d", "depth"], Some(sx))?;let sz = get_num_any(2, &["sz", "z", "h", "height"], Some(sy))?;+ if !sx.is_finite() || !sy.is_finite() || !sz.is_finite() || sx <= 1e-9 || sy <= 1e-9 || sz <= 1e-9 {+ return Err(format!("{ctx}: box requires positive dimensions (sx={sx}, sy={sy}, sz={sz})"));+ }forma_core::primitives::make_box(sx, sy, sz, op_id)}"cyl" | "cylinder" | "prism" => {let r = get_num_any(0, &["r", "radius"], None)?;let h = get_num_any(1, &["h", "height", "len", "length"], None)?;+ if !r.is_finite() || !h.is_finite() || r <= 1e-9 || h <= 1e-9 {+ return Err(format!("{ctx}: cyl requires positive radius and height (r={r}, h={h})"));+ }let segs = get_num_any(2, &["segs", "segments", "sides"], Some(32.0))? as usize;let mut m = forma_core::primitives::make_cylinder(r, h, segs, op_id);let axis = kw@@ -636,6 +642,9 @@ impl<'a> Parser<'a> {let r0 = get_num_any(0, &["r0", "r_bot", "r_bottom"], None)?;let r1 = get_num_any(1, &["r1", "r_top"], None)?;let h = get_num_any(2, &["h", "height"], None)?;+ if !h.is_finite() || h <= 1e-9 || !r0.is_finite() || !r1.is_finite() || r0 < 0.0 || r1 < 0.0 || r0.max(r1) <= 1e-9 {+ return Err(format!("{ctx}: cone requires positive height and at least one positive radius (r0={r0}, r1={r1}, h={h})"));+ }let segs = get_num_any(3, &["segs", "segments"], Some(32.0))? as usize;let mut m = forma_core::primitives::make_cone(r0, r1, h, segs, op_id);if let Some(ax) = kw.get("axis").and_then(|v| v.as_str(&ctx).ok()) {@@ -649,12 +658,18 @@ impl<'a> Parser<'a> {}"sphere" => {let r = get_num_any(0, &["r", "radius"], None)?;+ if !r.is_finite() || r <= 1e-9 {+ return Err(format!("{ctx}: sphere requires positive radius (r={r})"));+ }let segs = get_num_any(1, &["segs", "segments"], Some(32.0))? as usize;forma_core::primitives::make_sphere(r, segs, (segs / 2).max(12), op_id)}"torus" => {let maj = get_num_any(0, &["R", "major"], None)?;let min = get_num_any(1, &["r", "minor"], None)?;+ if !maj.is_finite() || !min.is_finite() || maj <= 1e-9 || min <= 1e-9 {+ return Err(format!("{ctx}: torus requires positive major and minor radii (R={maj}, r={min})"));+ }let segs = get_num_any(2, &["segs", "segments"], Some(32.0))? as usize;forma_core::primitives::make_torus(maj, min, segs, (segs / 2).max(12), op_id)}@@ -814,8 +829,13 @@ impl<'a> Parser<'a> {.or_else(|| pos.first()).ok_or(format!("{ctx}: missing path/asset string"))?.as_str(&ctx)?;+ let yup = kw+ .get("yup")+ .or_else(|| pos.get(1))+ .map(|v| v.as_bool(&ctx))+ .transpose()?;self.scene- .load_asset_mesh(path_or_key)+ .load_asset_mesh_with_opts(path_or_key, yup).map_err(|e| format!("{ctx}: {e}"))?}_ => return Err(format!("{ctx}: unknown function '{name}'")),@@ -996,6 +1016,11 @@ impl<'a> Parser<'a> {let sx = pos.first().ok_or(format!("{ctx}: missing scale"))?.as_num(&ctx)?;let sy = pos.get(1).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(sx);let sz = pos.get(2).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(sy);+ if !sx.is_finite() || !sy.is_finite() || !sz.is_finite()+ || sx.abs() <= 1e-9 || sy.abs() <= 1e-9 || sz.abs() <= 1e-9+ {+ return Err(format!("{ctx}: scale requires non-zero finite axes (sx={sx}, sy={sy}, sz={sz})"));+ }mesh.scale(Vec3::new(sx, sy, sz));Ok(mesh)}@@ -1066,13 +1091,19 @@ impl<'a> Parser<'a> {"pattern_linear" | "array" => {let cnt = kw.get("count").or_else(|| kw.get("n")).or_else(|| pos.first()).ok_or(format!("{ctx}: missing count"))?.as_num(&ctx)? as usize;let step = kw.get("step").or_else(|| pos.get(1)).ok_or(format!("{ctx}: missing step (dx,dy,dz)"))?.as_vec3(&ctx)?;- let u = kw.get("union").or_else(|| pos.get(2)).map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(false);+ let u = kw.get("union").or_else(|| pos.get(2)).map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(true);forma_core::ops::array_linear(&mesh, cnt, step, u, op_id).map_err(|e| format!("{ctx}: {e}"))}"pattern_radial" | "radial" => {let cnt = kw.get("count").or_else(|| kw.get("n")).or_else(|| pos.first()).ok_or(format!("{ctx}: missing count"))?.as_num(&ctx)? as usize;- let u = kw.get("union").or_else(|| pos.get(1)).map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(false);- forma_core::ops::array_radial(&mesh, cnt, u, op_id).map_err(|e| format!("{ctx}: {e}"))+ let (pos_r, pos_u) = match pos.get(1) {+ Some(Val::Bool(_)) => (None, pos.get(1)),+ Some(_) => (pos.get(1), pos.get(2)),+ None => (None, None),+ };+ let radius = kw.get("r").or_else(|| kw.get("radius")).or(pos_r).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.0);+ let u = kw.get("union").or(pos_u).map(|v| v.as_bool(&ctx)).transpose()?.unwrap_or(true);+ forma_core::ops::array_radial_with_radius(&mesh, cnt, radius, u, op_id).map_err(|e| format!("{ctx}: {e}"))}"decimate" | "lod" => {let ratio = kw.get("ratio").or_else(|| pos.first()).map(|v| v.as_num(&ctx)).transpose()?.unwrap_or(0.5);diff --git a/crates/forma-mcp/src/main.rs b/crates/forma-mcp/src/main.rsindex d9c526e..1a07ad8 100644--- a/crates/forma-mcp/src/main.rs+++ b/crates/forma-mcp/src/main.rs@@ -72,7 +72,7 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> (bool, Strinlet Some(code) = args.get("code").and_then(|v| v.as_str()) else {return (true, "ERR: missing 'code' string".into());};- scene.strict_manifold = args.get("strict").and_then(|v| v.as_bool()).unwrap_or(false);+ scene.strict_manifold = args.get("strict").and_then(|v| v.as_bool()).unwrap_or(true);match eval_script(scene, Dialect::Pipe, code) {Ok(obs) => (false, obs.text),Err(e) => (true, format!("ERR: {e}")),@@ -127,7 +127,7 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> (bool, Strin.map_or(false, |s| s.eq_ignore_ascii_case("png"));let is_scene = args.get("scene").and_then(|v| v.as_bool()).unwrap_or(false);if is_scene {- match scene.export_scene_glb_bytes(false) {+ 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())),Err(e) => (true, format!("ERR: {e}")),diff --git a/crates/forma-server/src/main.rs b/crates/forma-server/src/main.rsindex d3c4e96..3014707 100644--- a/crates/forma-server/src/main.rs+++ b/crates/forma-server/src/main.rs@@ -186,6 +186,7 @@ fn handle_eval(body: &[u8]) -> HttpResponse {let mut scene = Scene::new();scene.strict_manifold = strict;scene.allow_fs_import = false; // Zero host filesystem access in multi-tenant server!+ scene.max_statements = 1_024;// Attach any uploaded in-memory base64 assets (for `load("item.glb")` inside scripts)if let Some(assets) = req.get("assets").and_then(|v| v.as_object()) {@@ -272,7 +273,8 @@ fn handle_process(body: &[u8]) -> HttpResponse {Ok(b) => b,Err(e) => return HttpResponse::json(400, "Bad Request", json!({ "ok": false, "error": e })),};- let mut mesh = match forma_core::import::import_mesh_bytes(&raw, in_fmt) {+ let yup = req.get("yup").and_then(|v| v.as_bool());+ let mut mesh = match forma_core::import::import_mesh_bytes_with_opts(&raw, in_fmt, yup) {Ok(m) => m,Err(e) => return HttpResponse::json(422, "Unprocessable Entity", json!({ "ok": false, "error": e })),};diff --git a/lib/index.mjs b/lib/index.mjsindex ae2880a..158ac12 100644--- a/lib/index.mjs+++ b/lib/index.mjs@@ -77,7 +77,7 @@ export class FormaSession {}/** Evaluate Forma-Pipe (or compact) code transactionally; returns parsed Observation. */- eval(code, { dialect = "pipe", strict = false } = {}) {+ eval(code, { dialect = "pipe", strict = true } = {}) {this._checkOpen();const d = dialect === "compact" ? 1 : 0;this._engine._withUtf8(code, (ptr, len) => {diff --git a/wasm/forma.wasm b/wasm/forma.wasmindex d180713..ff86d20 100755Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ