Skip to content

armgit / forma

Public Imported from GitHub
0

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

feat(core,mcp,docs): add CAD feature compiler with wall p01, agent setup runbook, and print/craftsmanship blueprint upgrades

wrong-nebula087f3c362792
diff --git a/AGENTS.md b/AGENTS.md
index cedc183..abf8957 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -25,13 +25,13 @@ Add to your MCP client config (Claude Code, Cursor, Codex, Antigravity, etc.)
}
```
-> Also see [`SKILL.md`](SKILL.md) for a compact, drop-in Agent Skill file ready for LLM skill loaders.
+> Also see [`docs/agent-setup.md`](docs/agent-setup.md) for an agent-driven interactive setup runbook and [`SKILL.md`](SKILL.md) for a compact, drop-in Agent Skill file ready for LLM skill loaders.
### Exposed Tools
| Tool | Purpose |
|---|---|
| `eval` | Execute transactional `Forma-Pipe` code (`strict: true` auto-rolls back any non-manifold result); scalar variables persist across `eval` calls; delta-first `observe()` collapses unchanged healthy parts on >2-part incremental edits and emits `sync:` only when prior renders/exports go stale. Pass `out: ["preview.png", "part.glb", ...]` (with optional `scene`, `size`, `view`) to build, render, and export in **1 turn**. |
-| `inspect` | Inspect scene invariants without mutating state, drill into one part (`part: "name"`), run deterministic Layer A craftsmanship lint + pairwise assembly contact graph (`lint: true`), or load a progressive spec (`topic`: `deform`, `curves`, `uv`, `remesh`, `scene`). |
+| `inspect` | Inspect scene invariants without mutating state, drill into one part with compiled CAD facts (`part: "name"` — invariants, sync status, planes, cylindrical bores/bosses, symmetry, `min`/`p01`/`med` wall thickness), run deterministic Layer A craftsmanship lint + pairwise assembly contact graph (`lint: true`), or load a progressive spec (`topic`: `deform`, `curves`, `uv`, `remesh`, `scene`). |
| `tx` | O(1) copy-on-write state control: `checkpoint`, `rollback`, `undo`, `reset` (rolls back both geometry and scalar variables). |
| `export` | Export to `.glb` (glTF 2.0 Y-up, PBR + UVs), faceted `.step` (planar faces), `.3mf`, `.stl`, `.obj`, `.svg` blueprint, `.blend` (via Blender bridge), or render a zero-GPU studio `.png` preview (`~20–75 KB` in ~2.8 ms). Supports `paths: [...]` batching, `scene: true` multi-part export/render, and `view: "quad\|front\|back\|right\|left\|top\|iso"`. |
diff --git a/README.md b/README.md
index 9f6b778..8a5566a 100644
--- a/README.md
+++ b/README.md
@@ -23,7 +23,7 @@ Forma replaces headless Blender's 3D mesh modeling, boolean, and studio-preview
- **Declarative `Forma-Pipe` Language:** Chain primitives and ops cleanly (`box | bevel | shell | cut`) with semantic selectors (`vertical`, `top_rim`, `bottom_rim`, `outer_rim`, `top`, `sides`)—zero fragile integer vertex indices.
- **Fast, Watertight Pure-Rust Kernel:** Double-precision polyhedral mesh kernel (watertight manifold polygons/triangles), BVH-localized booleans with automatic batch chunking & fallback for multi-hole patterns, Link-Condition coplanar mesh simplification, ring-preserving bevels, shell/solidify, crease-aware Catmull-Clark subsurf, `pipe`, `loft` (`segs` 8..128), helical `thread`, `sweep`, `text3d`, and `pattern_linear`/`pattern_radial`.
-- **Spatial Constraints, Queries & Deterministic Craftsmanship Lint:** Relational placement (`| on(base)`, `| align(axis, min|center|max, val)`), BVH-accelerated 3D `clearance(a, b)`, 2D `section(part, z)` loop/area queries, Euler genus (`g`) diagnostics, and `forma lint` / `--critique` / MCP `inspect({ lint: true })` (zero-ML-weight craftsmanship checks + pairwise assembly contact graph: `INTERSECTING`, `CONTACT`, `NEAR_GAP`, `DISJOINT`; emits 0 extra tokens on clean builds).
+- **Spatial Constraints, Feature Queries & Deterministic Craftsmanship Lint:** Relational placement (`| on(base)`, `| align(axis, min|center|max, val)`), BVH-accelerated 3D `clearance(a, b)`, 2D `section(part, z)` loop/area queries, deterministic `features(part)` geometric fact extraction (planes, bores/bosses, symmetry, `min`/`p01`/`med` wall thickness — cached lazily per part and available via `forma inspect <mesh>` or MCP `inspect(part=...)`), Euler genus (`g`) diagnostics, and `forma lint` / `--critique` / MCP `inspect({ lint: true })` (zero-ML-weight craftsmanship checks + pairwise assembly contact graph: `INTERSECTING`, `CONTACT`, `NEAR_GAP`, `DISJOINT`; emits 0 extra tokens on clean builds).
- **Zero-GPU Rendering & Blueprints:** Built-in 4-view (`quad`) or single-view (`front|back|right|left|top|iso`) studio PNG renderer with branchless SSAO-lite + depth silhouettes + L1-streaming pure-Rust Deflate compression (`~20–75 KB` PNG in ~2.8 ms), plus dimensioned 1200×900 vector SVG technical blueprints (`forma draw`).
- **Universal Import, Decimation & Export:** Pure-Rust `.glb` (glTF 2.0 Y-up), `.obj`, and `.stl` importers (`load("item.glb")`), topology-preserving QEM mesh decimation (`| decimate(0.5)`), native `.glb` (PBR + LSCM/triplanar UVs), faceted ISO 10303-21 `.step` (watertight planar-face solid; no analytic cylinders/NURBS), `.3mf`, `.stl`, `.obj`, `.svg`, `.png`, and `.blend` (via optional Blender bridge). Declare your model unit with `units("mm")` (or `forma eval --unit mm`; default metres) and `.3mf`/`.step` carry it, `.glb` is scaled to metres.
- **Optional Headless Server (`forma-server`):** Separate opt-in HTTP/1.1 worker crate (`cargo build --release -p forma-server`, compact static binary, `< 5 MB` scratch `Dockerfile`) with zero impact on the core `forma` CLI, `forma-mcp`, or `forma-3d` npm/WASM bundle.
@@ -69,6 +69,11 @@ EOF
Forma is designed for drop-in agent use via **MCP**, **CLI**, **Agent Skills**, or **GBNF constrained decoding**:
+- **Let your coding agent set Forma up:** paste into Claude Code, Codex, Cursor, or Antigravity:
+ ```text
+ Run `curl -fsSL https://raw.githubusercontent.com/wrong-nebula/forma/main/docs/agent-setup.md`, read all of it, and set up Forma for me.
+ ```
+- **Agent setup runbook:** [`docs/agent-setup.md`](docs/agent-setup.md)
- **LLM Agent Skill:** [`SKILL.md`](SKILL.md)
- **Machine-readable index:** [`llms.txt`](llms.txt)
- **Full agent integration guide:** [`AGENTS.md`](AGENTS.md)
@@ -93,6 +98,7 @@ Or invoke directly from any shell-capable agent:
```bash
forma spec # ~485-token language reference
forma eval --strict --critique --out out.glb script.forma # transactional eval + 0-tok clean critique
+forma inspect part.stl # invariants + compiled CAD facts (planes, bores, wall thickness)
forma lint --json script.forma # Layer A geometric lint + contact graph
forma render --out preview.png script.forma # 4-view studio PNG (~2.8 ms, zero GPU)
forma draw --out blueprint.svg script.forma # dimensioned vector engineering blueprint
diff --git a/SKILL.md b/SKILL.md
index 3ef0b65..2063254 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -183,4 +183,5 @@ mug = _body | add(_handle)
- **Bevel order:** Apply `bevel(vertical, w)` *before* `shell(t)` when hollowing an enclosure so inner and outer walls stay clean and uniform.
- **Batch multi-hole cuts:** Pass a coordinate list (or comprehension `[... for i in range(n)]`) to `cut(cyl(r, h), at=...)` instead of chaining separate `cut()` calls — it is faster and produces cleaner topology.
- **Keep scenes clean:** Prefix intermediate meshes with `_` (`_cut`, `_body`) so only final parts enter `scene.parts`, or remove stale parts with `del("name")`.
+- **3D-print readiness:** Decide `render-only` vs. `print` upfront—for printable parts, start with `units("mm")`, use higher segment counts (`segs=64`) on measured bores/cylinders, and model functional mating faces/holes before aesthetic bevels.
- **Strict verification:** Never deliver a mesh that fails `--strict` (`WT=ok NM=0`). `eval(strict=true)` auto-rolls back failures cleanly; use `tx(action="undo")` if a valid edit needs reverting.
diff --git a/bin/forma-mcp.mjs b/bin/forma-mcp.mjs
index 0a7ad24..b9f0246 100755
--- a/bin/forma-mcp.mjs
+++ b/bin/forma-mcp.mjs
@@ -38,10 +38,11 @@ function buildToolsSchema(specPipe) {
},
{
name: "inspect",
- description: "Invariants, lint, or topic spec.",
+ description: "Invariants, part features, lint, or topic spec.",
inputSchema: {
type: "object",
properties: {
+ part: { type: "string" },
topic: {
type: "string",
enum: ["deform", "curves", "uv", "remesh", "scene"],
@@ -235,7 +236,10 @@ async function handleToolCall(engine, session, name, args) {
return [false, session.lint().text, []];
}
if (typeof args?.part === "string" && args.part.trim().length > 0) {
- return [false, session.inspectPart(args.part.trim()), []];
+ const partName = args.part.trim();
+ const obsText = session.inspectPart(partName);
+ const featText = session.features(partName).text;
+ return [false, `${obsText}\n${featText}`, []];
}
const obs = session.inspect();
return [false, obs.text, []];
diff --git a/contribute/craftsmanship.md b/contribute/craftsmanship.md
index b58a237..d17ca43 100644
--- a/contribute/craftsmanship.md
+++ b/contribute/craftsmanship.md
@@ -22,6 +22,7 @@ Instead, split quality feedback into:
1. **Deterministic Geometric Craftsmanship Critic (`forma lint` / `--critique`, `invariants.rs` & `spatial.rs`) — ✅ Implemented:**
- Emits **0 extra tokens** on clean `--critique` builds (`0.0%` FPR / `100.0%` recall verified across 28 reference + failure models; median `8.8 ms` end-to-end incl. eval).
- Flags `INVALID_SOLID`, `FLOATING_SHELL`, `DEGENERATE_FACES` (`> 0.5%`), `THIN_WALL` (`wall_proxy < 0.005`), `EXTREME_ASPECT` (`> 20:1`), `GRAZING_GAP` (scale-relative `5e-4 × pair_diag`), `PART_INTERSECTION`, and opt-in `RAW_BOX` (`--raw-box`).
+ - **Next refinements:** upgrade `THIN_WALL` to build on `WallThicknessReport`'s inward-ray `min`/`p01` in `features.rs` (separating localized chamfer/lip knife-edges from true thin walls), reuse `boolean::check_self_intersections`, and add center-of-mass stability/tipping overhang checks.
- **BVH-Accelerated Assembly Contact Graph (`spatial.rs`):** Computes exact pairwise part contacts (`INTERSECTING`, `CONTACT`, `NEAR_GAP`, `DISJOINT`) using `SpatialBvh` + strict-interior piercing witness & inward face-centroid winding disambiguation (distinguishing flush mating / exact pin-in-bore `CONTACT` from volumetric `INTERSECTING`). Exposed via `forma lint [--json] [--raw-box]`, `forma eval --critique`, MCP `inspect({ lint: true })`, and WASM/JS `session.lint()`. Semantic "missing hardware" judgment intentionally stays in **Layer B** (the host frontier LLM).
2. **Declarative Spatial Assertions & Stateless Articulation Sweeps (`assert` in `Forma-Pipe`):**
@@ -31,10 +32,10 @@ Instead, split quality feedback into:
assert connected(assembly)
assert grounded(base, z=0)
assert section_loops(flange, z=0) == 6
- assert swing_clear(lid, housing, origin=(0,-0.05,0.04), axis=(1,0,0), deg=110) >= 0.0003
- assert slide_clear(drawer, chassis, dir=(0,-1,0), dist=0.08) >= 0.0003
+ assert swing_clear(lid, housing, origin=(0,-0.05,0.04), axis=(1,0,0), deg=110, tol=2) >= 0.0003
+ assert slide_clear(drawer, chassis, dir=(0,-1,0), dist=0.08, tol=0.002) >= 0.0003
```
- - **Stateless Articulation Clearance (`swing_clear` / `slide_clear`):** Inspired by the geometric swing-collision testing and motion rectification stage of *Functionalization / GraFu* ([Zhao et al., SIGGRAPH Asia 2026](https://mingrui-zhao.github.io/Functionalization/), `arXiv:2605.18010`), samples rigid-transform poses along a revolute arc or prismatic travel with AABB pruning + `spatial::clearance()`, reporting the exact collision angle/distance and hit centroid in `< 5 ms` without introducing persistent rigging or animation state into core `Scene`.
+ - **Stateless Articulation Clearance (`swing_clear` / `slide_clear`):** Inspired by the geometric swing-collision testing and motion rectification stage of *Functionalization / GraFu* ([Zhao et al., SIGGRAPH Asia 2026](https://mingrui-zhao.github.io/Functionalization/), `arXiv:2605.18010`), samples rigid-transform poses along a revolute arc or prismatic travel with AABB pruning + `spatial::clearance()`, reporting the exact collision angle/distance and hit centroid in `< 5 ms` without introducing persistent rigging or animation state into core `Scene`. Always evaluates **exact range endpoints** (`0` and `max`) plus an optional **`tol` overtravel / tolerance-extreme margin** so nominal-only sweeps cannot hide collisions at worst-case stroke.
3. **Pure Parametric Macros (`def`) + Lazy Industrial-Design Stdlib (`inspect(topic="stdlib")`):**
- Reusable sub-assemblies (`def standoff(r_out, r_in, h) = ...`).
@@ -45,3 +46,7 @@ Instead, split quality feedback into:
5. **Actionable Grazing-Boolean Diagnostics (`boolean.rs`):**
- Pinpoint the exact offending edge centroid `(x, y, z)` and suggest a concrete overlap/extension fix whenever `--strict` rolls back a grazing coplanar boolean.
+
+6. **Agent Workflow Guardrails & Plugin Ergonomics (`forma-mcp` / `forma-cli`):**
+ - **Purpose-upfront & interfaces-before-cosmetics:** encourage deciding `render-only` vs. `print`/`both` before detailing (locking `units("mm")`, higher `segs` on printed bores, and real wall thickness up front), modeling mating faces/bores before aesthetic bevels, and taking a `tx(checkpoint)` before optional cleanup ops (`remesh`/`decimate`).
+ - **Zero-token MCP Prompts/Resources & `forma doctor`:** expose starter workflow prompts/resources alongside `forma-mcp`'s 4 tools (`0` extra tool-schema tokens), plus a lightweight offline `forma doctor` check for plugin/CLI installs.
diff --git a/contribute/forma-print.md b/contribute/forma-print.md
index fd3746d..559b8cf 100644
--- a/contribute/forma-print.md
+++ b/contribute/forma-print.md
@@ -40,13 +40,14 @@
| Constraint | FDM (`0.4 mm` Nozzle) | SLA / MSLA Resin | SLS (PA12) | Detection Algorithm in `forma-print` |
|---|---|---|---|---|
-| **Min Wall Thickness** | `≥ 0.84 mm` (2 lines); functional `≥ 1.6 mm` | `≥ 0.5 mm` supported / `≥ 1.0 mm` unsupported | `≥ 0.7–1.0 mm` | Inward BVH raycast along `-n_f` (+ 4 tilted cone rays ±12°) from face centroids; flag `t_min < min_wall`. |
-| **Overhang Angle** | **45°** (`n.z < -0.7071`; MK4S/X1C ~55°) | **30°** (`n.z < -0.866`) | None (powder bed) | Exclude bed faces (`z <= z_min + layer_h`); flag downward faces exceeding angle limit (excluding short bridges). |
+| **Min Wall Thickness (Screen)** | `≥ 0.84 mm` (2 lines); functional `≥ 1.6 mm` | `≥ 0.5 mm` supported / `≥ 1.0 mm` unsupported | `≥ 0.7–1.0 mm` | Inward BVH raycast along `-n_f` (+ 4 tilted cone rays ±12°) from face centroids; report `min` + `p01` (separates localized chamfer/lip artifacts from true thin walls) with all-positive-face fallback for fine collars. |
+| **Overhang Angle (Screen)** | **45°** (`n.z < -0.7071`; MK4S/X1C ~55°) | **30°** (`n.z < -0.866`) | None (powder bed) | Exclude bed faces (`z <= z_min + layer_h`); flag downward faces exceeding angle limit (excluding short bridges) and report % area share. |
+| **Self-Intersections (Screen)** | Fatal slicer artifacts / inverted shells | Cured internal voids / slicer errors | Bad slicing | Reuse `forma_core::boolean::check_self_intersections` (budgeted non-adjacent triangle-pair overlap check) to catch watertight meshes containing interpenetrating shells. |
| **Floating Islands (Z-Minima)** | Fatal without supports | **Catastrophic** (cured flake tears FEP/LCD) | N/A | Vertex-adjacency local Z-minima above `z_min` + `spatial::section_z` slice-to-slice XY overlap check (new loop with 0 overlap below = floating island). |
| **Bridge Spans** | Safe `≤ 10–25 mm` (PLA/PETG), `≤ 8–12 mm` (ABS) | Poor (`≤ 2–3 mm`) | Unlimited | Horizontal downward planar clusters (`n.z < -0.98`, `z > z_min + layer_h`): classify supported vs open boundary edges and span width. |
| **XY Clearances & Shrinkage** | Tight `0.15 mm`, snug `0.20 mm`, sliding/PIP `0.30–0.40 mm` | Tight `0.10 mm`, sliding `0.20–0.30 mm` | `≥ 0.50 mm` (powder clearing) | `forma_core::spatial::clearance(a, b)` on scene part pairs; flag fusing gaps `< min_clearance` or intersections. |
-| **Articulated / PIP Travel** | Rest `≥ 0.30–0.40 mm`; full travel `> 0`; pin axis aligned against layer shear | Rest `≥ 0.20–0.30 mm`; drain resin traps in knuckles | Rest `≥ 0.50 mm` for powder escape across joint | Stateless revolute/prismatic swept clearance (`swing_clear` / `slide_clear`) across full operating range + joint-axis orientation check against build Z. |
-| **Bed Adhesion & Tipping** | Elephant's foot `0.15–0.30 mm`; warn if contact `< 100 mm²` or `H / width > 4` | Usually angled 30–45° on raft | N/A | Bed-face area sum + 2D convex hull of bed footprint + divergence-theorem Center of Mass `(com.x, com.y)` inside-hull check. |
+| **Articulated / PIP Travel** | Rest `≥ 0.30–0.40 mm`; full travel `> 0`; pin axis aligned against layer shear | Rest `≥ 0.20–0.30 mm`; drain resin traps in knuckles | Rest `≥ 0.50 mm` for powder escape across joint | Stateless revolute/prismatic swept clearance (`swing_clear` / `slide_clear`) across exact range endpoints + tolerance overtravel, plus joint-axis orientation check against build Z. |
+| **Bed Fit, Adhesion & Tipping** | Usable XY = `bed_xy - 2 × brim_margin` (allowing 90° XY swap); elephant's foot `0.15–0.30 mm`; warn if contact `< 100 mm²` or `H / width > 4` | Usually angled 30–45° on raft | Check Z & XY packing envelope | Brim-aware sorted-XY bed fit (+ optional informational `bambu_a1_mini` 180³ mm flag), bed-face area sum, 2D convex hull of bed footprint, and divergence-theorem CoM `(com.x, com.y)` inside-hull check. |
| **SLA Suction Cups & Traps** | N/A | Vacuum tears layers / trapped liquid resin cracks part; needs ≥2 holes `Ø ≥ 3.5 mm` | Trapped powder; needs ≥2 holes `Ø ≥ 5.0 mm` | Track CW inner hole loops across `section_z` slices: closed-top downward-open cavity = **suction cup**; enclosed negative shell = **trapped cavity**. |
| **AMS / MMU Swap Waste** | `~0.4–1.5 g` purge + `~45–90 s` per swap on single-nozzle AMS/MMU | Single vat | Single bed | Count unique `mat_id` transitions per Z-layer band; estimate purge grams and recommend orientation minimizing color-change layers. |
@@ -79,7 +80,9 @@ model.3mf (ZIP + pure-Rust RFC-1951 Deflate, 5-8x smaller than stored ZIP)
Dragging a `forma-print`-exported `.3mf` into **Bambu Studio, OrcaSlicer, or PrusaSlicer** automatically pre-populates AMS/MMU filament slots with the colors from Forma's `mat()` calls — and supports tagging parts as `subtype="modifier_part"` (e.g. local 100% infill around bolt bosses).
-### 2.3 Verified CNC Kitchen / Voron Heat-Set Insert Table
+### 2.3 Verified Hardware & Fastener Standards (`fasteners.rs`)
+
+#### CNC Kitchen / Voron Heat-Set Insert Table
| Spec ID | Insert OD × L (mm) | CAD Pilot Ø (mm) | Blind Depth (mm) | Min Boss OD (mm) | Lead-in Chamfer |
|---|---|---|---|---|---|
@@ -90,6 +93,13 @@ Dragging a `forma-print`-exported `.3mf` into **Bambu Studio, OrcaSlicer, or Pru
| `M4` | `6.3 × 8.1` | `5.6` | `9.1` | `11.0` | `0.6 mm × 45°` |
| `M5` | `7.5 × 9.5` | `6.4` | `10.5` | `13.0` | `0.7 mm × 45°` |
+#### Published Metric Fastener Reference Tables (`M2`–`M12`)
+
+- **ISO 273:1979** clearance holes (`close` / `medium` / `coarse` series) for bolts and screws.
+- **ISO 4762** socket-head cap screw head dimensions (`dk_max`, `k_max`).
+- **DIN 974-1** counterbore diameters for ISO 4762 heads (`M3`–`M12`).
+- **No-guess rule:** Every table lookup carries its standard citation; any size absent from the table is reported as `unchecked` rather than interpolated. For heat-set inserts placed in through-holes without an explicit blind depth, check the part's thickness along the hole axis so an insert deeper than the plate cannot silently pass.
+
---
## 3. Zero-Bloat Addon Architecture
@@ -105,9 +115,9 @@ flowchart LR
### Five Clean Integration Surfaces
-1. **Standalone Binary (`forma-print`):** `forma-print check|orient|pack|split|export ...` (accepts `.forma`, `.glb`, `.stl`, `.obj`, or stdin).
+1. **Standalone Binary (`forma-print`):** `forma-print check|gate|orient|pack|split|export ...` (accepts `.forma`, `.glb`, `.stl`, `.obj`, or stdin).
2. **Git-Style CLI Dispatch (`forma print ...`):** ~25 LOC in `forma-cli` / `bin/forma.mjs` forwards `forma <subcmd>` to `forma-<subcmd>` on `$PATH` (`< 1 KB` core impact, `0` new deps).
-3. **Opt-In MCP Server (`forma-print --mcp`):** Registered separately *only* for 3D printing workflows — 4 composable tools (`print_check`, `print_prep`, `print_export`, `print_profiles`) at **`~380 o200k` tokens** (`0` tokens on core `forma-mcp`).
+3. **Opt-In MCP Server (`forma-print --mcp`):** Registered separately *only* for 3D printing workflows — 4 composable tools (`print_check`, `print_prep`, `print_export`, `print_profiles`) at **`~380 o200k` tokens** (`0` tokens on core `forma-mcp`), plus zero-tool-token MCP prompts & resources (starter build-spec schema, print-gate workflow prompt).
4. **Optional npm WASM (`@forma-3d/print`):** Client-side parametric `.3mf` + instant DFM heatmaps (~90–130 KB delta over core).
5. **Optional Cargo Feature (`--features print`):** Embeds `forma print` into `forma-cli` or `/v1/print/*` routes into `forma-server` on demand.
@@ -116,11 +126,12 @@ flowchart LR
## 4. Three-Tier Implementation Roadmap
### Tier 1 — MVP (Shipped in `crates/forma-print`, 0 new crates)
-- **`profiles.rs`:** 16+ verified FDM/SLA/SLS printer & filament profiles.
-- **`bvh.rs` + `dfm.rs`:** Pure-Rust DFM audit (`~8–25 ms` on 10k tris): watertight/manifold, build-volume fit, overhangs, floating islands, bridge vs. unsupported ceilings, BVH inward raycast min wall thickness, bed-adhesion/CoM stability, multi-part clearance, AMS swap count, material mass/time estimate.
+- **`profiles.rs` & `fasteners.rs`:** 16+ verified FDM/SLA/SLS printer & filament profiles plus published ISO 273 / ISO 4762 / DIN 974-1 / heat-set tables with explicit provenance strings.
+- **`bvh.rs` + `dfm.rs`:** Pure-Rust DFM audit (`~8–25 ms` on 10k tris): watertight/manifold, self-intersection check (reusing `forma_core::boolean::check_self_intersections`), brim-aware build-volume fit (+ optional informational compact-bed compatibility flag), overhangs, floating islands, bridge vs. unsupported ceilings, BVH inward raycast min/`p01` wall thickness screen (with small-face fallback), bed-adhesion/CoM stability, multi-part clearance, AMS swap count, material mass/time estimate.
+- **`gate.rs` (Spec-Driven Production Gate & Active Bore Metrology):** Validates an optional declarative `spec.json` contract (`units: "mm"`, target bbox ± tol, expected shells, `min_wall_mm`, `max_overhang_area_pct`, `brim_margin_mm`, declared bores/D-holes with fastener standards, `required_checks`) with deterministic exit codes (`0` pass, `1` requirement failed, `2` invalid contract). Includes active ray probes for declared holes: axial bore-clear & blind-depth probes (ray reach derived from projected mesh extent along the bore axis, never a fixed cap), 4-quadrant material-around breakout checks, median-of-3 jittered radial ring diameter sampling (immune to tessellation-edge leaks), and D-hole flat splitting (`r · cos(φ)`). Reports separate `checked`, `unchecked`, and `exclusions` lists so digital screens are never conflated with physical fit, load, thermal, or shrinkage qualification.
- **`heatmap.rs`:** Color-coded 4-view diagnostic PNG (`< 4 ms`) by assigning a 5-slot DFM severity palette to `face.mat_id` and calling `forma_core::render::render_quad_png_bytes` directly (no duplicate renderer).
- **`orient.rs`:** Auto-orientation solver testing planar face clusters + convex-hull facets against weighted `(overhangs, islands, support_vol, bed_area, z_height, ams_swaps)` in `~15–40 ms`.
-- **`export_3mf.rs`:** Pure-Rust Deflate-compressed `unit="millimeter"` 3MF with `<basematerials>`, `<m:colorgroup>`, Bambu/Orca `Metadata/model_settings.config` + `project_settings.config`, Prusa `Slic3r_PE_model.config`, embedded `256×256` thumbnail, plus mm-scaled `.step`.
+- **`export_3mf.rs` (+ Round-Trip Audit):** Pure-Rust Deflate-compressed `unit="millimeter"` 3MF with `<basematerials>`, `<m:colorgroup>`, Bambu/Orca `Metadata/model_settings.config` + `project_settings.config`, Prusa `Slic3r_PE_model.config`, embedded `256×256` thumbnail, plus mm-scaled `.step`. Supports `--verify-roundtrip` to re-import exported `.3mf`/`.stl` bytes via `forma_core::import`, re-check topology + mm bbox, and emit a `manifest.json` binding source/spec/output SHA-256 hashes and triangle counts.
### Tier 2 — Print-Native CAD, Splitting & Plate Nesting (~2.8k LOC, 0 new crates)
- **SLA Suction-Cup & Trapped-Cavity Detector:** Slice-graph tracking of CW inner loops across `section_z` + enclosed negative shells (`~20–60 ms`), plus **auto-hollow + lowest-Z drain & top vent holes** (`solidify_mesh` + boolean plugs).
diff --git a/crates/forma-cli/src/main.rs b/crates/forma-cli/src/main.rs
index 52c8ba1..284a688 100644
--- a/crates/forma-cli/src/main.rs
+++ b/crates/forma-cli/src/main.rs
@@ -4,10 +4,11 @@
//! forma eval [--dialect pipe|compact] [--unit m|cm|mm|um|in|ft] [--strict|--no-strict] [--no-fs] [--allow-import-dir DIR] [--json] [--scene] [--out FILE] [--render PNG] [--draw SVG] [file|-]
//! forma render [--scene] [--no-fs] [--allow-import-dir DIR] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]
//! forma draw [--scene] [--no-fs] [--allow-import-dir DIR] --out blueprint.svg [file|-]
+//! forma inspect [--unit m|cm|mm|um|in|ft] [--yup|--no-yup] [--json] <file.(glb|obj|stl)>
//! forma spec [--dialect pipe|compact] [--topic TOPIC] [--gbnf]
//! forma version | --version | -V
-use forma_core::{LintOptions, Scene, Unit};
+use forma_core::{LintOptions, MeshInvariants, Scene, Unit};
use forma_lang::{
eval_script, is_invariant_violation_err, spec_topic, Dialect, SPEC_COMPACT, SPEC_PIPE,
SPEC_PIPE_GBNF,
@@ -27,6 +28,7 @@ fn print_help() {
forma lint [--unit UNIT] [--strict|--no-strict] [--no-fs] [--allow-import-dir DIR] [--raw-box] [--json] [--dialect pipe|compact] [file|-]\n\
forma render [--scene] [--no-fs] [--allow-import-dir DIR] [--size 512] [--view quad|front|back|right|left|top|iso] --out preview.png [file|-]\n\
forma draw [--scene] [--no-fs] [--allow-import-dir DIR] --out blueprint.svg [file|-]\n\
+ forma inspect [--unit m|cm|mm|um|in|ft] [--yup|--no-yup] [--json] <file.(glb|obj|stl)>\n\
forma spec [--dialect pipe|compact] [--topic deform|curves|uv|remesh|scene] [--gbnf]\n\
forma version | --version | -V\n\
forma --help\n\
@@ -133,6 +135,99 @@ fn main() {
}
return;
}
+ "inspect" => {
+ let mut unit = Unit::default();
+ let mut as_json = false;
+ let mut yup: Option<bool> = None;
+ let mut mesh_file: Option<String> = None;
+ let mut i = 1;
+ while i < args.len() {
+ match args[i].as_str() {
+ "--unit" | "-u" => {
+ if i + 1 >= args.len() {
+ eprintln!("ERR: --unit requires value (m|cm|mm|um|in|ft)");
+ process::exit(2);
+ }
+ unit = Unit::parse(&args[i + 1]).unwrap_or_else(|e| {
+ eprintln!("ERR: {e}");
+ process::exit(2);
+ });
+ i += 2;
+ }
+ "--json" => {
+ as_json = true;
+ i += 1;
+ }
+ "--yup" => {
+ yup = Some(true);
+ i += 1;
+ }
+ "--no-yup" => {
+ yup = Some(false);
+ i += 1;
+ }
+ arg if arg.starts_with('-') => {
+ eprintln!("ERR: unknown flag '{arg}' for `forma inspect`. Run `forma --help`.");
+ process::exit(2);
+ }
+ arg if mesh_file.is_none() => {
+ mesh_file = Some(arg.to_string());
+ i += 1;
+ }
+ arg => {
+ eprintln!("ERR: unexpected extra argument '{arg}' for `forma inspect`");
+ process::exit(2);
+ }
+ }
+ }
+ let Some(path_str) = mesh_file else {
+ eprintln!("ERR: `forma inspect` requires a mesh file (.glb, .obj, or .stl)");
+ process::exit(2);
+ };
+ let path = PathBuf::from(&path_str);
+ let t0 = std::time::Instant::now();
+ match forma_core::import::import_mesh_with_opts(&path, yup) {
+ Ok(mesh) => {
+ let inv = MeshInvariants::compute(&mesh);
+ let feats = forma_core::features::extract_features(&mesh);
+ let ms = t0.elapsed().as_secs_f64() * 1000.0;
+ let name = path
+ .file_stem()
+ .and_then(|s| s.to_str())
+ .unwrap_or("mesh");
+ let text = format!(
+ "OK [{ms:.2}ms]\n{}\n{}",
+ inv.summary_line(name),
+ feats.summary(name, unit)
+ );
+ if as_json {
+ println!(
+ "{}",
+ serde_json::json!({
+ "ok": true,
+ "elapsed_ms": ms,
+ "part": name,
+ "unit": unit.symbol(),
+ "invariants": inv,
+ "features": feats,
+ "text": text,
+ })
+ );
+ } else {
+ println!("{text}");
+ }
+ }
+ Err(e) => {
+ if as_json {
+ println!("{}", serde_json::json!({ "ok": false, "error": e }));
+ } else {
+ eprintln!("ERR: {e}");
+ }
+ process::exit(1);
+ }
+ }
+ return;
+ }
"eval" | "lint" | "render" | "draw" => {}
other => {
eprintln!("ERR: unknown subcommand '{other}'. Run `forma --help`.");
diff --git a/crates/forma-core/src/features.rs b/crates/forma-core/src/features.rs
new file mode 100644
index 0000000..9694841
--- /dev/null
+++ b/crates/forma-core/src/features.rs
@@ -0,0 +1,1211 @@
+//! Deterministic geometric feature compiler ("compile at ingest, query compact facts").
+//!
+//! Extracts compact, machine-verified CAD facts from any `PolyMesh` (including imported
+//! `.glb`, `.obj`, and `.stl` meshes) so AI agents can query mounting planes, cylindrical
+//! bores/bosses, symmetry, and wall thickness without blind coordinate guesswork.
+
+use crate::math::{Aabb, Vec3};
+use crate::mesh::PolyMesh;
+use crate::units::Unit;
+use serde::{Deserialize, Serialize};
+use std::collections::{HashMap, HashSet, VecDeque};
+
+/// A merged coplanar face region (e.g. a flat mounting face, plate top/bottom, or flange wall).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct PlanarRegion {
+ pub orientation: String,
+ pub normal: [f64; 3],
+ pub offset: f64,
+ pub area: f64,
+ pub centroid: [f64; 3],
+ pub bbox_min: [f64; 3],
+ pub bbox_max: [f64; 3],
+ pub span: [f64; 3],
+ pub face_count: usize,
+}
+
+/// A detected cylindrical surface: either an internal `bore` (hole) or external `boss` (shaft).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct CylindricalFeature {
+ pub kind: String,
+ pub axis_label: String,
+ pub axis: [f64; 3],
+ pub center: [f64; 3],
+ pub radius: f64,
+ pub diameter: f64,
+ pub height: f64,
+ pub arc_deg: f64,
+ pub face_count: usize,
+}
+
+/// Opposite-wall raycast thickness screen (`min`, 1st percentile `p01`, and `median`).
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct WallThicknessReport {
+ pub min: f64,
+ #[serde(default)]
+ pub p01: f64,
+ pub median: f64,
+ pub samples: usize,
+}
+
+/// Compiled geometric fact sheet for a mesh, cached lazily per immutable `CachedPart`.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct MeshFeatures {
+ pub bbox_min: [f64; 3],
+ pub bbox_max: [f64; 3],
+ pub size: [f64; 3],
+ pub center: [f64; 3],
+ pub surface_area: f64,
+ pub symmetry: [bool; 3],
+ pub wall_thickness: Option<WallThicknessReport>,
+ pub planes: Vec<PlanarRegion>,
+ pub cylinders: Vec<CylindricalFeature>,
+}
+
+impl MeshFeatures {
+ /// Format a compact, agent-readable geometric fact sheet (~60–180 tokens).
+ pub fn summary(&self, name: &str, unit: Unit) -> String {
+ #[inline]
+ fn z0(v: f64) -> f64 {
+ if v.abs() < 5e-4 { 0.0 } else { v }
+ }
+ let sym_str = {
+ let mut s = String::new();
+ if self.symmetry[0] {
+ s.push('X');
+ }
+ if self.symmetry[1] {
+ s.push('Y');
+ }
+ if self.symmetry[2] {
+ s.push('Z');
+ }
+ if s.is_empty() {
+ "none".to_string()
+ } else {
+ s
+ }
+ };
+ let unit_suffix = if unit == Unit::Meter {
+ String::new()
+ } else {
+ format!(" unit={}", unit.symbol())
+ };
+ let wall_suffix = match &self.wall_thickness {
+ Some(w) => format!(
+ " wall_min={:.3} wall_p01={:.3} wall_med={:.3}",
+ z0(w.min),
+ z0(w.p01),
+ z0(w.median)
+ ),
+ None => String::new(),
+ };
+
+ let mut lines = Vec::new();
+ lines.push(format!(
+ "features({name}): size=[{:.3},{:.3},{:.3}] center=[{:.3},{:.3},{:.3}] sym={sym_str}{wall_suffix}{unit_suffix}",
+ z0(self.size[0]),
+ z0(self.size[1]),
+ z0(self.size[2]),
+ z0(self.center[0]),
+ z0(self.center[1]),
+ z0(self.center[2]),
+ ));
+
+ if !self.planes.is_empty() {
+ let shown = self.planes.len().min(6);
+ let extra = if self.planes.len() > shown {
+ format!(" (top {shown} of {})", self.planes.len())
+ } else {
+ String::new()
+ };
+ lines.push(format!(" planes({}){extra}:", self.planes.len()));
+ for p in self.planes.iter().take(shown) {
+ let coord_desc = match p.orientation.as_str() {
+ "+z" => format!("z={:.3}", z0(p.offset)),
+ "-z" => format!("z={:.3}", z0(-p.offset)),
+ "+x" => format!("x={:.3}", z0(p.offset)),
+ "-x" => format!("x={:.3}", z0(-p.offset)),
+ "+y" => format!("y={:.3}", z0(p.offset)),
+ "-y" => format!("y={:.3}", z0(-p.offset)),
+ _ => format!(
+ "n=[{:.2},{:.2},{:.2}] d={:.3}",
+ z0(p.normal[0]),
+ z0(p.normal[1]),
+ z0(p.normal[2]),
+ z0(p.offset)
+ ),
+ };
+ lines.push(format!(
+ " {} @ {coord_desc} area={:.3} center=[{:.3},{:.3},{:.3}] span=[{:.3},{:.3},{:.3}]",
+ p.orientation,
+ z0(p.area),
+ z0(p.centroid[0]),
+ z0(p.centroid[1]),
+ z0(p.centroid[2]),
+ z0(p.span[0]),
+ z0(p.span[1]),
+ z0(p.span[2]),
+ ));
+ }
+ }
+
+ if !self.cylinders.is_empty() {
+ let shown = self.cylinders.len().min(12);
+ let extra = if self.cylinders.len() > shown {
+ format!(" (top {shown} of {})", self.cylinders.len())
+ } else {
+ String::new()
+ };
+ lines.push(format!(" cylinders({}){extra}:", self.cylinders.len()));
+ for c in self.cylinders.iter().take(shown) {
+ let axis_desc = if c.axis_label == "oblique" {
+ format!("[{:.2},{:.2},{:.2}]", z0(c.axis[0]), z0(c.axis[1]), z0(c.axis[2]))
+ } else {
+ c.axis_label.clone()
+ };
+ lines.push(format!(
+ " {} axis={axis_desc} r={:.3} d={:.3} h={:.3} center=[{:.3},{:.3},{:.3}] arc={:.0}deg",
+ c.kind,
+ z0(c.radius),
+ z0(c.diameter),
+ z0(c.height),
+ z0(c.center[0]),
+ z0(c.center[1]),
+ z0(c.center[2]),
+ c.arc_deg,
+ ));
+ }
+ }
+
+ lines.join("\n")
+ }
+}
+
+struct CoplanarPatch {
+ faces: Vec<usize>,
+ normal: Vec3,
+ centroid: Vec3,
+ area: f64,
+ bbox: Aabb,
+}
+
+fn orient_label(n: Vec3) -> String {
+ const AXIS_COS: f64 = 0.996; // ~5 degrees
+ if n.z >= AXIS_COS {
+ "+z".into()
+ } else if n.z <= -AXIS_COS {
+ "-z".into()
+ } else if n.x >= AXIS_COS {
+ "+x".into()
+ } else if n.x <= -AXIS_COS {
+ "-x".into()
+ } else if n.y >= AXIS_COS {
+ "+y".into()
+ } else if n.y <= -AXIS_COS {
+ "-y".into()
+ } else {
+ "oblique".into()
+ }
+}
+
+fn canonical_axis(a: Vec3) -> Vec3 {
+ let u = a.normalized();
+ if u.len_sq() < 0.5 {
+ return Vec3::Z;
+ }
+ // Canonical sign: make the largest-magnitude component positive (tie-break Z > Y > X).
+ let (ax, ay, az) = (u.x.abs(), u.y.abs(), u.z.abs());
+ let sign = if az >= ay && az >= ax {
+ if u.z < 0.0 { -1.0 } else { 1.0 }
+ } else if ay >= ax {
+ if u.y < 0.0 { -1.0 } else { 1.0 }
+ } else if u.x < 0.0 {
+ -1.0
+ } else {
+ 1.0
+ };
+ u * sign
+}
+
+fn axis_label(a: Vec3) -> String {
+ const AXIS_COS: f64 = 0.996;
+ if a.z.abs() >= AXIS_COS {
+ "+z".into()
+ } else if a.x.abs() >= AXIS_COS {
+ "+x".into()
+ } else if a.y.abs() >= AXIS_COS {
+ "+y".into()
+ } else {
+ "oblique".into()
+ }
+}
+
+/// Solve 3x3 linear system `m * x = b` via partial pivoting.
+fn solve_3x3(mut m: [[f64; 3]; 3], mut b: [f64; 3]) -> Option<[f64; 3]> {
+ for col in 0..3 {
+ let mut pivot = col;
+ let mut best = m[col][col].abs();
+ for r in (col + 1)..3 {
+ let v = m[r][col].abs();
+ if v > best {
+ best = v;
+ pivot = r;
+ }
+ }
+ if best < 1e-14 {
+ return None;
+ }
+ if pivot != col {
+ m.swap(col, pivot);
+ b.swap(col, pivot);
+ }
+ let diag = m[col][col];
+ for r in (col + 1)..3 {
+ let factor = m[r][col] / diag;
+ for c in col..3 {
+ m[r][c] -= factor * m[col][c];
+ }
+ b[r] -= factor * b[col];
+ }
+ }
+ let mut x = [0.0; 3];
+ for i in (0..3).rev() {
+ let mut sum = b[i];
+ for j in (i + 1)..3 {
+ sum -= m[i][j] * x[j];
+ }
+ x[i] = sum / m[i][i];
+ }
+ if x.iter().all(|v| v.is_finite()) {
+ Some(x)
+ } else {
+ None
+ }
+}
+
+/// Numerically stable Kåsa 2D algebraic circle fit returning `(cx, cy, radius)`.
+fn fit_circle_2d(pts: &[(f64, f64)]) -> Option<(f64, f64, f64)> {
+ if pts.len() < 3 {
+ return None;
+ }
+ let inv_n = 1.0 / (pts.len() as f64);
+ let mut mx = 0.0;
+ let mut my = 0.0;
+ for &(x, y) in pts {
+ mx += x;
+ my += y;
+ }
+ mx *= inv_n;
+ my *= inv_n;
+
+ let mut sxx = 0.0;
+ let mut sxy = 0.0;
+ let mut syy = 0.0;
+ let mut sx = 0.0;
+ let mut sy = 0.0;
+ let mut bx = 0.0;
+ let mut by = 0.0;
+ let mut b1 = 0.0;
+ let n = pts.len() as f64;
+
+ for &(px, py) in pts {
+ let x = px - mx;
+ let y = py - my;
+ let z = x * x + y * y;
+ sxx += x * x;
+ sxy += x * y;
+ syy += y * y;
+ sx += x;
+ sy += y;
+ bx += x * z;
+ by += y * z;
+ b1 += z;
+ }
+
+ // Solve [2*sxx 2*sxy sx; 2*sxy 2*syy sy; 2*sx 2*sy n] * [cx', cy', d'] = [bx, by, b1]
+ let m = [
+ [2.0 * sxx, 2.0 * sxy, sx],
+ [2.0 * sxy, 2.0 * syy, sy],
+ [2.0 * sx, 2.0 * sy, n],
+ ];
+ let sol = solve_3x3(m, [bx, by, b1])?;
+ let cx_rel = sol[0];
+ let cy_rel = sol[1];
+ let d_rel = sol[2];
+ let r2 = cx_rel * cx_rel + cy_rel * cy_rel + d_rel;
+ if !r2.is_finite() || r2 <= 0.0 {
+ return None;
+ }
+ Some((cx_rel + mx, cy_rel + my, r2.sqrt()))
+}
+
+fn build_face_adjacency(mesh: &PolyMesh, face_valid: &[bool]) -> Vec<Vec<usize>> {
+ let mut edge_faces: HashMap<(usize, usize), Vec<usize>> = HashMap::new();
+ for (fi, f) in mesh.faces.iter().enumerate() {
+ if !face_valid[fi] {
+ continue;
+ }
+ let n = f.verts.len();
+ for i in 0..n {
+ let u = f.verts[i];
+ let v = f.verts[(i + 1) % n];
+ if u == v {
+ continue;
+ }
+ let key = if u < v { (u, v) } else { (v, u) };
+ edge_faces.entry(key).or_default().push(fi);
+ }
+ }
+ let mut face_adj: Vec<Vec<usize>> = vec![Vec::new(); mesh.faces.len()];
+ for faces in edge_faces.values() {
+ for i in 0..faces.len() {
+ for j in (i + 1)..faces.len() {
+ let a = faces[i];
+ let b = faces[j];
+ if a != b {
+ face_adj[a].push(b);
+ face_adj[b].push(a);
+ }
+ }
+ }
+ }
+ for nb in &mut face_adj {
+ nb.sort_unstable();
+ nb.dedup();
+ }
+ face_adj
+}
+
+fn segment_coplanar_patches(
+ mesh: &PolyMesh,
+ face_n: &[Vec3],
+ face_a: &[f64],
+ face_c: &[Vec3],
+ face_adj: &[Vec<usize>],
+ diag: f64,
+) -> (Vec<CoplanarPatch>, Vec<Option<usize>>) {
+ let nf = mesh.faces.len();
+ let mut patch_of_face: Vec<Option<usize>> = vec![None; nf];
+ let mut patches: Vec<CoplanarPatch> = Vec::new();
+ let coplanar_cos = 1.5_f64.to_radians().cos();
+ let plane_tol = (1e-4 * diag).max(1e-6);
+
+ for seed in 0..nf {
+ if patch_of_face[seed].is_some() || face_a[seed] <= 1e-12 || face_n[seed].len_sq() < 0.5 {
+ continue;
+ }
+ let pid = patches.len();
+ let n0 = face_n[seed];
+ let c0 = face_c[seed];
+
+ let mut queue = VecDeque::new();
+ queue.push_back(seed);
+ patch_of_face[seed] = Some(pid);
+
+ let mut faces = Vec::new();
+ let mut area_sum = 0.0;
+ let mut n_acc = Vec3::ZERO;
+ let mut c_acc = Vec3::ZERO;
+ let mut bb = Aabb::empty();
+
+ while let Some(fi) = queue.pop_front() {
+ faces.push(fi);
+ let a = face_a[fi];
+ area_sum += a;
+ n_acc += face_n[fi] * a;
+ c_acc += face_c[fi] * a;
+ for &vi in &mesh.faces[fi].verts {
+ bb.include(mesh.verts[vi]);
+ }
+
+ for &nb in &face_adj[fi] {
+ if patch_of_face[nb].is_some() || face_a[nb] <= 1e-12 || face_n[nb].len_sq() < 0.5 {
+ continue;
+ }
+ if n0.dot(face_n[nb]) < coplanar_cos {
+ continue;
+ }
+ if (face_c[nb] - c0).dot(n0).abs() > plane_tol {
+ continue;
+ }
+ let verts_on_plane = mesh.faces[nb]
+ .verts
+ .iter()
+ .all(|&vi| (mesh.verts[vi] - c0).dot(n0).abs() <= 2.5 * plane_tol);
+ if !verts_on_plane {
+ continue;
+ }
+ patch_of_face[nb] = Some(pid);
+ queue.push_back(nb);
+ }
+ }
+
+ let normal = if n_acc.len_sq() > 1e-18 {
+ n_acc.normalized()
+ } else {
+ n0
+ };
+ let centroid = if area_sum > 1e-18 {
+ c_acc / area_sum
+ } else {
+ face_c[seed]
+ };
+ patches.push(CoplanarPatch {
+ faces,
+ normal,
+ centroid,
+ area: area_sum,
+ bbox: bb,
+ });
+ }
+
+ (patches, patch_of_face)
+}
+
+fn detect_cylinders(
+ mesh: &PolyMesh,
+ patches: &[CoplanarPatch],
+ patch_of_face: &[Option<usize>],
+ face_adj: &[Vec<usize>],
+ diag: f64,
+) -> (Vec<CylindricalFeature>, Vec<bool>) {
+ let np = patches.len();
+ let mut patch_adj: Vec<Vec<usize>> = vec![Vec::new(); np];
+ for (fi, nbs) in face_adj.iter().enumerate() {
+ let Some(pa) = patch_of_face[fi] else { continue };
+ for &nb in nbs {
+ let Some(pb) = patch_of_face[nb] else { continue };
+ if pa != pb {
+ patch_adj[pa].push(pb);
+ }
+ }
+ }
+ for nbs in &mut patch_adj {
+ nbs.sort_unstable();
+ nbs.dedup();
+ }
+
+ let min_cos = 50.0_f64.to_radians().cos();
+ let max_cos = 1.5_f64.to_radians().cos();
+ let mut claimed = vec![false; np];
+ let mut cylinders = Vec::new();
+
+ for p0 in 0..np {
+ if claimed[p0] {
+ continue;
+ }
+ // Find a smooth curved neighbor to establish a candidate cylinder axis.
+ let mut seed_axis: Option<Vec3> = None;
+ for &q0 in &patch_adj[p0] {
+ if claimed[q0] {
+ continue;
+ }
+ let dot = patches[p0].normal.dot(patches[q0].normal);
+ if dot >= min_cos && dot <= max_cos {
+ let cross = patches[p0].normal.cross(patches[q0].normal);
+ if cross.len_sq() > 1e-10 {
+ seed_axis = Some(canonical_axis(cross));
+ break;
+ }
+ }
+ }
+ let Some(init_axis) = seed_axis else {
+ continue;
+ };
+
+ // Grow connected patch cluster whose normals stay perpendicular to `init_axis`
+ // and transition smoothly across shared edges.
+ let mut cluster_set: HashSet<usize> = HashSet::new();
+ let mut cluster: Vec<usize> = Vec::new();
+ let mut queue = VecDeque::new();
+ cluster_set.insert(p0);
+ queue.push_back(p0);
+
+ while let Some(cur) = queue.pop_front() {
+ cluster.push(cur);
+ for &nb in &patch_adj[cur] {
+ if claimed[nb] || cluster_set.contains(&nb) {
+ continue;
+ }
+ if patches[nb].normal.dot(init_axis).abs() > 0.05 {
+ continue;
+ }
+ let dot = patches[cur].normal.dot(patches[nb].normal);
+ if dot >= min_cos {
+ cluster_set.insert(nb);
+ queue.push_back(nb);
+ }
+ }
+ }
+
+ if cluster.len() < 5 {
+ continue;
+ }
+
+ // Refine cylinder axis from all smooth internal pairs in the cluster.
+ let mut axis_acc = Vec3::ZERO;
+ for &a in &cluster {
+ for &b in &patch_adj[a] {
+ if b > a && cluster_set.contains(&b) {
+ let cross = patches[a].normal.cross(patches[b].normal);
+ if cross.len_sq() > 1e-10 {
+ let aligned = if cross.dot(init_axis) < 0.0 {
+ -cross
+ } else {
+ cross
+ };
+ axis_acc += aligned;
+ }
+ }
+ }
+ }
+ let axis = if axis_acc.len_sq() > 1e-12 {
+ canonical_axis(axis_acc)
+ } else {
+ init_axis
+ };
+
+ // Re-verify all patches remain perpendicular to the refined axis.
+ if cluster.iter().any(|&p| patches[p].normal.dot(axis).abs() > 0.06) {
+ continue;
+ }
+
+ // Orthonormal 2D basis (u, v) perpendicular to axis.
+ let ref_v = if axis.z.abs() < 0.9 { Vec3::Z } else { Vec3::X };
+ let u = ref_v.cross(axis).normalized();
+ let v = axis.cross(u);
+
+ // Gather unique vertices in cluster and project to (x, y, t).
+ let mut vert_ids: Vec<usize> = Vec::new();
+ let mut face_count = 0usize;
+ for &pid in &cluster {
+ face_count += patches[pid].faces.len();
+ for &fi in &patches[pid].faces {
+ vert_ids.extend_from_slice(&mesh.faces[fi].verts);
+ }
+ }
+ vert_ids.sort_unstable();
+ vert_ids.dedup();
+ if vert_ids.len() < 6 {
+ continue;
+ }
+
+ let mut pts_2d: Vec<(f64, f64)> = Vec::with_capacity(vert_ids.len());
+ let mut t_min = f64::INFINITY;
+ let mut t_max = f64::NEG_INFINITY;
+ for &vi in &vert_ids {
+ let p = mesh.verts[vi];
+ pts_2d.push((p.dot(u), p.dot(v)));
+ let t = p.dot(axis);
+ t_min = t_min.min(t);
+ t_max = t_max.max(t);
+ }
+ let height = t_max - t_min;
+ if !height.is_finite() || height <= 1e-5 * diag {
+ continue;
+ }
+
+ let Some((cx, cy, radius)) = fit_circle_2d(&pts_2d) else {
+ continue;
+ };
+ if !radius.is_finite() || radius <= 1e-5 * diag || radius > 100.0 * diag {
+ continue;
+ }
+
+ // Radial fit verification against all cluster vertices.
+ let max_tol = (0.04 * radius).max(1e-4 * diag);
+ let rms_tol = (0.02 * radius).max(5e-5 * diag);
+ let mut sum_sq = 0.0;
+ let mut max_err = 0.0f64;
+ for &(x, y) in &pts_2d {
+ let err = ((x - cx).hypot(y - cy) - radius).abs();
+ max_err = max_err.max(err);
+ sum_sq += err * err;
+ }
+ let rms = (sum_sq / (pts_2d.len() as f64)).sqrt();
+ if max_err > max_tol || rms > rms_tol {
+ continue;
+ }
+
+ // Compute angular sweep around fitted circle center.
+ let mut angles: Vec<f64> = cluster
+ .iter()
+ .map(|&pid| {
+ let c = patches[pid].centroid;
+ (c.dot(v) - cy).atan2(c.dot(u) - cx)
+ })
+ .collect();
+ angles.sort_by(|a, b| a.total_cmp(b));
+ let mut gaps: Vec<f64> = Vec::with_capacity(angles.len());
+ for i in 0..angles.len() {
+ let gap = if i + 1 < angles.len() {
+ angles[i + 1] - angles[i]
+ } else {
+ std::f64::consts::TAU + angles[0] - angles[i]
+ };
+ gaps.push(gap.max(0.0));
+ }
+ gaps.sort_by(|a, b| a.total_cmp(b));
+ let max_gap = *gaps.last().unwrap_or(&std::f64::consts::TAU);
+ let med_gap = gaps[gaps.len() / 2];
+ let is_full_ring = max_gap <= 52.0_f64.to_radians() && max_gap <= (1.6 * med_gap).max(1e-6);
+ let arc_deg = if is_full_ring {
+ 360.0
+ } else {
+ (360.0 - max_gap.to_degrees() + med_gap.to_degrees()).clamp(0.0, 360.0)
+ };
+ if arc_deg < 175.0 {
+ continue;
+ }
+
+ // Guard against equatorial bands on spheres and curved-axis tube slices on tori.
+ let smooth_tilt_cos = 25.0_f64.to_radians().cos();
+ let mut smooth_tilted_neighbors = 0usize;
+ let mut pos_axial_bend = 0usize;
+ let mut neg_axial_bend = 0usize;
+ for &pid in &cluster {
+ let mut has_tilted = false;
+ for &nb in &patch_adj[pid] {
+ if cluster_set.contains(&nb) {
+ continue;
+ }
+ let n_ax = patches[nb].normal.dot(axis);
+ if n_ax.abs() > 0.06 && patches[pid].normal.dot(patches[nb].normal) >= smooth_tilt_cos {
+ has_tilted = true;
+ let dt = (patches[nb].centroid - patches[pid].centroid).dot(axis);
+ let bend = n_ax * if dt >= 0.0 { 1.0 } else { -1.0 };
+ if bend > 0.06 {
+ pos_axial_bend += 1;
+ } else if bend < -0.06 {
+ neg_axial_bend += 1;
+ }
+ }
+ }
+ if has_tilted {
+ smooth_tilted_neighbors += 1;
+ }
+ }
+ // Mixed +/- axial curvature across the ring boundary indicates a curved tube/torus;
+ // short bands with mostly smooth tilted neighbors indicate a sphere equator strip.
+ if (pos_axial_bend >= 2 && neg_axial_bend >= 2)
+ || (smooth_tilted_neighbors * 2 >= cluster.len() && height < 0.35 * radius)
+ {
+ continue;
+ }
+
+ // Classify internal bore vs. external boss from radial normal sign.
+ let mut radial_sign = 0.0;
+ for &pid in &cluster {
+ let p = patches[pid].centroid;
+ let dx = p.dot(u) - cx;
+ let dy = p.dot(v) - cy;
+ let nx = patches[pid].normal.dot(u);
+ let ny = patches[pid].normal.dot(v);
+ radial_sign += patches[pid].area * (dx * nx + dy * ny);
+ }
+ let kind = if radial_sign < 0.0 { "bore" } else { "boss" }.to_string();
+
+ let t_mid = 0.5 * (t_min + t_max);
+ let center_3d = u * cx + v * cy + axis * t_mid;
+
+ for &pid in &cluster {
+ claimed[pid] = true;
+ }
+ cylinders.push(CylindricalFeature {
+ kind,
+ axis_label: axis_label(axis),
+ axis: axis.to_array(),
+ center: center_3d.to_array(),
+ radius,
+ diameter: 2.0 * radius,
+ height,
+ arc_deg,
+ face_count,
+ });
+ }
+
+ // Absorb any boolean-split sliver patches lying directly on a detected cylinder surface
+ // so stray narrow triangles along a bore/boss seam never leak into `planes`.
+ if !cylinders.is_empty() {
+ for pid in 0..np {
+ if claimed[pid] {
+ continue;
+ }
+ let p = &patches[pid];
+ for c in &mut cylinders {
+ let axis = Vec3::from_array(c.axis);
+ if p.normal.dot(axis).abs() > 0.06 {
+ continue;
+ }
+ let center = Vec3::from_array(c.center);
+ let half_h = 0.5 * c.height + (1e-3 * diag).max(1e-5);
+ let r_tol = (0.04 * c.radius).max(1e-4 * diag);
+ let on_cyl = p.faces.iter().all(|&fi| {
+ mesh.faces[fi].verts.iter().all(|&vi| {
+ let d = mesh.verts[vi] - center;
+ let t = d.dot(axis);
+ let radial = (d - axis * t).len();
+ t.abs() <= half_h && (radial - c.radius).abs() <= r_tol
+ })
+ });
+ if !on_cyl {
+ continue;
+ }
+ let d_c = p.centroid - center;
+ let radial_vec = d_c - axis * d_c.dot(axis);
+ let sign = radial_vec.dot(p.normal);
+ let matches_kind = (c.kind == "bore" && sign < 0.0) || (c.kind == "boss" && sign > 0.0);
+ if matches_kind {
+ claimed[pid] = true;
+ c.face_count += p.faces.len();
+ break;
+ }
+ }
+ }
+ }
+
+ // Deterministic sort: bores before bosses, then descending radius, then coordinates.
+ cylinders.sort_by(|a, b| {
+ let ka = if a.kind == "bore" { 0 } else { 1 };
+ let kb = if b.kind == "bore" { 0 } else { 1 };
+ ka.cmp(&kb)
+ .then_with(|| b.radius.total_cmp(&a.radius))
+ .then_with(|| a.center[0].total_cmp(&b.center[0]))
+ .then_with(|| a.center[1].total_cmp(&b.center[1]))
+ .then_with(|| a.center[2].total_cmp(&b.center[2]))
+ });
+ cylinders.truncate(32);
+
+ (cylinders, claimed)
+}
+
+fn detect_symmetry(
+ mesh: &PolyMesh,
+ face_valid: &[bool],
+ face_a: &[f64],
+ face_c: &[Vec3],
+ bb: &Aabb,
+ diag: f64,
+) -> [bool; 3] {
+ if mesh.verts.is_empty() || !bb.is_valid() {
+ return [false; 3];
+ }
+ let center = bb.center();
+ let tol = (1e-3 * diag).max(1e-5);
+ let tol2 = tol * tol;
+ let inv_cell = 1.0 / tol;
+
+ let cell_of = |p: Vec3| -> (i64, i64, i64) {
+ let rel = p - center;
+ (
+ (rel.x * inv_cell).floor() as i64,
+ (rel.y * inv_cell).floor() as i64,
+ (rel.z * inv_cell).floor() as i64,
+ )
+ };
+
+ let mut grid: HashMap<(i64, i64, i64), Vec<usize>> = HashMap::with_capacity(mesh.verts.len());
+ for (vi, &v) in mesh.verts.iter().enumerate() {
+ if v.is_finite() {
+ grid.entry(cell_of(v)).or_default().push(vi);
+ }
+ }
+
+ let mut tris_cache: Option<Vec<([Vec3; 3], Aabb)>> = None;
+ let point_on_surface = |p: Vec3, cache: &mut Option<Vec<([Vec3; 3], Aabb)>>| -> bool {
+ let tris = cache.get_or_insert_with(|| {
+ let mut out = Vec::with_capacity(mesh.faces.len() * 2);
+ for (fi, &ok) in face_valid.iter().enumerate() {
+ if !ok {
+ continue;
+ }
+ for [a, b, c] in mesh.triangulate_face(fi) {
+ let va = mesh.verts[a];
+ let vb = mesh.verts[b];
+ let vc = mesh.verts[c];
+ out.push((
+ [va, vb, vc],
+ Aabb {
+ min: va.min(vb).min(vc),
+ max: va.max(vb).max(vc),
+ },
+ ));
+ }
+ }
+ out
+ });
+ for &(tri, ref tbb) in tris.iter() {
+ if p.x < tbb.min.x - tol
+ || p.x > tbb.max.x + tol
+ || p.y < tbb.min.y - tol
+ || p.y > tbb.max.y + tol
+ || p.z < tbb.min.z - tol
+ || p.z > tbb.max.z + tol
+ {
+ continue;
+ }
+ let q = crate::spatial::closest_pt_on_tri(p, tri[0], tri[1], tri[2]);
+ if (p - q).len_sq() <= tol2 {
+ return true;
+ }
+ }
+ false
+ };
+
+ let v_stride = (mesh.verts.len() / 2048).max(1);
+ let f_stride = (mesh.faces.len() / 1024).max(1);
+ let mut check_axis = |axis: usize| -> bool {
+ let mirror = |v: Vec3| -> Vec3 {
+ match axis {
+ 0 => Vec3::new(2.0 * center.x - v.x, v.y, v.z),
+ 1 => Vec3::new(v.x, 2.0 * center.y - v.y, v.z),
+ _ => Vec3::new(v.x, v.y, 2.0 * center.z - v.z),
+ }
+ };
+
+ // 1. Vertex check (O(V) spatial hash with surface-distance fallback for asymmetric tessellation).
+ let mut checked = 0usize;
+ let mut misses = 0usize;
+ let max_misses = ((mesh.verts.len() / v_stride) / 100).max(2);
+ for vi in (0..mesh.verts.len()).step_by(v_stride) {
+ let v = mesh.verts[vi];
+ if !v.is_finite() {
+ continue;
+ }
+ let mirrored = mirror(v);
+ checked += 1;
+ let (cx, cy, cz) = cell_of(mirrored);
+ let mut found = false;
+ 'search: for dx in -1..=1 {
+ for dy in -1..=1 {
+ for dz in -1..=1 {
+ if let Some(bucket) = grid.get(&(cx + dx, cy + dy, cz + dz)) {
+ for &ovi in bucket {
+ if (mesh.verts[ovi] - mirrored).len_sq() <= tol2 {
+ found = true;
+ break 'search;
+ }
+ }
+ }
+ }
+ }
+ }
+ if !found && !point_on_surface(mirrored, &mut tris_cache) {
+ misses += 1;
+ if misses > max_misses {
+ return false;
+ }
+ }
+ }
+ if checked == 0 || ((checked - misses) as f64) / (checked as f64) < 0.99 {
+ return false;
+ }
+
+ // 2. Face-centroid surface check: catches asymmetric through-holes whose vertices all
+ // sit on symmetric top/bottom cap planes while their interior wall centroids do not.
+ let mut f_checked = 0usize;
+ let mut f_misses = 0usize;
+ let max_f_misses = ((mesh.faces.len() / f_stride) / 100).max(1);
+ for fi in (0..mesh.faces.len()).step_by(f_stride) {
+ if !face_valid[fi] || face_a[fi] <= 1e-10 {
+ continue;
+ }
+ let c = face_c[fi];
+ if !c.is_finite() {
+ continue;
+ }
+ f_checked += 1;
+ if !point_on_surface(mirror(c), &mut tris_cache) {
+ f_misses += 1;
+ if f_misses > max_f_misses {
+ return false;
+ }
+ }
+ }
+ f_checked == 0 || ((f_checked - f_misses) as f64) / (f_checked as f64) >= 0.99
+ };
+
+ [check_axis(0), check_axis(1), check_axis(2)]
+}
+
+struct RayTri {
+ v0: Vec3,
+ e1: Vec3,
+ e2: Vec3,
+ normal: Vec3,
+ aabb: Aabb,
+}
+
+#[inline]
+fn ray_hits_aabb(orig: Vec3, inv_dir: Vec3, aabb: &Aabb, t_max: f64) -> bool {
+ let tx1 = (aabb.min.x - orig.x) * inv_dir.x;
+ let tx2 = (aabb.max.x - orig.x) * inv_dir.x;
+ let mut tmin = tx1.min(tx2);
+ let mut tmax = tx1.max(tx2);
+
+ let ty1 = (aabb.min.y - orig.y) * inv_dir.y;
+ let ty2 = (aabb.max.y - orig.y) * inv_dir.y;
+ tmin = tmin.max(ty1.min(ty2));
+ tmax = tmax.min(ty1.max(ty2));
+
+ let tz1 = (aabb.min.z - orig.z) * inv_dir.z;
+ let tz2 = (aabb.max.z - orig.z) * inv_dir.z;
+ tmin = tmin.max(tz1.min(tz2));
+ tmax = tmax.min(tz1.max(tz2));
+
+ tmax >= tmin.max(0.0) && tmin <= t_max
+}
+
+#[inline]
+fn ray_tri_hit(orig: Vec3, dir: Vec3, tri: &RayTri, t_min: f64, t_max: f64) -> Option<f64> {
+ let pvec = dir.cross(tri.e2);
+ let det = tri.e1.dot(pvec);
+ if det.abs() < 1e-12 {
+ return None;
+ }
+ let inv_det = 1.0 / det;
+ let tvec = orig - tri.v0;
+ let u = tvec.dot(pvec) * inv_det;
+ if !(0.0..=1.0).contains(&u) {
+ return None;
+ }
+ let qvec = tvec.cross(tri.e1);
+ let v = dir.dot(qvec) * inv_det;
+ if v < 0.0 || u + v > 1.0 {
+ return None;
+ }
+ let t = tri.e2.dot(qvec) * inv_det;
+ if t > t_min && t < t_max {
+ Some(t)
+ } else {
+ None
+ }
+}
+
+fn estimate_wall_thickness(
+ mesh: &PolyMesh,
+ face_valid: &[bool],
+ face_n: &[Vec3],
+ face_a: &[f64],
+ face_c: &[Vec3],
+ total_area: f64,
+ diag: f64,
+) -> Option<WallThicknessReport> {
+ let mut tris: Vec<RayTri> = Vec::with_capacity(mesh.faces.len() * 2);
+ for fi in 0..mesh.faces.len() {
+ if !face_valid[fi] {
+ continue;
+ }
+ for [a, b, c] in mesh.triangulate_face(fi) {
+ if a >= mesh.verts.len() || b >= mesh.verts.len() || c >= mesh.verts.len() {
+ continue;
+ }
+ let v0 = mesh.verts[a];
+ let v1 = mesh.verts[b];
+ let v2 = mesh.verts[c];
+ if !v0.is_finite() || !v1.is_finite() || !v2.is_finite() {
+ continue;
+ }
+ let e1 = v1 - v0;
+ let e2 = v2 - v0;
+ let n = e1.cross(e2).normalized();
+ if n.len_sq() < 0.5 {
+ continue;
+ }
+ tris.push(RayTri {
+ v0,
+ e1,
+ e2,
+ normal: n,
+ aabb: Aabb {
+ min: v0.min(v1).min(v2),
+ max: v0.max(v1).max(v2),
+ },
+ });
+ }
+ }
+ if tris.is_empty() {
+ return None;
+ }
+
+ // Deterministically pick top large faces + evenly strided faces so both major walls
+ // and thinner ribs/flanges are sampled. Skip tiny boolean slivers when larger faces exist,
+ // falling back to all positive-area faces for finely faceted micro-scale meshes.
+ let area_floor = (total_area * 1e-7).max(1e-12);
+ let mut valid_faces: Vec<usize> = (0..mesh.faces.len())
+ .filter(|&fi| face_a[fi] >= area_floor && face_n[fi].len_sq() > 0.5)
+ .collect();
+ if valid_faces.is_empty() {
+ valid_faces = (0..mesh.faces.len())
+ .filter(|&fi| face_a[fi] > 0.0 && face_n[fi].len_sq() > 0.5)
+ .collect();
+ }
+ if valid_faces.is_empty() {
+ return None;
+ }
+ valid_faces.sort_by(|&a, &b| face_a[b].total_cmp(&face_a[a]).then_with(|| a.cmp(&b)));
+
+ let max_rays = if tris.len() > 20_000 { 64 } else { 128 };
+ let mut sample_faces: Vec<usize> = Vec::with_capacity(max_rays);
+ if valid_faces.len() <= max_rays {
+ sample_faces = valid_faces;
+ } else {
+ let top_k = (max_rays / 3).min(valid_faces.len());
+ sample_faces.extend_from_slice(&valid_faces[..top_k]);
+ let rem = &valid_faces[top_k..];
+ let need = max_rays - top_k;
+ let stride = (rem.len() / need).max(1);
+ for &fi in rem.iter().step_by(stride).take(need) {
+ sample_faces.push(fi);
+ }
+ }
+
+ let eps = (1e-5 * diag).max(1e-7);
+ let mut distances: Vec<f64> = Vec::with_capacity(sample_faces.len());
+
+ for fi in sample_faces {
+ let fn0 = face_n[fi];
+ let dir = -fn0;
+ let orig = face_c[fi] + dir * eps;
+ let inv_dir = Vec3::new(
+ if dir.x.abs() > 1e-15 { 1.0 / dir.x } else { f64::INFINITY },
+ if dir.y.abs() > 1e-15 { 1.0 / dir.y } else { f64::INFINITY },
+ if dir.z.abs() > 1e-15 { 1.0 / dir.z } else { f64::INFINITY },
+ );
+
+ let mut best_t = f64::INFINITY;
+ let mut best_dot = 0.0;
+ for tri in &tris {
+ if !ray_hits_aabb(orig, inv_dir, &tri.aabb, best_t) {
+ continue;
+ }
+ if let Some(t) = ray_tri_hit(orig, dir, tri, eps, best_t) {
+ best_t = t;
+ best_dot = tri.normal.dot(fn0);
+ }
+ }
+ if best_t.is_finite() && best_dot < -0.5 {
+ distances.push(best_t + eps);
+ }
+ }
+
+ if distances.is_empty() {
+ return None;
+ }
+ distances.sort_by(|a, b| a.total_cmp(b));
+ let min = distances[0];
+ let p01 = distances[(distances.len() / 100).min(distances.len() - 1)];
+ let median = distances[distances.len() / 2];
+ Some(WallThicknessReport {
+ min,
+ p01,
+ median,
+ samples: distances.len(),
+ })
+}
+
+/// Compile compact, deterministic geometric facts from `mesh`.
+pub fn extract_features(mesh: &PolyMesh) -> MeshFeatures {
+ let empty = || MeshFeatures {
+ bbox_min: [0.0; 3],
+ bbox_max: [0.0; 3],
+ size: [0.0; 3],
+ center: [0.0; 3],
+ surface_area: 0.0,
+ symmetry: [false; 3],
+ wall_thickness: None,
+ planes: Vec::new(),
+ cylinders: Vec::new(),
+ };
+
+ if mesh.verts.is_empty() || mesh.faces.is_empty() {
+ return empty();
+ }
+
+ let nv = mesh.verts.len();
+ let nf = mesh.faces.len();
+ let face_valid: Vec<bool> = mesh
+ .faces
+ .iter()
+ .map(|f| f.verts.len() >= 3 && f.verts.iter().all(|&vi| vi < nv && mesh.verts[vi].is_finite()))
+ .collect();
+
+ let mut bb = Aabb::empty();
+ for (fi, f) in mesh.faces.iter().enumerate() {
+ if !face_valid[fi] {
+ continue;
+ }
+ for &vi in &f.verts {
+ bb.include(mesh.verts[vi]);
+ }
+ }
+ if !bb.is_valid() || !bb.min.is_finite() || !bb.max.is_finite() {
+ return empty();
+ }
+
+ let size = bb.size();
+ let diag = size.len();
+ if !diag.is_finite() || diag <= 1e-12 {
+ return empty();
+ }
+
+ let face_n: Vec<Vec3> = (0..nf)
+ .map(|fi| if face_valid[fi] { mesh.face_normal(fi) } else { Vec3::ZERO })
+ .collect();
+ let face_a: Vec<f64> = (0..nf)
+ .map(|fi| if face_valid[fi] { mesh.face_area(fi) } else { 0.0 })
+ .collect();
+ let face_c: Vec<Vec3> = (0..nf)
+ .map(|fi| if face_valid[fi] { mesh.face_centroid(fi) } else { Vec3::ZERO })
+ .collect();
+ let total_area: f64 = face_a.iter().filter(|a| a.is_finite()).sum();
+
+ let face_adj = build_face_adjacency(mesh, &face_valid);
+ let (patches, patch_of_face) = segment_coplanar_patches(mesh, &face_n, &face_a, &face_c, &face_adj, diag);
+ let (cylinders, claimed_by_cyl) = detect_cylinders(mesh, &patches, &patch_of_face, &face_adj, diag);
+
+ let area_floor = (total_area * 1e-5).max(1e-10);
+ let mut planes: Vec<PlanarRegion> = patches
+ .iter()
+ .enumerate()
+ .filter(|&(pid, p)| !claimed_by_cyl[pid] && p.area >= area_floor)
+ .map(|(_, p)| {
+ let psize = p.bbox.size();
+ PlanarRegion {
+ orientation: orient_label(p.normal),
+ normal: p.normal.to_array(),
+ offset: p.normal.dot(p.centroid),
+ area: p.area,
+ centroid: p.centroid.to_array(),
+ bbox_min: p.bbox.min.to_array(),
+ bbox_max: p.bbox.max.to_array(),
+ span: psize.to_array(),
+ face_count: p.faces.len(),
+ }
+ })
+ .collect();
+ planes.sort_by(|a, b| {
+ b.area
+ .total_cmp(&a.area)
+ .then_with(|| a.orientation.cmp(&b.orientation))
+ .then_with(|| a.offset.total_cmp(&b.offset))
+ });
+ planes.truncate(16);
+
+ let symmetry = detect_symmetry(mesh, &face_valid, &face_a, &face_c, &bb, diag);
+ let wall_thickness =
+ estimate_wall_thickness(mesh, &face_valid, &face_n, &face_a, &face_c, total_area, diag);
+
+ MeshFeatures {
+ bbox_min: bb.min.to_array(),
+ bbox_max: bb.max.to_array(),
+ size: size.to_array(),
+ center: bb.center().to_array(),
+ surface_area: total_area,
+ symmetry,
+ wall_thickness,
+ planes,
+ cylinders,
+ }
+}
diff --git a/crates/forma-core/src/invariants.rs b/crates/forma-core/src/invariants.rs
index 3731040..a8fbc4a 100644
--- a/crates/forma-core/src/invariants.rs
+++ b/crates/forma-core/src/invariants.rs
@@ -69,6 +69,12 @@ impl MeshInvariants {
bb.include(v);
}
+ let vol_origin = if bb.is_valid() && bb.center().is_finite() {
+ bb.center()
+ } else {
+ Vec3::ZERO
+ };
+
// Single-pass half-edge collection, face area/tri count, and signed volume!
let mut half_edges: Vec<(u32, u32, u32, i8)> = Vec::with_capacity(faces * 4);
let mut corner_count: Vec<u32> = vec![0; verts];
@@ -96,15 +102,21 @@ impl MeshInvariants {
let v1 = mesh.verts[fv[1]];
let v2 = mesh.verts[fv[2]];
area_vec = (v1 - v0).cross(v2 - v0);
- vol6 += v0.dot(v1.cross(v2));
+ let a = v0 - vol_origin;
+ let b = v1 - vol_origin;
+ let c = v2 - vol_origin;
+ vol6 += a.dot(b.cross(c));
} else {
for k in 1..(n - 1) {
let e1 = mesh.verts[fv[k]] - v0;
let e2 = mesh.verts[fv[k + 1]] - v0;
area_vec = area_vec + e1.cross(e2);
}
- for [a, b, c] in mesh.triangulate_face(fi) {
- vol6 += mesh.verts[a].dot(mesh.verts[b].cross(mesh.verts[c]));
+ for [ia, ib, ic] in mesh.triangulate_face(fi) {
+ let a = mesh.verts[ia] - vol_origin;
+ let b = mesh.verts[ib] - vol_origin;
+ let c = mesh.verts[ic] - vol_origin;
+ vol6 += a.dot(b.cross(c));
}
}
let f_area = 0.5 * area_vec.len();
diff --git a/crates/forma-core/src/lib.rs b/crates/forma-core/src/lib.rs
index 858f461..0084e4f 100644
--- a/crates/forma-core/src/lib.rs
+++ b/crates/forma-core/src/lib.rs
@@ -14,6 +14,7 @@ pub mod boolean;
pub mod curves;
pub mod deform;
pub mod export;
+pub mod features;
pub mod import;
pub mod instancing;
pub mod invariants;
@@ -30,6 +31,7 @@ pub mod units;
pub mod uv;
pub mod uv_policy;
+pub use features::{CylindricalFeature, MeshFeatures, PlanarRegion, WallThicknessReport};
pub use invariants::{LintFinding, LintOptions, LintReport, LintSeverity, MeshInvariants};
pub use mesh::{Face, LineageId, Material, PolyMesh};
pub use scene::{Observation, Scene, SceneError};
diff --git a/crates/forma-core/src/scene.rs b/crates/forma-core/src/scene.rs
index acb3b21..24e5565 100644
--- a/crates/forma-core/src/scene.rs
+++ b/crates/forma-core/src/scene.rs
@@ -3,6 +3,7 @@
use crate::boolean::{boolean_op, BoolOp, OverlapCheck};
use crate::export::export_mesh_with_unit;
+use crate::features::{extract_features, MeshFeatures};
use crate::instancing::{GlbSceneOptions, SceneExportNode, Trs};
use crate::invariants::MeshInvariants;
use crate::math::Vec3;
@@ -39,6 +40,7 @@ struct CachedPart {
inv: MeshInvariants,
overlap: OnceLock<OverlapCheck>,
self_ix: OnceLock<OverlapCheck>,
+ features: OnceLock<MeshFeatures>,
}
impl CachedPart {
@@ -61,9 +63,14 @@ impl CachedPart {
inv,
overlap: overlap_cell,
self_ix: self_ix_cell,
+ features: OnceLock::new(),
}
}
+ fn features(&self) -> &MeshFeatures {
+ self.features.get_or_init(|| extract_features(&self.mesh))
+ }
+
fn overlap_check(&self) -> OverlapCheck {
*self.overlap.get_or_init(|| {
if self.inv.components > 1 {
@@ -344,6 +351,21 @@ impl Scene {
Ok(crate::spatial::section_z(m, z))
}
+ /// Return lazily compiled, cached geometric features for a named part (or the latest part if `None`).
+ pub fn features(&self, part: Option<&str>) -> Result<(&str, &MeshFeatures), SceneError> {
+ let target = match part {
+ Some(name) if !name.is_empty() => name,
+ _ => self
+ .last_part_name()
+ .ok_or(SceneError::EmptyScene)?,
+ };
+ let (key, entry) = self
+ .parts
+ .get_key_value(target)
+ .ok_or_else(|| SceneError::UnknownPart(target.to_string(), self.part_list_str()))?;
+ Ok((key.as_str(), entry.features()))
+ }
+
pub fn render_preview(&self, path: &Path, part_opt: Option<&str>, size: usize) -> Result<(), SceneError> {
let mesh = self.merged_mesh(part_opt)?;
crate::render::render_quad_png(&mesh, path, size).map_err(SceneError::OpFailed)
diff --git a/crates/forma-core/tests/feature_extraction.rs b/crates/forma-core/tests/feature_extraction.rs
new file mode 100644
index 0000000..e26c660
--- /dev/null
+++ b/crates/forma-core/tests/feature_extraction.rs
@@ -0,0 +1,161 @@
+use forma_core::boolean::BoolOp;
+use forma_core::export::export_mesh_bytes_with_unit;
+use forma_core::features::extract_features;
+use forma_core::import::import_mesh_bytes;
+use forma_core::math::Vec3;
+use forma_core::primitives::{make_box, make_cylinder, make_pipe, make_sphere, make_torus};
+use forma_core::{Scene, Unit};
+
+#[test]
+fn box_planes_symmetry_and_wall_thickness() {
+ let m = make_box(4.0, 2.0, 0.4, 1);
+ let f = extract_features(&m);
+ assert_eq!(f.planes.len(), 6, "expected 6 planar faces, got {:?}", f.planes);
+ assert!(f.cylinders.is_empty(), "box should have no cylinders");
+ assert_eq!(f.symmetry, [true, true, true]);
+ let wt = f.wall_thickness.as_ref().expect("expected wall thickness");
+ assert!((wt.min - 0.4).abs() < 1e-3, "expected min thickness 0.4, got {}", wt.min);
+}
+
+#[test]
+fn pipe_detects_boss_bore_and_wall_thickness() {
+ let m = make_pipe(1.0, 0.75, 2.0, 32, 1).unwrap();
+ let f = extract_features(&m);
+ assert_eq!(f.planes.len(), 2, "expected top and bottom annular rings, got {:?}", f.planes);
+ assert_eq!(f.cylinders.len(), 2, "expected 1 bore + 1 boss, got {:?}", f.cylinders);
+
+ let bore = f.cylinders.iter().find(|c| c.kind == "bore").expect("missing inner bore");
+ let boss = f.cylinders.iter().find(|c| c.kind == "boss").expect("missing outer boss");
+ assert_eq!(bore.axis_label, "+z");
+ assert_eq!(boss.axis_label, "+z");
+ assert!((bore.radius - 0.75).abs() < 1e-3, "bore r={}", bore.radius);
+ assert!((boss.radius - 1.0).abs() < 1e-3, "boss r={}", boss.radius);
+ assert!((bore.height - 2.0).abs() < 1e-3, "bore h={}", bore.height);
+ assert!((boss.height - 2.0).abs() < 1e-3, "boss h={}", boss.height);
+ assert!((bore.arc_deg - 360.0).abs() < 1.0);
+ assert!((boss.arc_deg - 360.0).abs() < 1.0);
+
+ let wt = f.wall_thickness.as_ref().expect("expected wall thickness");
+ assert!((wt.min - 0.25).abs() < 0.02, "expected pipe wall ~0.25, got {}", wt.min);
+}
+
+#[test]
+fn flange_with_five_holes_survives_stl_and_glb_roundtrip() {
+ let mut scene = Scene::new();
+ scene.strict_manifold = true;
+ scene.add_box("flange", 4.0, 2.0, 0.4, Vec3::ZERO).unwrap();
+
+ scene.set_part("h0", make_cylinder(0.5, 1.0, 32, 2)).unwrap();
+ scene.boolean_parts("flange", "h0", BoolOp::Difference, false).unwrap();
+ for (idx, (x, y)) in [(-1.4, -0.5), (-1.4, 0.5), (1.4, -0.5), (1.4, 0.5)]
+ .into_iter()
+ .enumerate()
+ {
+ let mut bolt = make_cylinder(0.25, 1.0, 24, 3 + idx as u32);
+ bolt.translate(Vec3::new(x, y, 0.0));
+ scene.set_part("bolt", bolt).unwrap();
+ scene.boolean_parts("flange", "bolt", BoolOp::Difference, false).unwrap();
+ }
+
+ // Verify lazy caching returns the exact same allocation on repeated calls.
+ let (n1, f1) = scene.features(Some("flange")).unwrap();
+ let p1 = f1 as *const _;
+ let (n2, f2) = scene.features(Some("flange")).unwrap();
+ let p2 = f2 as *const _;
+ assert_eq!(n1, "flange");
+ assert_eq!(n2, "flange");
+ assert!(std::ptr::eq(p1, p2), "expected cached MeshFeatures pointer");
+
+ let verify_flange = |label: &str, f: &forma_core::MeshFeatures| {
+ assert_eq!(f.planes.len(), 6, "{label}: expected 6 planes, got {:?}", f.planes);
+ let bores: Vec<_> = f.cylinders.iter().filter(|c| c.kind == "bore").collect();
+ assert_eq!(bores.len(), 5, "{label}: expected 5 bores, got {:?}", f.cylinders);
+ assert!((bores[0].radius - 0.5).abs() < 0.01, "{label}: main bore r={}", bores[0].radius);
+ assert!(bores[0].center[0].abs() < 0.01 && bores[0].center[1].abs() < 0.01);
+ for b in &bores[1..] {
+ assert!((b.radius - 0.25).abs() < 0.01, "{label}: bolt bore r={}", b.radius);
+ assert!((b.height - 0.4).abs() < 0.01, "{label}: bolt bore h={}", b.height);
+ assert_eq!(b.axis_label, "+z");
+ }
+ assert_eq!(f.symmetry, [true, true, true], "{label}: expected XYZ symmetry");
+ };
+
+ verify_flange("native", f1);
+
+ let mesh = scene.get_part("flange").unwrap();
+ for ext in ["stl", "glb"] {
+ let bytes = export_mesh_bytes_with_unit(mesh, ext, Unit::Meter).unwrap();
+ let imported = import_mesh_bytes(&bytes, ext).unwrap();
+ let imported_feats = extract_features(&imported);
+ verify_flange(ext, &imported_feats);
+ }
+}
+
+#[test]
+fn horizontal_bore_and_asymmetry_detection() {
+ let mut scene = Scene::new();
+ scene.add_box("block", 3.0, 2.0, 2.0, Vec3::ZERO).unwrap();
+ let mut bore = make_cylinder(0.4, 4.0, 28, 2);
+ bore.rotate_deg(0.0, 90.0, 0.0);
+ bore.translate(Vec3::new(0.0, 0.3, 0.0));
+ scene.set_part("bore", bore).unwrap();
+ scene.boolean_parts("block", "bore", BoolOp::Difference, false).unwrap();
+
+ let (_, f) = scene.features(Some("block")).unwrap();
+ assert_eq!(f.cylinders.len(), 1, "expected 1 horizontal bore, got {:?}", f.cylinders);
+ let c = &f.cylinders[0];
+ assert_eq!(c.kind, "bore");
+ assert_eq!(c.axis_label, "+x");
+ assert!((c.radius - 0.4).abs() < 0.01, "r={}", c.radius);
+ assert!((c.height - 3.0).abs() < 0.01, "h={}", c.height);
+ assert!((c.center[1] - 0.3).abs() < 0.01, "cy={}", c.center[1]);
+ // Symmetric in X and Z, asymmetric in Y (hole shifted +0.3 in Y).
+ assert_eq!(f.symmetry, [true, false, true], "symmetry={:?}", f.symmetry);
+}
+
+#[test]
+fn sphere_and_torus_do_not_produce_false_cylinders() {
+ let sph = make_sphere(1.0, 24, 16, 1);
+ let sf = extract_features(&sph);
+ assert!(sf.cylinders.is_empty(), "sphere false cylinders: {:?}", sf.cylinders);
+
+ let tor = make_torus(2.0, 0.5, 24, 16, 2);
+ let tf = extract_features(&tor);
+ assert!(tf.cylinders.is_empty(), "torus false cylinders: {:?}", tf.cylinders);
+}
+
+#[test]
+fn shelled_box_measures_wall_thickness() {
+ let mut scene = Scene::new();
+ scene.add_box("box", 2.0, 2.0, 2.0, Vec3::ZERO).unwrap();
+ scene.shell("box", 0.15, true).unwrap();
+ let (_, f) = scene.features(Some("box")).unwrap();
+ let wt = f.wall_thickness.as_ref().expect("expected wall thickness");
+ assert!((wt.min - 0.15).abs() < 0.015, "expected wall_min ~0.15, got {}", wt.min);
+ assert!(wt.p01 >= wt.min && wt.p01 <= wt.median);
+ let summary = f.summary("box", Unit::Meter);
+ assert!(summary.contains("wall_p01="), "expected wall_p01 in summary: {summary}");
+}
+
+#[test]
+fn wall_thickness_p01_and_small_face_fallback() {
+ // High-segment pipe has >= 100 sampled faces so p01 is a genuine 1st-percentile check.
+ let pipe = make_pipe(1.0, 0.75, 2.0, 64, 1).unwrap();
+ let f = extract_features(&pipe);
+ let wt = f.wall_thickness.as_ref().expect("expected wall thickness on high-seg pipe");
+ assert!(wt.samples >= 100, "expected >= 100 samples, got {}", wt.samples);
+ assert!(wt.min <= wt.p01 && wt.p01 <= wt.median);
+ assert!((wt.p01 - 0.25).abs() < 0.02, "expected pipe wall_p01 ~0.25, got {}", wt.p01);
+
+ // Micro-scale collar where every triangle area falls below 1e-12 still samples via fallback.
+ let mut micro = make_pipe(1.0e-5, 0.75e-5, 2.0e-5, 32, 1).unwrap();
+ micro.translate(Vec3::ZERO);
+ let mf = extract_features(&micro);
+ let mwt = mf.wall_thickness.as_ref().expect("expected fallback wall thickness on micro collar");
+ assert!(mwt.samples > 0 && mwt.min > 0.0 && mwt.min <= mwt.p01 && mwt.p01 <= mwt.median);
+ assert!(
+ (mwt.p01 - 0.25e-5).abs() < 0.03e-5,
+ "expected micro wall_p01 ~0.25e-5, got {}",
+ mwt.p01
+ );
+}
diff --git a/crates/forma-core/tests/fuzz_features.rs b/crates/forma-core/tests/fuzz_features.rs
new file mode 100644
index 0000000..50ae248
--- /dev/null
+++ b/crates/forma-core/tests/fuzz_features.rs
@@ -0,0 +1,522 @@
+//! Adversarial & randomized fuzzing suite for `forma_core::features`.
+//!
+//! Exercises:
+//! - Malformed, OOB-index, NaN/Inf, degenerate, and random triangle-soup meshes (0 panics, 0 NaNs)
+//! - 60 randomized multi-bore plates across X/Y/Z axes + STL/GLB round-trips
+//! - 20 arbitrarily rotated oblique cylinders/pipes + counterbored coaxial stepped holes
+//! - Negative shapes (cones, 90deg filleted boxes, hex prisms, spheres, tori) for zero false cylinders
+//! - 100 randomized complex CAD meshes (gears, lofts, revolves, shells, remesh, deform) for determinism
+//! - Extreme scales (1e-3..1e4) and huge translations (1e6)
+//! - Scene `OnceLock` cache hit, invalidation on mutation, and CoW rollback/undo parity
+
+use forma_core::boolean::BoolOp;
+use forma_core::export::export_mesh_bytes_with_unit;
+use forma_core::features::{extract_features, MeshFeatures};
+use forma_core::import::import_mesh_bytes;
+use forma_core::math::Vec3;
+use forma_core::mesh::PolyMesh;
+use forma_core::ops::{bevel_edges, shell_solid, subsurf_catmull_clark};
+use forma_core::primitives::{
+ make_box, make_cone, make_cylinder, make_gear, make_loft, make_pipe, make_revolve, make_sphere, make_torus,
+};
+use forma_core::remesh::{bisect_mesh, remesh_voxel};
+use forma_core::selector::EdgeSelector;
+use forma_core::{Scene, Unit};
+
+struct Rng(u64);
+
+impl Rng {
+ fn new(seed: u64) -> Self {
+ Self(seed ^ 0x9e37_79b9_7f4a_7c15)
+ }
+ fn next_u64(&mut self) -> u64 {
+ let mut x = self.0;
+ x ^= x << 13;
+ x ^= x >> 7;
+ x ^= x << 17;
+ self.0 = x;
+ x
+ }
+ fn next_f64(&mut self) -> f64 {
+ ((self.next_u64() >> 11) as f64) / ((1u64 << 53) as f64)
+ }
+ fn range_f64(&mut self, lo: f64, hi: f64) -> f64 {
+ lo + (hi - lo) * self.next_f64()
+ }
+ fn range_usize(&mut self, lo: usize, hi: usize) -> usize {
+ lo + (self.next_u64() as usize) % (hi - lo)
+ }
+}
+
+fn assert_features_sane(label: &str, f: &MeshFeatures) {
+ for &v in f
+ .bbox_min
+ .iter()
+ .chain(&f.bbox_max)
+ .chain(&f.size)
+ .chain(&f.center)
+ .chain(std::iter::once(&f.surface_area))
+ {
+ assert!(v.is_finite(), "{label}: non-finite summary float {v}");
+ }
+ if let Some(w) = &f.wall_thickness {
+ assert!(w.min.is_finite() && w.min > 0.0, "{label}: bad wall_min {}", w.min);
+ assert!(
+ w.p01.is_finite() && w.p01 >= w.min && w.p01 <= w.median,
+ "{label}: bad wall_p01 {} (min={}, med={})",
+ w.p01,
+ w.min,
+ w.median
+ );
+ assert!(w.median.is_finite() && w.median >= w.min, "{label}: bad wall_med {}", w.median);
+ assert!(w.samples > 0, "{label}: wall_thickness samples == 0");
+ }
+ for p in &f.planes {
+ assert!(p.area.is_finite() && p.area > 0.0, "{label}: bad plane area {}", p.area);
+ assert!(p.offset.is_finite(), "{label}: non-finite plane offset");
+ for &v in p
+ .normal
+ .iter()
+ .chain(&p.centroid)
+ .chain(&p.bbox_min)
+ .chain(&p.bbox_max)
+ .chain(&p.span)
+ {
+ assert!(v.is_finite(), "{label}: non-finite plane value {v}");
+ }
+ }
+ for c in &f.cylinders {
+ assert!(c.kind == "bore" || c.kind == "boss", "{label}: bad kind {}", c.kind);
+ assert!(c.radius.is_finite() && c.radius > 0.0, "{label}: bad radius {}", c.radius);
+ assert!((c.diameter - 2.0 * c.radius).abs() < 1e-9);
+ assert!(c.height.is_finite() && c.height > 0.0, "{label}: bad height {}", c.height);
+ assert!(c.arc_deg.is_finite() && c.arc_deg >= 175.0 && c.arc_deg <= 360.0);
+ for &v in c.axis.iter().chain(&c.center) {
+ assert!(v.is_finite(), "{label}: non-finite cylinder value {v}");
+ }
+ }
+ let text = f.summary(label, Unit::Meter);
+ assert!(!text.contains("NaN"), "{label}: NaN in summary:\n{text}");
+ assert!(!text.contains("inf"), "{label}: inf in summary:\n{text}");
+ assert!(!text.contains("-0.000"), "{label}: -0.000 in summary:\n{text}");
+}
+
+#[test]
+fn fuzz_malformed_degenerate_and_nan_meshes_never_panic() {
+ // 1. Empty mesh
+ let empty = PolyMesh::new();
+ let f = extract_features(&empty);
+ assert!(f.planes.is_empty() && f.cylinders.is_empty());
+ assert_features_sane("empty", &f);
+
+ // 2. Vertices only, no faces
+ let mut v_only = PolyMesh::new();
+ v_only.add_vert(Vec3::new(1.0, 2.0, 3.0));
+ assert_features_sane("v_only", &extract_features(&v_only));
+
+ // 3. Out-of-bounds vertex indices + <3 vert faces + NaN/Inf vertices
+ let mut bad = PolyMesh::new();
+ bad.add_vert(Vec3::new(0.0, 0.0, 0.0));
+ bad.add_vert(Vec3::new(1.0, 0.0, 0.0));
+ bad.add_vert(Vec3::new(0.0, 1.0, 0.0));
+ bad.add_vert(Vec3::new(f64::NAN, 0.0, 0.0));
+ bad.add_vert(Vec3::new(f64::INFINITY, -f64::INFINITY, 1.0));
+ bad.add_face(vec![0, 1, 2], 1, None); // valid
+ bad.add_face(vec![0, 1, 9999], 1, None); // OOB
+ bad.add_face(vec![0, 1], 1, None); // degenerate 2-vert
+ bad.add_face(vec![0, 3, 2], 1, None); // NaN vert
+ bad.add_face(vec![0, 4, 1], 1, None); // Inf vert
+ bad.add_face(vec![0, 0, 0], 1, None); // zero-area
+ assert_features_sane("malformed", &extract_features(&bad));
+
+ // 4. 200 random triangle soups with mixed valid, degenerate, and OOB faces
+ let mut rng = Rng::new(0xBAD_F00D);
+ for case in 0..200 {
+ let mut m = PolyMesh::new();
+ let nv = rng.range_usize(1, 40);
+ for _ in 0..nv {
+ let roll = rng.range_usize(0, 25);
+ let v = match roll {
+ 0 => Vec3::new(f64::NAN, 1.0, 0.0),
+ 1 => Vec3::new(f64::INFINITY, 0.0, 0.0),
+ _ => Vec3::new(
+ rng.range_f64(-10.0, 10.0),
+ rng.range_f64(-10.0, 10.0),
+ rng.range_f64(-10.0, 10.0),
+ ),
+ };
+ m.add_vert(v);
+ }
+ let nf = rng.range_usize(1, 60);
+ for _ in 0..nf {
+ let k = rng.range_usize(1, 6);
+ let mut fverts = Vec::with_capacity(k);
+ for _ in 0..k {
+ let idx = if rng.range_usize(0, 15) == 0 {
+ nv + rng.range_usize(0, 10)
+ } else {
+ rng.range_usize(0, nv)
+ };
+ fverts.push(idx);
+ }
+ m.add_face(fverts, 1, None);
+ }
+ assert_features_sane(&format!("soup_{case}"), &extract_features(&m));
+ }
+}
+
+#[test]
+fn fuzz_60_random_multi_bore_plates_exact_recovery() {
+ let mut rng = Rng::new(0xF1A9_6E01);
+ for case in 0..60 {
+ let axis_idx = case % 3; // 0=Z, 1=X, 2=Y
+ let w = rng.range_f64(6.0, 12.0);
+ let d = rng.range_f64(5.0, 10.0);
+ let h = rng.range_f64(0.4, 2.0);
+ let offset = Vec3::new(
+ rng.range_f64(-500.0, 500.0),
+ rng.range_f64(-500.0, 500.0),
+ rng.range_f64(-500.0, 500.0),
+ );
+
+ let (sx, sy, sz) = match axis_idx {
+ 0 => (w, d, h),
+ 1 => (h, w, d),
+ _ => (w, h, d),
+ };
+ let mut scene = Scene::new();
+ scene.strict_manifold = true;
+ scene.add_box("plate", sx, sy, sz, offset).unwrap();
+
+ let n_holes = rng.range_usize(1, 6);
+ let mut placed: Vec<(f64, f64, f64)> = Vec::new();
+ for _ in 0..(n_holes * 12) {
+ if placed.len() >= n_holes {
+ break;
+ }
+ let r = rng.range_f64(0.25, 0.85);
+ let margin = r + 0.45;
+ let u = rng.range_f64(-0.5 * w + margin, 0.5 * w - margin);
+ let v = rng.range_f64(-0.5 * d + margin, 0.5 * d - margin);
+ if placed
+ .iter()
+ .all(|&(pu, pv, pr)| (u - pu).hypot(v - pv) > r + pr + 0.35)
+ {
+ placed.push((u, v, r));
+ }
+ }
+ assert!(!placed.is_empty());
+
+ for (i, &(u, v, r)) in placed.iter().enumerate() {
+ let segs = rng.range_usize(16, 40);
+ let mut cyl = make_cylinder(r, h + 1.0, segs, 2 + i as u32);
+ let hole_center = match axis_idx {
+ 0 => offset + Vec3::new(u, v, 0.0),
+ 1 => {
+ cyl.rotate_deg(0.0, 90.0, 0.0);
+ offset + Vec3::new(0.0, u, v)
+ }
+ _ => {
+ cyl.rotate_deg(90.0, 0.0, 0.0);
+ offset + Vec3::new(u, 0.0, v)
+ }
+ };
+ cyl.translate(hole_center);
+ scene.set_part("cutter", cyl).unwrap();
+ scene.boolean_parts("plate", "cutter", BoolOp::Difference, false).unwrap();
+ }
+
+ let expected_axis = ["+z", "+x", "+y"][axis_idx];
+ let verify = |tag: &str, f: &MeshFeatures| {
+ assert_features_sane(tag, f);
+ assert_eq!(f.planes.len(), 6, "{tag}: expected 6 planes, got {:?}", f.planes);
+ let bores: Vec<_> = f.cylinders.iter().filter(|c| c.kind == "bore").collect();
+ assert_eq!(
+ bores.len(),
+ placed.len(),
+ "{tag}: expected {} bores, got {:?}",
+ placed.len(),
+ f.cylinders
+ );
+ for &(u, v, r) in &placed {
+ let exp_c = match axis_idx {
+ 0 => offset + Vec3::new(u, v, 0.0),
+ 1 => offset + Vec3::new(0.0, u, v),
+ _ => offset + Vec3::new(u, 0.0, v),
+ };
+ let found = bores.iter().any(|b| {
+ b.axis_label == expected_axis
+ && (b.radius - r).abs() <= (0.02 * r).max(0.015)
+ && (b.height - h).abs() <= (0.02 * h).max(0.015)
+ && (Vec3::from_array(b.center) - exp_c).len() <= (0.03 * r).max(0.02)
+ });
+ assert!(
+ found,
+ "{tag}: missing expected bore r={r:.3} h={h:.3} center={exp_c:?} in {bores:?}"
+ );
+ }
+ };
+
+ let (_, feats) = scene.features(Some("plate")).unwrap();
+ verify(&format!("plate_{case}_native"), feats);
+
+ if case % 4 == 0 {
+ let mesh = scene.get_part("plate").unwrap();
+ for ext in ["stl", "glb"] {
+ let bytes = export_mesh_bytes_with_unit(mesh, ext, Unit::Meter).unwrap();
+ let reimported = import_mesh_bytes(&bytes, ext).unwrap();
+ let rf = extract_features(&reimported);
+ verify(&format!("plate_{case}_{ext}"), &rf);
+ }
+ }
+ }
+}
+
+#[test]
+fn fuzz_oblique_cylinders_and_counterbored_coaxial_holes() {
+ let mut rng = Rng::new(0x0B11_C0DE);
+ for i in 0..20 {
+ let r_out = rng.range_f64(0.6, 2.5);
+ let r_in = r_out * rng.range_f64(0.4, 0.75);
+ let h = rng.range_f64(1.0, 5.0);
+ let segs = rng.range_usize(18, 40);
+ let rx = rng.range_f64(10.0, 80.0);
+ let ry = rng.range_f64(10.0, 80.0);
+ let rz = rng.range_f64(0.0, 180.0);
+ let shift = Vec3::new(
+ rng.range_f64(-20.0, 20.0),
+ rng.range_f64(-20.0, 20.0),
+ rng.range_f64(-20.0, 20.0),
+ );
+
+ let mut pipe = make_pipe(r_out, r_in, h, segs, 1).unwrap();
+ pipe.rotate_deg(rx, ry, rz);
+ pipe.translate(shift);
+ let exp_axis = Vec3::Z.rotate_euler_xyz_deg(rx, ry, rz).normalized();
+
+ let f = extract_features(&pipe);
+ assert_features_sane(&format!("oblique_pipe_{i}"), &f);
+ assert_eq!(f.planes.len(), 2, "oblique pipe {i}: planes={:?}", f.planes);
+ assert_eq!(f.cylinders.len(), 2, "oblique pipe {i}: cyls={:?}", f.cylinders);
+
+ let bore = f.cylinders.iter().find(|c| c.kind == "bore").expect("missing oblique bore");
+ let boss = f.cylinders.iter().find(|c| c.kind == "boss").expect("missing oblique boss");
+ for (label, c, exp_r) in [("bore", bore, r_in), ("boss", boss, r_out)] {
+ let dot = Vec3::from_array(c.axis).dot(exp_axis).abs();
+ assert!(dot > 0.995, "oblique {i} {label}: axis dot={dot}");
+ assert!((c.radius - exp_r).abs() < 0.015 * exp_r, "oblique {i} {label}: r={} vs {exp_r}", c.radius);
+ assert!((c.height - h).abs() < 0.02 * h, "oblique {i} {label}: h={} vs {h}", c.height);
+ assert!((Vec3::from_array(c.center) - shift).len() < 0.03 * exp_r);
+ }
+ }
+
+ // Counterbored stepped coaxial hole: blind r=0.8 depth=0.4 + through r=0.35 depth=1.0
+ let mut scene = Scene::new();
+ scene.strict_manifold = true;
+ scene.add_box("block", 4.0, 4.0, 1.0, Vec3::ZERO).unwrap();
+ let mut cbore = make_cylinder(0.8, 0.6, 32, 2);
+ cbore.translate(Vec3::new(0.0, 0.0, 0.4)); // cuts z in [0.1, 0.5] (depth 0.4)
+ scene.set_part("cbore", cbore).unwrap();
+ scene.boolean_parts("block", "cbore", BoolOp::Difference, false).unwrap();
+ let through = make_cylinder(0.35, 2.0, 28, 3);
+ scene.set_part("through", through).unwrap();
+ scene.boolean_parts("block", "through", BoolOp::Difference, false).unwrap();
+
+ let (_, f) = scene.features(Some("block")).unwrap();
+ assert_features_sane("counterbore", f);
+ let bores: Vec<_> = f.cylinders.iter().filter(|c| c.kind == "bore").collect();
+ assert_eq!(bores.len(), 2, "expected 2 coaxial stepped bores, got {:?}", bores);
+ assert!((bores[0].radius - 0.8).abs() < 0.01, "cbore r={}", bores[0].radius);
+ assert!((bores[0].height - 0.4).abs() < 0.01, "cbore h={}", bores[0].height);
+ assert!((bores[1].radius - 0.35).abs() < 0.01, "through r={}", bores[1].radius);
+ assert!((bores[1].height - 0.6).abs() < 0.01, "through h={}", bores[1].height);
+}
+
+#[test]
+fn fuzz_negative_shapes_no_false_cylinders() {
+ let mut rng = Rng::new(0xDEC0_DE01);
+
+ // 1. Cones & frustums (15 random tapers with half-angle >= 5deg)
+ for i in 0..15 {
+ let r0 = rng.range_f64(0.8, 2.5);
+ let r1 = rng.range_f64(0.0, r0 * 0.72);
+ let h = rng.range_f64(0.8, 3.0);
+ let segs = rng.range_usize(16, 40);
+ let cone = make_cone(r0, r1, h, segs, 1);
+ let f = extract_features(&cone);
+ assert_features_sane(&format!("cone_{i}"), &f);
+ assert!(f.cylinders.is_empty(), "cone_{i} (r0={r0:.2}, r1={r1:.2}, h={h:.2}) false cyl: {:?}", f.cylinders);
+ }
+
+ // 2. Beveled boxes (90deg fillets must NOT trigger false cylinders)
+ for segs in 1..=4 {
+ let b = make_box(3.0, 2.0, 1.5, 1);
+ let bev = bevel_edges(&b, &EdgeSelector::Vertical, 0.25, segs, 2).unwrap();
+ let f = extract_features(&bev);
+ assert_features_sane(&format!("bevel_{segs}"), &f);
+ assert!(f.cylinders.is_empty(), "bevel segs={segs} false cyl: {:?}", f.cylinders);
+ }
+
+ // 3. Hexagonal prism (60deg dihedral => 6 planar walls, 0 cylinders)
+ let hex = make_cylinder(1.0, 2.0, 6, 1);
+ let hf = extract_features(&hex);
+ assert_features_sane("hex_prism", &hf);
+ assert!(hf.cylinders.is_empty(), "hex prism false cyl: {:?}", hf.cylinders);
+ assert_eq!(hf.planes.len(), 8, "hex prism should have 8 planar faces, got {:?}", hf.planes);
+
+ // 4. Multiple sphere & torus resolutions
+ for (u, v) in [(12, 8), (20, 12), (32, 20)] {
+ let s = make_sphere(1.2, u, v, 1);
+ let sf = extract_features(&s);
+ assert_features_sane(&format!("sphere_{u}x{v}"), &sf);
+ assert!(sf.cylinders.is_empty(), "sphere {u}x{v} false cyl: {:?}", sf.cylinders);
+
+ let t = make_torus(2.2, 0.55, u, v, 2);
+ let tf = extract_features(&t);
+ assert_features_sane(&format!("torus_{u}x{v}"), &tf);
+ assert!(tf.cylinders.is_empty(), "torus {u}x{v} false cyl: {:?}", tf.cylinders);
+ }
+}
+
+#[test]
+fn fuzz_100_random_complex_cad_parts_determinism_and_finiteness() {
+ let mut rng = Rng::new(0xCAAD_F022);
+ for case in 0..100 {
+ let mesh: PolyMesh = match case % 7 {
+ 0 => {
+ // Spur gear with central bore — must detect the bore cleanly!
+ let teeth = rng.range_usize(10, 26);
+ let module = rng.range_f64(0.5, 2.0);
+ let h = rng.range_f64(1.0, 4.0);
+ let pitch_r = 0.5 * module * teeth as f64;
+ let bore_r = (pitch_r * 0.35).max(0.4);
+ let g = make_gear(teeth, module, h, 20.0, bore_r, 1).unwrap();
+ let f = extract_features(&g);
+ assert_features_sane(&format!("gear_{case}"), &f);
+ let has_bore = f.cylinders.iter().any(|c| {
+ c.kind == "bore" && (c.radius - bore_r).abs() < 0.03 * bore_r
+ });
+ assert!(has_bore, "gear_{case} missing expected bore r={bore_r:.3}: {:?}", f.cylinders);
+ g
+ }
+ 1 => {
+ // Revolve profile
+ let prof = [
+ (0.4, 0.0),
+ (rng.range_f64(0.7, 1.4), 0.2),
+ (rng.range_f64(0.5, 1.0), 0.9),
+ (rng.range_f64(0.8, 1.5), 1.6),
+ (0.3, 1.8),
+ ];
+ make_revolve(&prof, rng.range_usize(16, 36), 1).unwrap()
+ }
+ 2 => {
+ // Multi-section loft
+ let s0 = rng.range_f64(0.8, 1.6);
+ let s1 = rng.range_f64(0.4, 1.1);
+ let h = rng.range_f64(1.0, 3.0);
+ make_loft(
+ &[
+ (0.0, vec![(-s0, -s0), (s0, -s0), (s0, s0), (-s0, s0)]),
+ (h, vec![(-s1, -s1), (s1, -s1), (s1, s1), (-s1, s1)]),
+ ],
+ rng.range_usize(12, 32),
+ 1,
+ )
+ .unwrap()
+ }
+ 3 => {
+ // Shelled beveled box
+ let b = make_box(rng.range_f64(2.0, 4.0), rng.range_f64(2.0, 4.0), rng.range_f64(1.5, 3.0), 1);
+ let bev = bevel_edges(&b, &EdgeSelector::Vertical, 0.2, 2, 2).unwrap();
+ shell_solid(&bev, 0.15, true, 3).unwrap()
+ }
+ 4 => {
+ // Subdivided box
+ let b = make_box(2.0, 1.5, 1.0, 1);
+ subsurf_catmull_clark(&b, 2, 2)
+ }
+ 5 => {
+ // Bisected cylinder
+ let c = make_cylinder(rng.range_f64(0.6, 1.5), rng.range_f64(1.5, 3.0), 24, 1);
+ let n = Vec3::new(rng.range_f64(-1.0, 1.0), rng.range_f64(-1.0, 1.0), 0.5).normalized();
+ bisect_mesh(&c, n, 0.1, false, 2).unwrap()
+ }
+ _ => {
+ // Voxel remeshed box
+ let b = make_box(2.0, 1.6, 1.2, 1);
+ remesh_voxel(&b, 0.22, 2).unwrap()
+ }
+ };
+
+ let f1 = extract_features(&mesh);
+ let f2 = extract_features(&mesh);
+ assert_features_sane(&format!("complex_{case}"), &f1);
+ let j1 = serde_json::to_string(&f1).unwrap();
+ let j2 = serde_json::to_string(&f2).unwrap();
+ assert_eq!(j1, j2, "complex_{case}: non-deterministic feature extraction!");
+ }
+}
+
+#[test]
+fn fuzz_extreme_scales_and_huge_translations() {
+ for (scale, shift) in [
+ (1e-3, Vec3::ZERO),
+ (1e4, Vec3::ZERO),
+ (1.0, Vec3::new(1e6, -2e6, 5e5)),
+ ] {
+ let mut scene = Scene::new();
+ scene.add_box("p", 4.0 * scale, 2.0 * scale, 0.4 * scale, shift).unwrap();
+ let mut hole = make_cylinder(0.4 * scale, 1.0 * scale, 28, 2);
+ hole.translate(shift);
+ scene.set_part("h", hole).unwrap();
+ scene.boolean_parts("p", "h", BoolOp::Difference, false).unwrap();
+
+ let (_, f) = scene.features(Some("p")).unwrap();
+ assert_features_sane(&format!("scale_{scale}"), f);
+ assert_eq!(f.planes.len(), 6);
+ assert_eq!(f.cylinders.len(), 1);
+ assert_eq!(f.cylinders[0].kind, "bore", "scale={scale} shift={shift:?} f={f:?}");
+ assert!((f.cylinders[0].radius - 0.4 * scale).abs() < 0.01 * scale);
+ assert_eq!(f.symmetry, [true, true, true]);
+ let wt = f.wall_thickness.as_ref().unwrap();
+ assert!((wt.min - 0.4 * scale).abs() < 0.02 * scale);
+ }
+}
+
+#[test]
+fn cache_invalidation_on_mutation_and_cow_rollback() {
+ let mut scene = Scene::new();
+ scene.add_box("p", 4.0, 2.0, 0.4, Vec3::ZERO).unwrap();
+
+ // Populate cache before checkpoint
+ let (_, f_before) = scene.features(Some("p")).unwrap();
+ let ptr_before = f_before as *const _;
+ assert_eq!(f_before.cylinders.len(), 0);
+
+ scene.checkpoint("clean");
+
+ // Mutate part -> cache must invalidate and reflect the new bore
+ let hole = make_cylinder(0.5, 1.0, 24, 2);
+ scene.set_part("h", hole).unwrap();
+ scene.boolean_parts("p", "h", BoolOp::Difference, false).unwrap();
+
+ let (_, f_after) = scene.features(Some("p")).unwrap();
+ let ptr_after = f_after as *const _;
+ assert!(!std::ptr::eq(ptr_before, ptr_after));
+ assert_eq!(f_after.cylinders.len(), 1);
+
+ // Rollback restores the original Arc<CachedPart> WITH its already-compiled features!
+ scene.rollback("clean").unwrap();
+ let (_, f_rolled) = scene.features(Some("p")).unwrap();
+ let ptr_rolled = f_rolled as *const _;
+ assert!(std::ptr::eq(ptr_before, ptr_rolled), "rollback should restore original cached Arc");
+ assert_eq!(f_rolled.cylinders.len(), 0);
+
+ // Undo restores the mutated Arc<CachedPart> WITH its cached features!
+ scene.undo().unwrap();
+ let (_, f_undone) = scene.features(Some("p")).unwrap();
+ let ptr_undone = f_undone as *const _;
+ assert!(std::ptr::eq(ptr_after, ptr_undone), "undo should restore mutated cached Arc");
+ assert_eq!(f_undone.cylinders.len(), 1);
+}
diff --git a/crates/forma-lang/src/lib.rs b/crates/forma-lang/src/lib.rs
index ed88e5a..1b7e124 100644
--- a/crates/forma-lang/src/lib.rs
+++ b/crates/forma-lang/src/lib.rs
@@ -78,7 +78,7 @@ Ops (| or op(m,...); add/cut take at=):
add(b,at=) cut(b,at=) intersect(b) mirror(x|y|z) array(n,step) radial(n,r=,axis=z) shell(t,open_top=true) subsurf(levels=1,crease=false)
bevel(edges,w,segs=1) [vertical|top_rim|bottom_rim|outer_rim|sharp|all] extrude(faces,d) inset(faces,amt,depth=0) [top|bottom|sides|all]
move(x,y,z) rot(rx,ry,rz) scale(sx,sy,sz) align(x|y|z,min|center|max,val) on(base) align_z0(z)
-mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) smooth(angle=35) flat() group(path) inst(p,at=,rot=,group=) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z)
+mat(name,color=(r,g,b[,a]),metallic=0,roughness=0.5,alpha=1,emissive=(r,g,b),transmission=0,double_sided=false) color(r,g,b[,a]) smooth(angle=35) flat() group(path) inst(p,at=,rot=,group=) units("mm") [m|cm|mm|um|in|ft] clearance(a,b) section(part,z) features(part)
Topics: deform|curves|uv|remesh|scene"#;
/// Progressive on-demand domain specs (loaded only when requested).
@@ -108,7 +108,8 @@ pub fn spec_topic(topic: &str) -> Result<&'static str, String> {
"Forma-Pipe // Remesh, Bisect & Import:\n\
- `remesh(voxel_size=0.0)` — Surface Nets voxel remesh (0 = auto diag/28; heals dirty/multi-shell meshes to watertight)\n\
- `bisect(normal=(0,0,1), offset=0.0, clear_inner=false)` — exact watertight half-space plane cut + planar cap\n\
- - `load(\"path.glb|obj|stl\")` — import external 3D asset (or uploaded key in forma-server)"
+ - `load(\"path.glb|obj|stl\")` — import external 3D asset (or uploaded key in forma-server)\n\
+ - `features(part)` — compile & cache compact CAD facts (planes, bores/bosses, symmetry, wall thickness)"
),
"scene" => Ok(
"Forma-Pipe // Multi-Object Scene Graph, Hierarchy & Instancing:\n\
@@ -236,4 +237,25 @@ mod tests {
let bb = p.aabb();
assert!(bb.max.y > 0.35, "expected X-axis curve warp to displace in Y, got bbox={bb:?}");
}
+
+ #[test]
+ fn test_features_query_in_pipe() {
+ let mut s = Scene::new();
+ s.strict_manifold = true;
+ let obs = eval_script(
+ &mut s,
+ Dialect::Pipe,
+ "units(\"mm\")\n\
+ plate = box(40, 20, 4) | cut(cyl(5, 10))\n\
+ n = features(plate)\n",
+ )
+ .unwrap();
+ assert!(obs.ok, "{}", obs.text);
+ assert!(obs.text.contains("features(plate):"), "{}", obs.text);
+ assert!(obs.text.contains("planes(6):"), "{}", obs.text);
+ assert!(obs.text.contains("cylinders(1):"), "{}", obs.text);
+ assert!(obs.text.contains("bore axis=+z r=5.000"), "{}", obs.text);
+ assert!(obs.text.contains("unit=mm"), "{}", obs.text);
+ assert_eq!(s.get_scalar("n"), Some(7.0));
+ }
}
diff --git a/crates/forma-lang/src/pipeline.rs b/crates/forma-lang/src/pipeline.rs
index 5797528..e96d1e8 100644
--- a/crates/forma-lang/src/pipeline.rs
+++ b/crates/forma-lang/src/pipeline.rs
@@ -366,6 +366,7 @@ fn max_call_positional(name: &str) -> Option<usize> {
"bezier" => 2,
"nurbs" | "bspline" => 3,
"clearance" | "section" => 2,
+ "features" | "facts" => 1,
"checkpoint" | "rollback" | "del" | "remove" | "units" | "unit" => 1,
"undo" => 0,
"box" => 3,
@@ -427,7 +428,7 @@ fn check_positional_count(n: usize, max: Option<usize>, allowed_kw: Option<&[&st
const CALL_NAMES: &[&str] = &[
"box", "cyl", "cylinder", "prism", "cone", "frustum", "sphere", "torus", "revolve", "arc_tube", "tube", "extrude2d",
"pipe", "hollow_cyl", "loft", "sheet", "thread", "helix", "sweep", "text3d", "text", "gear", "load", "import", "bezier", "nurbs",
- "bspline", "clearance", "section", "checkpoint", "rollback", "undo", "units", "unit", "del", "remove", "group", "inst", "instance", "sqrt", "sin",
+ "bspline", "clearance", "section", "features", "facts", "checkpoint", "rollback", "undo", "units", "unit", "del", "remove", "group", "inst", "instance", "sqrt", "sin",
"cos", "tan", "asin", "acos", "atan", "atan2", "abs", "deg", "rad",
];
@@ -498,6 +499,7 @@ fn allowed_call_kwargs(name: &str) -> Option<&'static [&'static str]> {
"nurbs" | "bspline" => &["points", "pts", "degree", "deg", "segs", "segments", "weights"],
"clearance" => &["a", "b"],
"section" => &["part", "p", "z"],
+ "features" | "facts" => &["part", "p"],
"checkpoint" | "rollback" | "del" | "remove" => &["name", "tag"],
"group" => &["path", "name", "parts", "children"],
"inst" | "instance" => &["part", "mesh", "proto", "at", "pos", "rot", "rotate", "scale", "group", "parent", "name"],
@@ -1404,6 +1406,30 @@ impl<'a> Parser<'a> {
self.scene.push_note(rep.summary(part_name));
return Ok(Val::Num(rep.area));
}
+ "features" | "facts" => {
+ let (val, part_name) = if let Some(v) = pos.first() {
+ (v, arg_names.pos.first().and_then(|o| o.as_deref()))
+ } else if let Some(v) = kw.get("part") {
+ (v, arg_names.kw.get("part").map(String::as_str))
+ } else if let Some(v) = kw.get("p") {
+ (v, arg_names.kw.get("p").map(String::as_str))
+ } else {
+ return Err(format!("{ctx}: missing part"));
+ };
+ if let Some(name) = part_name {
+ if let Ok((_, rep)) = self.scene.features(Some(name)) {
+ let count = (rep.planes.len() + rep.cylinders.len()) as f64;
+ let summary = rep.summary(name, self.scene.unit);
+ self.scene.push_note(summary);
+ return Ok(Val::Num(count));
+ }
+ }
+ let m = val.as_mesh(&ctx)?;
+ let rep = forma_core::features::extract_features(&m);
+ let count = (rep.planes.len() + rep.cylinders.len()) as f64;
+ self.scene.push_note(rep.summary(part_name.unwrap_or("part"), self.scene.unit));
+ return Ok(Val::Num(count));
+ }
"checkpoint" => {
let tag = pos.first().or_else(|| kw.get("name")).or_else(|| kw.get("tag")).ok_or(format!("{ctx}: missing tag"))?.as_str(&ctx)?;
self.scene.checkpoint(tag);
diff --git a/crates/forma-mcp/src/main.rs b/crates/forma-mcp/src/main.rs
index c20f225..c4888d8 100644
--- a/crates/forma-mcp/src/main.rs
+++ b/crates/forma-mcp/src/main.rs
@@ -90,10 +90,11 @@ fn tools_schema() -> Value {
},
{
"name": "inspect",
- "description": "Invariants, lint, or topic spec.",
+ "description": "Invariants, part features, lint, or topic spec.",
"inputSchema": {
"type": "object",
"properties": {
+ "part": { "type": "string" },
"topic": {
"type": "string",
"enum": ["deform", "curves", "uv", "remesh", "scene"],
@@ -358,7 +359,13 @@ fn handle_tool_call(scene: &mut Scene, name: &str, args: &Value) -> ToolCallResu
.filter(|s| !s.is_empty())
{
match scene.observe_part(part) {
- Ok(text) => ToolCallResult::ok(text),
+ Ok(mut text) => {
+ if let Ok((name, feats)) = scene.features(Some(part)) {
+ text.push('\n');
+ text.push_str(&feats.summary(name, scene.unit));
+ }
+ ToolCallResult::ok(text)
+ }
Err(e) => ToolCallResult::err(format!("ERR: {e}")),
}
} else {
@@ -675,6 +682,13 @@ mod tests {
assert!(!insp.is_error, "{}", insp.text);
assert!(insp.text.contains("parts=1"), "{}", insp.text);
+ // inspect(part="a") compiles and returns compact geometric facts.
+ let feats = handle_tool_call(&mut scene, "inspect", &json!({ "part": "a" }));
+ assert!(!feats.is_error, "{}", feats.text);
+ assert!(feats.text.contains("features(a):"), "{}", feats.text);
+ assert!(feats.text.contains("planes(6):"), "{}", feats.text);
+ assert!(feats.text.contains("sym=XYZ"), "{}", feats.text);
+
// Unknown tool lists valid tool names.
let bad = handle_tool_call(&mut scene, "nope", &json!({}));
assert!(bad.is_error);
diff --git a/crates/forma-wasm/src/lib.rs b/crates/forma-wasm/src/lib.rs
index b779285..d2914a9 100644
--- a/crates/forma-wasm/src/lib.rs
+++ b/crates/forma-wasm/src/lib.rs
@@ -593,3 +593,33 @@ pub extern "C" fn forma_session_invariants(id: u32, part_ptr: *const u8, part_le
s.set_ok_str(payload)
})
}
+
+/// Compile (lazily cached) geometric features for the current or named part.
+#[no_mangle]
+pub extern "C" fn forma_session_features(id: u32, part_ptr: *const u8, part_len: usize) -> u32 {
+ let part_opt = match unsafe { read_utf8(part_ptr, part_len) } {
+ Ok(s) if !s.is_empty() => Some(s),
+ Ok(_) => None,
+ Err(e) => return STATE.with(|st| st.borrow_mut().set_err(e)),
+ };
+ STATE.with(|st| {
+ let mut s = st.borrow_mut();
+ let Some(scene) = s.sessions.get(&id) else {
+ return s.set_err(format!("invalid session id {id}"));
+ };
+ match scene.features(part_opt.as_deref()) {
+ Ok((name, feats)) => {
+ let text = feats.summary(name, scene.unit);
+ let payload = json!({
+ "part": name,
+ "unit": scene.unit.symbol(),
+ "text": text,
+ "features": feats,
+ })
+ .to_string();
+ s.set_ok_str(payload)
+ }
+ Err(e) => s.set_err(e.to_string()),
+ }
+ })
+}
diff --git a/docs/README.md b/docs/README.md
index bc3018d..28c639b 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -38,6 +38,7 @@ flowchart LR
| If you want to... | Start here |
| --- | --- |
+| Let a coding agent install and verify Forma for you | [Agent-driven setup runbook (`docs/agent-setup.md`)](agent-setup.md) |
| Build and verify your first 3D part from scratch | [Tutorial: Build your first watertight part](tutorials/first-part.md) |
| Connect Claude Code, Cursor, Codex, ChatGPT VM, or a local LLM | [How to connect AI agents (MCP, CLI, GBNF, and Sandboxes)](how-to/connect-ai-agents.md) |
| Embed `forma-3d` in Node.js, Cloudflare Workers, Edge, or browsers | [How to embed forma-3d in JS, Edge, and Browsers](how-to/embed-wasm-js.md) |
@@ -53,6 +54,7 @@ flowchart LR
These root files are packaged inside the `forma-3d` npm tarball and tuned for coding agents:
+- [`docs/agent-setup.md`](agent-setup.md): Self-contained interactive setup runbook for coding agents (with truncation guard and per-step checks).
- [`SKILL.md`](../SKILL.md): Drop-in agent skill with five smoke-tested `Forma-Pipe` recipes.
- [`AGENTS.md`](../AGENTS.md): Compact agent workflow rules and CLI/MCP invocation guide.
- [`llms.txt`](../llms.txt): Self-contained machine-readable language cheat sheet and repository index.
diff --git a/docs/agent-setup.md b/docs/agent-setup.md
new file mode 100644
index 0000000..de3d584
--- /dev/null
+++ b/docs/agent-setup.md
@@ -0,0 +1,179 @@
+# Set up Forma for the person you work with
+
+You are a coding agent with a shell, and the person is in this chat. Forma is a pure-Rust (~1.7 MB native / ~0.8 MB WASM) headless 3D polyhedral modeling engine with strict watertightness verification, a minimal 4-tool MCP server (`< 800` tokens), and a zero-GPU studio preview renderer. Follow these steps in order, and run each **Check** before moving on.
+
+**Check you have all of it.** This file has six numbered steps, and its last line is `End of setup file.` If you see fewer steps or no such line, you were given a summary or a truncated copy. Do not start. Fetch the exact file with `curl -fsSL https://raw.githubusercontent.com/wrong-nebula/forma/main/docs/agent-setup.md` and read all of it.
+
+## Rules for you
+
+- Never modify shell profiles (`~/.zshrc`, `~/.bashrc`, `~/.profile`) or agent/IDE config files (`~/.claude.json`, `~/.cursor/mcp.json`, `~/.codex/config.toml`, etc.) without asking the person first and showing the exact change.
+- Never silently install system toolchains (Homebrew, Node.js, Rust/Cargo). Check what is already installed first and ask before installing anything.
+- Do not rely on `cd` persisting between shell calls; pass explicit paths or chain commands inside a single shell invocation.
+- Never pass `--no-strict` or work around a failed invariant check to make a smoke test pass. On an error, stop that step and show the person the exact command output.
+- Write smoke-test artifacts into `/tmp/forma-setup-check` rather than polluting the person's project directory, and clean them up when asked.
+- If a step waits on the person (for example, restarting their MCP client), complete any independent steps first and list what is waiting in your final summary.
+
+---
+
+## 1. Ask the person, all at once
+
+Ask these four questions together (some chat UIs cap multi-question prompts at four):
+
+1. **Install mode:** Zero-install npm WASM (`npx -y forma-3d`, ~0.8 MB, works immediately with Node 18+) or native Rust release build (~1.7 MB binary, ~4 ms studio renders, supports local filesystem `load()` and `forma inspect`)?
+2. **Integration:** MCP server (`forma-mcp` / `forma-3d-mcp`), shell CLI (`forma` / `forma-3d`), or both?
+3. **Client configuration** (if using MCP or Agent Skills): Which client should be configured — Claude Code, Cursor, Codex, Antigravity, or print the config snippet only without editing files?
+4. **Default model unit:** `mm` (recommended for 3D printing and mechanical CAD) or `m` (default for glTF / web / game engines)?
+
+---
+
+## 2. Check what is already installed
+
+Run a non-mutating check for existing Forma binaries and runtimes:
+
+```sh
+command -v forma && forma --version || true
+command -v node && node -v || true
+command -v cargo && cargo --version || true
+```
+
+**Check:**
+- If `forma` is already installed, report its version and path and ask whether to keep it or rebuild.
+- For **npm WASM**, confirm Node.js is `v18.0.0` or newer. If Node is missing or too old, tell the person and ask before installing or switching to the native Rust build.
+- For **native Rust**, confirm `cargo` and `git` are installed. If Cargo is missing, offer the npm WASM path or ask before installing Rust (`rustup`).
+
+---
+
+## 3. Install or build Forma
+
+### Path A — Zero-install npm WASM (`forma-3d`)
+
+No global install is required. Verify that `npx` can resolve and run `forma-3d`:
+
+```sh
+npx -y forma-3d --version
+```
+
+**Check:** Prints `forma <version>` (for example `forma 0.4.4`).
+
+If the person wants a persistent local CLI without `npx` startup overhead, ask before running `npm install -g forma-3d`.
+
+### Path B — Native Rust release build (`forma` + `forma-mcp`)
+
+Ask the person where to clone the repo (suggest `~/src/forma`). If that directory already exists, ask before touching or updating it.
+
+```sh
+git clone https://github.com/wrong-nebula/forma.git ~/src/forma
+cd ~/src/forma && cargo build --release
+```
+
+Record the absolute paths to both binaries (`~/src/forma/target/release/forma` and `~/src/forma/target/release/forma-mcp`) and use those full paths in all later steps unless the person asks to symlink them onto `PATH`.
+
+**Check:**
+
+```sh
+~/src/forma/target/release/forma --version
+~/src/forma/target/release/forma spec | head -n 3
+```
+
+Prints `forma <version>` and the `Forma-Pipe` header.
+
+---
+
+## 4. Wire up the MCP server (if requested)
+
+Forma's MCP server exposes **4 tools** (`eval`, `inspect`, `tx`, `export`) in under 800 tokens.
+
+Choose the command matching Step 3:
+- **Path A (npm WASM):** command `"npx"`, args `["-y", "-p", "forma-3d", "forma-3d-mcp"]`
+- **Path B (native binary):** command `"/absolute/path/to/forma-mcp"`, args `[]`
+
+Before editing any config file, show the exact snippet to the person and wait for approval:
+
+- **Generic MCP JSON** (Cursor `.cursor/mcp.json` or `~/.cursor/mcp.json`, Antigravity, Windsurf, Claude Desktop):
+ ```json
+ {
+ "mcpServers": {
+ "forma": {
+ "command": "npx",
+ "args": ["-y", "-p", "forma-3d", "forma-3d-mcp"]
+ }
+ }
+ }
+ ```
+- **Claude Code CLI** (ask before running):
+ ```sh
+ claude mcp add forma -- npx -y -p forma-3d forma-3d-mcp
+ ```
+- **Codex (`~/.codex/config.toml`)** (ask before editing):
+ ```toml
+ [mcp_servers.forma]
+ command = "npx"
+ args = ["-y", "-p", "forma-3d", "forma-3d-mcp"]
+ ```
+
+**Check:** Probe the MCP stdio server directly without touching the person's IDE (replace `npx -y -p forma-3d forma-3d-mcp` with the native `forma-mcp` path for Path B):
+
+```sh
+printf '%s\n%s\n' \
+ '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' \
+ '{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}' \
+ | npx -y -p forma-3d forma-3d-mcp
+```
+
+Confirm the second JSON line lists all 4 tools: `eval`, `inspect`, `tx`, and `export`. Tell the person if their MCP client needs a reload/restart to pick up the new server.
+
+---
+
+## 5. Install the Agent Skill (`SKILL.md`, optional)
+
+Forma ships a compact Agent Skill ([`SKILL.md`](https://raw.githubusercontent.com/wrong-nebula/forma/main/SKILL.md)) with verified recipes and token-efficient modeling rules. Ask the person whether they want it installed:
+
+- **Project-local:** `.agents/skills/forma/SKILL.md`
+- **User-global:** `~/.agents/skills/forma/SKILL.md` (requires explicit approval since it is outside the workspace)
+
+Install with:
+
+```sh
+mkdir -p .agents/skills/forma
+curl -fsSL https://raw.githubusercontent.com/wrong-nebula/forma/main/SKILL.md -o .agents/skills/forma/SKILL.md
+```
+
+(On Path B, you may copy `~/src/forma/SKILL.md` instead of curling.)
+
+**Check:** `head -n 5 .agents/skills/forma/SKILL.md` shows `name: forma`.
+
+---
+
+## 6. Run a verified end-to-end smoke test
+
+Run a strict flanged-plate build, cross-section query, geometric feature compilation, GLB export, 4-view studio PNG render, and SVG blueprint into `/tmp/forma-setup-check`.
+
+Substitute `<FORMA_CMD>` with either `npx -y forma-3d` (Path A) or `~/src/forma/target/release/forma` (Path B). Use `units("mm")` if the person picked millimeters in Step 1 (scaling dimensions by 10x or keeping meters as below):
+
+```sh
+mkdir -p /tmp/forma-setup-check
+<FORMA_CMD> eval --strict \
+ --out /tmp/forma-setup-check/flange.glb \
+ --render /tmp/forma-setup-check/flange.png \
+ --draw /tmp/forma-setup-check/flange.svg <<'EOF'
+flange = box(4, 2, 0.4)
+ | mat("steel", color=(0.55, 0.68, 0.85), metallic=0.9, roughness=0.25)
+ | cut(cyl(0.5, 1))
+ | cut(cyl(0.25, 1), at=[(-1.4,-0.5,0), (-1.4,0.5,0), (1.4,-0.5,0), (1.4,0.5,0)])
+section(flange, 0.0)
+features(flange)
+EOF
+```
+
+If on Path B (native CLI), also verify direct mesh feature inspection on the exported `.glb`:
+
+```sh
+~/src/forma/target/release/forma inspect /tmp/forma-setup-check/flange.glb
+```
+
+**Check:**
+1. Exit code is `0` and stdout contains `WT=ok`, `NM=0`, `B=0`, `g=5`, `loops=6`, `planes(6):`, and `cylinders(5):`.
+2. `ls -lh /tmp/forma-setup-check/flange.{glb,png,svg}` shows three non-empty files.
+3. Report to the person: installed mode/version, configured MCP/Skill paths, smoke-test verification results, and any remaining action waiting on them (such as reloading their IDE). Offer to delete `/tmp/forma-setup-check` once they have inspected the preview.
+
+End of setup file.
diff --git a/lib/edge.mjs b/lib/edge.mjs
index fdf800b..504e881 100644
--- a/lib/edge.mjs
+++ b/lib/edge.mjs
@@ -345,6 +345,15 @@ export class FormaSession {
return JSON.parse(this._engine._readResultString());
}
+ /** Compile (lazily cached) geometric facts (planes, bores/bosses, symmetry, wall thickness) for a part. */
+ features(part = "") {
+ this._checkOpen();
+ this._engine._withUtf8(part || "", (pp, pl) => {
+ this._engine.exports.forma_session_features(this._id, pp, pl);
+ });
+ return JSON.parse(this._engine._readResultString());
+ }
+
/** Free session memory in the WASM heap. */
free() {
if (!this._freed) {
diff --git a/lib/index.d.ts b/lib/index.d.ts
index 2e45f08..2840521 100644
--- a/lib/index.d.ts
+++ b/lib/index.d.ts
@@ -75,6 +75,55 @@ export interface FormaInvariants {
tags: Record<string, number>;
}
+export interface FormaPlanarRegion {
+ orientation: string;
+ normal: [number, number, number];
+ offset: number;
+ area: number;
+ centroid: [number, number, number];
+ bbox_min: [number, number, number];
+ bbox_max: [number, number, number];
+ span: [number, number, number];
+ face_count: number;
+}
+
+export interface FormaCylindricalFeature {
+ kind: "bore" | "boss" | string;
+ axis_label: string;
+ axis: [number, number, number];
+ center: [number, number, number];
+ radius: number;
+ diameter: number;
+ height: number;
+ arc_deg: number;
+ face_count: number;
+}
+
+export interface FormaWallThickness {
+ min: number;
+ median: number;
+ samples: number;
+}
+
+export interface FormaMeshFeatures {
+ bbox_min: [number, number, number];
+ bbox_max: [number, number, number];
+ size: [number, number, number];
+ center: [number, number, number];
+ surface_area: number;
+ symmetry: [boolean, boolean, boolean];
+ wall_thickness: FormaWallThickness | null;
+ planes: FormaPlanarRegion[];
+ cylinders: FormaCylindricalFeature[];
+}
+
+export interface FormaFeaturesResult {
+ part: string;
+ unit: FormaUnit | string;
+ text: string;
+ features: FormaMeshFeatures;
+}
+
export interface FormaObservation {
ok: boolean;
elapsed_ms: number;
@@ -157,6 +206,8 @@ export class FormaSession {
exportSceneSvg(): string;
/** Compute topological & spatial invariants for the current or named part. */
invariants(part?: string): FormaInvariants;
+ /** Compile (lazily cached) geometric features (planes, bores/bosses, symmetry, wall thickness). */
+ features(part?: string): FormaFeaturesResult;
/** Release this session's memory from the WASM heap. */
free(): void;
}
diff --git a/llms.txt b/llms.txt
index 1e8b364..24991a6 100644
--- a/llms.txt
+++ b/llms.txt
@@ -5,6 +5,7 @@
## Repository Map
- [SKILL.md](SKILL.md): Ready-to-use Agent Skill (`name: forma`) with token-efficient workflow, full syntax cheat sheet, verified recipes, and troubleshooting
+- [docs/agent-setup.md](docs/agent-setup.md): Step-by-step agent-driven setup runbook (interactive install, MCP wiring, skill install, and verified smoke test)
- [README.md](README.md): Overview, quickstart, npm/CLI/MCP usage, and full 12-model / 9-lab benchmarks
- [AGENTS.md](AGENTS.md): Step-by-step integration guide for AI agents (MCP, CLI, constrained decoding, feedback loop)
- [grammar/forma_pipe.gbnf](grammar/forma_pipe.gbnf): Formal GBNF grammar for zero-syntax-error constrained decoding (llama.cpp, vLLM, XGrammar)
@@ -67,6 +68,7 @@ cargo build --release
- Spatial Queries & State (emitted in compact observation output):
- `clearance(part_a, part_b)` — exact 3D minimum surface distance & collision check
- `section(part, z)` — exact 2D cross-section loop count, area, perimeter, XY bounds
+ - `features(part)` (alias `facts(part)`) — compile & cache compact CAD facts (planar mounting regions, cylindrical bores/bosses with axis/radius/center/height, XYZ symmetry, opposite-wall thickness); also available via MCP `inspect({ part })` and CLI `forma inspect <file.(glb|obj|stl)>`
- `del("name")` — remove a named part from `scene.parts`
## Supported Runtimes & Deployment Targets
@@ -79,6 +81,6 @@ cargo build --release
## MCP Tools (`forma-mcp`, 721 o200k tokens total)
1. `eval({ code, strict? })` — Run transactional Forma-Pipe code (auto-rollback on error; scalar variables persist across calls); returns compact ~100-token diff (`V`, `F`, `WT`, `NM`, `B`, `g` genus, `vol`, `bbox`, `size`, tags, query results).
-2. `inspect({ topic? })` — Return current scene summary without mutating state, or an on-demand domain spec (`deform|curves|uv|remesh|scene`).
+2. `inspect({ part?, topic? })` — Return current scene summary without mutating state, compiled CAD facts for `part` (planes, bores/bosses, symmetry, wall thickness), or an on-demand domain spec (`deform|curves|uv|remesh|scene`).
3. `tx({ action: "checkpoint"|"rollback"|"undo"|"reset", tag? })` — Instant O(1) copy-on-write state control (snapshots both geometry and scalar variables).
4. `export({ path, part?, scene?, size? })` — Export to `.glb` (PBR + UVs), `.step`, `.3mf`, `.stl`, `.obj`, `.svg` blueprint, `.blend` (via Blender bridge), or render a 4-view `.png` preview (`scene: true` exports/renders all named parts together for `.glb`, `.blend`, `.png`, and `.svg`).
diff --git a/tests/npm_smoke.mjs b/tests/npm_smoke.mjs
index fedee29..0d12dc5 100644
--- a/tests/npm_smoke.mjs
+++ b/tests/npm_smoke.mjs
@@ -363,9 +363,10 @@ section(flange, 0.0)
assert.equal(mcpResponses[2].result.content.length, 2);
assert.equal(mcpResponses[2].result.content[1].type, "image");
assert.ok(mcpResponses[3].result.content[0].text.includes("solidify"));
- // Single-part drill-down omits p0/p1 and reports sync status
+ // Single-part drill-down omits p0/p1, reports sync status, and includes compiled CAD features
const partText = mcpResponses[4].result.content[0].text;
- assert.ok(partText.includes("- p2:") && !partText.includes("- p0:") && partText.includes("sync: rev=r1"));
+ assert.ok(partText.includes("- p2:") && !partText.includes("- p0:") && partText.includes("sync: rev=r1"), partText);
+ assert.ok(partText.includes("features(p2):") && partText.includes("boss axis=+z r=0.500") && partText.includes("wall_p01="), partText);
// Delta-first incremental eval collapses unchanged p0, p2 and reports stale render/export
const incText = mcpResponses[6].result.content[0].text;
assert.ok(incText.includes("unchanged(2): p0, p2 (all WT=ok)"), incText);
@@ -386,7 +387,7 @@ section(flange, 0.0)
assert.equal(journal[0].rec, "r1");
assert.equal(journal[4].stale_render, true);
assert.equal(journal[5].stale_render, false);
- console.log("PASS 5/5: MCP stdio server bin/forma-mcp.mjs (fused eval+out, batch paths[], view, inspect(part), delta-first, staleness, --log)");
+ console.log("PASS 5/5: MCP stdio server bin/forma-mcp.mjs (fused eval+out, batch paths[], view, inspect(part+features), delta-first, staleness, --log)");
} finally {
rmSync(tmp, { recursive: true, force: true });
}
diff --git a/wasm/forma.wasm b/wasm/forma.wasm
index 288fcaa..030eab3 100755
Binary files a/wasm/forma.wasm and b/wasm/forma.wasm differ