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

Merge remote-tracking branch 'origin/main' into pr-101

wrong-nebula7aff60e3d8fa
diff --cc crates/forma-cli/src/main.rs
index 7638947,7671ecc..b6ac599
--- a/crates/forma-cli/src/main.rs
+++ b/crates/forma-cli/src/main.rs
@@@ -7,11 -7,8 +7,11 @@@
//! forma spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]
//! forma version | --version | -V
- use forma_core::{Scene, Unit};
+ use forma_core::{LintOptions, Scene, Unit};
-use forma_lang::{eval_script, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE, SPEC_PIPE_GBNF};
+use forma_lang::{
+ eval_script, is_invariant_violation_err, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE,
+ SPEC_PIPE_GBNF,
+};
use std::io::{self, Read};
use std::path::PathBuf;
use std::process;
diff --cc crates/forma-core/tests/kernel_tests.rs
index 30bc5b0,4b1e90f..3817134
--- a/crates/forma-core/tests/kernel_tests.rs
+++ b/crates/forma-core/tests/kernel_tests.rs
@@@ -1151,72 -1157,195 +1157,265 @@@ fn test_deform_curve_on_3d_bezier_has_n
assert!(inv.is_valid_solid());
}
+#[test]
+fn test_issue_82_glb_base_color_srgb_to_linear_roundtrip() {
+ let mut b = forma_core::primitives::make_box(1.0, 1.0, 1.0, 1);
+ let srgb = [0.5_f32, 0.2, 0.8, 0.75];
+ b.assign_material(
+ forma_core::Material {
+ name: "swatch".into(),
+ color: srgb,
+ metallic: 0.2,
+ roughness: 0.7,
+ },
+ None,
+ );
+
+ let parse_glb_base_color = |glb: &[u8]| -> [f64; 4] {
+ let json_len = u32::from_le_bytes([glb[12], glb[13], glb[14], glb[15]]) as usize;
+ let v: serde_json::Value = serde_json::from_slice(&glb[20..20 + json_len]).unwrap();
+ let arr = v["materials"][0]["pbrMetallicRoughness"]["baseColorFactor"]
+ .as_array()
+ .unwrap();
+ [
+ arr[0].as_f64().unwrap(),
+ arr[1].as_f64().unwrap(),
+ arr[2].as_f64().unwrap(),
+ arr[3].as_f64().unwrap(),
+ ]
+ };
+
+ // Expected IEC 61966-2-1 linear RGB values (alpha stays linear)
+ let expected_lin = [0.21404114_f64, 0.03310477, 0.60382734, 0.75];
+
+ // Single-mesh GLB export
+ let single_glb = forma_core::export::write_glb_bytes(&b, true).unwrap();
+ let single_bc = parse_glb_base_color(&single_glb);
+ for i in 0..4 {
+ assert!(
+ (single_bc[i] - expected_lin[i]).abs() < 1e-4,
+ "single GLB baseColorFactor[{i}]={} != expected {}",
+ single_bc[i],
+ expected_lin[i]
+ );
+ }
+
+ // Multi-part scene GLB export
+ let mut scene = Scene::new();
+ scene.set_part("swatch", b).unwrap();
+ let scene_glb = scene.export_scene_glb_bytes(true).unwrap();
+ let scene_bc = parse_glb_base_color(&scene_glb);
+ for i in 0..4 {
+ assert!(
+ (scene_bc[i] - expected_lin[i]).abs() < 1e-4,
+ "scene GLB baseColorFactor[{i}]={} != expected {}",
+ scene_bc[i],
+ expected_lin[i]
+ );
+ }
+
+ // Importing the GLB back converts linear -> sRGB losslessly
+ let reimported = forma_core::import::read_glb_bytes_with_opts(&single_glb, None).unwrap();
+ assert_eq!(reimported.materials.len(), 1);
+ for i in 0..4 {
+ assert!(
+ (reimported.materials[0].color[i] - srgb[i]).abs() < 1e-4,
+ "round-trip sRGB color[{i}]={} != {}",
+ reimported.materials[0].color[i],
+ srgb[i]
+ );
+ }
+}
++
+ #[test]
+ fn test_issue_93_open_top_requires_flat_top_face() {
+ let sph = forma_core::primitives::make_sphere(1.0, 24, 16, 1);
+ let err = forma_core::ops::shell_solid(&sph, 0.1, true, 2).unwrap_err();
+ assert!(err.contains("open_top=true"), "expected open_top error on sphere, got {err}");
+ let err2 = forma_core::deform::solidify_mesh(&sph, 0.1, -1.0, true, 3).unwrap_err();
+ assert!(err2.contains("open_top=true"), "expected open_top error on solidify sphere, got {err2}");
+
+ let mut hcyl = forma_core::primitives::make_cylinder(1.0, 3.0, 24, 4);
+ hcyl.rotate_deg(0.0, 90.0, 0.0);
+ assert!(forma_core::ops::shell_solid(&hcyl, 0.1, true, 5).is_err());
+
+ // Closed shell (open_top=false) on sphere still works cleanly
+ let closed = forma_core::ops::shell_solid(&sph, 0.1, false, 6).unwrap();
+ let cinv = MeshInvariants::compute(&closed);
+ assert!(cinv.is_valid_solid() && cinv.components == 2);
+ }
+
+ #[test]
+ fn test_issue_94_bevel_general_polyhedron_is_deterministic() {
+ let build = || -> Vec<u8> {
+ let mut m = forma_core::primitives::make_box(2.0, 1.0, 1.0, 1);
+ m = forma_core::ops::bevel_edges(&m, &EdgeSelector::All, 0.1, 1, 2).unwrap();
+ let stats = forma_core::uv::unwrap_lscm(&mut m, 45.0, 0.01).unwrap();
+ assert_eq!(stats.inverted_tris, 0);
+ forma_core::export::write_glb_bytes(&m, true).unwrap()
+ };
+ let first = build();
+ for _ in 0..8 {
+ assert_eq!(build(), first, "bevel(all) + unwrap() must produce byte-identical GLB");
+ }
+ }
+
+ #[test]
+ fn test_issue_81_remesh_voxel_preserves_center_all_axes() {
+ for &vs in &[0.03, 0.05, 0.1] {
+ let b = forma_core::primitives::make_box(1.0, 1.0, 1.0, 1);
+ let r = forma_core::remesh::remesh_voxel(&b, vs, 2).unwrap();
+ let c = r.aabb().center();
+ assert!(
+ c.len() < 1e-3,
+ "voxel_size={vs}: expected center near (0,0,0), got {c:?}"
+ );
+ }
+ let mut b_off = forma_core::primitives::make_box(1.0, 1.0, 1.0, 3);
+ b_off.translate(Vec3::new(10.0, 10.0, 10.0));
+ let r_off = forma_core::remesh::remesh_voxel(&b_off, 0.1, 4).unwrap();
+ let c_off = r_off.aabb().center();
+ assert!(
+ (c_off - Vec3::new(10.0, 10.0, 10.0)).len() < 1e-3,
+ "translated box center shifted to {c_off:?}"
+ );
+ }
+
+ #[test]
+ fn test_issue_78_high_res_twisted_loft_shell_and_cut() {
+ use forma_core::boolean::has_self_intersections;
+ use std::f64::consts::PI;
+
+ let side = 0.20_f64;
+ let r_corner = 0.03_f64;
+ let inr = side / (2.0 * 3.0_f64.sqrt());
+ let cd = 2.0 * (inr - r_corner);
+ let levels = [0.0_f64, 0.10, 0.20, 0.30];
+
+ // Exact rounded-equilateral-triangle polar radius sampler from issue #78
+ let polar_radii = |n: usize, flip: bool, rr: f64| -> Vec<f64> {
+ let samples = 240usize;
+ let mut boundary: Vec<(f64, f64)> = Vec::with_capacity(3 * samples);
+ for k in 0..3 {
+ let t = (90.0 + 120.0 * (k as f64) + if flip { 180.0 } else { 0.0 }).to_radians();
+ let (cx, cy) = (cd * t.cos(), cd * t.sin());
+ for j in 0..samples {
+ let a = t - 60.0_f64.to_radians() + 120.0_f64.to_radians() * (j as f64) / (samples as f64);
+ boundary.push((cx + rr * a.cos(), cy + rr * a.sin()));
+ }
+ }
+ let m = boundary.len();
+ (0..n)
+ .map(|i| {
+ let phi = 2.0 * PI * (i as f64) / (n as f64);
+ let (dx, dy) = (phi.cos(), phi.sin());
+ let mut best = f64::INFINITY;
+ for j in 0..m {
+ let (x1, y1) = boundary[j];
+ let (x2, y2) = boundary[(j + 1) % m];
+ let (ex, ey) = (x2 - x1, y2 - y1);
+ let den = dx * ey - dy * ex;
+ if den.abs() < 1e-15 {
+ continue;
+ }
+ let t = (x1 * ey - y1 * ex) / den;
+ let u = (x1 * dy - y1 * dx) / den;
+ if t > 0.0 && (-1e-9..=1.0 + 1e-9).contains(&u) && t < best {
+ best = t;
+ }
+ }
+ best
+ })
+ .collect()
+ };
+
+ let build_sections = |n: usize, sub: usize, rr: f64, z0: f64, ztop: f64| -> Vec<(f64, Vec<(f64, f64)>)> {
+ let ra = polar_radii(n, false, rr);
+ let rb = polar_radii(n, true, rr);
+ let mut raw: Vec<(f64, Vec<f64>)> = Vec::new();
+ for l in 0..3 {
+ let (a, b) = if l % 2 == 0 { (&ra, &rb) } else { (&rb, &ra) };
+ for s in 0..sub {
+ let f = (s as f64) / (sub as f64);
+ let w = 0.5 - 0.5 * (PI * f).cos();
+ let zl = (levels[l] + f * (levels[l + 1] - levels[l])).max(z0);
+ let rs: Vec<f64> = (0..n).map(|i| a[i] * (1.0 - w) + b[i] * w).collect();
+ raw.push((zl, rs));
+ }
+ }
+ raw.push((if ztop > levels[3] { ztop } else { levels[3] }, rb));
+ let mut dedup: Vec<(f64, Vec<f64>)> = Vec::new();
+ for (z, r) in raw {
+ if let Some(prev) = dedup.last_mut() {
+ if (prev.0 - z).abs() < 1e-9 {
+ *prev = (z, r);
+ continue;
+ }
+ }
+ dedup.push((z, r));
+ }
+ dedup
+ .into_iter()
+ .map(|(z, rs)| {
+ let z_r = (z * 1e5).round() * 1e-5;
+ let poly: Vec<(f64, f64)> = (0..n)
+ .map(|i| {
+ let phi = 2.0 * PI * (i as f64) / (n as f64);
+ let x = (rs[i] * phi.cos() * 1e5).round() * 1e-5;
+ let y = (rs[i] * phi.sin() * 1e5).round() * 1e-5;
+ (x, y)
+ })
+ .collect();
+ (z_r, poly)
+ })
+ .collect()
+ };
+
+ // Part 1: shell(0.01) must succeed even when vertical section spacing dz <= thickness (SUB >= 9..15)
+ for (n, sub) in [(48usize, 9usize), (48, 10), (48, 12), (48, 15), (96, 12)] {
+ let outer = forma_core::primitives::make_loft(&build_sections(n, sub, r_corner, 0.0, 0.30), n, 1).unwrap();
+ for open_top in [true, false] {
+ let shelled = forma_core::ops::shell_solid(&outer, 0.01, open_top, 2)
+ .unwrap_or_else(|e| panic!("shell(0.01, open_top={open_top}) failed at N={n} SUB={sub}: {e}"));
+ let inv = MeshInvariants::compute(&shelled);
+ assert!(
+ inv.is_valid_solid() && inv.genus == 0 && !has_self_intersections(&shelled),
+ "invalid shell(0.01, open_top={open_top}) at N={n} SUB={sub}: {inv:?}"
+ );
+ }
+ }
+ // Excessive thickness (> 30 mm corner radius) must still be cleanly rejected
+ let outer_48 = forma_core::primitives::make_loft(&build_sections(48, 12, r_corner, 0.0, 0.30), 48, 3).unwrap();
+ assert!(
+ forma_core::ops::shell_solid(&outer_48, 0.045, true, 4).is_err(),
+ "shell exceeding corner radius must still return Err"
+ );
+
+ // Part 2: outer_loft | cut(inner_loft) across previously failing (N, SUB) combinations
+ for (n, sub) in [
+ (32usize, 8usize),
+ (32, 12),
+ (48, 12),
+ (64, 6),
+ (64, 10),
+ (64, 12),
+ (96, 6),
+ (96, 8),
+ (96, 10),
+ (96, 11),
+ (96, 12),
+ (128, 6),
+ (128, 10),
+ (128, 12),
+ ] {
+ let outer = forma_core::primitives::make_loft(&build_sections(n, sub, r_corner, 0.0, 0.30), n, 10).unwrap();
+ let inner = forma_core::primitives::make_loft(&build_sections(n, sub, r_corner - 0.01, 0.01, 0.32), n, 11).unwrap();
+ let vase = forma_core::boolean::boolean_op(&outer, &inner, BoolOp::Difference, None, 12)
+ .unwrap_or_else(|e| panic!("loft cut failed at N={n} SUB={sub}: {e}"));
+ let inv = MeshInvariants::compute(&vase);
+ assert!(
+ inv.is_valid_solid() && inv.genus == 0 && !has_self_intersections(&vase),
+ "invalid loft cut at N={n} SUB={sub}: {inv:?}"
+ );
+ }
+ }
diff --cc crates/forma-lang/tests/audit_regressions.rs
index 017cf5a,233347e..626da07
--- a/crates/forma-lang/tests/audit_regressions.rs
+++ b/crates/forma-lang/tests/audit_regressions.rs
@@@ -296,75 -296,212 +296,285 @@@ fn remove_part_keeps_last_modified_on_r
assert!(step.contains("CLOSED_SHELL"));
}
+#[test]
+fn issue_83_subsurf_levels_and_bevel_width_emit_clamp_warnings() {
+ // 1. subsurf(levels > 4) warns; levels <= 4 does not
+ let mut s_ok = Scene::new();
+ s_ok.strict_manifold = true;
+ let obs_ok = eval_script(&mut s_ok, Dialect::Pipe, "s4 = box(1, 1, 1) | subsurf(4)").unwrap();
+ assert!(obs_ok.warnings.is_empty(), "subsurf(4) should not warn: {:?}", obs_ok.warnings);
+
+ let mut s_hi = Scene::new();
+ s_hi.strict_manifold = true;
+ let obs_hi = eval_script(&mut s_hi, Dialect::Pipe, "s9 = box(1, 1, 1) | subsurf(9)").unwrap();
+ assert!(
+ obs_hi.warnings.iter().any(|w| w.contains("subsurf: levels=9 clamped to 4")),
+ "expected subsurf clamp warning, got {:?}",
+ obs_hi.warnings
+ );
+
+ // 2. bevel(all, w) oversized width on unit cube warns
+ let mut b_all = Scene::new();
+ b_all.strict_manifold = true;
+ let obs_all = eval_script(&mut b_all, Dialect::Pipe, "b8 = box(1, 1, 1) | bevel(all, 0.8)").unwrap();
+ assert!(
+ obs_all.warnings.iter().any(|w| w.contains("bevel: width=0.8 clamped to")),
+ "expected bevel(all) width clamp warning, got {:?}",
+ obs_all.warnings
+ );
+
+ // 3. bevel(top_rim, w) warns when clamped, clean when within range
+ let mut c_ok = Scene::new();
+ c_ok.strict_manifold = true;
+ let obs_c_ok = eval_script(&mut c_ok, Dialect::Pipe, "c05 = cyl(1, 2) | bevel(top_rim, 0.5, segs=3)").unwrap();
+ assert!(obs_c_ok.warnings.is_empty(), "bevel(top_rim, 0.5) should not warn: {:?}", obs_c_ok.warnings);
+
+ let mut c_hi = Scene::new();
+ c_hi.strict_manifold = true;
+ let obs_c_hi = eval_script(&mut c_hi, Dialect::Pipe, "c15 = cyl(1, 2) | bevel(top_rim, 1.5, segs=3)").unwrap();
+ assert!(
+ obs_c_hi.warnings.iter().any(|w| w.contains("bevel: width=1.5 clamped to")),
+ "expected bevel(top_rim) width clamp warning, got {:?}",
+ obs_c_hi.warnings
+ );
+
+ // 4. bevel(vertical, w) warns when clamped, clean when within range
+ let mut v_ok = Scene::new();
+ v_ok.strict_manifold = true;
+ let obs_v_ok = eval_script(&mut v_ok, Dialect::Pipe, "v = box(1, 1, 1) | bevel(vertical, 0.2, segs=2)").unwrap();
+ assert!(obs_v_ok.warnings.is_empty(), "bevel(vertical, 0.2) should not warn: {:?}", obs_v_ok.warnings);
+
+ let mut v_hi = Scene::new();
+ v_hi.strict_manifold = true;
+ let obs_v_hi = eval_script(&mut v_hi, Dialect::Pipe, "v = box(1, 1, 1) | bevel(vertical, 0.8, segs=2)").unwrap();
+ assert!(
+ obs_v_hi.warnings.iter().any(|w| w.contains("bevel: width=0.8 clamped to")),
+ "expected bevel(vertical) width clamp warning, got {:?}",
+ obs_v_hi.warnings
+ );
+
+ // 5. Compact DSL subdiv & bev propagate warnings too
+ let mut sc = Scene::new();
+ sc.strict_manifold = true;
+ let obs_c = eval_script(&mut sc, Dialect::Compact, "new p box 1 1 1\nbev p all 0.8\nsubdiv p 6").unwrap();
+ assert!(
+ obs_c.warnings.iter().any(|w| w.contains("bevel: width=0.8 clamped to")),
+ "compact bev should warn: {:?}",
+ obs_c.warnings
+ );
+ assert!(
+ obs_c.warnings.iter().any(|w| w.contains("subsurf: levels=6 clamped to 4")),
+ "compact subdiv should warn: {:?}",
+ obs_c.warnings
+ );
+}
++
+ #[test]
+ fn reserved_constant_assignment_rejected_and_bare_selector_last_assignment_diagnosed() {
+ // 1. Assigning to `pi` / `PI` / `true` / `false` must fail cleanly instead of creating an unreferenceable part
+ for name in ["pi", "PI", "true", "false"] {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ let err = eval_script(&mut s, Dialect::Pipe, &format!("{name} = box(2,2,1)")).unwrap_err();
+ assert!(
+ err.contains("cannot assign to built-in constant"),
+ "expected built-in constant error for '{name}', got: {err}"
+ );
+ }
+
+ // 2. Final assignment `result = all` under strict mode fails loudly instead of exporting `knob`
+ let mut s_strict = Scene::new();
+ s_strict.strict_manifold = true;
+ let err = eval_script(
+ &mut s_strict,
+ Dialect::Pipe,
+ "body = box(2,2,1)\nknob = sphere(0.3) | move(0,0,1)\nresult = all",
+ )
+ .unwrap_err();
+ assert!(
+ err.contains("selector keyword 'all'") && err.contains("knob"),
+ "expected selector assignment error, got: {err}"
+ );
+
+ // 3. Under non-strict mode, final bare selector assignment warns clearly
+ let mut s_lax = Scene::new();
+ s_lax.strict_manifold = false;
+ let obs = eval_script(
+ &mut s_lax,
+ Dialect::Pipe,
+ "body = box(2,2,1)\nknob = sphere(0.3) | move(0,0,1)\nresult = all",
+ )
+ .unwrap();
+ assert!(
+ obs.warnings.iter().any(|w| w.contains("selector keyword 'all'")),
+ "expected selector warning, got: {:?}",
+ obs.warnings
+ );
+
+ // 4. Intermediate bare selector variable followed by real mesh assignment still works cleanly
+ let mut s_ok = Scene::new();
+ s_ok.strict_manifold = true;
+ let obs_ok = eval_script(
+ &mut s_ok,
+ Dialect::Pipe,
+ "sel = vertical\np = box(2,2,1) | bevel(sel, 0.2)",
+ )
+ .unwrap();
+ assert!(obs_ok.ok);
+ }
+
+ #[test]
+ fn issue_80_subsurfed_loft_add_cone_left_and_right_valid_solids() {
+ use forma_core::boolean::has_self_intersections;
+
+ let case_a = r#"
+ def egg(cz, rz, ry, n=14) = [(-cz - rz * cos(2 * pi * i / n), ry * sin(2 * pi * i / n)) for i in range(n)]
+ _s = loft([(-0.64, egg(0.58, 0.08, 0.07)), (-0.57, egg(0.57, 0.20, 0.17)), (-0.40, egg(0.57, 0.26, 0.23)), (-0.15, egg(0.58, 0.28, 0.26))], segs=14) | rot(0, 90, 0) | subsurf(1)
+ left = _s | add(cone(0.05, 0.11, 0.44, segs=10, z0=0.08, at=(-0.43, -0.15, 0)))
+ right = _s | add(cone(0.05, 0.11, 0.44, segs=10, z0=0.08, at=(-0.43, 0.15, 0)))
+ "#;
+ let case_b = r#"
+ def egg(cz, rz, ry, n=14) = [(-cz - rz * cos(2 * pi * i / n), ry * sin(2 * pi * i / n)) for i in range(n)]
+ _s = loft([(-0.15, egg(0.55, 0.29, 0.26)), (0.08, egg(0.58, 0.32, 0.27)), (0.24, egg(0.60, 0.33, 0.26)), (0.38, egg(0.59, 0.29, 0.23)), (0.48, egg(0.56, 0.20, 0.17))], segs=14) | rot(0, 90, 0) | subsurf(1)
+ left = _s | add(cone(0.045, 0.085, 0.40, segs=12, z0=0.08, at=(0.27, -0.13, 0)))
+ right = _s | add(cone(0.045, 0.085, 0.40, segs=12, z0=0.08, at=(0.27, 0.13, 0)))
+ "#;
+
+ for (label, script) in [("case_a_hole", case_a), ("case_b_flip", case_b)] {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ eval_script(&mut s, Dialect::Pipe, script)
+ .unwrap_or_else(|e| panic!("issue #80 {label} failed in strict mode: {e}"));
+ let left = s.get_part("left").expect("left part");
+ let right = s.get_part("right").expect("right part");
+ let inv_l = MeshInvariants::compute(left);
+ let inv_r = MeshInvariants::compute(right);
+ assert!(inv_l.is_valid_solid() && inv_l.genus == 0 && !has_self_intersections(left), "{label} left: {inv_l:?}");
+ assert!(inv_r.is_valid_solid() && inv_r.genus == 0 && !has_self_intersections(right), "{label} right: {inv_r:?}");
+ assert!(
+ (inv_l.volume - inv_r.volume).abs() < 1e-4,
+ "{label} mirror volumes diverged: left={} right={}",
+ inv_l.volume,
+ inv_r.volume
+ );
+ }
+ }
+
+ #[test]
+ fn issue_116_lattice_mast_crossing_box_and_tube_beams() {
+ use forma_core::boolean::has_self_intersections;
+
+ fn gen_mast(tiers: usize, use_tube: bool) -> String {
+ let t = 0.6_f64;
+ let a = 5.0_f64;
+ let h = 8.0_f64;
+ let fmt = |v: f64| {
+ let s = format!("{v:.4}");
+ s.trim_end_matches('0').trim_end_matches('.').to_string()
+ };
+ let mut parts: Vec<String> = Vec::with_capacity(4 + 12 * tiers);
+ for (sx, sy) in [(1.0, 1.0), (1.0, -1.0), (-1.0, -1.0), (-1.0, 1.0)] {
+ parts.push(format!(
+ "box({}, {}, {}, at=({}, {}, 0), z0=0)",
+ fmt(t),
+ fmt(t),
+ fmt(tiers as f64 * h),
+ fmt(sx * a),
+ fmt(sy * a)
+ ));
+ }
+ let diag_len = (2.0 * a).hypot(h);
+ let ang = h.atan2(2.0 * a).to_degrees();
+ for k in 0..tiers {
+ let zc = (k as f64) * h + h / 2.0;
+ for face in 0..4 {
+ let turn = 90 * face;
+ for s in [1.0, -1.0] {
+ if use_tube {
+ parts.push(format!(
+ "tube([({}, {}, {}), ({}, {}, {})], r={}) | rot(0, 0, {})",
+ fmt(-a),
+ fmt(a),
+ fmt(zc - s * h / 2.0),
+ fmt(a),
+ fmt(a),
+ fmt(zc + s * h / 2.0),
+ fmt(t / 2.0),
+ turn
+ ));
+ } else {
+ parts.push(format!(
+ "box({}, {}, {}, at=(0, 0, 0), rot=(0, {}, 0)) | move(0, {}, {}) | rot(0, 0, {})",
+ fmt(diag_len),
+ fmt(t),
+ fmt(t),
+ fmt(s * ang),
+ fmt(a),
+ fmt(zc),
+ turn
+ ));
+ }
+ }
+ parts.push(format!(
+ "box({}, {}, {}, at=(0, {}, {})) | rot(0, 0, {})",
+ fmt(2.0 * a),
+ fmt(t),
+ fmt(t),
+ fmt(a),
+ fmt((k + 1) as f64 * h),
+ turn
+ ));
+ }
+ }
+ let mut out: Vec<String> = parts
+ .iter()
+ .enumerate()
+ .map(|(i, p)| format!("_b{i} = {p}"))
+ .collect();
+ let mut chain = String::from("mast = _b0");
+ for i in 1..parts.len() {
+ chain.push_str(&format!(" | add(_b{i})"));
+ }
+ out.push(chain);
+ out.join("\n")
+ }
+
+ // Box-brace lattice masts: 3 tiers (40 beams), 6 tiers (76 beams), 12 tiers (148 beams)
+ let mut prev_vol: Option<(usize, f64)> = None;
+ for (tiers, expected_genus) in [(3usize, 45i64), (6, 93), (12, 189)] {
+ let script = gen_mast(tiers, false);
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ eval_script(&mut s, Dialect::Pipe, &script)
+ .unwrap_or_else(|e| panic!("box mast tiers={tiers} failed under strict: {e}"));
+ let mast = s.get_part("mast").expect("mast part");
+ let inv = MeshInvariants::compute(mast);
+ assert!(
+ inv.is_valid_solid() && inv.genus == expected_genus && !has_self_intersections(mast),
+ "box mast tiers={tiers} invalid: {inv:?}"
+ );
+ if let Some((prev_t, pv)) = prev_vol {
+ let per_tier = (inv.volume - pv) / ((tiers - prev_t) as f64);
+ assert!(
+ (per_tier - 57.6556).abs() < 0.05,
+ "box mast volume per tier drifted: {per_tier:.4} (tiers {prev_t}->{tiers})"
+ );
+ }
+ prev_vol = Some((tiers, inv.volume));
+ }
+
+ // Tube-brace lattice masts: 3 tiers (40 beams) and 12 tiers (148 beams)
+ for (tiers, expected_genus) in [(3usize, 45i64), (12, 189)] {
+ let script = gen_mast(tiers, true);
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ eval_script(&mut s, Dialect::Pipe, &script)
+ .unwrap_or_else(|e| panic!("tube mast tiers={tiers} failed under strict: {e}"));
+ let mast = s.get_part("mast").expect("mast part");
+ let inv = MeshInvariants::compute(mast);
+ assert!(
+ inv.is_valid_solid() && inv.genus == expected_genus && !has_self_intersections(mast),
+ "tube mast tiers={tiers} invalid: {inv:?}"
+ );
+ }
+ }
diff --cc lib/index.d.ts
index 8775c48,1afa0d5..6b2fadc
--- a/lib/index.d.ts
+++ b/lib/index.d.ts
@@@ -21,7 -21,35 +21,36 @@@ export type WasmSource
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 type FormaRenderView = "quad" | "front" | "back" | "right" | "left" | "top" | "iso";
+ export type FormaView = "quad" | "front" | "back" | "right" | "left" | "top" | "iso";
++export type FormaRenderView = FormaView;
+
+ export interface FormaSyncStatus {
+ rev: number;
+ stale_render: boolean;
+ stale_export: boolean;
+ text: string;
+ }
+
+ export interface FormaLintFinding {
+ severity: "warn" | "info";
+ code: string;
+ part: string;
+ message: string;
+ }
+
+ export interface FormaPartContact {
+ a: string;
+ b: string;
+ kind: "Intersecting" | "FlushContact" | "NearGap" | "Disjoint";
+ min_distance: number;
+ }
+
+ export interface FormaLintReport {
+ clean: boolean;
+ findings: FormaLintFinding[];
+ contacts: FormaPartContact[];
+ text: string;
+ }
export interface FormaInvariants {
verts: number;
@@@ -108,14 -134,22 +137,22 @@@ export class FormaSession
eval(code: string, opts?: SessionEvalOptions): FormaObservation;
/** Inspect current scene invariants without mutating state. */
inspect(): FormaObservation;
+ /** Inspect a single named part's invariants, tags, and sync status. */
+ inspectPart(part: string): string;
+ /** Return revision & render/export staleness status. */
+ syncStatus(): FormaSyncStatus;
+ /** Run deterministic Layer A geometric craftsmanship lint & assembly contact graph. */
+ lint(opts?: { includeRawBox?: boolean }): FormaLintReport;
/** Copy-on-write snapshot control: `checkpoint`, `rollback`, `undo`, or `reset`. */
tx(action: "checkpoint" | "rollback" | "undo" | "reset", tag?: string): string;
- /** 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 a part to `.glb`, `.step`, `.3mf`, `.stl`, `.obj`, `.svg`, or `.png` bytes. */
+ exportBytes(format: FormaExportFormat, opts?: { part?: string; size?: number; view?: FormaRenderView | string }): Uint8Array;
/** Export all named parts as a multi-node binary glTF 2.0 (`.glb`) scene graph. */
exportSceneBytes(): Uint8Array;
- /** Render a 4-view studio PNG preview of all named scene parts combined. */
- exportScenePngBytes(size?: number): Uint8Array;
+ /** Render a studio PNG preview (`quad|front|back|right|left|top|iso`) of all named scene parts combined. */
- exportScenePngBytes(size?: number, view?: FormaRenderView | string): Uint8Array;
++ exportScenePngBytes(size?: number, view?: FormaView | string): Uint8Array;
+ /** Render a named view (`quad|front|back|right|left|top|iso`) PNG for a part or the full scene. */
+ exportViewPngBytes(opts?: { part?: string; size?: number; view?: FormaView | string; scene?: boolean }): 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. */
diff --cc tests/npm_smoke.mjs
index 7ddb50a,7d131ae..cb22541
--- a/tests/npm_smoke.mjs
+++ b/tests/npm_smoke.mjs
@@@ -166,65 -174,22 +174,75 @@@ section(flange, 0.0
badFlagCode = err.status;
}
assert.equal(badFlagCode, 2, "unknown flag must exit with code 2");
- console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict, --unit mm, exit codes, .glb/.png/.svg)");
+
+ // Issue #84: strict invariant violation exits with status 3 (while syntax error exits 1)
+ let strictFailCode = 0;
+ try {
+ execFileSync(process.execPath, [cli, "eval", "--strict", "-"], { input: "a = torus(0.5, 1)\n", stdio: "pipe" });
+ } catch (err) {
+ strictFailCode = err.status;
+ }
+ assert.equal(strictFailCode, 3, "strict invariant violation must exit with code 3");
+
+ let syntaxErrCode = 0;
+ try {
+ execFileSync(process.execPath, [cli, "eval", "--strict", "-"], { input: "a = box(1,\n", stdio: "pipe" });
+ } catch (err) {
+ syntaxErrCode = err.status;
+ }
+ assert.equal(syntaxErrCode, 1, "syntax error must exit with code 1");
+
+ // Issue #58: --scene renders & draws all named parts, and --view selects single-angle camera
+ const twoPartCode = "a = box(1, 1, 1)\nb = sphere(0.5) | move(3, 0, 0)\n";
+ const singlePng = join(tmp, "single.png");
+ const singleSvg = join(tmp, "single.svg");
+ const scenePng = join(tmp, "scene.png");
+ const sceneIsoPng = join(tmp, "scene-iso.png");
+ const sceneSvg = join(tmp, "scene.svg");
+ execFileSync(
+ process.execPath,
+ [cli, "eval", "--strict", "--render", singlePng, "--draw", singleSvg],
+ { input: twoPartCode, encoding: "utf-8" }
+ );
+ execFileSync(
+ process.execPath,
+ [cli, "eval", "--strict", "--scene", "--render", scenePng, "--draw", sceneSvg],
+ { input: twoPartCode, encoding: "utf-8" }
+ );
+ execFileSync(
+ process.execPath,
+ [cli, "render", "--scene", "--size", "256", "--view", "iso", "--out", sceneIsoPng],
+ { input: twoPartCode, encoding: "utf-8" }
+ );
+ const singleSvgText = readFileSync(singleSvg, "utf-8");
+ const sceneSvgText = readFileSync(sceneSvg, "utf-8");
+ assert.ok(singleSvgText.includes("1.000 m"), "single-part SVG should span only sphere (1.000 m)");
+ assert.ok(sceneSvgText.includes("4.000 m"), "scene SVG must span both box and shifted sphere (4.000 m)");
+ const singlePngBytes = readFileSync(singlePng);
+ const scenePngBytes = readFileSync(scenePng);
+ const sceneIsoBytes = readFileSync(sceneIsoPng);
+ assert.ok(!singlePngBytes.equals(scenePngBytes), "--scene --render PNG must differ from single-part PNG");
+ assert.equal(sceneIsoBytes[0], 0x89);
+ assert.equal(sceneIsoBytes[1], 0x50);
+ const topViewBytes = await renderPng(twoPartCode, 128, { scene: true, view: "top", strict: true });
+ assert.equal(topViewBytes[0], 0x89);
+ assert.equal(topViewBytes[1], 0x50);
+ console.log("PASS 3/5: CLI bin/forma.mjs (eval --strict, --unit mm, --scene, --view, exit codes, .glb/.png/.svg)");
- // 3. Test every recipe inside SKILL.md via npm WASM CLI
+ // 3. Test every recipe inside SKILL.md via npm WASM CLI + verify packaged docs/llms.txt links (#102, #103)
const skillMd = readFileSync(join(ROOT, "SKILL.md"), "utf-8");
- const recipes = [...skillMd.matchAll(/```forma\n([\s\S]*?)\n```/g)].map((m) => m[1]);
+ const recipes = [...skillMd.matchAll(/```forma\r?\n([\s\S]*?)\r?\n```/g)].map((m) => m[1]);
- assert.ok(recipes.length >= 4, "SKILL.md has >=4 recipes");
+ assert.equal(recipes.length, 5, "SKILL.md has 5 recipes");
+ const docsReadme = readFileSync(join(ROOT, "docs", "README.md"), "utf-8");
+ assert.ok(docsReadme.includes("five smoke-tested `Forma-Pipe` recipes"), "docs/README.md recipe count matches SKILL.md");
+ const pkgJson = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf-8"));
+ assert.ok(pkgJson.files.includes("docs/"), "package.json files must include docs/ so llms.txt links resolve");
+ const llmsTxt = readFileSync(join(ROOT, "llms.txt"), "utf-8");
+ const docsLinks = [...llmsTxt.matchAll(/\]\((docs\/[^)]+)\)/g)].map((m) => m[1]);
+ assert.ok(docsLinks.length >= 6, "llms.txt links docs/ pages");
+ for (const rel of docsLinks) {
+ assert.ok(statSync(join(ROOT, rel)).isFile(), `llms.txt link target missing: ${rel}`);
+ }
for (let i = 0; i < recipes.length; i++) {
const out = execFileSync(process.execPath, [cli, "eval", "--strict"], {
input: recipes[i],