Skip to content

Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.

feat(viewer): show STEP AP242 PMI (model-based definition) in the model viewer (#2048)

Brad Barbin67f6b7d5c1bb
diff --git a/.ai/lessons.md b/.ai/lessons.md
index 4f4dafbffe..1e0ceb8694 100644
--- a/.ai/lessons.md
+++ b/.ai/lessons.md
@@ -4130,3 +4130,13 @@ The write was then removed (nothing reads it), so the rail always starts collaps
**Applies to:** list reads in `apps/erp/app/modules/*/*.service.ts` that call `setGenericQueryFilters`, and the `types.ts` row types derived from them.
+
+## OCCT keeps every document it opened by path, and refuses to open it again
+
+**Context:** The optimize ingest gained a PMI pass (`read_pmi`, `crates/occt-bridge/src/pmi.cc`) that reads the same `.xbf` the optimiser had just tessellated with `read_xbf` (2026-10-26).
+
+**Problem:** `TDocStd_Application::Open(path, doc)` registers the document with the application until `Close(doc)`. `read_xbf` never closes it, so the second open of the same path failed with `PCDM_RS_AlreadyRetrieved` ("could not open XBF document"). The hermetic converter test passed, because it opened the `.xbf` only once; only the assembler's ingest test, which runs both passes, showed it.
+
+**Rule:** A second reader of an `.xbf` opens it from a stream (`Open(std::istream&, doc)`), which skips the path check, and calls `xcaf_app()->Close(doc)` when done. Test any new pass over the ingest's xbf through `run_ingest`, not only through the converter.
+
+**Applies to:** `crates/occt-bridge/src/*.cc` (any function that opens a BinXCAF document), `apps/assembler/src/actions/optimize.rs` (`run_ingest`).
diff --git a/.ai/plans/2026-10-26-step-pmi-viewer.md b/.ai/plans/2026-10-26-step-pmi-viewer.md
new file mode 100644
index 0000000000..ada413ab8a
--- /dev/null
+++ b/.ai/plans/2026-10-26-step-pmi-viewer.md
@@ -0,0 +1,312 @@
+# PMI in the STEP viewer — implementation plan
+
+**Spec:** .ai/specs/2026-10-26-step-pmi-viewer.md
+**Research:** .ai/research/step-pmi-viewer.md
+**Closest sibling:** the optimize thumbnail (a second ingest output of `model-optimize`)
+**Branch:** tokyo
+
+## Progress
+- [x] Task 1: Add `read_pmi` and the AP242 fixture writer to `occt-bridge`
+- [x] Task 2: Build `pmi.json` in `converter`, with tests
+- [x] Task 3: Write the `pmi` output from the `optimize` action
+- [x] Task 4: Add `modelUpload.pmiPath`
+- [x] Task 5: Request, persist and back up `pmiPath` in `@carbon/jobs`
+- [x] Task 6: Return `pmiPath` from the artifacts routes
+- [x] Task 7: Add the `pmi.ts` contract and formatter to `@carbon/viewer`, with tests
+- [x] Task 8: Draw the PMI layer and the PMI panel
+- [x] Task 9: Pass `pmiUrl` from the ERP and MES hosts
+- [x] Task 10: Verify end to end
+
+## Deviations during the build
+
+- `CODE_VERSION` stays at 4. Only `plan` reads the result-pointer cache, so a bump would only throw away cached results.
+- The `pmi.json` path is unique per run, after the self-review found a race between two runs of one model.
+- Task 4 ran against a throwaway database restored from a sibling worktree's schema (same 1,238 migrations), because the shared Redis pool was full and `crbn` could not start this worktree's stack.
+- Task 2 step 15 changed: OCCT reads none of NIST STC 06's 12 views (it stops at the first camera with no draughting model). The test asserts STC 06's PMI only; CTC 01 (1 view) and CTC 05 (2 views) carry the view tests.
+- Task 10 ran the browser check on a throwaway Vite page that mounts the real `ModelPreview`, for the same reason.
+
+## Dependencies
+- Task 2 needs Task 1. Task 3 needs Task 2.
+- Task 5 needs Task 4. Task 6 needs Task 4.
+- Task 8 needs Task 7. Task 9 needs Tasks 6 and 8.
+- Tasks 1–3 (Rust) and Tasks 4–8 (TypeScript) are independent of each other.
+
+## Build environment
+
+The host has no Rust toolchain and no OCCT. Run every cargo command in the dev container:
+
+```bash
+docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry \
+ -v "$PWD/.context/pmi-fixtures":/fixtures carbon-rust-dev <cargo command>
+```
+
+The image `carbon-rust-dev` is built from `.context/dev/Dockerfile` (OCCT `carbon-occt:8.0.0-p1`, FCL, Draco, Rust 1.99). NIST fixtures are in `.context/pmi-fixtures/` (not committed).
+
+---
+
+## Task 1: Add `read_pmi` and the AP242 fixture writer to `occt-bridge`
+
+**Depends on:** none
+**Files:**
+- Modify: `crates/occt-bridge/src/lib.rs` — new shared structs and two functions in the cxx bridge
+- Modify: `crates/occt-bridge/src/occt.h` — declarations
+- Create: `crates/occt-bridge/src/pmi.cc` — the PMI walk
+- Modify: `crates/occt-bridge/build.rs` — compile `pmi.cc`
+- Copy from (precedent): `read_xbf`, `doc_to_tree`, `write_test_step` in `crates/occt-bridge/src/occt.cc`; `XDEDRAW_GDTs.cxx` in `.context/occt-src` for the getters
+
+**Steps:**
+1. Add these shared structs to the bridge: `PmiTree { ok, error, items: Vec<PmiRaw>, faces: Vec<PmiMesh>, edges: Vec<PmiPolyline>, views: Vec<PmiViewRaw> }`.
+2. `PmiRaw` holds: `kind` (0 dimension, 1 tolerance, 2 datum, 3 note), `type_name`, `name`, the number fields, the string-list fields, `lines: Vec<PmiPolyline>`, `mesh: PmiMesh`, plane and text point (with `has_*` flags), `faces: Vec<u32>`, `edges: Vec<u32>`, `datum_refs: Vec<String>`, `datum_ref_modifiers: Vec<String>`.
+3. `PmiViewRaw` holds `name`, `direction[3]`, `up[3]`, `projection` (0 none, 1 parallel, 2 central), `items: Vec<u32>`.
+4. Declare `fn read_pmi(path: &str, angular_deflection: f64) -> PmiTree;` and `fn write_test_pmi_step(path: &str) -> bool;`.
+5. In `read_pmi`, open the file as `.xbf` when it starts with `BINFILE`, else as STEP with the same reader setup as `read_step_to_doc`.
+6. If `DimTolTool` has no dimension, tolerance or datum labels and `ViewTool` has no view labels, return `ok=true` with empty lists.
+7. Walk the free shapes and their components once. Record the first world `TopLoc_Location` of every product label.
+8. For each GD&T label, read the object once with `GetObject()`. Read the referenced shapes with `GetRefShapeLabel`.
+9. Find the owner part: `refL.Father()` when `IsSubShape(refL)`, else `refL`. Use the owner's first world location; identity when unknown.
+10. Discretize presentation edges with `BRepAdaptor_Curve` and `GCPnts_TangentialDeflection`. Read presentation faces with `BRep_Tool::Triangulation`.
+11. Mesh each referenced face once with `BRepMesh_IncrementalMesh`, then read its triangulation. Store it once in `faces` and index it.
+12. Discretize each referenced edge into `edges`, once per edge.
+13. Transform every point, normal and direction by the owner location.
+14. Map every OCCT enum to a stable lower camel case string in a `switch` (for example `Location_LinearDistance` → `linearDistance`).
+15. Store the dimension's lower tolerance as a negative number.
+16. For tolerances, read datum references with `GetDatumWithObjectOfTolerLabels`, in datum `GetPosition` order.
+17. For views, read `XCAFView_Object` `ViewDirection`, `UpDirection` and `Type`, and map `GetRefGDTLabel` to item indices.
+18. Wrap the walk in `try { } catch (Standard_Failure&) { }`. On a throw, return `ok=false` with the message.
+19. In `write_test_pmi_step`, build a 100×50×20 mm box in a new XCAF document.
+20. Add one linear distance dimension (two opposite faces, 100 mm, +0.1 / −0.05), with a presentation of two edges.
+21. Add one flatness tolerance (value 0.05) on the top face, referencing datum A.
+22. Add datum A on the bottom face.
+23. Write the document with `STEPCAFControl_Writer` and `write.step.schema` 5 (AP242).
+
+**Verify:**
+```bash
+docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry carbon-rust-dev cargo build -p occt-bridge --release
+# Expected: "Finished `release` profile"
+```
+
+If the OCCT writer does not write the semantic GD&T, STOP and report — do not improvise.
+
+**Out of scope:** `read_step`, `read_xbf`, `tessellate`, `Builder` — their output must not change.
+
+## Task 2: Build `pmi.json` in `converter`, with tests
+
+**Depends on:** Task 1
+**Files:**
+- Create: `crates/converter/src/pmi.rs`
+- Modify: `crates/converter/src/lib.rs` — `pub mod pmi;`
+- Create: `crates/converter/tests/pmi.rs`
+- Copy from (precedent): `crates/converter/src/graph.rs` (serde emit), `crates/converter/tests/multibody_split.rs` (hermetic fixture test)
+
+**Steps:**
+1. Define the serde types of `pmi.json` version 1 in `pmi.rs`, exactly as the spec's `PmiDocument`. Use `#[serde(rename_all = "camelCase")]`.
+2. Add `pub fn extract_pmi(path: &str, source_unit: Option<&str>) -> Result<Option<PmiDocument>, String>`.
+3. Return `Ok(None)` when the tree has no items and no views.
+4. Give ids in document order per kind: `d1…`, `t1…`, `a1…`, `n1…`.
+5. Merge datums with the same name. Keep the first copy with lines or a mesh. Point every view at the kept id.
+6. Round every coordinate to 4 decimals (0.1 µm).
+7. Add `pub fn to_json(doc: &PmiDocument) -> Result<Vec<u8>, String>` with the 16 MB cap.
+8. If the JSON is over the cap, empty `faces` and retry once. If it is still over, return an error.
+9. In `tests/pmi.rs`, write the fixture with `write_test_pmi_step`. Assert 1 dimension, 1 tolerance and 1 datum.
+10. Assert the dimension's values (100, 0.1, −0.05) and that it references 2 faces with triangles.
+11. Assert that the tolerance lists datum `A`.
+12. Write the fixture to `.xbf` with `step_to_xbf`. Assert that `extract_pmi` on the `.xbf` gives the same JSON.
+13. Add `nist_fixtures` tests that skip unless `PMI_FIXTURES` is set.
+14. For CTC 01: assert at least 20 items, each with lines or a mesh.
+15. For STC 06: assert 12 views.
+16. For CTC 01: assert that the PMI bounding box overlaps the bounding box of `convert_step_head(...).graph`'s root.
+
+**Verify:**
+```bash
+docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry -v "$PWD/.context/pmi-fixtures":/fixtures -e PMI_FIXTURES=/fixtures carbon-rust-dev cargo test -p converter --release
+# Expected: every test result "ok", including the pmi tests
+```
+
+If the NIST counts differ from the spec, update the spec's acceptance criteria with the real counts. Explain why in the run record.
+
+**Out of scope:** `graph.rs`, `glb.rs`, `nodeid.rs`.
+
+## Task 3: Write the `pmi` output from the `optimize` action
+
+**Depends on:** Task 2
+**Files:**
+- Modify: `apps/assembler/src/actions/optimize.rs` — `PmiOut`, `run_ingest`, `spawn`
+- Modify: `apps/assembler/src/request.rs` — parse `pmi: { path }` in `optimize_ingest`
+- Modify: `apps/assembler/AGENTS.md` — document the `pmi` output
+- Copy from (precedent): `ThumbnailOut` and the `thumbnail` output in `optimize.rs`
+
+**Steps:**
+1. Add `pub pmi: Option<Option<String>>` to `OptimizeReq` (outer `Some` = asked for, inner = path).
+2. In `run_ingest`, after a successful optimize, call `converter::pmi::extract_pmi` on `ingest.load_path`.
+3. Pass the source unit from `converter::graph::detect_source_unit_bytes` when the source is STEP.
+4. If the call fails, push `pmi: <message>` into `outcome.warnings`. Never fail the job.
+5. If a document exists, add output `pmi` (`application/json`) and `result.outputs.pmi = { path, bytes, items, views }`.
+
+**Verify:**
+```bash
+docker run --rm -v "$PWD":/repo -v carbon-target:/target -v carbon-cargo:/usr/local/cargo/registry carbon-rust-dev cargo test -p assembler --release
+# Expected: every test result "ok"
+```
+
+**Out of scope:** the `convert`, `plan`, `compact` and `thumbnail` actions.
+
+## Task 4: Add `modelUpload.pmiPath`
+
+**Depends on:** none
+**Files:**
+- Create: `packages/database/supabase/migrations/<timestamp>_model-pmi-artifact.sql` (via `pnpm db:migrate:new model-pmi-artifact`)
+- Modify (generated): `packages/database/src/types.ts`, `packages/database/src/swagger-docs-schema.ts`
+- Copy from (precedent): `packages/database/supabase/migrations/20260714120000_model-optimize-artifact.sql`
+
+**Steps:**
+1. Run `pnpm db:migrate:new model-pmi-artifact`.
+2. Write the SQL: a comment and `ALTER TABLE "modelUpload" ADD COLUMN IF NOT EXISTS "pmiPath" TEXT;`.
+3. Run `pnpm db:migrate`.
+4. Run `pnpm run generate:types`.
+
+**Verify:**
+```bash
+grep -c '"pmiPath"' packages/database/src/types.ts
+# Expected: 3 or more (Row, Insert, Update)
+```
+
+If the local database is down, add the column to `types.ts` by hand in Row, Insert and Update, in the same place as `optimizedModelPath`. Record that in the run record.
+
+**Out of scope:** RLS (the table keeps its policies).
+
+## Task 5: Request, persist and back up `pmiPath` in `@carbon/jobs`
+
+**Depends on:** Task 4
+**Files:**
+- Modify: `packages/jobs/src/inngest/functions/tasks/model-optimize.ts`
+- Modify: `packages/jobs/src/inngest/functions/tasks/model-rows.ts` — `pmiPath` in the row type and the select
+- Modify: `packages/jobs/src/inngest/functions/tasks/company-backup.ts` — `STORAGE_PATH_COLUMNS`
+- Modify: `packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts` — `MODEL_UPLOAD_PATH_COLUMNS`
+- Copy from (precedent): the `thumbnail` path, mint and persist in `model-optimize.ts`
+
+**Steps:**
+1. Set `pmiPath = ${companyId}/models/${modelUploadId}/pmi-${run}.json` (unique per run, like the thumbnail).
+2. Send `pmi: { path: pmiPath }` in the body.
+3. Sign a `pmi` upload URL in the company bucket.
+4. Add `pmi?: { bytes?: number }` to `IngestOutputs`.
+5. In `persist`, set `pmiPath: outputs.pmi ? pmiPath : null`.
+6. If the row held a different `pmiPath`, remove that object (best effort, log a warning on failure).
+7. Add `"pmiPath"` to `STORAGE_PATH_COLUMNS` and to `MODEL_UPLOAD_PATH_COLUMNS`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/jobs && pnpm --filter @carbon/jobs test -- company-backup.closure
+# Expected: typecheck passes; the closure tests pass
+```
+
+**Out of scope:** `assembly-convert.ts`, `model-compact.ts`.
+
+## Task 6: Return `pmiPath` from the artifacts routes
+
+**Depends on:** Task 4
+**Files:**
+- Modify: `apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts`
+- Modify: `apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts`
+- Modify: `packages/viewer/src/useOptimizedModel.ts` — `pmiPath?: string | null` in `ModelArtifacts`
+
+**Steps:**
+1. Add `pmiPath` to the `select` in both routes.
+2. Return `pmiPath: model.data?.pmiPath ?? null`.
+3. Add the optional `pmiPath` field to `ModelArtifacts` with a doc comment.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --filter=mes
+# Expected: both pass
+```
+
+## Task 7: Add the `pmi.ts` contract and formatter to `@carbon/viewer`, with tests
+
+**Depends on:** none
+**Files:**
+- Create: `packages/viewer/src/pmi.ts`
+- Create: `packages/viewer/src/pmi.test.ts`
+- Copy from (precedent): `packages/viewer/src/graph.ts` and `graph.test.ts`
+
+**Steps:**
+1. Export the TypeScript types of the spec's `PmiDocument`. They must match `crates/converter/src/pmi.rs` field for field.
+2. Export `parsePmiDocument(json: unknown): PmiDocument | null`. It returns null for a wrong `version` or a wrong shape.
+3. Export `formatPmiItem(item, unit: "mm" | "in", sourceUnit): { label: string; symbol: string | null; title: string }`.
+4. Format dimensions: prefix (⌀, R, S⌀, SR), the nominal, then `±t`, `+u/−l`, limits `u/l`, or the fit class.
+5. Format angles in degrees with `°`, never converted.
+6. Format tolerances as a frame: the characteristic symbol, the zone (`⌀` for a diameter zone), Ⓜ/Ⓛ, then the datum letters.
+7. Use the file's decimals only when the display unit is the source unit. Else use 3 decimals for mm and 4 for in, trimming zeros.
+8. Export `groupPmiItems(doc)` (Dimensions, Tolerances, Datums, Notes) and `visibleItemIds(doc, viewId | null)`.
+9. Write tests: parse a good and a bad document, and each format rule above, in mm and in.
+
+**Verify:**
+```bash
+pnpm --filter @carbon/viewer test -- pmi
+# Expected: all pmi tests pass
+```
+
+## Task 8: Draw the PMI layer and the PMI panel
+
+**Depends on:** Task 7
+**Files:**
+- Create: `packages/viewer/src/PmiLayer.tsx`
+- Modify: `packages/viewer/src/ModelCanvas.tsx` — `pmi`, `pmiState` props; render `PmiLayer` in `ModelScene`; camera focus
+- Modify: `packages/viewer/src/ModelPreview.tsx` — `pmiUrl` prop, load, shared unit state, `PmiPanel`
+- Copy from (precedent): `ModelMetricsPanel`, `UnitToggle` and `Row` in `ModelPreview.tsx`; `frameBox` in `ModelCanvas.tsx`
+
+**Steps:**
+1. In `PmiLayer`, merge each item's `lines` into one `LineSegments` per item.
+2. Draw a mesh for each item's `mesh`.
+3. Color unselected items with the theme foreground. Color the selected item blue (`0x3b82f6`), with `depthTest: false` and a high `renderOrder`.
+4. Draw the selected item's faces as a blue transparent mesh with `polygonOffset`.
+5. Draw the selected item's edges as blue lines.
+6. For items with no lines and no mesh, draw a drei `Html` label at `textPosition`, else at the center of its faces. Cap the labels at 200.
+7. In `ModelCanvas`, add a `focus` request. For an item, look along the plane normal and fit the item's and its faces' box.
+8. For a view, use the view's `direction` and `up`, then fit the view's items' box.
+9. Reuse `frameBox` with a given direction and up vector.
+10. In `ModelPreview`, fetch `pmiUrl` once (`fetch` + `parsePmiDocument` in a `useEffect`).
+11. Lift the unit state out of `ModelMetricsPanel`. Start it at the PMI `sourceUnit` when it is `mm` or `in`, else `imperial`.
+12. Add `PmiPanel` under the Measurements panel. It holds the eye toggle, a view select (when views exist) and the grouped list.
+13. Make a click on an item select it, and a second click clear it.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=@carbon/viewer && pnpm --filter @carbon/viewer test
+# Expected: typecheck passes; all viewer tests pass
+```
+
+**Out of scope:** `AssemblyPlayer.tsx`, `RawModelCanvas`.
+
+## Task 9: Pass `pmiUrl` from the ERP and MES hosts
+
+**Depends on:** Tasks 6 and 8
+**Files:**
+- Modify: `apps/erp/app/components/CadModel.tsx`
+- Modify: `apps/mes/app/components/JobOperation/JobOperation.tsx`
+- Modify: `apps/mes/app/components/AssemblyView.tsx` — only where `ModelPreview` gets `optimizedUrl` from `artifacts`
+- Copy from (precedent): the `optimizedUrl` prop in `CadModel.tsx` (with the `?v=` cache-buster)
+
+**Steps:**
+1. Pass `pmiUrl={artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null}`. The path is unique per run, so it needs no cache-buster.
+2. Do the same in each MES host that reads `artifacts`.
+
+**Verify:**
+```bash
+pnpm exec turbo run typecheck --filter=erp --filter=mes && pnpm exec biome check packages/viewer apps/erp/app/components/CadModel.tsx apps/mes/app/components
+# Expected: both typechecks pass; Biome reports no errors
+```
+
+## Task 10: Verify end to end
+
+**Depends on:** Tasks 1–9
+**Steps:**
+1. Run all Rust tests (Task 2 command, plus `cargo test -p assembler`).
+2. Run `pnpm --filter @carbon/viewer test` and the scoped typechecks.
+3. If a local stack with the assembler runs, upload `nist_ctc_01_asme1_ap242-e1.stp` to a part.
+4. Open the PMI panel. Pick a position tolerance. Take a screenshot to `.context/`.
+5. If no stack with the assembler runs, record "browser test skipped" and the reason in the run record.
+
+**Verify:**
+```bash
+# Expected: every command above passes; the screenshot shows the PMI panel and a highlighted face
+```
diff --git a/.ai/research/step-pmi-viewer.md b/.ai/research/step-pmi-viewer.md
new file mode 100644
index 0000000000..33fb7792f8
--- /dev/null
+++ b/.ai/research/step-pmi-viewer.md
@@ -0,0 +1,172 @@
+# PMI in the STEP Viewer Research: Best Practices Survey
+
+## Summary
+
+This file surveys how CAD viewers show PMI (Product Manufacturing Information) from a model-based definition (MBD). It also records how OCCT reads AP242 PMI and which public test files exist. All surveyed viewers show the CAD author's graphical PMI in its annotation plane. Each one lists the PMI in a panel and has saved views that set the camera and the visible PMI. Siemens and the SOLIDWORKS outputs highlight the faces that a picked annotation references.
+
+Semantic PMI (the machine-readable values) is data. Quality tools use it to build a bill of characteristics. OCCT V8 already reads both kinds into the XCAF document that Carbon's converter loads today.
+
+## Competitors Surveyed
+
+- **SAP 3D Visual Enterprise Viewer** — the SAP reference for 3D product data in the enterprise.
+- **Siemens JT2Go / Teamcenter Visualization** — the most common free PMI viewer in aerospace and automotive.
+- **SOLIDWORKS MBD + eDrawings** — the MBD tool that most Carbon customers (job shops) use.
+- **CAD Exchanger** — a CAD data SDK and viewer with an explicit graphical/semantic PMI model.
+- **High QA, 1factory** — quality tools that turn PMI or drawings into inspection characteristics.
+- **NIST STEP File Analyzer and Viewer (SFA)** — the reference tool for AP242 PMI conformance.
+
+## Key Consensus Patterns
+
+### 1. Two kinds of PMI: graphical and semantic
+
+- **CAD Exchanger**: each PMI element has a graphical representation (outlines, text, filled triangles) and a semantic representation (dimension, geometric tolerance, datum, surface finish components).
+- **SAP**: each PMI node carries "semantic information": type, main value, tolerance high, tolerance low, unit.
+- **NIST SFA**: the viewer draws only the graphical PMI. The analyzer writes the semantic PMI to a spreadsheet.
+- **Rationale**: the author's drawing is what a designer expects to see. Software can only read the semantic values.
+
+### 2. The annotation sits in its plane
+
+- **SAP**: PMI sits in its plane by default. "Billboard Mode" can turn it to face the camera.
+- **Siemens**: PMI sits in its plane by default. "Parallel to Screen" is an option per display instance.
+- **SOLIDWORKS**: annotations sit on their annotation view planes. Only the "Notes Area" faces the screen.
+- **Rationale**: the plane is part of the author's intent. A rotated plane tells the reader which face a dimension measures.
+
+### 3. A PMI list with show/hide
+
+- **SAP**: one "Show/Hide all PMI" toggle, plus "PMI Points on Top".
+- **Siemens**: a PMI tree holds PMI and model views. A filter shows PMI by type.
+- **CAD Exchanger**: a PMI panel turns all entities on, or one at a time.
+- **Rationale**: a model can hold hundreds of annotations. The reader needs to reduce the clutter.
+
+### 4. Saved views set the camera and the visible PMI
+
+- **SAP**: "Model Views" in "Portfolios". A click activates a view; Home then resets to it.
+- **Siemens**: "Model Views" in the PMI tree.
+- **SOLIDWORKS**: "3D Views" save the orientation, the zoom and the annotations. eDrawings, 3D PDF and STEP 242 export keep them.
+- **NIST SFA**: saved views become viewpoints. Each one switches its PMI on and the rest off.
+- **Rationale**: the author groups annotations by the view that reads them best.
+
+### 5. A picked annotation highlights its faces
+
+- **Siemens**: the preference "Highlight attached surfaces and PMI" controls it (seen in a search summary only).
+- **SOLIDWORKS**: eDrawings highlights the geometry an annotation is attached to (seen in a search summary only).
+- **SAP**: no source found for face highlight. Selection turns an object red.
+- **Rationale**: the highlight answers "which feature does this tolerance control?".
+
+## Answers to Research Questions
+
+1. Which PMI kinds do viewers show, and what are they called? — Dimensions, geometric tolerances (feature control frames), datums, datum targets, notes and surface finish. "PMI", "semantic PMI", "graphical PMI" and "model view" are the common terms (SAP, Siemens, CAD Exchanger). SOLIDWORKS says "3D View" for a saved view.
+2. Which interactions are standard? — A PMI list, a show/hide toggle, saved views, and a face highlight on pick (Siemens, SOLIDWORKS). Filter by type exists in Siemens and SOLIDWORKS only.
+3. Graphical or re-rendered from semantic? — Viewers draw the graphical PMI (CAD Exchanger, NIST SFA). When only semantic PMI exists, CAD Exchanger Cloud showed nothing. Carbon must draw its own label in that case.
+4. Which edge cases matter? — Inch files (NIST CTC 05 is inch). Duplicate datums (OCCT adds a datum once per tolerance that uses it). Graphic-only PMI with no semantic data. Saved views whose camera position is not reliable (see the OCCT section).
+5. What does a quality tool extract per characteristic? — Type, nominal, upper and lower tolerance or limits, the GD&T symbol, the zone value, modifiers and datum references (High QA, 1factory). This is the data a later inspection link needs.
+
+## Competitor-Specific Details
+
+### SAP 3D Visual Enterprise Viewer
+
+The Information panel has "Show/Hide all PMI". The "Load Model Views" import setting (All, Top Level, Assembly, Parts, None) ties a model view to a node of the product structure. "Always on Top" draws PMI through all geometry.
+
+### Siemens JT2Go
+
+The user picks a part in a "toggle single" or "toggle multiple" mode to show its PMI. Menu → PMI → Filter Configuration switches between "Display all PMI entities" and "Filter PMI entities by type".
+
+### SOLIDWORKS MBD / eDrawings
+
+"MBD Dimensions" (formerly DimXpert) are the PMI. "Annotation views" are the planes. "3D Views" are saved views. "Dynamic Annotation Views" shows only the planes that face the current camera.
+
+### CAD Exchanger
+
+`PMI::Element` has `GraphicalRepresentation` (`OutlinedComponent`, `TextComponent`, `TriangulatedComponent`) and `SemanticRepresentation` (`DimensionComponent`, `GeometricToleranceComponent`, `DatumComponent`, `SurfaceFinishComponent`). The viewer marks the parts that have PMI in the product tree.
+
+### High QA
+
+Inspection Manager reads PMI from native and neutral models (STEP included) with HOOPS Exchange. One click makes a ballooned drawing and a bill of characteristics.
+
+### OCCT V8 (Carbon's CAD kernel)
+
+The facts below come from the OCCT V8_0_0_p1 source (`.context/occt-src`).
+
+| Fact | Where |
+|---|---|
+| `STEPCAFControl_Reader` reads GD&T and saved views by default (`myGDTMode`, `myViewMode` are true) | `STEPCAFControl_Reader.cxx:286-288` |
+| `XCAFDoc_DimTolTool` lists dimensions, geometric tolerances and datums | `XCAFDoc_DimTolTool.hxx:63,89,171` |
+| `GetRefShapeLabel` returns the referenced shapes of any GD&T label | `XCAFDoc_DimTolTool.hxx:153` |
+| A referenced face is a sub-shape label directly under its part's label | `XCAFDoc_ShapeTool.cxx:1139,1209` |
+| The presentation is a compound of edges (polyline PMI) and of faces with only a `Poly_Triangulation` (filled text in tessellated PMI) | reader `:2532-2711` |
+| The presentation is in the owning part's local frame, in mm | reader `:2808-2814` |
+| Angles are in degrees | reader `:4476` |
+| The lower tolerance is stored as a positive number | reader `:4765` |
+| A datum is added once per tolerance that references it | reader `:3329-3655` |
+| A saved view stores a reliable view direction and up direction; its projection point is relative to the camera's own frame | reader `:5900-6070` |
+| BinXCAF (`.xbf`) keeps all GD&T attributes and the surface-less faces | `BinMDF_ADriverTable.cxx`, `BinTools_ShapeWriter.cxx:235` |
+| AP242 notes are not read | no `NotesTool` use in `TKDESTEP` |
+
+### NIST MBE PMI test files
+
+NIST publishes 18 AP242 files (CTC 01–05, FTC 06–11, STC 06–10). US federal law puts them in the public domain in the US. NIST asks for credit. Three files cover the main paths:
+
+| File | Graphical PMI | Unit | Saved views |
+|---|---|---|---|
+| `nist_ctc_01_asme1_ap242-e1.stp` (396 KB) | tessellated | mm | 1 |
+| `nist_ctc_05_asme1_ap242-e1.stp` (878 KB) | polyline | inch | 2 |
+| `nist_stc_06_asme1_ap242-e3.stp` (1 MB) | tessellated, placeholders | mm geometry, inch values | 12 |
+
+### GD&T symbols in Unicode
+
+| Characteristic | Symbol | Code point |
+|---|---|---|
+| Straightness | ⏤ | U+23E4 |
+| Flatness | ⏥ | U+23E5 |
+| Circularity | ○ | U+25CB |
+| Cylindricity | ⌭ | U+232D |
+| Profile of a line | ⌒ | U+2312 |
+| Profile of a surface | ⌓ | U+2313 |
+| Angularity | ∠ | U+2220 |
+| Perpendicularity | ⟂ | U+27C2 |
+| Parallelism | ∥ | U+2225 |
+| Position | ⌖ | U+2316 |
+| Concentricity | ◎ | U+25CE |
+| Symmetry | ⌯ | U+232F |
+| Circular runout | ↗ | U+2197 (no dedicated code point) |
+| Total runout | ⌰ | U+2330 |
+| Diameter | ⌀ | U+2300 |
+| MMC, LMC, projected zone, free state | Ⓜ Ⓛ Ⓟ Ⓕ | U+24C2, U+24C1, U+24C5, U+24BB |
+
+## Recommended Approach for Carbon
+
+1. Read both kinds of PMI with OCCT during the optimize ingest. The XCAF document is already loaded there. This follows the CAD Exchanger two-representation model.
+2. Draw the graphical PMI in its own plane, with the lines on top of the model. This follows SAP, Siemens and SOLIDWORKS defaults, plus SAP's "Always on Top".
+3. Draw a text label from the semantic values only when an item has no graphical PMI. CAD Exchanger showed nothing in that case, which hides real data.
+4. List the PMI in a panel with one show/hide toggle (SAP), grouped by kind.
+5. Show saved views. Use the view direction and the up direction, and fit the camera to the view's PMI. Do not trust the projection point.
+6. Highlight the referenced faces when the user picks a PMI item (Siemens, SOLIDWORKS).
+7. Keep the semantic values in the artifact, so a later change can make inspection characteristics from them (High QA pattern).
+8. Use the three NIST files as manual fixtures and an OCCT-written AP242 file as the committed hermetic test.
+
+## Sources
+
+- https://help.sap.com/doc/a54961fccc8d4c399e0620a442eb0b98/9.0.0.9/en-US/Viewer_help_EN.pdf
+- https://help.sap.com/docs/SAP_3D_VISUAL_ENTERPRISE_AUTHOR/67c291fba1bd10148bea8dce7b0caa3e/b32d64427d294d88952b5fa066d2f5c1.html?version=9.0.0.13
+- https://help.sap.com/docs/SAP_3D_VISUAL_ENTERPRISE_AUTHOR/8e4c65bb3a6c4ef6b56dc27d1d95cde6/4c831292013d4ac0a70c39f770f189bd.html?version=9.0.0.17
+- https://community.sw.siemens.com/s/question/0D54O000061xqScSAI/pmi-filter-configuration
+- https://community.sw.siemens.com/s/question/0D5Vb00000No6bHKAR/nx-pmi-chamfer-function-shows-wrong-chamfer-surface-in-jt2go
+- https://community.sw.siemens.com/s/question/0D54O000061xk0GSAQ/pmi-parallel-to-screen-display
+- https://help.solidworks.com/2021/English/eDrawings/c_annotations.htm
+- https://help.solidworks.com/2025/English/SolidWorks/sldworks/c_annotation_view_flat_to_screen.htm
+- https://hawkridgesys.com/blog/mbd-dimxpert-and-mbd-dimensions-whats-the-difference
+- https://www.engineersrule.com/getting-closer-losing-drawing/
+- https://www.engineersrule.com/building-photo-storyline-mbd-data-3d-views/
+- https://www.cati.com/blog/capturing-3d-views-solidworks-mbd/
+- https://cadexchanger.com/blog/pmi-in-cad-exchanger-cloud/
+- https://docs.cadexsoft.com/mtk/mtk_data_model_pmi
+- https://cadexchanger.com/blog/new-formats-semantic-pmi-import-in-cad-exchanger-3-7-0/
+- https://www.techsoft3d.com/resources/case-studies/high-qa/
+- https://www.highqa.com/3d-mbd-integration/
+- https://www.1factory.com/drawing-auto-ballooning-first-article.html
+- https://www.nist.gov/ctl/smart-connected-systems-division/smart-connected-manufacturing-systems-group/mbe-pmi-0
+- https://www.nist.gov/open/license
+- https://www.nist.gov/services-resources/software/step-file-analyzer-and-viewer
+- https://github.com/usnistgov/SFA
+- https://www.unicode.org/Public/UCD/latest/ucd/NamesList.txt
+- OCCT V8_0_0_p1 source: https://github.com/Open-Cascade-SAS/OCCT/tree/V8_0_0_p1
diff --git a/.ai/runs/2026-10-26-step-pmi-viewer.md b/.ai/runs/2026-10-26-step-pmi-viewer.md
new file mode 100644
index 0000000000..76168051ec
--- /dev/null
+++ b/.ai/runs/2026-10-26-step-pmi-viewer.md
@@ -0,0 +1,28 @@
+# Feature run: PMI (model-based definition) in the STEP viewer
+
+- Date: 2026-10-26
+- Mode: fully-autonomous
+- Request: "we need to support tolerances in our step file viewer. model based definitions spec i believe it's called" — then "fully autonomous".
+- Phase plan: research [run — new technical domain: AP242 PMI, OCCT XCAF API, how CAD viewers show PMI] · spec [run — crosses the Rust converter, the Inngest jobs, the shared graph contract and the viewer] · plan [run] · execute [run] · test [run only if a local stack can run the assembler; else skip with reason] · self-review [run]
+
+## Decisions
+- Spec gate (open questions): resolved autonomously — assembly player out of v1; no backfill (Reoptimize adds PMI); new nullable `modelUpload.pmiPath`; first instance of a part in an assembly; no face-click picking in v1. Ask-First checks: the column is on an artifact table, not a production-critical one; `pmi.json` is an additive, versioned internal contract — 2026-10-26.
+- Plan gate: approved autonomously — the plan follows the spec's thumbnail sibling and keeps the converter output byte-identical — 2026-10-26.
+- Scope: view-only. The viewer shows PMI. Inspection features from PMI are a later change — the recommendation given to the user, who did not object — 2026-10-26.
+- PMI kinds: semantic values AND graphical presentation — the semantic values make a later inspection link possible; the presentation is what designers expect to see — 2026-10-26.
+- Build environment: no Rust toolchain or OCCT on the host. Build the `carbon-occt:8.0.0-p1` base image in Docker and compile and test the crates inside a container — 2026-10-26.
+
+## Phase log
+- research: `.ai/research/step-pmi-viewer.md`. The first product-survey agent stalled; the user asked to retry; two smaller agents finished it. STE-80 pass done.
+- spec: `.ai/specs/2026-10-26-step-pmi-viewer.md`. All open questions resolved autonomously and marked so. STE-80 pass done.
+- plan: `.ai/plans/2026-10-26-step-pmi-viewer.md`, 10 tasks. STE-80 pass done.
+- execute: Tasks 1–10 done. Rust (occt-bridge, converter, assembler) built and tested in the `carbon-rust-dev` container: 63 assembler tests and every converter test pass, 8 of them for PMI (NIST fixtures through `PMI_FIXTURES`). Viewer: 231 tests pass; typecheck of `@carbon/viewer`, `@carbon/jobs`, `erp` and `mes` passes; Biome clean on changed files. Types generated from a throwaway database (see the plan's Deviations). The viewer subagent built Tasks 7–8; its prose went into no artifact.
+- test: browser check on a throwaway Vite page mounting the real `ModelPreview` with NIST CTC 01 and CTC 05 ingest outputs. PMI lines up with the model; a picked tolerance turns blue, highlights its faces and turns the camera; a saved view filters and turns the camera. The full `/test` skill was skipped: `crbn` could not start this worktree's stack (shared Redis pool full, 16 of 16), and freeing a slot would stop another session's stack.
+- self-review: a review subagent found 2 must-fix items (wire edges joined into one polyline; Latin-1 names throwing in `rust::String`) and 4 risks or suggestions taken (per-run `pmi.json` path, non-finite numbers, empty documents, datum view remap). All fixed and retested. `CODE_VERSION` bump reverted: only `plan` reads that cache.
+- STE-80 pass done on the spec, the plan and this record after the last edits.
+- setup: OCCT V8_0_0_p1 source cloned to `.context/occt-src` for API reference. `STEPCAFControl_Reader` defaults `myGDTMode` and `myViewMode` to true (`STEPCAFControl_Reader.cxx:286-288`), so today's convert already loads the PMI into the XCAF document.
+
+- self-review (second, /self-review): 1 must-fix (picked annotation lying flat read rotated: focus now uses the plane's own up) and docs drift (jobs AGENTS, backup rule, viewer AGENTS, swagger). Fixed; a PMI-panel unit toggle added. Checked in the running ERP on NIST CTC 05: picked frames read upright. The local stack now runs the assembler in Docker (`carbon-assembler-pmi`, forced in `.env`), since this Mac has no native OCCT.
+
+## Outcome
+- PR: https://github.com/crbnos/carbon/pull/2048 (commit 701ca4df88). Not merged.
diff --git a/.ai/specs/2026-10-26-step-pmi-viewer.md b/.ai/specs/2026-10-26-step-pmi-viewer.md
new file mode 100644
index 0000000000..c148d05f7c
--- /dev/null
+++ b/.ai/specs/2026-10-26-step-pmi-viewer.md
@@ -0,0 +1,242 @@
+# PMI (model-based definition) in the STEP viewer
+
+> Status: implemented (pending review)
+> Author: Claude (autonomous `/feature` run for Brad)
+> Date: 2026-10-26
+
+## TLDR
+
+A STEP AP242 file can carry PMI (Product Manufacturing Information): dimensions, geometric tolerances, datums and saved views. This is the model-based definition (MBD) of the part. Carbon's viewer shows none of it today.
+
+This spec adds a `pmi.json` artifact that the assembler writes during the model ingest. It also adds a PMI layer and a PMI panel to `ModelPreview`. The user sees the author's annotations on the model, reads each tolerance in a list, opens the saved views, and picks an item to highlight the faces it controls. The change is view-only. Inspection characteristics from PMI are a later change.
+
+Research: `.ai/research/step-pmi-viewer.md`.
+
+## Overview diagram
+
+```mermaid
+sequenceDiagram
+ participant U as User
+ participant J as model-optimize job
+ participant A as Assembler optimize
+ participant S as Storage
+ participant V as ModelPreview
+ U->>J: upload or Reoptimize
+ J->>A: optimize with a pmi path
+ A->>A: read_pmi on the XCAF doc
+ A->>S: PUT optimized.glb and pmi.json
+ J->>J: persist pmiPath
+ V->>S: GET pmi.json
+ V->>U: PMI layer and PMI panel
+```
+
+## Problem Statement
+
+Customers send STEP AP242 files that hold the tolerances of the part. A machinist or an inspector opens the part in Carbon and sees only the shape. To read a tolerance, the user must open the CAD tool or a separate PDF drawing. Two examples:
+
+1. NIST test part CTC 01 holds 12 dimensions, 6 geometric tolerances and 3 datums. Carbon shows none of them.
+2. NIST test part CTC 05 has 2 saved views, each with its own camera and its own set of annotations. Carbon shows one default camera.
+
+OCCT already reads this data into the XCAF document that the converter opens (`STEPCAFControl_Reader` reads GD&T and views by default). The converter keeps only names, colors and the assembly tree, and drops the PMI.
+
+## Proposed Solution
+
+1. The assembler reads the PMI from the XCAF document in a new pass, `read_pmi` (`crates/occt-bridge`). The pass does not change the tessellation, the GLB or any `nodeId`.
+2. `crates/converter` turns the result into a `pmi.json` document (version 1). All geometry is in world mm, in the same frame as the GLB.
+3. The `optimize` action writes `pmi.json` as a fourth ingest output when the caller asks for it and the model has PMI.
+4. The `model-optimize` job asks for it, uploads it to `{companyId}/models/{modelUploadId}/pmi-{run}.json` and sets `modelUpload.pmiPath`. It removes the file of the run before.
+5. The artifacts routes (ERP and MES) return `pmiPath`. The hosts pass `pmiUrl` to `ModelPreview`.
+6. `ModelPreview` loads the document. It draws the PMI layer and shows a PMI panel.
+
+### What the artifact holds
+
+| Part | Content |
+|---|---|
+| `items[]` | One entry per dimension, geometric tolerance, datum and graphic-only annotation |
+| `item` semantic values | Kind, type, nominal, upper and lower tolerance, limits, fit class, decimals, zone value and modifiers, datum references |
+| `item.lines` | The graphical PMI as polylines (leader lines, frames, stroked text) |
+| `item.mesh` | Filled graphical PMI (tessellated text) as triangles |
+| `item.plane`, `item.textPosition` | The annotation plane and the text anchor |
+| `item.faces`, `item.edges` | Indices into the document's referenced faces and edges |
+| `faces[]`, `edges[]` | Triangles of each referenced face and polylines of each referenced edge |
+| `views[]` | Saved views: name, view direction, up direction, projection, the ids of the items the view shows |
+
+### Viewer behavior
+
+| Action | Result |
+|---|---|
+| The model has PMI | A "PMI" panel shows under the Measurements panel, with the item count |
+| Toggle the eye button | The PMI layer shows or hides |
+| Open the panel | The user sees the items grouped as Dimensions, Tolerances, Datums and Notes, each with its formatted label |
+| Pick an item | The item turns blue and draws on top of the model. Its faces and edges get a blue highlight. The camera turns to face the annotation plane and fits the item |
+| Pick the item again | The selection clears |
+| Pick a saved view | The camera takes the view's direction and up direction and fits the view's items. Only those items show |
+| Pick "All PMI" | All items show again |
+| Change the unit (mm / in) | Measurements and PMI labels change together |
+
+If an item has no graphical PMI, the viewer draws a text label at the item's text anchor. If the item has no text anchor, the viewer draws the label at the center of its referenced faces.
+
+### Design Decisions
+
+| Decision | Choice | Rationale |
+|---|---|---|
+| Graphical or semantic PMI | Both | The drawing is what designers expect (SAP, Siemens, NIST SFA). The semantic values make a later inspection link possible (High QA pattern) |
+| Where PMI is read | A new pass `read_pmi` that opens the document again, in the optimize ingest | The converter, its tessellation and every `nodeId` stay unchanged. The ingest already has the `.xbf`, which parses fast |
+| Which action writes it | `optimize` (ingest) only, opt-in through a `pmi` body key | `ModelPreview` shows the optimized GLB. `convert` (assembly player) is out of scope for v1. Opt-in keeps other callers unchanged |
+| Face highlight | Ship each referenced face's own triangles in `pmi.json` | The optimized GLB merges and can simplify meshes, so per-face ranges in the GLB would not survive. Only referenced faces ship, so the size stays small |
+| Coordinate frame | World mm. Part-level PMI uses the first instance of its part | OCCT stores presentation in the part frame. One instance keeps the list free of copies. MBD files are mostly single parts |
+| Duplicate datums | Merge datums with the same name. Keep the first copy that has graphical PMI | OCCT adds a datum once per tolerance that uses it |
+| Saved view camera | Use view direction and up direction. Fit the view's items | OCCT stores the projection point relative to the camera frame, so it is not a world point |
+| Annotation placement | In its plane, as the author drew it | SAP, Siemens and SOLIDWORKS defaults |
+| Depth | Depth-tested by default. The selected item draws on top | Hundreds of always-on-top annotations hide the model. SAP offers "Always on Top" as an option, not a default |
+| Label formatting | In TypeScript (`pmi.ts`), from the semantic values | The unit toggle changes the label, and vitest can test the formatter |
+| Display unit | One mm / in toggle for Measurements and PMI. It starts at the PMI's source unit when known. Otherwise it keeps today's default (in) | An inch file reads naturally in inches. The decimals in the file only apply in its own unit. Models with no PMI keep today's behavior |
+| Storage column | New nullable `modelUpload.pmiPath` | Same shape as `glbPath`, `graphPath`, `optimizedModelPath` |
+| Existing models | No backfill. "Reoptimize from source file" writes `pmi.json` | The action already exists on the GLB badge. A forced backfill would re-optimize every model |
+| Failure | A PMI failure never fails the optimize. It adds a warning and writes no `pmi.json` | The preview matters more than the PMI |
+| Size cap | 16 MB of JSON. Over the cap, drop face triangles first. Still over: no `pmi.json`, plus a warning | A bad file must not make a huge artifact |
+| Heuristic 1–3 (tenancy, service shape, RLS) | No new table. One column on `modelUpload`, which keeps its RLS | — |
+| Heuristic 4 (permissions) | The artifacts routes keep `role: "employee"`. The preview proxy keeps its company path check | No change to RBAC |
+| Heuristic 5 (forms) | N/A | No form |
+| Heuristic 6 (module layout) | No ERP module change. Viewer code goes in `packages/viewer/src` | — |
+| Heuristic 7 (compatibility) | Additive only. `graph.json` and `types.ts` stay as they are. `pmi.json` is a new versioned contract in `packages/viewer/src/pmi.ts` and `crates/converter/src/pmi.rs`. `CODE_VERSION` stays at 4 | Only `plan` reads the result-pointer cache, and `convert` the file cache. `optimize` reads neither, so a bump would only throw away convert and plan results |
+
+## Data Model Changes
+
+```sql
+ALTER TABLE "modelUpload" ADD COLUMN "pmiPath" TEXT;
+```
+
+`modelUpload` keeps its RLS policies. `STORAGE_PATH_COLUMNS` (`company-backup.ts`) adds `pmiPath`, so a cross-company restore rewrites it with the other model paths. The closure test (`company-backup.closure.test.ts`) adds it to `MODEL_UPLOAD_PATH_COLUMNS`.
+
+### `pmi.json` version 1
+
+```ts
+type PmiDocument = {
+ version: 1;
+ unit: "mm";
+ sourceUnit: "mm" | "in" | null;
+ items: PmiItem[];
+ faces: { positions: number[]; indices: number[] }[];
+ edges: number[][]; // each a flat polyline x,y,z,…
+ views: PmiView[];
+};
+
+type PmiItem = {
+ id: string; // "d1", "t1", "a1", "n1" in document order
+ kind: "dimension" | "tolerance" | "datum" | "note";
+ name: string | null;
+ dimension: PmiDimension | null;
+ tolerance: PmiTolerance | null;
+ datum: PmiDatum | null;
+ lines: number[][];
+ mesh: { positions: number[]; indices: number[] } | null;
+ plane: { origin: Vec3; normal: Vec3; xDirection: Vec3 } | null;
+ textPosition: Vec3 | null;
+ faces: number[];
+ edges: number[];
+};
+
+type PmiView = {
+ id: string;
+ name: string;
+ direction: Vec3; // from the camera towards the model
+ up: Vec3;
+ projection: "parallel" | "central" | null;
+ itemIds: string[];
+};
+```
+
+`PmiDimension`, `PmiTolerance` and `PmiDatum` carry the OCCT values as lower camel case strings and numbers. Lengths are mm. Angles are degrees. The lower tolerance is negative (OCCT stores its magnitude).
+
+## API / Service Changes
+
+| Layer | Change |
+|---|---|
+| `crates/occt-bridge` | `read_pmi(path) -> Pmi` (STEP or `.xbf`). `write_test_pmi_step(path)`, an AP242 fixture writer for the hermetic test |
+| `crates/converter` | `pmi.rs`: `extract_pmi(path) -> Option<PmiDocument>` and the serde types |
+| `apps/assembler` | `optimize` takes `pmi: { path }`. On success it adds output `pmi` (`application/json`) and `result.outputs.pmi` |
+| `packages/jobs` | `model-optimize` sends `pmi.path` (unique per run), signs a `pmi` upload URL, and persists `pmiPath` (or `null`). It removes the previous run's file |
+| `apps/erp`, `apps/mes` | `api+/model.artifacts.$modelUploadId.ts` returns `pmiPath` |
+| `packages/viewer` | `pmi.ts` (contract, parsing, formatting), `PmiLayer.tsx`, `ModelCanvas` and `ModelPreview` props, `ModelArtifacts.pmiPath` |
+
+## Closest Sibling
+
+The sibling is the optimize thumbnail: a second ingest output of the same job, uploaded through a signed URL, stored as a `modelUpload` path column, and returned by the artifacts route. This feature copies:
+
+| Thumbnail | PMI |
+|---|---|
+| `ThumbnailOut` in `OptimizeReq` (`optimize.rs`) | `PmiOut` |
+| `outputs.thumbnail` in `result` | `outputs.pmi` |
+| `thumbnailPath` in `model-optimize.ts` mint and persist | `pmiPath` |
+| superseded thumbnail removal | superseded `pmi-{run}.json` removal |
+| `thumbnailPath` in the artifacts route | `pmiPath` |
+
+The viewer UI copies `ModelMetricsPanel` in `ModelPreview.tsx`: same card, same collapse button, same unit toggle. Deviation: the PMI panel holds a scrolling list. That is a Design Decision above.
+
+## UI Changes
+
+Archetype: none. The change is a panel inside the existing model viewer card (`ModelPreview`). It copies the Measurements panel. The pages that show `ModelPreview` get the panel with no page change: part, tool, quote line, job, sales and purchase order lines, RFQs and change notices in the ERP, and the job operation model tab and assembly view in the MES.
+
+## Acceptance Criteria
+
+- [x] `cargo test -p converter --test pmi` passes. The fixture writer makes an AP242 file with 1 dimension, 1 geometric tolerance and 1 datum, and `extract_pmi` returns all 3 with their referenced faces.
+- [x] Reading the same fixture through `step_to_xbf` then `.xbf` gives the same `pmi.json`.
+- [x] With `PMI_FIXTURES` set, `extract_pmi` on NIST CTC 01 returns at least 20 items, and each item has lines or a mesh.
+- [x] NIST CTC 01 returns 1 saved view and CTC 05 returns 2. Each view looks down (negative Z) with +Z up, and names only existing items.
+- [x] NIST CTC 01 merges its 9 datum copies to 3 datums: A, B and C.
+- [x] On NIST CTC 01, the referenced faces lie inside the model's bounding box, and the annotations' box overlaps it.
+- [x] Converter tests that existed before this change give the same `graph.json` and GLB bytes.
+- [x] `pnpm --filter @carbon/viewer test` passes, with new tests for parsing and label formatting (dimension with ±, limits, fit class, diameter; tolerance frame with zone and datums; mm and inch).
+- [x] `pnpm exec turbo run typecheck --filter=@carbon/viewer --filter=erp --filter=mes --filter=@carbon/jobs` passes.
+- [x] A user opens a NIST CTC 01 model, sees the PMI panel with the item count, and picks a position tolerance. The tolerance turns blue and its faces highlight.
+- [x] A model with no PMI shows no PMI panel, and its optimize writes no `pmi.json`.
+
+## Risks
+
+| Risk | Severity | Mitigation |
+|---|---|---|
+| The optimized GLB is not in the same frame as the XCAF world | High | Acceptance criterion on bounding box overlap with NIST CTC 01 |
+| `read_pmi` opens the document a second time, which adds time to large ingests | Med | It returns early when the document has no GD&T labels and no views. The `.xbf` parses fast |
+| OCCT reads a file's PMI wrongly (NIST files hold known errors) | Med | A PMI failure is a warning only. The panel shows what OCCT read |
+| The browser font has no glyph for a GD&T symbol | Low | The symbols are in Unicode blocks that system fonts cover. The label also has the type name as a tooltip |
+| A `.xbf` re-optimize does not know the source unit | Low | The unit toggle keeps its default (in) for those models. The user can switch |
+| Hundreds of HTML labels slow the viewer | Low | Labels draw only for items with no graphical PMI, capped at 200 |
+
+## Open Questions
+
+> HARD STOP: Do not proceed with implementation until these are answered.
+
+- [x] Show PMI in the assembly player too? — **Autonomous:** No, `ModelPreview` only in v1. Parts move in the player, and the player loads `convert` output, not `optimize` output. Follow-up.
+- [x] Make inspection characteristics from PMI? — **Answer (user, scope):** No, view-only first. Follow-up.
+- [x] Backfill existing models? — **Autonomous:** No. "Reoptimize from source file" adds PMI to one model. A backfill would re-optimize every model.
+- [x] A column or a fixed path? — **Autonomous:** A nullable `pmiPath` column, the same as every other `modelUpload` artifact. A fixed path would need a storage probe to know whether PMI exists.
+- [x] Which instance of a part in an assembly? — **Autonomous:** The first instance in the tree walk. MBD files are mostly single parts, and copies clutter the list.
+- [x] Click a face to list its PMI? — **Autonomous:** Not in v1. It needs face picking on the optimized GLB, which has no face ids. Follow-up.
+- [x] Schema change on `modelUpload` (Ask-First check)? — **Autonomous:** Not production-critical. It is an artifact table, and the change adds one nullable column.
+- [x] New contract (Ask-First check)? — **Autonomous:** Additive. `graph.json` and `types.ts` do not change. `pmi.json` is a new, versioned, internal artifact.
+
+## Implementation notes
+
+These facts came out of the build. They change details, not the design.
+
+| Finding | Result |
+|---|---|
+| OCCT's `XCAFView_Object::ViewDirection` is the look direction (camera to model), not the eye axis | `read_pmi` copies it as it is. NIST CTC 01's isometric view proves the sign |
+| OCCT stops reading saved views at the first camera with no draughting model | NIST STC 06 (AP242 edition 3) reads its PMI but none of its 12 views. An OCCT reader limit, recorded in `apps/assembler/AGENTS.md` |
+| OCCT makes a dimension with no value and no drawing when the drawing is a separate graphic-only item | `build_document` drops such a dimension. The drawing stays as a note. NIST CTC 01 has 4 |
+| `TDocStd_Application` refuses to open a path it already holds open (`PCDM_RS_AlreadyRetrieved`) | `read_pmi` opens an `.xbf` from a stream and closes it after. `read_xbf` never closes its document, so the ingest's xbf is still open when `read_pmi` runs |
+| CAD exporters give graphic-only notes a generic name ("DGT:Dimension") | The panel labels them "Note 1", "Note 2" |
+| The MES assembly view loads its preview from the model path, not the artifacts route | `pmiUrl` is wired in the ERP `CadModel` and the MES job operation model tab only. The MES assembly view is a follow-up |
+| The local stack could not start (the shared Redis pool was full) | Types came from a throwaway database restored from a sibling worktree's schema with the same 1,238 migrations. Without the migration the generated files matched the committed ones byte for byte. With it, the diff was the 3 `pmiPath` lines. `generate:swagger` needs PostgREST and did not run |
+| The self-review found that a stable `pmi.json` path let two runs of one model delete each other's file | The path is unique per run (`pmi-{run}.json`), as the thumbnail's is |
+| The self-review found that one Latin-1 name made `rust::String` throw and lost the file's PMI | `read_pmi` builds strings with `rust::String::lossy` |
+| A picked annotation lying flat (normal ±Z) read at an arbitrary turn, because the focus kept +Z as the camera's up | The focus uses the annotation plane's own Y axis (normal × X) as up, so the text reads left to right |
+| Switching PMI units meant opening the Measurements panel | The PMI panel has its own mm / in toggle. It shares one unit with Measurements |
+| The browser test ran on a throwaway Vite page that mounts the real `ModelPreview` | The page used the optimized GLB and `pmi.json` that `run_ingest` wrote for NIST CTC 01 and CTC 05. The PMI lines up with the model, picks highlight, and saved views filter and turn the camera |
+
+## Changelog
+
+- 2026-10-26: Implemented. Acceptance criteria updated for the OCCT view limit (STC 06) and the real NIST counts.
+
+- 2026-10-26: Created (autonomous `/feature` run). The Open Questions section marks each autonomous decision.
diff --git a/.claude/rules/company-backup-restore.md b/.claude/rules/company-backup-restore.md
index 45607dff1f..79096cbcbe 100644
--- a/.claude/rules/company-backup-restore.md
+++ b/.claude/rules/company-backup-restore.md
@@ -175,7 +175,7 @@ both use it; `company-backup.ts` re-exports it), exported to app code as
`{targetCompanyId}/` + remapped id segments), `rewriteToTemplateAssetPath`
(`{co}/…` → `_templates/{industryId}/…`). `STORAGE_PATH_COLUMNS` =
`thumbnailPath`, `modelPath`, `originalPath`, `optimizedModelPath`,
- `glbPath`, `graphPath` — every `modelUpload` artifact column. A backup enumerates assets by LISTING the bucket under
+ `glbPath`, `graphPath`, `pmiPath` — every `modelUpload` artifact column. A backup enumerates assets by LISTING the bucket under
`{companyId}/` (`company-export.ts`), not by reading these columns, so raw CAD
IS carried; a column missing from this set survives a cross-company restore
still pointing at the SOURCE company's prefix (which is what left restored
diff --git a/apps/assembler/AGENTS.md b/apps/assembler/AGENTS.md
index f91f78083f..d18b2e853a 100644
--- a/apps/assembler/AGENTS.md
+++ b/apps/assembler/AGENTS.md
@@ -27,7 +27,11 @@ crates/
│ # Fusion/SolidWorks export) split into per-solid child components; guarded so any
│ # sheet/surface geometry beside the solids keeps the merged mesh (nothing vanishes).
│ # write_test_step generates hermetic multi-solid STEP fixtures for tests.
+│ # pmi.cc: read_pmi — a second, read-only pass over the XCAF doc for the PMI
+│ # (dimensions, geometric tolerances, datums, saved views) in world mm;
+│ # write_test_pmi_step writes a hermetic AP242 fixture with semantic PMI.
├── converter/ # STEP → graph.json + GLB. nodeid (sha1), graph (tree/bbox/source-unit), convert, glb.
+│ # pmi: the pmi.json document (contract: packages/viewer/src/pmi.ts).
├── thumbnail/ # GLB → PNG preview, on the CPU: reads plain or EXT_meshopt_compression GLBs,
│ # z-buffer rasteriser through the viewer's camera (45° perspective, Z up; home
│ # direction unless the caller names one),
@@ -363,18 +367,29 @@ lossless `convert` GLB). It replaced a headless-browser screenshot of the viewer
page. A Draco-compressed GLB is refused (`thumbnail_failed`); textures and vertex
colours are ignored in favour of the material colour.
-## Ingest (optimize with compact and thumbnail)
+## Ingest (optimize with compact, thumbnail and PMI)
A new model is processed by ONE `/v1/optimize` job, which reads the raw once.
-Two optional request fields add outputs:
+Three optional request fields add outputs:
| Field | Output | What it writes |
|---|---|---|
| `compact: { path? }` | `raw` (`application/zstd`) | A STEP is converted to BinXCAF once; the optimiser tessellates from that xbf, and the xbf is compressed (`.xbf.zst`). A mesh source is compressed as it is. An xbf source needs nothing. |
| `thumbnail: { path?, size?, direction? }` | `thumbnail` (`image/png`) | Rendered from the optimised GLB in memory, with the camera of `/v1/thumbnail`. |
-
-Neither extra can fail the job: a failed compaction or render becomes a warning
-and the output is left out. The caller is `@carbon/jobs` `tasks/model-optimize.ts`.
+| `pmi: { path? }` | `pmi` (`application/json`) | The STEP's PMI (`pmi.json`, `converter::pmi`), read by `occt_bridge::read_pmi` from the same xbf (or the STEP/xbf source). Only for STEP and xbf sources, and only when the model has PMI; `result.outputs.pmi` carries `{ path, bytes, items, views }`. |
+
+No extra can fail the job: a failed compaction, render or PMI read becomes a
+warning and the output is left out.
+
+`read_pmi` opens an xbf from a STREAM and closes it after: `TDocStd_Application`
+keeps every document it opened by path until it is closed, and refuses to open
+the same path again (`PCDM_RS_AlreadyRetrieved`) — `read_xbf` has just opened
+it. Coordinates are world mm in the GLB's frame: a part's PMI is moved to the
+first world placement of the part its first referenced shape belongs to. OCCT
+reads AP242 saved views only when every camera has a draughting model, so an
+edition 3 file such as NIST STC 06 can arrive with none. The NIST MBE PMI models
+(public domain, not committed) run in `converter/tests/pmi.rs` when
+`PMI_FIXTURES` names their directory. The caller is `@carbon/jobs` `tasks/model-optimize.ts`.
It asks for `compact` only while the raw is still in `temp-staging`; without a
`raw` output it copies the raw out of staging as it is. `/v1/compact` and
`/v1/thumbnail` stay for the cases outside ingest: a raw left in staging with the
diff --git a/apps/assembler/src/actions/optimize.rs b/apps/assembler/src/actions/optimize.rs
index 7579e2affd..92e94f2964 100644
--- a/apps/assembler/src/actions/optimize.rs
+++ b/apps/assembler/src/actions/optimize.rs
@@ -8,7 +8,8 @@
//! glTF to GLB via a streaming base64 decode), then runs the
//! meshopt geometry passes + codec encode (via `crates/optimize`), walking a
//! simplify ladder until the render-weight + output-size gates pass. Async job;
-//! uploads the single `glb` output to its submit-time URL. Fails loud with a typed error
+//! uploads the `glb` output (plus the ingest outputs it was asked for: `raw`,
+//! `thumbnail`, `pmi`) to their submit-time URLs. Fails loud with a typed error
//! (`unsupported_format` / `ambiguous_format` / `tessellation_failed` /
//! `cannot_fit_budget`) rather than storing an over-cap or wrong result.
@@ -31,6 +32,50 @@ pub struct OptimizeReq {
/// Ingest: also render the preview thumbnail (output `thumbnail`) from the
/// optimised GLB, still in memory.
pub thumbnail: Option<ThumbnailOut>,
+ /// Ingest: also read the model's PMI (output `pmi`, `pmi.json`) when the
+ /// source is a STEP or BinXCAF. `Some(path)` records where it goes. A
+ /// model with no PMI writes no output; a failed read is a warning.
+ pub pmi: Option<Option<String>>,
+}
+
+/// The `pmi.json` an ingest read, with its counts for the result.
+struct PmiOut {
+ bytes: Vec<u8>,
+ items: usize,
+ views: usize,
+}
+
+/// Read the PMI of `load_path` (the BinXCAF the ingest made, or the source
+/// itself). `source_format` is what was uploaded. `Ok(None)`: the model has
+/// none, or is not a format that carries it (only STEP does; a BinXCAF is a
+/// STEP the ingest already read).
+fn read_ingest_pmi(
+ load_path: &str,
+ source_format: &str,
+ source_path: &str,
+) -> Result<Option<PmiOut>, String> {
+ if source_format != "step" && source_format != "xbf" {
+ return Ok(None);
+ }
+ // The STEP header names the unit the author drew in; a BinXCAF has none.
+ let source_unit = if source_format == "step" {
+ read_head_bytes(source_path, converter::graph::SOURCE_UNIT_SCAN_BYTES)
+ .ok()
+ .and_then(|head| {
+ converter::pmi::pmi_source_unit(&converter::graph::detect_source_unit_bytes(&head))
+ })
+ } else {
+ None
+ };
+ let Some(doc) = converter::pmi::extract_pmi(load_path, source_unit)? else {
+ return Ok(None);
+ };
+ let bytes = converter::pmi::to_json(&doc)?;
+ Ok(Some(PmiOut {
+ bytes,
+ items: doc.items.len(),
+ views: doc.views.len(),
+ }))
}
/// The thumbnail an ingest renders (see `thumbnail` for the camera).
@@ -103,6 +148,7 @@ fn prepare_ingest(path: &str, declared: &str, ext: Option<&str>) -> Result<Inges
/// Optimise, with the ingest outputs when asked for: the optimised GLB, the
/// compacted raw, and the thumbnail (or why it failed: a preview never fails
/// the job).
+#[allow(clippy::type_complexity)]
fn run_ingest(
path: &str,
declared: &str,
@@ -110,13 +156,32 @@ fn run_ingest(
opts: &Opts,
compact: bool,
thumbnail: Option<(u32, [f32; 3])>,
-) -> Result<(Outcome, Option<Compacted>, Option<Result<Vec<u8>, String>>), ActionErr> {
+ pmi: bool,
+) -> Result<
+ (
+ Outcome,
+ Option<Compacted>,
+ Option<Result<Vec<u8>, String>>,
+ Option<PmiOut>,
+ ),
+ ActionErr,
+> {
let ingest = if compact { Some(prepare_ingest(path, declared, ext)?) } else { None };
let (load_path, load_declared) = match &ingest {
Some(i) => (i.load_path.as_str(), i.declared.as_str()),
None => (path, declared),
};
let outcome = run_optimize(load_path, load_declared, ext, opts);
+ // The PMI is read from the same BinXCAF, before it is deleted, and only
+ // once the optimise has succeeded. A failure is a warning: the preview
+ // matters more than its annotations.
+ let pmi_read = match (&outcome, pmi) {
+ (Ok(o), true) => {
+ let source_format = ingest.as_ref().map_or(o.detected_format, |i| i.source_format);
+ Some(read_ingest_pmi(load_path, source_format, path))
+ }
+ _ => None,
+ };
// Compress the retained raw only once the optimise has succeeded, and
// before the BinXCAF it may be made from is deleted.
let compacted = match (&outcome, ingest.as_ref().and_then(|i| i.compact_from.as_ref())) {
@@ -142,10 +207,18 @@ fn run_ingest(
}
None => None,
};
+ let pmi_out = match pmi_read {
+ Some(Ok(p)) => p,
+ Some(Err(e)) => {
+ outcome.warnings.push(format!("pmi: {e}"));
+ None
+ }
+ None => None,
+ };
let png = thumbnail.map(|(size, direction)| {
thumbnail::render_png(&outcome.glb, size, direction).map_err(|e| e.0)
});
- Ok((outcome, compacted, png))
+ Ok((outcome, compacted, png, pmi_out))
}
pub struct Opts {
@@ -230,6 +303,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
let mut opts = req.opts;
let compact = req.compact.is_some();
let thumbnail = req.thumbnail.as_ref().map(|t| (t.size, t.direction));
+ let pmi = req.pmi.is_some();
let res = {
let grant = admission
@@ -249,13 +323,13 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
);
opts.deadline = opts.budget.map(|b| Instant::now() + b);
compute::run(Some(grant), move || {
- run_ingest(&tmp_str, &declared, ext.as_deref(), &opts, compact, thumbnail)
+ run_ingest(&tmp_str, &declared, ext.as_deref(), &opts, compact, thumbnail, pmi)
})
.await
};
drop(src);
- let (mut outcome, compacted, png) = match res {
+ let (mut outcome, compacted, png, pmi_out) = match res {
Ok(Ok(o)) => o,
Ok(Err(e)) => {
eprintln!("[{job_id}] optimize failed ({}): {}", e.code, e.message);
@@ -310,6 +384,14 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
"bytes": png.len(),
});
}
+ if let Some(p) = &pmi_out {
+ result_outputs["pmi"] = json!({
+ "path": req.pmi.clone().flatten(),
+ "bytes": p.bytes.len(),
+ "items": p.items,
+ "views": p.views,
+ });
+ }
let done = Done {
result: json!({
"detected_format": outcome.detected_format,
@@ -327,6 +409,7 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
"optimise_ms": optimise_ms,
"compact_bytes": compacted.as_ref().map(|c| c.bytes.len()),
"thumbnail_bytes": png.as_ref().map(|p| p.len()),
+ "pmi_bytes": pmi_out.as_ref().map(|p| p.bytes.len()),
}),
};
let mut outputs = vec![Output {
@@ -348,6 +431,13 @@ pub fn spawn(state: &AppState, job_id: &str, req: OptimizeReq) {
bytes: png.into(),
});
}
+ if let Some(p) = pmi_out {
+ outputs.push(Output {
+ name: "pmi".into(),
+ content_type: "application/json".into(),
+ bytes: p.bytes.into(),
+ });
+ }
jobs.finish(&job_id, outputs, done, None).await;
});
}
@@ -799,13 +889,14 @@ mod tests {
let opts = default_opts();
let plain = run_optimize(&step, "step", Some("step"), &opts).expect("plain optimise");
- let (outcome, compacted, png) = run_ingest(
+ let (outcome, compacted, png, pmi) = run_ingest(
&step,
"step",
Some("step"),
&opts,
true,
Some((64, thumbnail::DEFAULT_DIRECTION)),
+ true,
)
.expect("ingest");
@@ -822,6 +913,36 @@ mod tests {
assert!(xbf.starts_with(b"BINFILE"), "the compact form is BinXCAF");
let png = png.expect("thumbnail asked for").expect("thumbnail rendered");
assert!(png.starts_with(b"\x89PNG"));
+ assert!(pmi.is_none(), "plain boxes carry no PMI");
+ assert!(
+ outcome.warnings.iter().all(|w| !w.starts_with("pmi:")),
+ "{:?}",
+ outcome.warnings
+ );
+ }
+
+ #[test]
+ fn ingest_of_an_ap242_step_writes_its_pmi() {
+ let dir = std::env::temp_dir().join("carbon-ingest-pmi");
+ std::fs::create_dir_all(&dir).unwrap();
+ let step = dir.join("fixture.step").to_string_lossy().to_string();
+ assert!(occt_bridge::write_test_pmi_step(&step), "write AP242 fixture");
+ let (outcome, _, _, pmi) =
+ run_ingest(&step, "step", Some("step"), &default_opts(), true, None, true)
+ .expect("ingest");
+ let pmi = pmi.expect("the fixture has PMI");
+ assert_eq!(pmi.items, 3);
+ let doc: serde_json::Value = serde_json::from_slice(&pmi.bytes).unwrap();
+ assert_eq!(doc["version"], 1);
+ assert_eq!(doc["sourceUnit"], "mm");
+ assert_eq!(doc["items"][0]["dimension"]["value"], 100.0);
+ assert!(outcome.warnings.is_empty(), "{:?}", outcome.warnings);
+
+ // Not asked for: not read.
+ let (_, _, _, none) =
+ run_ingest(&step, "step", Some("step"), &default_opts(), true, None, false)
+ .expect("ingest");
+ assert!(none.is_none());
}
#[test]
@@ -837,8 +958,11 @@ mod tests {
std::fs::write(&glb_path, &glb).unwrap();
let glb_str = glb_path.to_string_lossy().to_string();
- let (_, compacted, png) =
- run_ingest(&glb_str, "auto", Some("glb"), &opts, true, None).expect("ingest");
+ let (outcome, compacted, png, pmi) =
+ run_ingest(&glb_str, "auto", Some("glb"), &opts, true, None, true).expect("ingest");
+ // A mesh has no PMI to read, and asking is not a warning.
+ assert!(pmi.is_none());
+ assert!(outcome.warnings.iter().all(|w| !w.starts_with("pmi:")));
let compacted = compacted.expect("compacted raw");
assert_eq!(compacted.kind, "zstd");
@@ -849,8 +973,9 @@ mod tests {
#[test]
fn a_plain_optimise_writes_no_ingest_outputs() {
let step = fixture_step("plain", 1);
- let (_, compacted, png) =
- run_ingest(&step, "step", Some("step"), &default_opts(), false, None).unwrap();
+ let (_, compacted, png, pmi) =
+ run_ingest(&step, "step", Some("step"), &default_opts(), false, None, false).unwrap();
+ assert!(pmi.is_none());
assert!(compacted.is_none());
assert!(png.is_none());
}
diff --git a/apps/assembler/src/request.rs b/apps/assembler/src/request.rs
index 1e82065165..27b32cb1e1 100644
--- a/apps/assembler/src/request.rs
+++ b/apps/assembler/src/request.rs
@@ -62,7 +62,7 @@ pub fn parse(action: &str, req: &Value) -> Result<ActionReq, ApiError> {
optimize: req["options"]["optimize"].as_bool().unwrap_or(true),
}),
"optimize" => {
- let (compact, thumbnail) = optimize_ingest(req);
+ let (compact, thumbnail, pmi) = optimize_ingest(req);
ActionReq::Optimize(actions::optimize::OptimizeReq {
source_url,
// `auto` content-detects the format in the action.
@@ -71,6 +71,7 @@ pub fn parse(action: &str, req: &Value) -> Result<ActionReq, ApiError> {
opts: optimize_opts(&req["output"], &req["quality"]),
compact,
thumbnail,
+ pmi,
})
}
"plan" => ActionReq::Plan(actions::plan::PlanReq {
@@ -194,11 +195,16 @@ fn parse_ladder(quality: &Value) -> Vec<Option<f32>> {
}
/// The ingest outputs an optimize may also write: `compact: { path? }` (the
-/// retained raw's compact form, output `raw`) and `thumbnail: { path?, size?,
-/// direction? }` (output `thumbnail`).
+/// retained raw's compact form, output `raw`), `thumbnail: { path?, size?,
+/// direction? }` (output `thumbnail`) and `pmi: { path? }` (output `pmi`).
+#[allow(clippy::type_complexity)]
fn optimize_ingest(
req: &Value,
-) -> (Option<Option<String>>, Option<actions::optimize::ThumbnailOut>) {
+) -> (
+ Option<Option<String>>,
+ Option<actions::optimize::ThumbnailOut>,
+ Option<Option<String>>,
+) {
let compact = req["compact"]
.is_object()
.then(|| req["compact"]["path"].as_str().map(str::to_string));
@@ -210,7 +216,10 @@ fn optimize_ingest(
direction: t.direction,
}
});
- (compact, thumbnail)
+ let pmi = req["pmi"]
+ .is_object()
+ .then(|| req["pmi"]["path"].as_str().map(str::to_string));
+ (compact, thumbnail, pmi)
}
/// `output: { path?, size?, direction? }`. `direction` is `[x, y, z]`, model
@@ -270,6 +279,24 @@ mod tests {
assert!(parse("compact", &body).is_err());
}
+ #[test]
+ fn an_optimize_reads_pmi_only_when_asked() {
+ let asked = json!({
+ "source": { "url": "https://storage.test/m.step" },
+ "pmi": { "path": "co/models/m/pmi.json" }
+ });
+ let ActionReq::Optimize(req) = parse("optimize", &asked).unwrap() else {
+ panic!("not an optimize");
+ };
+ assert_eq!(req.pmi, Some(Some("co/models/m/pmi.json".to_string())));
+
+ let plain = json!({ "source": { "url": "https://storage.test/m.step" } });
+ let ActionReq::Optimize(req) = parse("optimize", &plain).unwrap() else {
+ panic!("not an optimize");
+ };
+ assert_eq!(req.pmi, None);
+ }
+
#[test]
fn an_unknown_action_is_not_found() {
let body = json!({ "source": { "url": "https://storage.test/m.step" } });
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsx
index 7f4e76a7ed..a060f16133 100644
--- a/apps/erp/app/components/CadModel.tsx
+++ b/apps/erp/app/components/CadModel.tsx
@@ -291,6 +291,10 @@ const CadModel = ({
glbUrl={
artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null
}
+ pmiUrl={
+ // Unique per optimise run, so no cache-buster is needed.
+ artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null
+ }
lodUrl={
artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null
}
diff --git a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
index 5e30fa6011..66593a7754 100644
--- a/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/erp/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -25,7 +25,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const model = await client
.from("modelUpload")
.select(
- "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, optimizedAt, modelPath, originalPath"
+ "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, pmiPath, optimizeStatus, optimizedAt, modelPath, originalPath"
)
.eq("id", modelUploadId)
.eq("companyId", companyId)
@@ -68,6 +68,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
lodPath: null as string | null,
glbPath: model.data?.glbPath ?? null,
thumbnailPath: model.data?.thumbnailPath ?? null,
+ // The model's PMI (pmi.json), when its STEP carried any.
+ pmiPath: model.data?.pmiPath ?? null,
rawPath,
rawBucket: rawBucket ?? getCompanyPrivateBucket(companyId),
// Whether the optimiser is configured at all. When false, the viewer hides
diff --git a/apps/mes/app/components/JobOperation/JobOperation.tsx b/apps/mes/app/components/JobOperation/JobOperation.tsx
index e8281a3c29..aa8440ab9c 100644
--- a/apps/mes/app/components/JobOperation/JobOperation.tsx
+++ b/apps/mes/app/components/JobOperation/JobOperation.tsx
@@ -2265,6 +2265,10 @@ export const JobOperation = ({
glbUrl={
artifacts?.glbPath ? getPrivateUrl(artifacts.glbPath) : null
}
+ pmiUrl={
+ // Unique per optimise run, so no cache-buster is needed.
+ artifacts?.pmiPath ? getPrivateUrl(artifacts.pmiPath) : null
+ }
lodUrl={
artifacts?.lodPath ? getPrivateUrl(artifacts.lodPath) : null
}
diff --git a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
index 1473a2e09b..ace2016f56 100644
--- a/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
+++ b/apps/mes/app/routes/api+/model.artifacts.$modelUploadId.ts
@@ -24,7 +24,7 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
const model = await client
.from("modelUpload")
.select(
- "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, optimizeStatus, optimizedAt, modelPath, originalPath"
+ "size, originalSize, optimizedSize, optimizedModelPath, glbPath, thumbnailPath, pmiPath, optimizeStatus, optimizedAt, modelPath, originalPath"
)
.eq("id", modelUploadId)
.eq("companyId", companyId)
@@ -66,6 +66,8 @@ export async function loader({ request, params }: LoaderFunctionArgs) {
lodPath: null as string | null,
glbPath: model.data?.glbPath ?? null,
thumbnailPath: model.data?.thumbnailPath ?? null,
+ // The model's PMI (pmi.json), when its STEP carried any.
+ pmiPath: model.data?.pmiPath ?? null,
rawPath,
rawBucket: rawBucket ?? getCompanyPrivateBucket(companyId),
// Whether the optimiser is configured at all. When false, the viewer hides
diff --git a/crates/converter/src/lib.rs b/crates/converter/src/lib.rs
index 6eccbbe4b3..b7136a3318 100644
--- a/crates/converter/src/lib.rs
+++ b/crates/converter/src/lib.rs
@@ -9,3 +9,4 @@ pub mod convert;
pub mod glb;
pub mod graph;
pub mod nodeid;
+pub mod pmi;
diff --git a/crates/converter/src/pmi.rs b/crates/converter/src/pmi.rs
new file mode 100644
index 0000000000..e20bba2e8c
--- /dev/null
+++ b/crates/converter/src/pmi.rs
@@ -0,0 +1,429 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! `pmi.json` — the PMI (Product Manufacturing Information) of a STEP AP242
+//! model: dimensions, geometric tolerances, datums, graphic-only notes and the
+//! saved views, read by `occt_bridge::read_pmi`. The contract is
+//! `packages/viewer/src/pmi.ts`; the two must agree field for field.
+//!
+//! Everything is world mm in the frame of the optimised GLB (angles degrees).
+//! The geometry of `convert` is untouched: this is a separate read.
+
+use serde::Serialize;
+use std::collections::HashMap;
+
+pub const PMI_VERSION: u32 = 1;
+
+/// Largest `pmi.json` the ingest writes. Over it the referenced-face triangles
+/// go first (the highlight is the only thing they feed); still over, no PMI.
+pub const MAX_PMI_JSON_BYTES: usize = 16 * 1024 * 1024;
+
+/// Samples curved presentation and referenced edges (radians).
+pub const PMI_ANGULAR_DEFLECTION: f64 = 0.2;
+
+pub type Vec3 = [f64; 3];
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiDocument {
+ pub version: u32,
+ pub unit: &'static str,
+ pub source_unit: Option<&'static str>,
+ pub items: Vec<PmiItem>,
+ pub faces: Vec<PmiMesh>,
+ pub edges: Vec<Vec<f64>>,
+ pub views: Vec<PmiView>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct PmiMesh {
+ pub positions: Vec<f64>,
+ pub indices: Vec<u32>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiPlane {
+ pub origin: Vec3,
+ pub normal: Vec3,
+ pub x_direction: Vec3,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiItem {
+ pub id: String,
+ pub kind: &'static str,
+ pub name: Option<String>,
+ pub dimension: Option<PmiDimension>,
+ pub tolerance: Option<PmiTolerance>,
+ pub datum: Option<PmiDatum>,
+ pub lines: Vec<Vec<f64>>,
+ pub mesh: Option<PmiMesh>,
+ pub plane: Option<PmiPlane>,
+ pub text_position: Option<Vec3>,
+ pub faces: Vec<u32>,
+ pub edges: Vec<u32>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiFitClass {
+ pub hole: bool,
+ pub form_variance: String,
+ pub grade: String,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct PmiDecimals {
+ pub left: i32,
+ pub right: i32,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiDimension {
+ #[serde(rename = "type")]
+ pub kind: String,
+ pub value: Option<f64>,
+ pub upper: Option<f64>,
+ pub lower: Option<f64>,
+ pub upper_bound: Option<f64>,
+ pub lower_bound: Option<f64>,
+ pub fit_class: Option<PmiFitClass>,
+ pub qualifier: Option<String>,
+ pub decimals: Option<PmiDecimals>,
+ pub modifiers: Vec<String>,
+ pub descriptions: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct PmiDatumRef {
+ pub name: String,
+ pub modifiers: Vec<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiTolerance {
+ #[serde(rename = "type")]
+ pub kind: String,
+ pub value: Option<f64>,
+ pub zone_shape: Option<String>,
+ pub material: Option<String>,
+ pub zone_modifier: Option<String>,
+ pub zone_modifier_value: Option<f64>,
+ pub modifiers: Vec<String>,
+ pub max_value: Option<f64>,
+ pub datums: Vec<PmiDatumRef>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct PmiDatum {
+ pub name: String,
+ pub modifiers: Vec<String>,
+ pub target: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PmiView {
+ pub id: String,
+ pub name: String,
+ pub direction: Vec3,
+ pub up: Vec3,
+ pub projection: Option<&'static str>,
+ pub item_ids: Vec<String>,
+}
+
+/// The `sourceUnit` the viewer can start its unit toggle at: only the two it
+/// offers. Takes [`crate::graph::detect_source_unit_bytes`]'s answer.
+pub fn pmi_source_unit(detected: &str) -> Option<&'static str> {
+ match detected {
+ "mm" => Some("mm"),
+ "inch" => Some("in"),
+ _ => None,
+ }
+}
+
+/// Read a STEP or `.xbf` file's PMI. `Ok(None)` when it has none.
+pub fn extract_pmi(
+ path: &str,
+ source_unit: Option<&'static str>,
+) -> Result<Option<PmiDocument>, String> {
+ let tree = occt_bridge::read_pmi(path, PMI_ANGULAR_DEFLECTION);
+ if !tree.ok {
+ return Err(if tree.error.is_empty() {
+ "PMI read failed".to_string()
+ } else {
+ tree.error
+ });
+ }
+ Ok(build_document(&tree, source_unit))
+}
+
+/// 0.1 µm — far below any tolerance, and it keeps the JSON short. A
+/// non-finite value becomes 0: serde_json writes NaN as `null`, which the
+/// viewer's parser refuses, and one bad point would drop the whole document.
+fn r4(v: f64) -> f64 {
+ if !v.is_finite() {
+ return 0.0;
+ }
+ let r = (v * 10_000.0).round() / 10_000.0;
+ if r == 0.0 {
+ 0.0 // no "-0.0"
+ } else {
+ r
+ }
+}
+
+fn r4_all(values: &[f64]) -> Vec<f64> {
+ values.iter().map(|&v| r4(v)).collect()
+}
+
+fn vec3(values: &[f64], at: usize) -> Vec3 {
+ [r4(values[at]), r4(values[at + 1]), r4(values[at + 2])]
+}
+
+fn non_empty(s: &str) -> Option<String> {
+ if s.trim().is_empty() {
+ None
+ } else {
+ Some(s.trim().to_string())
+ }
+}
+
+fn some_if(cond: bool, v: f64) -> Option<f64> {
+ if cond && v.is_finite() {
+ Some(r4(v))
+ } else {
+ None
+ }
+}
+
+const KINDS: [&str; 4] = ["dimension", "tolerance", "datum", "note"];
+const ID_PREFIX: [&str; 4] = ["d", "t", "a", "n"];
+
+fn has_graphics(item: &occt_bridge::PmiRaw) -> bool {
+ !item.lines.is_empty() || !item.mesh.indices.is_empty()
+}
+
+/// A dimension with no value and no drawing shows nothing. OCCT makes these
+/// for a dimension whose drawing it stored as a separate graphic-only item
+/// (NIST CTC 01 has four), which the document keeps as a note.
+fn is_empty_dimension(item: &occt_bridge::PmiRaw) -> bool {
+ item.kind == 0 && !item.has_value && !has_graphics(item)
+}
+
+pub fn build_document(
+ tree: &occt_bridge::PmiTree,
+ source_unit: Option<&'static str>,
+) -> Option<PmiDocument> {
+ if tree.items.is_empty() && tree.views.is_empty() {
+ return None;
+ }
+
+ // OCCT adds a datum once per tolerance that references it. Keep one per
+ // letter: the first copy with graphics, else the first copy.
+ let mut kept_datum: HashMap<&str, usize> = HashMap::new();
+ for (i, raw) in tree.items.iter().enumerate() {
+ if raw.kind != 2 {
+ continue;
+ }
+ let name = raw.name.trim();
+ match kept_datum.get(name) {
+ Some(&k) if has_graphics(&tree.items[k]) || !has_graphics(raw) => {}
+ _ => {
+ kept_datum.insert(name, i);
+ }
+ }
+ }
+ // Raw index → output index (a merged datum points at the one kept).
+ let mut out_index: Vec<Option<usize>> = vec![None; tree.items.len()];
+ let mut counters = [0usize; 4];
+ let mut items: Vec<PmiItem> = Vec::new();
+ for (i, raw) in tree.items.iter().enumerate() {
+ let kind = (raw.kind as usize).min(3);
+ if kind == 2 && kept_datum.get(raw.name.trim()) != Some(&i) {
+ continue;
+ }
+ if is_empty_dimension(raw) {
+ continue;
+ }
+ counters[kind] += 1;
+ out_index[i] = Some(items.len());
+ items.push(item(
+ raw,
+ kind,
+ format!("{}{}", ID_PREFIX[kind], counters[kind]),
+ ));
+ }
+ for (i, raw) in tree.items.iter().enumerate() {
+ if raw.kind == 2 && out_index[i].is_none() {
+ out_index[i] = kept_datum.get(raw.name.trim()).and_then(|&k| out_index[k]);
+ }
+ }
+ if items.is_empty() && tree.views.is_empty() {
+ return None;
+ }
+
+ let views = tree
+ .views
+ .iter()
+ .enumerate()
+ .map(|(i, v)| {
+ let mut item_ids: Vec<String> = Vec::new();
+ for &raw in &v.items {
+ if let Some(Some(o)) = out_index.get(raw as usize) {
+ let id = &items[*o].id;
+ if !item_ids.contains(id) {
+ item_ids.push(id.clone());
+ }
+ }
+ }
+ PmiView {
+ id: format!("v{}", i + 1),
+ name: non_empty(&v.name).unwrap_or_else(|| format!("View {}", i + 1)),
+ direction: vec3(&v.direction, 0),
+ up: vec3(&v.up, 0),
+ projection: match v.projection {
+ 1 => Some("parallel"),
+ 2 => Some("central"),
+ _ => None,
+ },
+ item_ids,
+ }
+ })
+ .collect();
+
+ Some(PmiDocument {
+ version: PMI_VERSION,
+ unit: "mm",
+ source_unit,
+ items,
+ faces: tree
+ .faces
+ .iter()
+ .map(|m| PmiMesh {
+ positions: r4_all(&m.positions),
+ indices: m.indices.clone(),
+ })
+ .collect(),
+ edges: tree.edges.iter().map(|e| r4_all(&e.points)).collect(),
+ views,
+ })
+}
+
+fn item(raw: &occt_bridge::PmiRaw, kind: usize, id: String) -> PmiItem {
+ let modifiers: Vec<String> = raw
+ .modifiers
+ .iter()
+ .filter(|m| !m.is_empty())
+ .cloned()
+ .collect();
+ let dimension = (kind == 0).then(|| PmiDimension {
+ kind: raw.type_name.clone(),
+ value: some_if(raw.has_value, raw.value),
+ upper: some_if(raw.has_plus_minus, raw.upper),
+ lower: some_if(raw.has_plus_minus, raw.lower),
+ upper_bound: some_if(raw.has_range, raw.upper_bound),
+ lower_bound: some_if(raw.has_range, raw.lower_bound),
+ fit_class: raw.has_fit.then(|| PmiFitClass {
+ hole: raw.fit_hole,
+ form_variance: raw.fit_variance.clone(),
+ grade: raw.fit_grade.clone(),
+ }),
+ qualifier: non_empty(&raw.qualifier),
+ decimals: raw.has_decimals.then_some(PmiDecimals {
+ left: raw.decimals_left,
+ right: raw.decimals_right,
+ }),
+ modifiers: modifiers.clone(),
+ descriptions: raw.descriptions.clone(),
+ });
+ let tolerance = (kind == 1).then(|| PmiTolerance {
+ kind: raw.type_name.clone(),
+ value: some_if(raw.has_value, raw.value),
+ zone_shape: non_empty(&raw.zone_shape),
+ material: non_empty(&raw.material),
+ zone_modifier: non_empty(&raw.zone_modifier),
+ zone_modifier_value: some_if(raw.zone_modifier_value > 0.0, raw.zone_modifier_value),
+ modifiers: modifiers.clone(),
+ max_value: some_if(raw.max_value > 0.0, raw.max_value),
+ datums: raw
+ .datum_refs
+ .iter()
+ .enumerate()
+ .filter(|(_, n)| !n.trim().is_empty())
+ .map(|(i, n)| PmiDatumRef {
+ name: n.trim().to_string(),
+ modifiers: raw
+ .datum_ref_modifiers
+ .get(i)
+ .map(|m| {
+ m.split(',')
+ .filter(|s| !s.is_empty())
+ .map(str::to_string)
+ .collect()
+ })
+ .unwrap_or_default(),
+ })
+ .collect(),
+ });
+ let datum = (kind == 2).then(|| PmiDatum {
+ name: raw.name.trim().to_string(),
+ modifiers: modifiers.clone(),
+ target: non_empty(&raw.datum_target),
+ });
+ PmiItem {
+ id,
+ kind: KINDS[kind],
+ name: non_empty(&raw.name),
+ dimension,
+ tolerance,
+ datum,
+ lines: raw
+ .lines
+ .iter()
+ .filter(|l| l.points.len() >= 6)
+ .map(|l| r4_all(&l.points))
+ .collect(),
+ mesh: (!raw.mesh.indices.is_empty()).then(|| PmiMesh {
+ positions: r4_all(&raw.mesh.positions),
+ indices: raw.mesh.indices.clone(),
+ }),
+ plane: (raw.has_plane && raw.plane.len() == 9).then(|| PmiPlane {
+ origin: vec3(&raw.plane, 0),
+ normal: vec3(&raw.plane, 3),
+ x_direction: vec3(&raw.plane, 6),
+ }),
+ text_position: (raw.has_text && raw.text.len() == 3).then(|| vec3(&raw.text, 0)),
+ faces: raw.faces.clone(),
+ edges: raw.edges.clone(),
+ }
+}
+
+/// Serialize under [`MAX_PMI_JSON_BYTES`]. Over the cap the referenced-face
+/// triangles and every item's face indices go (the highlight is lost, the
+/// annotations stay); still over, an error.
+pub fn to_json(doc: &PmiDocument) -> Result<Vec<u8>, String> {
+ let bytes = serde_json::to_vec(doc).map_err(|e| e.to_string())?;
+ if bytes.len() <= MAX_PMI_JSON_BYTES {
+ return Ok(bytes);
+ }
+ let mut lean = doc.clone();
+ lean.faces.clear();
+ for item in &mut lean.items {
+ item.faces.clear();
+ }
+ let bytes = serde_json::to_vec(&lean).map_err(|e| e.to_string())?;
+ if bytes.len() <= MAX_PMI_JSON_BYTES {
+ return Ok(bytes);
+ }
+ Err(format!(
+ "pmi.json is {} bytes, over the {} byte cap",
+ bytes.len(),
+ MAX_PMI_JSON_BYTES
+ ))
+}
diff --git a/crates/converter/tests/pmi.rs b/crates/converter/tests/pmi.rs
new file mode 100644
index 0000000000..3327a075fd
--- /dev/null
+++ b/crates/converter/tests/pmi.rs
@@ -0,0 +1,260 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+//! PMI extraction (`pmi.json`). Hermetic: the AP242 fixture is written by the
+//! occt bridge itself. The NIST MBE PMI test models are public domain but not
+//! committed; set `PMI_FIXTURES` to a directory holding them to run those
+//! checks too (https://www.nist.gov/document/nist-pmi-step-files).
+
+use converter::pmi::{extract_pmi, to_json, PmiDocument};
+
+fn fixture(name: &str) -> (std::path::PathBuf, String) {
+ let dir = std::env::temp_dir().join(format!("carbon-pmi-{name}"));
+ std::fs::create_dir_all(&dir).unwrap();
+ let step = dir.join("fixture.step");
+ let step_str = step.to_str().unwrap().to_string();
+ assert!(
+ occt_bridge::write_test_pmi_step(&step_str),
+ "failed to write the AP242 fixture"
+ );
+ (dir, step_str)
+}
+
+fn read(path: &str) -> PmiDocument {
+ extract_pmi(path, Some("mm"))
+ .expect("PMI read")
+ .expect("the fixture has PMI")
+}
+
+#[test]
+fn reads_dimension_tolerance_and_datum_from_ap242() {
+ let (_dir, step) = fixture("semantic");
+ let doc = read(&step);
+
+ let kinds: Vec<&str> = doc.items.iter().map(|i| i.kind).collect();
+ assert_eq!(kinds, vec!["dimension", "tolerance", "datum"], "{doc:#?}");
+
+ let dim = &doc.items[0];
+ assert_eq!(dim.id, "d1");
+ let d = dim.dimension.as_ref().unwrap();
+ assert_eq!(d.kind, "linearDistance");
+ assert_eq!(d.value, Some(100.0));
+ assert_eq!(d.upper, Some(0.1));
+ assert_eq!(d.lower, Some(-0.05));
+ assert_eq!(dim.faces.len(), 2, "the two X faces");
+ for &f in &dim.faces {
+ assert!(!doc.faces[f as usize].indices.is_empty());
+ }
+ assert!(!dim.lines.is_empty(), "the two-edge presentation");
+
+ let tol = &doc.items[1];
+ let t = tol.tolerance.as_ref().unwrap();
+ assert_eq!(t.kind, "flatness");
+ assert_eq!(t.value, Some(0.05));
+ assert_eq!(
+ t.datums.iter().map(|d| d.name.as_str()).collect::<Vec<_>>(),
+ vec!["A"]
+ );
+ assert_eq!(tol.faces.len(), 1, "the top face");
+
+ let datum = &doc.items[2];
+ assert_eq!(datum.datum.as_ref().unwrap().name, "A");
+ assert_eq!(datum.faces.len(), 1, "the bottom face");
+
+ // The top face (z = 20) and the bottom face (z = 0) are where the box says.
+ let z_of = |f: u32| {
+ let p = &doc.faces[f as usize].positions;
+ p.iter()
+ .skip(2)
+ .step_by(3)
+ .copied()
+ .fold(f64::NAN, f64::max)
+ };
+ assert_eq!(z_of(tol.faces[0]), 20.0);
+ assert_eq!(z_of(datum.faces[0]), 0.0);
+}
+
+#[test]
+fn xbf_round_trip_keeps_the_pmi() {
+ let (dir, step) = fixture("xbf");
+ let xbf = dir.join("fixture.xbf");
+ let xbf_str = xbf.to_str().unwrap();
+ assert!(occt_bridge::step_to_xbf(&step, xbf_str), "step_to_xbf");
+ let from_step = to_json(&read(&step)).unwrap();
+ let from_xbf = to_json(&read(xbf_str)).unwrap();
+ assert_eq!(
+ String::from_utf8(from_step).unwrap(),
+ String::from_utf8(from_xbf).unwrap()
+ );
+}
+
+#[test]
+fn a_model_without_pmi_has_no_document() {
+ let dir = std::env::temp_dir().join("carbon-pmi-none");
+ std::fs::create_dir_all(&dir).unwrap();
+ let step = dir.join("box.step");
+ let step_str = step.to_str().unwrap();
+ assert!(occt_bridge::write_test_step(step_str, 1));
+ assert_eq!(extract_pmi(step_str, None).unwrap(), None);
+}
+
+// --- NIST MBE PMI test models (opt-in) ---------------------------------------
+
+fn nist(name: &str) -> Option<String> {
+ let dir = std::env::var("PMI_FIXTURES").ok()?;
+ let path = std::path::Path::new(&dir).join(name);
+ assert!(
+ path.exists(),
+ "PMI_FIXTURES is set but {} is missing",
+ path.display()
+ );
+ Some(path.to_string_lossy().into_owned())
+}
+
+fn bounds(points: impl Iterator<Item = f64>) -> ([f64; 3], [f64; 3]) {
+ let mut min = [f64::INFINITY; 3];
+ let mut max = [f64::NEG_INFINITY; 3];
+ for (i, v) in points.enumerate() {
+ min[i % 3] = min[i % 3].min(v);
+ max[i % 3] = max[i % 3].max(v);
+ }
+ (min, max)
+}
+
+#[test]
+fn nist_ctc_01_reads_semantic_and_graphical_pmi() {
+ let Some(path) = nist("nist_ctc_01_asme1_ap242-e1.stp") else {
+ return;
+ };
+ let doc = read(&path);
+ let count = |k: &str| doc.items.iter().filter(|i| i.kind == k).count();
+ eprintln!(
+ "CTC 01: {} dimensions, {} tolerances, {} datums, {} notes, {} views, {} faces",
+ count("dimension"),
+ count("tolerance"),
+ count("datum"),
+ count("note"),
+ doc.views.len(),
+ doc.faces.len()
+ );
+ assert!(doc.items.len() >= 20, "{} items", doc.items.len());
+ for item in &doc.items {
+ assert!(
+ !item.lines.is_empty() || item.mesh.is_some(),
+ "{} has no graphical PMI",
+ item.id
+ );
+ }
+ let json = to_json(&doc).unwrap();
+ eprintln!("CTC 01 pmi.json: {} bytes", json.len());
+
+ // The PMI sits on the model: its faces' box lies inside the model's box,
+ // and the annotations' box overlaps it.
+ let conv =
+ converter::convert::convert_step_head(&path, &std::fs::read(&path).unwrap(), 0.1, 0.5)
+ .expect("convert");
+ let bbox = &conv.graph["root"]["bbox"];
+ let model_min: Vec<f64> = bbox["min"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_f64().unwrap())
+ .collect();
+ let model_max: Vec<f64> = bbox["max"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|v| v.as_f64().unwrap())
+ .collect();
+ let (fmin, fmax) = bounds(doc.faces.iter().flat_map(|f| f.positions.iter().copied()));
+ for a in 0..3 {
+ assert!(
+ fmin[a] >= model_min[a] - 0.5 && fmax[a] <= model_max[a] + 0.5,
+ "faces {fmin:?}..{fmax:?} outside model {model_min:?}..{model_max:?}"
+ );
+ }
+ let (lmin, lmax) = bounds(doc.items.iter().flat_map(|i| {
+ i.lines
+ .iter()
+ .flatten()
+ .copied()
+ .chain(i.mesh.iter().flat_map(|m| m.positions.iter().copied()))
+ }));
+ for a in 0..3 {
+ assert!(
+ lmin[a] <= model_max[a] && lmax[a] >= model_min[a],
+ "annotations {lmin:?}..{lmax:?} do not overlap model {model_min:?}..{model_max:?}"
+ );
+ }
+}
+
+#[test]
+fn nist_ctc_05_inch_polyline_pmi() {
+ let Some(path) = nist("nist_ctc_05_asme1_ap242-e1.stp") else {
+ return;
+ };
+ let doc = read(&path);
+ eprintln!(
+ "CTC 05: {} items, {} views",
+ doc.items.len(),
+ doc.views.len()
+ );
+ assert!(!doc.items.is_empty());
+ assert!(
+ doc.items.iter().any(|i| !i.lines.is_empty()),
+ "polyline presentation"
+ );
+}
+
+#[test]
+fn nist_saved_views_carry_a_look_direction_and_their_items() {
+ let Some(ctc01) = nist("nist_ctc_01_asme1_ap242-e1.stp") else {
+ return;
+ };
+ let doc = read(&ctc01);
+ assert_eq!(doc.views.len(), 1);
+ let view = &doc.views[0];
+ // An isometric from front-right-top looks down: -Z, with +Z up.
+ assert!(view.direction[2] < 0.0, "{:?}", view.direction);
+ assert!(view.up[2] > 0.0, "{:?}", view.up);
+ assert!(!view.item_ids.is_empty());
+ for id in &view.item_ids {
+ assert!(
+ doc.items.iter().any(|i| &i.id == id),
+ "view names unknown item {id}"
+ );
+ }
+
+ let Some(ctc05) = nist("nist_ctc_05_asme1_ap242-e1.stp") else {
+ return;
+ };
+ assert_eq!(read(&ctc05).views.len(), 2);
+}
+
+#[test]
+fn nist_stc_06_reads_pmi_without_views() {
+ // OCCT stops reading views at the first camera it cannot tie to a
+ // draughting model; this AP242 e3 file's 12 cameras all arrive dropped.
+ // The PMI itself still reads.
+ let Some(path) = nist("nist_stc_06_asme1_ap242-e3.stp") else {
+ return;
+ };
+ let doc = read(&path);
+ assert!(doc.items.len() >= 30, "{} items", doc.items.len());
+ assert!(doc.views.is_empty());
+}
+
+#[test]
+fn nist_datums_merge_to_one_per_letter() {
+ let Some(path) = nist("nist_ctc_01_asme1_ap242-e1.stp") else {
+ return;
+ };
+ let doc = read(&path);
+ let datums: Vec<&str> = doc
+ .items
+ .iter()
+ .filter_map(|i| i.datum.as_ref().map(|d| d.name.as_str()))
+ .collect();
+ assert_eq!(datums, vec!["A", "B", "C"]);
+}
diff --git a/crates/occt-bridge/build.rs b/crates/occt-bridge/build.rs
index 1b21f462dc..4c5f09cf57 100644
--- a/crates/occt-bridge/build.rs
+++ b/crates/occt-bridge/build.rs
@@ -87,6 +87,7 @@ fn main() {
cxx_build::bridge("src/lib.rs")
.file("src/occt.cc")
+ .file("src/pmi.cc")
.std("c++17")
.include(&include_dir)
.warnings(false)
@@ -121,6 +122,8 @@ fn main() {
println!("cargo:rerun-if-changed=src/lib.rs");
println!("cargo:rerun-if-changed=src/occt.cc");
println!("cargo:rerun-if-changed=src/occt.h");
+ println!("cargo:rerun-if-changed=src/occt_doc.h");
+ println!("cargo:rerun-if-changed=src/pmi.cc");
println!("cargo:rerun-if-env-changed=OCCT_PREFIX");
println!("cargo:rerun-if-env-changed=OCCT_LINK");
}
diff --git a/crates/occt-bridge/src/lib.rs b/crates/occt-bridge/src/lib.rs
index 8730ae8df8..a4585afc0c 100644
--- a/crates/occt-bridge/src/lib.rs
+++ b/crates/occt-bridge/src/lib.rs
@@ -38,6 +38,93 @@ pub mod ffi {
pub nodes: Vec<RawNode>,
}
+ /// A polyline, flat x,y,z, world mm.
+ #[derive(Debug, Clone, Default)]
+ pub struct PmiPolyline {
+ pub points: Vec<f64>,
+ }
+
+ /// Triangles, flat x,y,z positions (world mm) and flat index triples.
+ #[derive(Debug, Clone, Default)]
+ pub struct PmiMesh {
+ pub positions: Vec<f64>,
+ pub indices: Vec<u32>,
+ }
+
+ /// One PMI item as OCCT reads it (see `pmi.cc`). `kind`: 0 dimension,
+ /// 1 geometric tolerance, 2 datum, 3 graphic-only note. Enum values are
+ /// lower camel case strings; an empty string is "none". Lengths are mm,
+ /// angles degrees.
+ #[derive(Debug, Clone)]
+ pub struct PmiRaw {
+ pub kind: u8,
+ pub type_name: String,
+ pub name: String,
+ pub has_value: bool,
+ pub value: f64,
+ pub has_plus_minus: bool,
+ pub upper: f64,
+ /// Negative: the lower deviation, signed.
+ pub lower: f64,
+ pub has_range: bool,
+ pub upper_bound: f64,
+ pub lower_bound: f64,
+ pub has_fit: bool,
+ pub fit_hole: bool,
+ pub fit_variance: String,
+ pub fit_grade: String,
+ pub qualifier: String,
+ pub has_decimals: bool,
+ pub decimals_left: i32,
+ pub decimals_right: i32,
+ pub modifiers: Vec<String>,
+ pub descriptions: Vec<String>,
+ pub zone_shape: String,
+ pub material: String,
+ pub zone_modifier: String,
+ pub zone_modifier_value: f64,
+ pub max_value: f64,
+ /// Datum letters a tolerance references, in precedence order.
+ pub datum_refs: Vec<String>,
+ /// Per datum reference: its modifiers, comma-joined.
+ pub datum_ref_modifiers: Vec<String>,
+ pub datum_target: String,
+ pub lines: Vec<PmiPolyline>,
+ pub mesh: PmiMesh,
+ pub has_plane: bool,
+ /// 9 when `has_plane`: origin, normal, x direction.
+ pub plane: Vec<f64>,
+ pub has_text: bool,
+ /// 3 when `has_text`.
+ pub text: Vec<f64>,
+ /// Indices into `PmiTree::faces` / `PmiTree::edges`.
+ pub faces: Vec<u32>,
+ pub edges: Vec<u32>,
+ }
+
+ /// A saved view. `direction` is the look direction (camera → model);
+ /// `projection`: 0 none, 1 parallel, 2 central. `items` index `PmiTree::items`.
+ #[derive(Debug, Clone)]
+ pub struct PmiViewRaw {
+ pub name: String,
+ pub direction: Vec<f64>,
+ pub up: Vec<f64>,
+ pub projection: u8,
+ pub items: Vec<u32>,
+ }
+
+ /// The PMI of a document. `ok=false` with `error` when the file could not
+ /// be read; `ok=true` and empty lists when it has no PMI.
+ #[derive(Debug, Clone)]
+ pub struct PmiTree {
+ pub ok: bool,
+ pub error: String,
+ pub items: Vec<PmiRaw>,
+ pub faces: Vec<PmiMesh>,
+ pub edges: Vec<PmiPolyline>,
+ pub views: Vec<PmiViewRaw>,
+ }
+
unsafe extern "C++" {
include!("occt-bridge/src/occt.h");
@@ -63,6 +150,17 @@ pub mod ffi {
/// on failure.
fn read_xbf(path: &str, linear_deflection: f64, angular_deflection: f64) -> Tree;
+ /// Read the PMI (dimensions, geometric tolerances, datums, saved
+ /// views) of a STEP or BinXCAF (`.xbf`) file, in world mm. A second,
+ /// read-only pass: the geometry of `read_step` / `read_xbf` is not
+ /// touched. `angular_deflection` samples curved presentation and
+ /// referenced edges.
+ fn read_pmi(path: &str, angular_deflection: f64) -> PmiTree;
+
+ /// Test fixture generator: a 100 x 50 x 20 mm box as AP242 with one
+ /// dimension, one flatness tolerance and datum A (see `pmi.cc`).
+ fn write_test_pmi_step(path: &str) -> bool;
+
/// Test fixture generator: write `boxes` disjoint solids as ONE
/// product (flat multi-body, no assembly tree) to a STEP file.
/// Hermetic tests use this instead of committed fixture files.
@@ -86,6 +184,7 @@ pub mod ffi {
}
pub use ffi::{
- read_brep, read_iges, read_step, read_xbf, step_to_xbf, write_test_cylinder,
- write_test_plate_with_holes, write_test_step, RawNode, Tree,
+ read_brep, read_iges, read_pmi, read_step, read_xbf, step_to_xbf, write_test_cylinder,
+ write_test_plate_with_holes, write_test_pmi_step, write_test_step, PmiMesh, PmiPolyline,
+ PmiRaw, PmiTree, PmiViewRaw, RawNode, Tree,
};
diff --git a/crates/occt-bridge/src/occt.cc b/crates/occt-bridge/src/occt.cc
index e10507fde8..1a28a7321b 100644
--- a/crates/occt-bridge/src/occt.cc
+++ b/crates/occt-bridge/src/occt.cc
@@ -1,4 +1,5 @@
#include "occt-bridge/src/occt.h"
+#include "occt-bridge/src/occt_doc.h"
#include <map>
#include <string>
@@ -69,7 +70,7 @@ static const std::vector<double> IDENTITY_4X4 = {
// UTF-8, not TCollection_AsciiString: the ASCII conversion replaces every
// non-Latin character with '?', which mangles e.g. CJK part names.
-static std::string to_utf8(const TCollection_ExtendedString &ext) {
+std::string to_utf8(const TCollection_ExtendedString &ext) {
const int len = ext.LengthOfCString();
if (len <= 0) return "";
std::string out(static_cast<size_t>(len) + 1, '\0');
@@ -79,7 +80,7 @@ static std::string to_utf8(const TCollection_ExtendedString &ext) {
return out;
}
-static std::string label_name(const TDF_Label &label) {
+std::string label_name(const TDF_Label &label) {
Handle(TDataStd_Name) attr;
if (label.FindAttribute(TDataStd_Name::GetID(), attr)) {
return to_utf8(attr->Get());
@@ -144,7 +145,7 @@ static bool mesh_parallel() {
// handful of facets. Scale it to the shape: 0.05% of the bbox diagonal, never
// coarser than requested, floored at 5% of the request so a tiny part can't
// demand micron-level meshes.
-static double adaptive_deflection(const TopoDS_Shape &shape, double lin) {
+double adaptive_deflection(const TopoDS_Shape &shape, double lin) {
Bnd_Box box;
BRepBndLib::Add(shape, box);
if (box.IsVoid()) return lin;
@@ -478,7 +479,7 @@ class Builder {
// no concurrent STEPControl_Controller::Init(). So warm both ONCE here,
// single-threaded; concurrent reads then only touch their own local reader
// instance and read (never write) the shared config.
-static void ensure_step_init() {
+void ensure_step_init() {
static std::once_flag occt_init;
std::call_once(occt_init, [] {
STEPControl_Controller::Init();
@@ -489,7 +490,7 @@ static void ensure_step_init() {
// One process-wide XCAF application with the BinXCAF (`.xbf`) storage/retrieval
// drivers registered — required to SaveAs/Open XCAF documents. TDocStd_Application
// is internally guarded, so a single shared instance is fine across threads.
-static const Handle(TDocStd_Application) & xcaf_app() {
+const Handle(TDocStd_Application) & xcaf_app() {
static Handle(TDocStd_Application) app = [] {
Handle(TDocStd_Application) a = new TDocStd_Application();
BinXCAFDrivers::DefineFormat(a);
@@ -500,8 +501,8 @@ static const Handle(TDocStd_Application) & xcaf_app() {
// Read + transfer a STEP file into a fresh XCAF document. Returns null and sets
// `error` on failure (unreadable STEP, transfer failure).
-static Handle(TDocStd_Document) read_step_to_doc(const std::string &p,
- std::string &error) {
+Handle(TDocStd_Document) read_step_to_doc(const std::string &p,
+ std::string &error) {
ensure_step_init();
STEPCAFControl_Reader reader;
reader.SetColorMode(true);
diff --git a/crates/occt-bridge/src/occt.h b/crates/occt-bridge/src/occt.h
index 1dde2ee87b..d8cb3432e1 100644
--- a/crates/occt-bridge/src/occt.h
+++ b/crates/occt-bridge/src/occt.h
@@ -4,6 +4,7 @@
namespace carbon_occt {
struct Tree; // generated by cxx from the shared struct
+struct PmiTree;
Tree read_step(rust::Str path, double linear_deflection, double angular_deflection);
@@ -21,4 +22,7 @@ bool write_test_cylinder(rust::Str path, double radius, double height);
bool write_test_plate_with_holes(rust::Str path, double size, double thickness,
double hole_radius, uint32_t holes);
+PmiTree read_pmi(rust::Str path, double angular_deflection);
+
+bool write_test_pmi_step(rust::Str path);
} // namespace carbon_occt
diff --git a/crates/occt-bridge/src/occt_doc.h b/crates/occt-bridge/src/occt_doc.h
new file mode 100644
index 0000000000..e76c90b656
--- /dev/null
+++ b/crates/occt-bridge/src/occt_doc.h
@@ -0,0 +1,21 @@
+#pragma once
+// Document helpers shared by occt.cc (geometry) and pmi.cc (PMI). Internal to
+// the bridge: not part of the cxx surface.
+#include <string>
+
+#include <TCollection_ExtendedString.hxx>
+#include <TDF_Label.hxx>
+#include <TDocStd_Application.hxx>
+#include <TDocStd_Document.hxx>
+#include <TopoDS_Shape.hxx>
+
+namespace carbon_occt {
+
+std::string to_utf8(const TCollection_ExtendedString &ext);
+std::string label_name(const TDF_Label &label);
+void ensure_step_init();
+const Handle(TDocStd_Application) & xcaf_app();
+Handle(TDocStd_Document) read_step_to_doc(const std::string &p, std::string &error);
+double adaptive_deflection(const TopoDS_Shape &shape, double lin);
+
+} // namespace carbon_occt
diff --git a/crates/occt-bridge/src/pmi.cc b/crates/occt-bridge/src/pmi.cc
new file mode 100644
index 0000000000..07c8f6bc30
--- /dev/null
+++ b/crates/occt-bridge/src/pmi.cc
@@ -0,0 +1,803 @@
+// PMI (Product Manufacturing Information) out of an XCAF document: the
+// dimensions, geometric tolerances and datums OCCT's STEP reader puts in the
+// DimTolTool (AP242 semantic PMI, with the graphical presentation it found),
+// and the saved views in the ViewTool. A second, read-only pass over the
+// document: it never touches the geometry walk in occt.cc, so the GLB and
+// every nodeId stay as they are.
+//
+// Every point leaves here in world mm. OCCT keeps a part's PMI in the part's
+// own frame; the walk below records the first world placement of every
+// product, and each item moves with the part its first referenced shape
+// belongs to.
+#include "occt-bridge/src/occt.h"
+#include "occt-bridge/src/occt_doc.h"
+
+#include <algorithm>
+#include <fstream>
+#include <map>
+#include <string>
+#include <utility>
+#include <vector>
+
+#include <BRepAdaptor_Curve.hxx>
+#include <BRepBuilderAPI_MakeEdge.hxx>
+#include <BRepMesh_IncrementalMesh.hxx>
+#include <BRepPrimAPI_MakeBox.hxx>
+#include <BRep_Builder.hxx>
+#include <BRep_Tool.hxx>
+#include <GCPnts_TangentialDeflection.hxx>
+#include <Interface_Static.hxx>
+#include <NCollection_HArray1.hxx>
+#include <PCDM_ReaderStatus.hxx>
+#include <Poly_Polygon3D.hxx>
+#include <Poly_Triangulation.hxx>
+#include <STEPCAFControl_Writer.hxx>
+#include <Standard_Failure.hxx>
+#include <TCollection_HAsciiString.hxx>
+#include <TDF_Label.hxx>
+#include <TDF_LabelSequence.hxx>
+#include <TDF_Tool.hxx>
+#include <TopExp_Explorer.hxx>
+#include <TopLoc_Location.hxx>
+#include <TopoDS.hxx>
+#include <TopoDS_Compound.hxx>
+#include <TopoDS_Edge.hxx>
+#include <TopoDS_Face.hxx>
+#include <XCAFDimTolObjects_DatumObject.hxx>
+#include <XCAFDimTolObjects_DimensionObject.hxx>
+#include <XCAFDimTolObjects_GeomToleranceObject.hxx>
+#include <XCAFDoc_Datum.hxx>
+#include <XCAFDoc_DimTolTool.hxx>
+#include <XCAFDoc_Dimension.hxx>
+#include <XCAFDoc_DocumentTool.hxx>
+#include <XCAFDoc_GeomTolerance.hxx>
+#include <XCAFDoc_ShapeTool.hxx>
+#include <XCAFDoc_View.hxx>
+#include <XCAFDoc_ViewTool.hxx>
+#include <XCAFView_Object.hxx>
+#include <gp_Ax2.hxx>
+#include <gp_Pnt.hxx>
+#include <gp_Trsf.hxx>
+
+#include "occt-bridge/src/lib.rs.h"
+
+namespace carbon_occt {
+
+namespace {
+
+// ---- enum names: lower camel case, in each OCCT enum's declaration order ----
+
+const char *const DIMENSION_TYPES[] = {
+ "none",
+ "curvedDistance",
+ "linearDistance",
+ "linearDistanceFromCenterToOuter",
+ "linearDistanceFromCenterToInner",
+ "linearDistanceFromOuterToCenter",
+ "linearDistanceFromOuterToOuter",
+ "linearDistanceFromOuterToInner",
+ "linearDistanceFromInnerToCenter",
+ "linearDistanceFromInnerToOuter",
+ "linearDistanceFromInnerToInner",
+ "angular",
+ "oriented",
+ "withPath",
+ "curveLength",
+ "diameter",
+ "sphericalDiameter",
+ "radius",
+ "sphericalRadius",
+ "toroidalMinorDiameter",
+ "toroidalMajorDiameter",
+ "toroidalMinorRadius",
+ "toroidalMajorRadius",
+ "toroidalHighMajorDiameter",
+ "toroidalLowMajorDiameter",
+ "toroidalHighMajorRadius",
+ "toroidalLowMajorRadius",
+ "thickness",
+ "angularSize",
+ "sizeWithPath",
+ "commonLabel",
+ "presentation",
+};
+
+const char *const TOLERANCE_TYPES[] = {
+ "none", "angularity", "circularRunout",
+ "circularityOrRoundness", "coaxiality", "concentricity",
+ "cylindricity", "flatness", "parallelism",
+ "perpendicularity", "position", "profileOfLine",
+ "profileOfSurface", "straightness", "symmetry",
+ "totalRunout",
+};
+
+const char *const DIMENSION_MODIFIERS[] = {
+ "controlledRadius",
+ "square",
+ "statisticalTolerance",
+ "continuousFeature",
+ "twoPointSize",
+ "localSizeDefinedBySphere",
+ "leastSquaresAssociationCriterion",
+ "maximumInscribedAssociation",
+ "minimumCircumscribedAssociation",
+ "circumferenceDiameter",
+ "areaDiameter",
+ "volumeDiameter",
+ "maximumSize",
+ "minimumSize",
+ "averageSize",
+ "medianSize",
+ "midRangeSize",
+ "rangeOfSizes",
+ "anyRestrictedPortionOfFeature",
+ "anyCrossSection",
+ "specificFixedCrossSection",
+ "commonTolerance",
+ "freeStateCondition",
+ "between",
+};
+
+const char *const TOLERANCE_MODIFIERS[] = {
+ "anyCrossSection",
+ "commonZone",
+ "eachRadialElement",
+ "freeState",
+ "leastMaterialRequirement",
+ "lineElement",
+ "majorDiameter",
+ "maximumMaterialRequirement",
+ "minorDiameter",
+ "notConvex",
+ "pitchDiameter",
+ "reciprocityRequirement",
+ "separateRequirement",
+ "statisticalTolerance",
+ "tangentPlane",
+ "allAround",
+ "allOver",
+};
+
+const char *const DATUM_MODIFIERS[] = {
+ "anyCrossSection",
+ "anyLongitudinalSection",
+ "basic",
+ "contactingFeature",
+ "degreeOfFreedomConstraintU",
+ "degreeOfFreedomConstraintV",
+ "degreeOfFreedomConstraintW",
+ "degreeOfFreedomConstraintX",
+ "degreeOfFreedomConstraintY",
+ "degreeOfFreedomConstraintZ",
+ "distanceVariable",
+ "freeState",
+ "leastMaterialRequirement",
+ "line",
+ "majorDiameter",
+ "maximumMaterialRequirement",
+ "minorDiameter",
+ "orientation",
+ "pitchDiameter",
+ "plane",
+ "point",
+ "translation",
+};
+
+const char *const DATUM_TARGET_TYPES[] = {"point", "line", "rectangle", "circle", "area"};
+
+const char *const FORM_VARIANCES[] = {
+ "", "A", "B", "C", "CD", "D", "E", "EF", "F", "FG", "G", "H", "JS", "J", "K",
+ "M", "N", "P", "R", "S", "T", "U", "V", "X", "Y", "Z", "ZA", "ZB", "ZC",
+};
+
+const char *const GRADES[] = {
+ "IT01", "IT0", "IT1", "IT2", "IT3", "IT4", "IT5", "IT6", "IT7", "IT8",
+ "IT9", "IT10", "IT11", "IT12", "IT13", "IT14", "IT15", "IT16", "IT17", "IT18",
+};
+
+template <size_t N>
+const char *enum_name(const char *const (&names)[N], int value) {
+ return value >= 0 && static_cast<size_t>(value) < N ? names[value] : "";
+}
+
+// Lossy: a name an older exporter wrote in Latin-1 is not valid UTF-8, and
+// rust::String's own constructor would throw on it and lose the whole tree.
+rust::String hstring(const Handle(TCollection_HAsciiString) &s) {
+ return s.IsNull() ? rust::String() : rust::String::lossy(s->ToCString());
+}
+
+std::string entry_of(const TDF_Label &label) {
+ TCollection_AsciiString entry;
+ TDF_Tool::Entry(label, entry);
+ return std::string(entry.ToCString());
+}
+
+// The walk ends here when an item names a shape its document never placed.
+const TopLoc_Location IDENTITY;
+
+// ---- the extraction ----
+
+class PmiReader {
+ public:
+ PmiReader(const Handle(TDocStd_Document) &doc, double angular)
+ : doc_(doc), angular_(angular) {
+ shape_tool_ = XCAFDoc_DocumentTool::ShapeTool(doc->Main());
+ }
+
+ PmiTree read() {
+ PmiTree tree;
+ tree.ok = true;
+ // DimTolTool()/ViewTool() create the tool on a document without one, so
+ // ask first. The STEP reader creates both on every document it reads, so
+ // this skips only documents from elsewhere; a STEP with no PMI is caught
+ // below, where every label list comes back empty.
+ const bool has_gdt = XCAFDoc_DocumentTool::CheckDimTolTool(doc_->Main());
+ const bool has_views = XCAFDoc_DocumentTool::CheckViewTool(doc_->Main());
+ if (!has_gdt && !has_views) return tree;
+
+ place_free_shapes();
+
+ if (has_gdt) {
+ Handle(XCAFDoc_DimTolTool) tool = XCAFDoc_DocumentTool::DimTolTool(doc_->Main());
+ TDF_LabelSequence labels;
+ tool->GetDimensionLabels(labels);
+ for (int i = 1; i <= labels.Length(); ++i) read_dimension(labels.Value(i), tree);
+ labels.Clear();
+ tool->GetGeomToleranceLabels(labels);
+ for (int i = 1; i <= labels.Length(); ++i) read_tolerance(labels.Value(i), tree);
+ labels.Clear();
+ tool->GetDatumLabels(labels);
+ for (int i = 1; i <= labels.Length(); ++i) read_datum(labels.Value(i), tree);
+ }
+ if (has_views) read_views(tree);
+ return tree;
+ }
+
+ private:
+ Handle(TDocStd_Document) doc_;
+ Handle(XCAFDoc_ShapeTool) shape_tool_;
+ double angular_;
+ // Product label entry → its first world placement in the tree walk.
+ std::map<std::string, TopLoc_Location> placement_;
+ // GD&T label entry → index in tree.items (for the views).
+ std::map<std::string, uint32_t> item_index_;
+ // Referenced shape label entry → index in tree.faces, or the indices in
+ // tree.edges (a wire reference is one polyline per edge).
+ std::map<std::string, uint32_t> face_index_;
+ std::map<std::string, std::vector<uint32_t>> edge_index_;
+
+ void place_free_shapes() {
+ TDF_LabelSequence free_shapes;
+ shape_tool_->GetFreeShapes(free_shapes);
+ for (int i = 1; i <= free_shapes.Length(); ++i) place(free_shapes.Value(i), TopLoc_Location());
+ }
+
+ // Mirrors Builder::build in occt.cc: a component's world placement is its
+ // parent's times the component's own location.
+ void place(const TDF_Label &product, const TopLoc_Location &world) {
+ placement_.emplace(entry_of(product), world);
+ if (!XCAFDoc_ShapeTool::IsAssembly(product)) return;
+ TDF_LabelSequence components;
+ XCAFDoc_ShapeTool::GetComponents(product, components);
+ for (int i = 1; i <= components.Length(); ++i) {
+ TDF_Label comp = components.Value(i);
+ TDF_Label referred;
+ if (!XCAFDoc_ShapeTool::GetReferredShape(comp, referred)) continue;
+ place(referred, world * XCAFDoc_ShapeTool::GetLocation(comp));
+ }
+ }
+
+ // The world placement of the part a referenced shape label belongs to. A
+ // face/edge reference is a sub-shape label directly under its part's label.
+ const TopLoc_Location &placement_of(const TDF_Label &shape_label) const {
+ TDF_Label owner = XCAFDoc_ShapeTool::IsSubShape(shape_label) ? shape_label.Father()
+ : shape_label;
+ auto it = placement_.find(entry_of(owner));
+ return it == placement_.end() ? IDENTITY : it->second;
+ }
+
+ static void push_point(rust::Vec<double> &out, const gp_Pnt &p, const gp_Trsf &t) {
+ gp_Pnt q = p.Transformed(t);
+ out.push_back(q.X());
+ out.push_back(q.Y());
+ out.push_back(q.Z());
+ }
+
+ static void push_dir(rust::Vec<double> &out, const gp_Dir &d, const gp_Trsf &t) {
+ gp_Dir q = d.Transformed(t);
+ out.push_back(q.X());
+ out.push_back(q.Y());
+ out.push_back(q.Z());
+ }
+
+ // An edge as a polyline: its 3D curve sampled by tangential deflection, else
+ // the 3D polygon a tessellated presentation carries. Empty when neither.
+ bool edge_polyline(const TopoDS_Edge &edge, const gp_Trsf &t, double sag,
+ PmiPolyline &out) const {
+ if (BRep_Tool::Degenerated(edge)) return false;
+ double first, last;
+ if (!BRep_Tool::Curve(edge, first, last).IsNull()) {
+ BRepAdaptor_Curve curve(edge);
+ GCPnts_TangentialDeflection sampler(curve, angular_, sag, 2);
+ if (sampler.NbPoints() < 2) return false;
+ for (int i = 1; i <= sampler.NbPoints(); ++i) push_point(out.points, sampler.Value(i), t);
+ return true;
+ }
+ TopLoc_Location loc;
+ Handle(Poly_Polygon3D) polygon = BRep_Tool::Polygon3D(edge, loc);
+ if (polygon.IsNull() || polygon->NbNodes() < 2) return false;
+ const gp_Trsf local = t * loc.Transformation();
+ for (int i = 1; i <= polygon->NbNodes(); ++i) push_point(out.points, polygon->Nodes().Value(i), local);
+ return true;
+ }
+
+ static void append_triangulation(const TopoDS_Face &face, const gp_Trsf &t, PmiMesh &mesh) {
+ TopLoc_Location loc;
+ Handle(Poly_Triangulation) tri = BRep_Tool::Triangulation(face, loc);
+ if (tri.IsNull()) return;
+ const gp_Trsf local = t * loc.Transformation();
+ const uint32_t offset = static_cast<uint32_t>(mesh.positions.size() / 3);
+ for (int i = 1; i <= tri->NbNodes(); ++i) push_point(mesh.positions, tri->Node(i), local);
+ for (int i = 1; i <= tri->NbTriangles(); ++i) {
+ Standard_Integer a, b, c;
+ tri->Triangle(i).Get(a, b, c);
+ mesh.indices.push_back(offset + a - 1);
+ mesh.indices.push_back(offset + b - 1);
+ mesh.indices.push_back(offset + c - 1);
+ }
+ }
+
+ // The author's drawing: edges become polylines, the surface-less triangulated
+ // faces of a tessellated annotation (filled text) become triangles.
+ void read_presentation(const TopoDS_Shape &shape, const gp_Trsf &t, PmiRaw &item) const {
+ if (shape.IsNull()) return;
+ for (TopExp_Explorer exp(shape, TopAbs_EDGE); exp.More(); exp.Next()) {
+ PmiPolyline line;
+ if (edge_polyline(TopoDS::Edge(exp.Current()), t, 0.01, line)) item.lines.push_back(line);
+ }
+ for (TopExp_Explorer exp(shape, TopAbs_FACE); exp.More(); exp.Next()) {
+ append_triangulation(TopoDS::Face(exp.Current()), t, item.mesh);
+ }
+ }
+
+ // Each referenced face or edge is meshed once and shared by every item that
+ // references it. Solids, vertices and whole parts get no highlight.
+ void read_references(const TDF_LabelSequence &labels, PmiTree &tree, PmiRaw &item) {
+ for (int i = 1; i <= labels.Length(); ++i) {
+ const TDF_Label &label = labels.Value(i);
+ TopoDS_Shape shape = XCAFDoc_ShapeTool::GetShape(label);
+ if (shape.IsNull()) continue;
+ const gp_Trsf t = placement_of(label).Transformation();
+ const std::string key = entry_of(label);
+ if (shape.ShapeType() == TopAbs_FACE) {
+ auto found = face_index_.find(key);
+ if (found == face_index_.end()) {
+ TopoDS_Face face = TopoDS::Face(shape);
+ TopLoc_Location loc;
+ if (BRep_Tool::Triangulation(face, loc).IsNull()) {
+ BRepMesh_IncrementalMesh(face, adaptive_deflection(face, 0.1), Standard_False, 0.5);
+ }
+ PmiMesh mesh;
+ append_triangulation(face, t, mesh);
+ if (mesh.indices.empty()) continue;
+ tree.faces.push_back(mesh);
+ found = face_index_.emplace(key, static_cast<uint32_t>(tree.faces.size() - 1)).first;
+ }
+ item.faces.push_back(found->second);
+ } else if (shape.ShapeType() == TopAbs_EDGE || shape.ShapeType() == TopAbs_WIRE) {
+ auto found = edge_index_.find(key);
+ if (found == edge_index_.end()) {
+ // One polyline per edge: the explorer neither orders a wire's edges
+ // nor orients them, so joining them would draw lines across it.
+ std::vector<uint32_t> indices;
+ for (TopExp_Explorer exp(shape, TopAbs_EDGE); exp.More(); exp.Next()) {
+ PmiPolyline line;
+ if (edge_polyline(TopoDS::Edge(exp.Current()), t, 0.05, line)) {
+ tree.edges.push_back(line);
+ indices.push_back(static_cast<uint32_t>(tree.edges.size() - 1));
+ }
+ }
+ found = edge_index_.emplace(key, indices).first;
+ }
+ for (uint32_t index : found->second) item.edges.push_back(index);
+ }
+ }
+ }
+
+ // The first referenced shape decides the frame of the item's own geometry.
+ gp_Trsf frame_of(const TDF_LabelSequence &first, const TDF_LabelSequence &second) const {
+ if (first.Length() > 0) return placement_of(first.Value(1)).Transformation();
+ if (second.Length() > 0) return placement_of(second.Value(1)).Transformation();
+ return gp_Trsf();
+ }
+
+ static void set_plane(PmiRaw &item, bool has, const gp_Ax2 &plane, const gp_Trsf &t) {
+ if (!has) return;
+ item.has_plane = true;
+ push_point(item.plane, plane.Location(), t);
+ push_dir(item.plane, plane.Direction(), t);
+ push_dir(item.plane, plane.XDirection(), t);
+ }
+
+ static void set_text(PmiRaw &item, bool has, const gp_Pnt &p, const gp_Trsf &t) {
+ if (!has) return;
+ item.has_text = true;
+ push_point(item.text, p, t);
+ }
+
+ static PmiRaw blank(uint8_t kind) {
+ PmiRaw item;
+ item.kind = kind;
+ item.has_value = false;
+ item.value = 0;
+ item.has_plus_minus = false;
+ item.upper = 0;
+ item.lower = 0;
+ item.has_range = false;
+ item.upper_bound = 0;
+ item.lower_bound = 0;
+ item.has_fit = false;
+ item.fit_hole = false;
+ item.has_decimals = false;
+ item.decimals_left = 0;
+ item.decimals_right = 0;
+ item.zone_modifier_value = 0;
+ item.max_value = 0;
+ item.has_plane = false;
+ item.has_text = false;
+ return item;
+ }
+
+ void finish(const TDF_Label &label, PmiRaw &item, PmiTree &tree) {
+ item_index_[entry_of(label)] = static_cast<uint32_t>(tree.items.size());
+ tree.items.push_back(item);
+ }
+
+ void read_dimension(const TDF_Label &label, PmiTree &tree) {
+ Handle(XCAFDoc_Dimension) attr;
+ if (!label.FindAttribute(XCAFDoc_Dimension::GetID(), attr)) return;
+ Handle(XCAFDimTolObjects_DimensionObject) obj = attr->GetObject();
+ if (obj.IsNull()) return;
+ const XCAFDimTolObjects_DimensionType type = obj->GetType();
+ const bool graphic_only = type == XCAFDimTolObjects_DimensionType_CommonLabel ||
+ type == XCAFDimTolObjects_DimensionType_DimensionPresentation;
+ PmiRaw item = blank(graphic_only ? 3 : 0);
+ item.type_name = enum_name(DIMENSION_TYPES, static_cast<int>(type));
+ item.name = hstring(obj->GetSemanticName());
+ if (item.name.empty()) item.name = hstring(obj->GetPresentationName());
+
+ if (!graphic_only) {
+ Handle(NCollection_HArray1<double>) values = obj->GetValues();
+ if (!values.IsNull() && values->Length() > 0) {
+ item.has_value = true;
+ item.value = obj->GetValue();
+ }
+ if (obj->IsDimWithPlusMinusTolerance()) {
+ item.has_plus_minus = true;
+ item.upper = obj->GetUpperTolValue();
+ // OCCT's STEP reader keeps only the lower deviation's magnitude, so a
+ // one-sided tolerance (+0.03/+0.01) cannot be told apart here; the
+ // artifact signs it as the usual case, below the nominal.
+ item.lower = -std::abs(obj->GetLowerTolValue());
+ }
+ if (obj->IsDimWithRange()) {
+ item.has_range = true;
+ item.upper_bound = obj->GetUpperBound();
+ item.lower_bound = obj->GetLowerBound();
+ }
+ if (obj->IsDimWithClassOfTolerance()) {
+ bool hole = false;
+ XCAFDimTolObjects_DimensionFormVariance variance;
+ XCAFDimTolObjects_DimensionGrade grade;
+ if (obj->GetClassOfTolerance(hole, variance, grade)) {
+ item.has_fit = true;
+ item.fit_hole = hole;
+ item.fit_variance = enum_name(FORM_VARIANCES, static_cast<int>(variance));
+ item.fit_grade = enum_name(GRADES, static_cast<int>(grade));
+ }
+ }
+ if (obj->HasQualifier()) {
+ switch (obj->GetQualifier()) {
+ case XCAFDimTolObjects_DimensionQualifier_Min: item.qualifier = "min"; break;
+ case XCAFDimTolObjects_DimensionQualifier_Max: item.qualifier = "max"; break;
+ case XCAFDimTolObjects_DimensionQualifier_Avg: item.qualifier = "avg"; break;
+ default: break;
+ }
+ }
+ int left = 0, right = 0;
+ obj->GetNbOfDecimalPlaces(left, right);
+ if (left > 0 || right > 0) {
+ item.has_decimals = true;
+ item.decimals_left = left;
+ item.decimals_right = right;
+ }
+ NCollection_Sequence<XCAFDimTolObjects_DimensionModif> modifiers = obj->GetModifiers();
+ for (int i = 1; i <= modifiers.Length(); ++i) {
+ item.modifiers.push_back(enum_name(DIMENSION_MODIFIERS, static_cast<int>(modifiers.Value(i))));
+ }
+ }
+ for (int i = 0; i < obj->NbDescriptions(); ++i) {
+ rust::String text = hstring(obj->GetDescription(i));
+ if (!text.empty()) item.descriptions.push_back(text);
+ }
+
+ TDF_LabelSequence first, second;
+ XCAFDoc_DimTolTool::GetRefShapeLabel(label, first, second);
+ const gp_Trsf t = frame_of(first, second);
+ read_presentation(obj->GetPresentation(), t, item);
+ set_plane(item, obj->HasPlane(), obj->GetPlane(), t);
+ set_text(item, obj->HasTextPoint(), obj->GetPointTextAttach(), t);
+ read_references(first, tree, item);
+ read_references(second, tree, item);
+ finish(label, item, tree);
+ }
+
+ void read_tolerance(const TDF_Label &label, PmiTree &tree) {
+ Handle(XCAFDoc_GeomTolerance) attr;
+ if (!label.FindAttribute(XCAFDoc_GeomTolerance::GetID(), attr)) return;
+ Handle(XCAFDimTolObjects_GeomToleranceObject) obj = attr->GetObject();
+ if (obj.IsNull()) return;
+ PmiRaw item = blank(1);
+ item.type_name = enum_name(TOLERANCE_TYPES, static_cast<int>(obj->GetType()));
+ item.name = hstring(obj->GetSemanticName());
+ if (item.name.empty()) item.name = hstring(obj->GetPresentationName());
+ item.has_value = true;
+ item.value = obj->GetValue();
+ switch (obj->GetTypeOfValue()) {
+ case XCAFDimTolObjects_GeomToleranceTypeValue_Diameter: item.zone_shape = "diameter"; break;
+ case XCAFDimTolObjects_GeomToleranceTypeValue_SphericalDiameter:
+ item.zone_shape = "sphericalDiameter";
+ break;
+ default: break;
+ }
+ switch (obj->GetMaterialRequirementModifier()) {
+ case XCAFDimTolObjects_GeomToleranceMatReqModif_M: item.material = "M"; break;
+ case XCAFDimTolObjects_GeomToleranceMatReqModif_L: item.material = "L"; break;
+ default: break;
+ }
+ switch (obj->GetZoneModifier()) {
+ case XCAFDimTolObjects_GeomToleranceZoneModif_Projected: item.zone_modifier = "projected"; break;
+ case XCAFDimTolObjects_GeomToleranceZoneModif_Runout: item.zone_modifier = "runout"; break;
+ case XCAFDimTolObjects_GeomToleranceZoneModif_NonUniform: item.zone_modifier = "nonUniform"; break;
+ default: break;
+ }
+ item.zone_modifier_value = obj->GetValueOfZoneModifier();
+ item.max_value = obj->GetMaxValueModifier();
+ NCollection_Sequence<XCAFDimTolObjects_GeomToleranceModif> modifiers = obj->GetModifiers();
+ for (int i = 1; i <= modifiers.Length(); ++i) {
+ item.modifiers.push_back(enum_name(TOLERANCE_MODIFIERS, static_cast<int>(modifiers.Value(i))));
+ }
+
+ // Datum references in precedence order. The "with object" variant drops
+ // the extra labels a datum's targets add.
+ TDF_LabelSequence datum_labels;
+ XCAFDoc_DimTolTool::GetDatumWithObjectOfTolerLabels(label, datum_labels);
+ std::vector<std::pair<int, std::pair<std::string, std::string>>> datums;
+ for (int i = 1; i <= datum_labels.Length(); ++i) {
+ Handle(XCAFDoc_Datum) datum_attr;
+ if (!datum_labels.Value(i).FindAttribute(XCAFDoc_Datum::GetID(), datum_attr)) continue;
+ Handle(XCAFDimTolObjects_DatumObject) datum = datum_attr->GetObject();
+ if (datum.IsNull()) continue;
+ std::string mods;
+ NCollection_Sequence<XCAFDimTolObjects_DatumSingleModif> dm = datum->GetModifiers();
+ for (int j = 1; j <= dm.Length(); ++j) {
+ if (!mods.empty()) mods += ",";
+ mods += enum_name(DATUM_MODIFIERS, static_cast<int>(dm.Value(j)));
+ }
+ datums.push_back({datum->GetPosition(), {std::string(hstring(datum->GetName())), mods}});
+ }
+ std::stable_sort(datums.begin(), datums.end(),
+ [](const auto &a, const auto &b) { return a.first < b.first; });
+ for (const auto &d : datums) {
+ item.datum_refs.push_back(d.second.first);
+ item.datum_ref_modifiers.push_back(d.second.second);
+ }
+
+ TDF_LabelSequence first, second;
+ XCAFDoc_DimTolTool::GetRefShapeLabel(label, first, second);
+ const gp_Trsf t = frame_of(first, second);
+ read_presentation(obj->GetPresentation(), t, item);
+ set_plane(item, obj->HasPlane(), obj->GetPlane(), t);
+ set_text(item, obj->HasPointText(), obj->GetPointTextAttach(), t);
+ read_references(first, tree, item);
+ finish(label, item, tree);
+ }
+
+ void read_datum(const TDF_Label &label, PmiTree &tree) {
+ Handle(XCAFDoc_Datum) attr;
+ if (!label.FindAttribute(XCAFDoc_Datum::GetID(), attr)) return;
+ Handle(XCAFDimTolObjects_DatumObject) obj = attr->GetObject();
+ if (obj.IsNull()) return;
+ PmiRaw item = blank(2);
+ item.type_name = "datum";
+ item.name = hstring(obj->GetName());
+ NCollection_Sequence<XCAFDimTolObjects_DatumSingleModif> modifiers = obj->GetModifiers();
+ for (int i = 1; i <= modifiers.Length(); ++i) {
+ item.modifiers.push_back(enum_name(DATUM_MODIFIERS, static_cast<int>(modifiers.Value(i))));
+ }
+ if (obj->IsDatumTarget()) {
+ item.datum_target = enum_name(DATUM_TARGET_TYPES, static_cast<int>(obj->GetDatumTargetType()));
+ }
+ TDF_LabelSequence first, second;
+ XCAFDoc_DimTolTool::GetRefShapeLabel(label, first, second);
+ const gp_Trsf t = frame_of(first, second);
+ read_presentation(obj->GetPresentation(), t, item);
+ set_plane(item, obj->HasPlane(), obj->GetPlane(), t);
+ set_text(item, obj->HasPointText(), obj->GetPointTextAttach(), t);
+ read_references(first, tree, item);
+ finish(label, item, tree);
+ }
+
+ // Saved views. OCCT's view direction is the look direction, camera towards
+ // model (NIST CTC 01's isometric "MBD_0" reads (-0.59, 0.57, -0.58) with up
+ // +Z). The projection point is relative to the camera's own frame and not a
+ // world point, so it is not read: the viewer fits the view's items instead.
+ // OCCT stops reading views at the first camera it cannot tie to a
+ // draughting model (STEPCAFControl_Reader::ReadViews), so an AP242 e3 file
+ // such as NIST STC 06 can arrive with none.
+ void read_views(PmiTree &tree) {
+ Handle(XCAFDoc_ViewTool) tool = XCAFDoc_DocumentTool::ViewTool(doc_->Main());
+ TDF_LabelSequence labels;
+ tool->GetViewLabels(labels);
+ for (int i = 1; i <= labels.Length(); ++i) {
+ Handle(XCAFDoc_View) attr;
+ if (!labels.Value(i).FindAttribute(XCAFDoc_View::GetID(), attr)) continue;
+ Handle(XCAFView_Object) obj = attr->GetObject();
+ if (obj.IsNull()) continue;
+ PmiViewRaw view;
+ view.name = hstring(obj->Name());
+ const gp_Dir look = obj->ViewDirection();
+ const gp_Dir up = obj->UpDirection();
+ view.direction = {look.X(), look.Y(), look.Z()};
+ view.up = {up.X(), up.Y(), up.Z()};
+ switch (obj->Type()) {
+ case XCAFView_ProjectionType_Parallel: view.projection = 1; break;
+ case XCAFView_ProjectionType_Central: view.projection = 2; break;
+ default: view.projection = 0; break;
+ }
+ TDF_LabelSequence gdt;
+ tool->GetRefGDTLabel(labels.Value(i), gdt);
+ std::vector<uint32_t> seen;
+ for (int j = 1; j <= gdt.Length(); ++j) {
+ auto found = item_index_.find(entry_of(gdt.Value(j)));
+ if (found == item_index_.end()) continue;
+ // ReadViews can list one GD&T once per annotation plane element.
+ if (std::find(seen.begin(), seen.end(), found->second) != seen.end()) continue;
+ seen.push_back(found->second);
+ view.items.push_back(found->second);
+ }
+ tree.views.push_back(view);
+ }
+ }
+};
+
+// A BinXCAF document is read from a stream, not opened by path: the
+// application refuses a path whose document it already holds open
+// (PCDM_RS_AlreadyRetrieved), and the optimize ingest's `read_xbf` has just
+// opened this one. `opened_by_app` tells the caller to Close() it again, so the
+// application does not keep the document alive.
+Handle(TDocStd_Document) open_document(const std::string &path, std::string &error,
+ bool &opened_by_app) {
+ opened_by_app = false;
+ std::ifstream file(path, std::ios::binary);
+ char magic[7] = {0};
+ const bool xbf = file && file.read(magic, 7) && std::string(magic, 7) == "BINFILE";
+ if (!xbf) return read_step_to_doc(path, error);
+ file.clear();
+ file.seekg(0);
+ Handle(TDocStd_Document) doc;
+ PCDM_ReaderStatus rs = xcaf_app()->Open(file, doc);
+ if (rs != PCDM_RS_OK || doc.IsNull()) {
+ error = "could not open XBF document";
+ return nullptr;
+ }
+ opened_by_app = true;
+ return doc;
+}
+
+} // namespace
+
+PmiTree read_pmi(rust::Str path, double angular_deflection) {
+ PmiTree tree;
+ tree.ok = false;
+ try {
+ std::string error;
+ bool opened_by_app = false;
+ Handle(TDocStd_Document) doc = open_document(std::string(path), error, opened_by_app);
+ if (doc.IsNull()) {
+ tree.error = error;
+ return tree;
+ }
+ struct CloseOnExit {
+ Handle(TDocStd_Document) doc;
+ bool active;
+ ~CloseOnExit() {
+ if (!active) return;
+ try {
+ xcaf_app()->Close(doc);
+ } catch (...) {
+ }
+ }
+ } close_on_exit{doc, opened_by_app};
+ tree = PmiReader(doc, angular_deflection).read();
+ } catch (Standard_Failure &e) {
+ tree = PmiTree();
+ tree.ok = false;
+ tree.error = std::string("OCCT error: ") + e.GetMessageString();
+ } catch (...) {
+ tree = PmiTree();
+ tree.ok = false;
+ tree.error = "unknown OCCT error";
+ }
+ return tree;
+}
+
+// Test fixture generator: a 100 x 50 x 20 mm box as AP242 with semantic PMI —
+// a 100 mm (+0.1/-0.05) distance between the two X faces with a two-edge
+// presentation, a 0.05 flatness on the top face referencing datum A, and
+// datum A on the bottom face. Hermetic converter tests read it back.
+bool write_test_pmi_step(rust::Str path) {
+ try {
+ ensure_step_init();
+ Handle(TDocStd_Document) doc = new TDocStd_Document(TCollection_ExtendedString("BinXCAF"));
+ Handle(XCAFDoc_ShapeTool) shapes = XCAFDoc_DocumentTool::ShapeTool(doc->Main());
+ Handle(XCAFDoc_DimTolTool) gdt = XCAFDoc_DocumentTool::DimTolTool(doc->Main());
+
+ TopoDS_Shape box = BRepPrimAPI_MakeBox(100.0, 50.0, 20.0).Shape();
+ TDF_Label part = shapes->AddShape(box, Standard_False);
+
+ // BRepPrimAPI_MakeBox face order: -X, +X, -Y, +Y, -Z (bottom), +Z (top).
+ std::vector<TopoDS_Shape> faces;
+ for (TopExp_Explorer exp(box, TopAbs_FACE); exp.More(); exp.Next()) faces.push_back(exp.Current());
+ if (faces.size() != 6) return false;
+ TDF_Label left = shapes->AddSubShape(part, faces[0]);
+ TDF_Label right = shapes->AddSubShape(part, faces[1]);
+ TDF_Label bottom = shapes->AddSubShape(part, faces[4]);
+ TDF_Label top = shapes->AddSubShape(part, faces[5]);
+
+ TDF_Label dim = gdt->AddDimension();
+ gdt->SetDimension(left, right, dim);
+ Handle(XCAFDimTolObjects_DimensionObject) dim_obj = new XCAFDimTolObjects_DimensionObject();
+ dim_obj->SetType(XCAFDimTolObjects_DimensionType_Location_LinearDistance);
+ dim_obj->SetValue(100.0);
+ dim_obj->SetUpperTolValue(0.1);
+ dim_obj->SetLowerTolValue(0.05);
+ dim_obj->SetPlane(gp_Ax2(gp_Pnt(50.0, -10.0, 10.0), gp_Dir(0.0, -1.0, 0.0), gp_Dir(1.0, 0.0, 0.0)));
+ dim_obj->SetPointTextAttach(gp_Pnt(50.0, -10.0, 30.0));
+ TopoDS_Compound presentation;
+ BRep_Builder builder;
+ builder.MakeCompound(presentation);
+ builder.Add(presentation, BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, -10.0, 25.0), gp_Pnt(100.0, -10.0, 25.0)).Edge());
+ builder.Add(presentation, BRepBuilderAPI_MakeEdge(gp_Pnt(0.0, -10.0, 20.0), gp_Pnt(0.0, -10.0, 28.0)).Edge());
+ dim_obj->SetPresentation(presentation, new TCollection_HAsciiString("length"));
+ XCAFDoc_Dimension::Set(dim)->SetObject(dim_obj);
+
+ TDF_Label datum = gdt->AddDatum();
+ TDF_LabelSequence datum_shapes;
+ datum_shapes.Append(bottom);
+ gdt->SetDatum(datum_shapes, datum);
+ Handle(XCAFDimTolObjects_DatumObject) datum_obj = new XCAFDimTolObjects_DatumObject();
+ datum_obj->SetName(new TCollection_HAsciiString("A"));
+ datum_obj->SetPosition(1);
+ XCAFDoc_Datum::Set(datum)->SetObject(datum_obj);
+
+ TDF_Label tol = gdt->AddGeomTolerance();
+ gdt->SetGeomTolerance(top, tol);
+ Handle(XCAFDimTolObjects_GeomToleranceObject) tol_obj = new XCAFDimTolObjects_GeomToleranceObject();
+ tol_obj->SetType(XCAFDimTolObjects_GeomToleranceType_Flatness);
+ tol_obj->SetValue(0.05);
+ XCAFDoc_GeomTolerance::Set(tol)->SetObject(tol_obj);
+ gdt->SetDatumToGeomTol(datum, tol);
+
+ STEPCAFControl_Writer writer;
+ writer.SetDimTolMode(Standard_True);
+ Interface_Static::SetIVal("write.step.schema", 5);
+ if (!writer.Transfer(doc, STEPControl_AsIs)) return false;
+ std::string p(path);
+ return writer.Write(p.c_str()) == IFSelect_RetDone;
+ } catch (...) {
+ return false;
+ }
+}
+
+} // namespace carbon_occt
diff --git a/packages/database/src/swagger-docs-schema.ts b/packages/database/src/swagger-docs-schema.ts
index 0c79b40661..0e437ea639 100644
--- a/packages/database/src/swagger-docs-schema.ts
+++ b/packages/database/src/swagger-docs-schema.ts
@@ -70662,6 +70662,9 @@ export default {
{
$ref: "#/parameters/rowFilter.modelUpload.originalPath"
},
+ {
+ $ref: "#/parameters/rowFilter.modelUpload.pmiPath"
+ },
{
$ref: "#/parameters/select"
},
@@ -70793,6 +70796,9 @@ export default {
{
$ref: "#/parameters/rowFilter.modelUpload.originalPath"
},
+ {
+ $ref: "#/parameters/rowFilter.modelUpload.pmiPath"
+ },
{
$ref: "#/parameters/preferReturn"
}
@@ -70878,6 +70884,9 @@ export default {
{
$ref: "#/parameters/rowFilter.modelUpload.originalPath"
},
+ {
+ $ref: "#/parameters/rowFilter.modelUpload.pmiPath"
+ },
{
$ref: "#/parameters/body.modelUpload"
},
@@ -151640,6 +151649,10 @@ export default {
originalPath: {
format: "text",
type: "string"
+ },
+ pmiPath: {
+ format: "text",
+ type: "string"
}
},
type: "object"
@@ -205721,6 +205734,12 @@ export default {
in: "query",
type: "string"
},
+ "rowFilter.modelUpload.pmiPath": {
+ name: "pmiPath",
+ required: false,
+ in: "query",
+ type: "string"
+ },
"body.costLedger": {
name: "costLedger",
description: "costLedger",
diff --git a/packages/database/src/types.ts b/packages/database/src/types.ts
index 88e0ac1134..3688e81eee 100644
--- a/packages/database/src/types.ts
+++ b/packages/database/src/types.ts
@@ -37108,6 +37108,7 @@ export type Database = {
optimizeStatus: Database["public"]["Enums"]["modelProcessingStatus"]
originalPath: string | null
originalSize: number | null
+ pmiPath: string | null
processedAt: string | null
processingError: string | null
processingStatus: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -37134,6 +37135,7 @@ export type Database = {
optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
originalPath?: string | null
originalSize?: number | null
+ pmiPath?: string | null
processedAt?: string | null
processingError?: string | null
processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
@@ -37160,6 +37162,7 @@ export type Database = {
optimizeStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
originalPath?: string | null
originalSize?: number | null
+ pmiPath?: string | null
processedAt?: string | null
processingError?: string | null
processingStatus?: Database["public"]["Enums"]["modelProcessingStatus"]
diff --git a/packages/database/supabase/migrations/20261026224620_model-pmi-artifact.sql b/packages/database/supabase/migrations/20261026224620_model-pmi-artifact.sql
new file mode 100644
index 0000000000..709ed5b896
--- /dev/null
+++ b/packages/database/supabase/migrations/20261026224620_model-pmi-artifact.sql
@@ -0,0 +1,7 @@
+-- PMI artifact. The optimize ingest reads a STEP AP242 model's PMI (Product
+-- Manufacturing Information: dimensions, geometric tolerances, datums, saved
+-- views) and writes it beside the optimised GLB as pmi.json. NULL when the
+-- model has none, or was optimised before the ingest read PMI.
+-- Reuses modelUpload's RLS.
+
+ALTER TABLE "modelUpload" ADD COLUMN IF NOT EXISTS "pmiPath" TEXT;
diff --git a/packages/jobs/AGENTS.md b/packages/jobs/AGENTS.md
index 261c415066..2f395c0b6a 100644
--- a/packages/jobs/AGENTS.md
+++ b/packages/jobs/AGENTS.md
@@ -74,7 +74,7 @@ pnpm --filter @carbon/jobs plan:company -- --company <id> --user <id> # MRP +
| `notification-digest` | `carbon/notification-digest.process` (sent by the `notification-digest-sweeper` pg_cron job every 15 min, only when `util.notification_digest_has_work()`) | Roll unread notifications into one digest per user, company and topic |
| `workflow-run-retention` | `carbon/workflow-run-retention.process` (sent by the `workflow-run-retention-sweeper` pg_cron job at 04:00 UTC, only when `util.workflow_run_retention_has_work()`) | Reap stale runs, compact and drop step detail, purge old run headers |
| `kanban-level-check` | `carbon/kanban.level-check` `{ companyId, kanbanIds }` (sent by the database only: the `queue_kanban_level_checks` statement handler on `itemLedger`, the `sync_kanban_level_check` interceptor on `kanban`, and the hourly `kanban-level-sweeper` pg_cron job through `util.sweep_kanban_levels()`, each only for Transfer kanbans already below their `replenishmentLevel`) | Calls `postingOrThrow("kanban-replenish", …)` in level mode (`userId "system"`, concurrency 1 per company, no `debounce`). It re-checks the projected quantity under a row lock, so a stale or duplicate event writes nothing. See `.claude/rules/kanban-system.md` |
-| `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, and the thumbnail. Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created |
+| `model-optimize` | `carbon/model-optimize` `{ modelUploadId, companyId }` (sent by the database: the `queue_model_pipeline` statement handler on `modelUpload` for every new row, except under `app.sync_in_progress` and for bundled `_templates/` paths; also by the viewer's Retry) | One assembler job per new model (`runAssemblerJob`, `tasks/assembler-client.ts`): the optimised preview GLB, the raw's compact form while the raw is in `temp-staging`, the thumbnail, and for a STEP with PMI the `pmi-{run}.json` the viewer draws (`modelUpload.pmiPath`, null when the model has none; the previous run's file is removed). Then it moves the raw out of staging (`settleCompactedRaw`, else `relocateRaw`, `tasks/model-compact.ts`). The model's file is read only from its own company (`resolveModelSourceBucket`). pg_cron `model-pipeline-reaper` (`util.reap_model_pipeline()`, at :13 and :43) marks an optimise, conversion or plan job Queued or Processing for 8 hours as Failed, and resends this event for a model still Idle 30 to 60 minutes after it was created |
| `embedding-queue` | `carbon/embedding-queue.process` (sent by the 10 s `process-embeddings` pg_cron doorbell while visible messages wait) | Drain the pgmq `embedding_jobs` queue and write embeddings |
| `mrp` | `*/15 * * * *` | Scheduled MRP. Each tick plans only the companies that are DUE — every 3 hours (UTC) by default, or once a day at `companySettings.mrpRunTime` on the company's clock (`isMrpDue` / `mrpTick`) — and have planning work (`companiesWithPlanningWork`), both in `scheduled/mrp-companies.ts`; one `step.run` per company |
diff --git a/packages/jobs/manifests/schema.json b/packages/jobs/manifests/schema.json
index cba7786dec..bd173d47d7 100644
--- a/packages/jobs/manifests/schema.json
+++ b/packages/jobs/manifests/schema.json
@@ -1,11 +1,11 @@
{
"kind": "carbon-company-backup",
"version": 1,
- "schemaVersion": "20261026134712",
+ "schemaVersion": "20261026224620",
"sourceCompanyId": "schema-baseline",
"sourceCompanyGroupId": null,
"sourceCompanyName": null,
- "exportedAt": "2026-10-26T20:21:00.335Z",
+ "exportedAt": "2026-10-26T22:56:32.405Z",
"exportedBy": "schema-baseline",
"label": "schema baseline",
"includeStorage": "none",
@@ -1396,7 +1396,8 @@
"optimizedAt",
"optimizedSize",
"originalSize",
- "originalPath"
+ "originalPath",
+ "pmiPath"
]
},
{
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
index db8ef81905..0b240b19ec 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.closure.test.ts
@@ -835,7 +835,8 @@ describe("cross-company restore invariants", () => {
"originalPath",
"optimizedModelPath",
"glbPath",
- "graphPath"
+ "graphPath",
+ "pmiPath"
] as const satisfies readonly ModelUploadPathColumn[];
// Fails to compile when a new `*Path` column exists that the list omits.
type _EveryPathColumnListed =
diff --git a/packages/jobs/src/inngest/functions/tasks/company-backup.ts b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
index ce079fe06b..2f36d394bc 100644
--- a/packages/jobs/src/inngest/functions/tasks/company-backup.ts
+++ b/packages/jobs/src/inngest/functions/tasks/company-backup.ts
@@ -64,7 +64,8 @@ export const STORAGE_PATH_COLUMNS = new Set([
"originalPath",
"optimizedModelPath",
"glbPath",
- "graphPath"
+ "graphPath",
+ "pmiPath"
]);
/**
diff --git a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
index cc5f58e1b5..5dfa9fb5f1 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-optimize.ts
@@ -36,12 +36,15 @@ type IngestOutputs = {
glb?: { bytes?: number };
raw?: { bytes?: number };
thumbnail?: { bytes?: number };
+ pmi?: { bytes?: number; items?: number; views?: number };
};
/**
* Model ingest on upload: one assembler job reads the raw once and writes the
* optimised GLB (`optimizedModelPath`, the preview), the raw's compact form
- * (STEP → BinXCAF `.xbf.zst`, mesh → `.zst`), and the preview thumbnail. Before
+ * (STEP → BinXCAF `.xbf.zst`, mesh → `.zst`), the preview thumbnail, and —
+ * for a STEP with PMI (dimensions, tolerances, datums, saved views) — the
+ * `pmi.json` the viewer draws (`pmiPath`; null when the model has none). Before
* this they were three jobs, each downloading and parsing the raw again.
* Separate from assembly-convert, which produces the lossless GLB and graph
* the assembly viewer needs, and only on demand.
@@ -163,6 +166,9 @@ export const modelOptimizeFunction = inngest.createFunction(
// URL, so reusing a path would keep showing the browser-cached image.
const run = event.id ?? event.ts ?? "run";
const thumbnailPath = `${companyId}/thumbnails/${modelUploadId}/${modelUploadId}-${run}.png`;
+ // Unique per run, like the thumbnail: two runs of one model (a forced
+ // regen beside a retry) never write, or remove, each other's file.
+ const pmiPath = `${companyId}/models/${modelUploadId}/pmi-${run}.json`;
// Idempotent per model — a re-run attaches to the in-flight optimise. A
// FORCED regen must not: the assembler's job store keeps completed results
// (24h TTL), so the stable id would attach to the previous run's result.
@@ -187,7 +193,9 @@ export const modelOptimizeFunction = inngest.createFunction(
source: { url: internalizeStorageUrl(signedUrl), format },
output: { path: optimizedPath },
...(compact ? { compact: { path: compact.path } } : {}),
- thumbnail: { path: thumbnailPath }
+ thumbnail: { path: thumbnailPath },
+ // Written only when the model carries PMI.
+ pmi: { path: pmiPath }
// quality omitted → the service applies its size-adaptive policy.
};
},
@@ -197,6 +205,7 @@ export const modelOptimizeFunction = inngest.createFunction(
return signUploadUrls({
glb: { bucket, path: optimizedPath },
thumbnail: { bucket, path: thumbnailPath },
+ pmi: { bucket, path: pmiPath },
...(compact
? {
raw: {
@@ -213,18 +222,24 @@ export const modelOptimizeFunction = inngest.createFunction(
const stats: Json = optimize.stats;
await step.run("persist", async () => {
- // Read the thumbnail now, not at queue time: an earlier run's thumbnail
- // is superseded too.
- const superseded = outputs.thumbnail
- ? (await getModelUpload(companyId, modelUploadId))?.thumbnailPath
- : null;
+ // Read the row now, not at queue time: an earlier run's thumbnail is
+ // superseded too.
+ const current = await getModelUpload(companyId, modelUploadId);
+ const superseded = outputs.thumbnail ? current?.thumbnailPath : null;
+ // An earlier run's pmi.json is superseded either way: by this run's, or
+ // by "no PMI" (the model has none, or this run could not read it).
+ const stalePmi =
+ current?.pmiPath && current.pmiPath !== pmiPath
+ ? current.pmiPath
+ : null;
await updateModelUpload(companyId, modelUploadId, {
optimizeStatus: "Success",
optimizeError: null,
optimizedModelPath: optimizedPath,
optimizedSize: outputs.glb?.bytes ?? null,
optimizedAt: datetime.timestamp(),
- ...(outputs.thumbnail ? { thumbnailPath } : {})
+ ...(outputs.thumbnail ? { thumbnailPath } : {}),
+ pmiPath: outputs.pmi ? pmiPath : null
});
// Drop the superseded thumbnail (best-effort — never fail the run over it).
if (superseded && superseded !== thumbnailPath) {
@@ -239,6 +254,18 @@ export const modelOptimizeFunction = inngest.createFunction(
});
}
}
+ if (stalePmi) {
+ const removed = await storage(getCarbonServiceRole())
+ .company(companyId)
+ .remove([stalePmi]);
+ if (removed.error) {
+ logger.warn("failed to remove the superseded pmi.json", {
+ modelUploadId,
+ path: stalePmi,
+ error: removed.error
+ });
+ }
+ }
});
if (compact) {
diff --git a/packages/jobs/src/inngest/functions/tasks/model-rows.ts b/packages/jobs/src/inngest/functions/tasks/model-rows.ts
index 0b30322324..9156826567 100644
--- a/packages/jobs/src/inngest/functions/tasks/model-rows.ts
+++ b/packages/jobs/src/inngest/functions/tasks/model-rows.ts
@@ -35,6 +35,7 @@ export type ModelUploadRow = {
glbPath: string | null;
graphPath: string | null;
thumbnailPath: string | null;
+ pmiPath: string | null;
};
export async function getModelUpload(
@@ -54,7 +55,8 @@ export async function getModelUpload(
"optimizedModelPath",
"glbPath",
"graphPath",
- "thumbnailPath"
+ "thumbnailPath",
+ "pmiPath"
])
.where("id", "=", modelUploadId)
.where("companyId", "=", companyId)
diff --git a/packages/viewer/AGENTS.md b/packages/viewer/AGENTS.md
index ba0d7d6c8f..fcdf53feec 100644
--- a/packages/viewer/AGENTS.md
+++ b/packages/viewer/AGENTS.md
@@ -11,6 +11,7 @@
- **Sub-assemblies** (`subassembly.ts`) — a header step (`isSubAssembly`) groups the steps whose `parentStepId` points at it; those steps sit directly before it in play order and are BUILT ON THEIR OWN: while one is active the player isolates its sub-assembly's parts (focus-style, ancestors kept, not cleared by playback, framed on their own bounds). A header's `usedInStepId` names the later step that carries the finished unit in. A header whose `motion` is not `none` has a path of its own: the unit plays it (`buildStepClip`'s `units`, one after another in sub-assembly order) before the step's own parts move — a step with no animation of its own fades its parts in only after those units seat (`fadeProgress`). One `stepClipTiming` per step feeds the timeline segment, the clip and the fade delay; while picking components it gives the units and the glide no time. `buildCarryPlans` is THE per-step answer to which units fly (`pathUnits`), which glide, what the step's own insertion moves (`ownMovingPartIds`) and whether the step is an unused header joining on its own path (`joinsOnOwnPath`: that path is the header's motion, so it has no insertion of its own); `carriesUnits` says whether a step brings any unit in. The clip, the fade, the path editor and the framing all read it. Each header's unit parts come from `buildSubAssemblyPlan` (`unitPartIds`). A unit whose header has no path of its own (`motion` `none`) glides from beside the build (`CARRY_IN_GLIDE_SECONDS` / `buildStepClip`'s `glide.nodeIds`), then rides the using step's insertion. A header nothing uses is where its unit joins the main build; a USED header plays nothing (0-length segment, skipped by prev/next). A step whose own insertion moves nothing (`stepClipTiming`'s `ownParts: false`, e.g. a header joining on its own path) gets a slot of just its units and the hold — the fixed `none` slot is for process-only steps and own parts that fade in. No nesting — a step USES a finished sub-assembly instead, so chains of any length work. `arrivalIndexByNode(steps, world)` is THE answer to "when does this part appear in the build on screen" and drives visibility; `validateSubAssemblies` is THE structural rule the ERP service and editor share. `scopeStepIds` limits the timeline to an opened sub-assembly.
- **Motion** — discriminated union `linear | L | helix | path | waypoints | none`. `waypoints` is editor-authored: poses relative to the seated pose, turning about the moving set's seated bounds center, then shifting (`waypointMatrix`), so one motion fits a part, a rigid group or a sub-assembly. The player takes that center from graph.json's seated bounds for the clip (`buildStepClip`'s required `pivot`), the path editor and the framed start pose alike — the live nodes are mid-animation when framing runs. `resampleEased` keeps every input keyframe (at its eased time) besides its evenly spaced samples, so easing never cuts a turning leg's 15° samples short. The path editor saves `linear`/`L` until a waypoint is turned (`editorWaypointsToMotion`); it has a Move / Rotate tool (`pathToolLabels` on the player, host-translated — no labels, no switch): Rotate shows drei `TransformControls` rings on the selected waypoint and stops the spheres dragging, because the rings' invisible free-rotation grip sits over the sphere. Insertion motion; the player derives removal (reverse) and start poses. `flagged`/`blockedBy` steps use `none` and fade in (no collision-free path exists — a synthesized path would clip through geometry).
- **Artifact tiers** — a model renders from best-available: LOD GLB → optimised GLB → lossless GLB → raw WASM (in-browser occt-import-js) fallback.
+- **pmi.json** (`PmiDocument`, `pmi.ts`) — a STEP AP242 model's PMI (dimensions, geometric tolerances, datums, graphic-only notes, saved views), written by the optimize ingest (`crates/converter/src/pmi.rs` is the other half of the contract). World mm in the optimised GLB's frame; each referenced face ships its own triangles, so the highlight never depends on the GLB's mesh layout. `ModelPreview` takes `pmiUrl`, draws it through `PmiLayer` inside `ModelCanvas`, and lists it in the PMI panel; `formatPmiItem` builds every label (mm/in, the file's decimals only in its own unit). Only over a server GLB — never the raw tier.
## Always
@@ -25,6 +26,7 @@
## Ask First
- Changing `types.ts` (`Motion`, `AssemblyGraph`, `AssemblyPlan`, `AssemblyStep`) — these are a shared contract with the geometry service and the ERP/Inngest layer; change all three together (see the header comment in `types.ts`).
+- Changing the `pmi.ts` types — a contract with `crates/converter/src/pmi.rs`; an incompatible change bumps `PMI_VERSION` on both sides (`parsePmiDocument` drops any other version).
- Bumping `CURRENT_PLAN_VERSION` — it invalidates every stored plan and forces a re-plan across the fleet; coordinate with the geometry service's `PLAN_VERSION`. (Note: the heuristic step-building in `plan.ts` is tuned freely and is NOT a version event.)
## Never
@@ -36,7 +38,7 @@
## Validation Commands
```bash
-pnpm --filter @carbon/viewer test # vitest — camera, clip, display, fallback, graph, keyframes, orientation, path-editing, plan, quat, step-flags, subassembly, timing, validate-motion, visibility (shared helpers: src/test-utils.ts)
+pnpm --filter @carbon/viewer test # vitest — camera, clip, display, fallback, graph, keyframes, orientation, path-editing, plan, pmi, quat, step-flags, subassembly, timing, validate-motion, visibility (shared helpers: src/test-utils.ts)
pnpm --filter @carbon/viewer typecheck # tsc --noEmit
```
@@ -47,7 +49,7 @@ pnpm --filter @carbon/viewer typecheck # tsc --noEmit
| `.` | `AssemblyPlayer` (+ `AssemblyPlayerHandle`/`Props`), `AssemblyViewer`, `ModelCanvas`, all plan/motion/graph/camera/describe/visibility helpers and types |
| `./steps` | Three-free plan→steps logic for server code: `buildAssemblyStepGroups`, `assignStepPhases`, `indexAssemblyGraph`, `CURRENT_PLAN_VERSION`, the sub-assembly structure helpers, and the step flags `isSavedView` / `hasCustomMotion` / `isPlanFlagged` (also on `.`) |
| `./canvas` | `ModelCanvas` — standalone static GLB viewer (orbit + view, no steps) |
-| `./model-preview` | `ModelPreview` — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view |
+| `./model-preview` | `ModelPreview` — progressive multi-tier preview (LOD → optimised → raw WASM), lazy-loads three.js on scroll-into-view; `pmiUrl` adds the PMI layer and panel |
| `./optimize-progress` | `OptimizeProgress` — optimise-status chip |
| `./use-optimized-model` | `useOptimizedModel` — TanStack Query polling of the model optimise lifecycle (shared by ERP `CadModel` + MES model tab) |
diff --git a/packages/viewer/src/ModelCanvas.tsx b/packages/viewer/src/ModelCanvas.tsx
index 142ee42929..f8697a5cfd 100644
--- a/packages/viewer/src/ModelCanvas.tsx
+++ b/packages/viewer/src/ModelCanvas.tsx
@@ -4,7 +4,7 @@
import { useThree } from "@react-three/fiber";
import type { MutableRefObject } from "react";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { LuRotateCw } from "react-icons/lu";
import {
Box3,
@@ -15,6 +15,15 @@ import {
} from "three";
import type { OrbitControls as OrbitControlsImpl } from "three-stdlib";
import { AssemblyViewer } from "./AssemblyViewer";
+import { PmiLayer } from "./PmiLayer";
+import {
+ type PmiBounds,
+ type PmiDisplayUnit,
+ type PmiDocument,
+ pmiItemBounds,
+ pmiViewBounds,
+ visibleItemIds
+} from "./pmi";
import { useAssembly } from "./useAssembly";
import { cn } from "./utils";
@@ -30,6 +39,15 @@ export type ModelMetrics = {
volume: number | null;
};
+/**
+ * Turn the camera to a PMI item (face its annotation plane and fit it) or a
+ * saved view (its direction and up, fitting its items). A new `seq` repeats
+ * the request.
+ */
+export type PmiFocusRequest =
+ | { kind: "item"; id: string; seq: number }
+ | { kind: "view"; id: string; seq: number };
+
export type ModelCanvasProps = {
/** URL of a meshopt-compressed GLB (the assembler's optimised / LOD artifact). */
glbUrl: string | null;
@@ -55,6 +73,20 @@ export type ModelCanvasProps = {
/** Fired once with the loaded model's measurements (bbox always; area/volume
* when the mesh is small enough to measure client-side). */
onMetrics?: (metrics: ModelMetrics) => void;
+ /** The model's PMI (`pmi.json`), drawn over the model when `pmiVisible`. */
+ pmi?: PmiDocument | null;
+ /** The PMI items to draw (default: all). */
+ pmiVisibleIds?: Set<string>;
+ /** The PMI item drawn blue and on top. */
+ pmiSelectedId?: string | null;
+ /** Show the PMI layer (default true). */
+ pmiVisible?: boolean;
+ /** Display unit of the PMI text labels (default mm). */
+ pmiUnit?: PmiDisplayUnit;
+ /** Fired when a PMI text label is clicked. */
+ onPmiSelect?: (id: string) => void;
+ /** Turn the camera to a PMI item or saved view (see `PmiFocusRequest`). */
+ focusRequest?: PmiFocusRequest | null;
className?: string;
};
@@ -82,6 +114,13 @@ export function ModelCanvas({
viewDirectionRef,
onLoaded,
onMetrics,
+ pmi = null,
+ pmiVisibleIds,
+ pmiSelectedId = null,
+ pmiVisible = true,
+ pmiUnit = "mm",
+ onPmiSelect,
+ focusRequest = null,
className
}: ModelCanvasProps) {
const [reloadKey, setReloadKey] = useState(0);
@@ -114,6 +153,14 @@ export function ModelCanvas({
autoFrame={autoFrame}
resetSignal={resetSignal}
viewDirectionRef={viewDirectionRef}
+ pmi={pmi}
+ pmiVisibleIds={pmiVisibleIds}
+ pmiSelectedId={pmiSelectedId}
+ pmiVisible={pmiVisible}
+ pmiUnit={pmiUnit}
+ onPmiSelect={onPmiSelect}
+ focusRequest={focusRequest}
+ mode={mode}
/>
)}
</AssemblyViewer>
@@ -202,16 +249,45 @@ function useLoadedObject(
return state;
}
+/** Models are Z-up; a saved PMI view may set another up, which reset undoes. */
+const MODEL_UP = new Vector3(0, 0, 1);
+
+/** A focused PMI item's box is grown to at least this share of the model's
+ * diagonal, so a tiny datum does not put the camera inside the near plane. */
+const MIN_FOCUS_FRACTION = 0.15;
+
+/** How much wider than its bounding sphere a focused PMI item is framed. */
+const PMI_FOCUS_MARGIN = 1.6;
+
+const toBox3 = (bounds: PmiBounds) =>
+ new Box3(new Vector3(...bounds.min), new Vector3(...bounds.max));
+
function ModelScene({
scene,
autoFrame,
resetSignal,
- viewDirectionRef
+ viewDirectionRef,
+ pmi,
+ pmiVisibleIds,
+ pmiSelectedId,
+ pmiVisible,
+ pmiUnit,
+ onPmiSelect,
+ focusRequest,
+ mode
}: {
scene: Object3D;
autoFrame: boolean;
resetSignal: number;
viewDirectionRef?: MutableRefObject<(() => ViewDirection) | null>;
+ pmi: PmiDocument | null;
+ pmiVisibleIds?: Set<string>;
+ pmiSelectedId: string | null;
+ pmiVisible: boolean;
+ pmiUnit: PmiDisplayUnit;
+ onPmiSelect?: (id: string) => void;
+ focusRequest: PmiFocusRequest | null;
+ mode: "dark" | "light";
}) {
const camera = useThree((state) => state.camera);
const controls = useThree(
@@ -237,8 +313,13 @@ function ModelScene({
// renderer's logarithmic depth buffer (`logarithmicDepthBuffer` on the Canvas)
// plus the near/far fit above.
+ // `direction` (from the target towards the camera), `up` and `margin` are
+ // for the PMI focus; without them the camera keeps where it looks from.
const frameBox = useCallback(
- (box: Box3) => {
+ (
+ box: Box3,
+ aim?: { direction?: Vector3; up?: Vector3; margin?: number }
+ ) => {
if (box.isEmpty() || !controls) return;
const center = box.getCenter(new Vector3());
const radius = box.getSize(new Vector3()).length() / 2;
@@ -246,15 +327,15 @@ function ModelScene({
// Fit the bounding sphere with a small margin. Lower factors zoom in more —
// the sphere circumscribes the model, so a tight fit still leaves headroom.
const distance = Math.max(
- (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * 1.1,
+ (radius / Math.tan(((fov / 2) * Math.PI) / 180)) * (aim?.margin ?? 1.1),
radius * 1.5
);
- const direction = camera.position
- .clone()
- .sub(controls.target)
- .normalize();
+ const direction =
+ aim?.direction?.clone().normalize() ??
+ camera.position.clone().sub(controls.target).normalize();
// Front-top-right isometric (models are Z-up, -Y front).
if (direction.lengthSq() === 0) direction.set(1, -1, 1).normalize();
+ if (aim?.up) camera.up.copy(aim.up).normalize();
camera.position.copy(center).addScaledVector(direction, distance);
controls.target.copy(center);
controls.update();
@@ -276,8 +357,71 @@ function ModelScene({
useEffect(() => {
if (resetSignal === resetSeenRef.current) return;
resetSeenRef.current = resetSignal;
+ // A saved PMI view may have turned the camera's up; reset stands it
+ // upright again (a no-op otherwise).
+ if (!camera.up.equals(MODEL_UP)) camera.up.copy(MODEL_UP);
frameBox(new Box3().setFromObject(scene));
- }, [resetSignal, scene, frameBox]);
+ }, [resetSignal, scene, frameBox, camera]);
+
+ // Turn to a PMI item or saved view, once per request.
+ const focusSeenRef = useRef<number | null>(null);
+ useEffect(() => {
+ if (!focusRequest || !pmi || !controls) return;
+ if (focusRequest.seq === focusSeenRef.current) return;
+ focusSeenRef.current = focusRequest.seq;
+ const modelBox = new Box3().setFromObject(scene);
+
+ if (focusRequest.kind === "view") {
+ const view = pmi.views.find((v) => v.id === focusRequest.id);
+ if (!view) return;
+ const bounds = pmiViewBounds(pmi, view.id);
+ frameBox(bounds ? toBox3(bounds) : modelBox, {
+ // The view looks from the camera towards the model; the camera sits
+ // on the other side.
+ direction: new Vector3(...view.direction).negate(),
+ up: new Vector3(...view.up)
+ });
+ return;
+ }
+
+ const item = pmi.items.find((i) => i.id === focusRequest.id);
+ if (!item) return;
+ const bounds = pmiItemBounds(pmi, item, true);
+ if (!bounds) return;
+ const box = toBox3(bounds);
+ const minSize =
+ modelBox.getSize(new Vector3()).length() * MIN_FOCUS_FRACTION;
+ const size = box.getSize(new Vector3()).length();
+ if (size < minSize) box.expandByScalar((minSize - size) / 2);
+
+ let direction: Vector3 | undefined;
+ let up = MODEL_UP;
+ if (item.plane) {
+ const normal = new Vector3(...item.plane.normal);
+ if (normal.lengthSq() > 0) {
+ // Face the plane from whichever side the camera is on now.
+ const current = camera.position.clone().sub(controls.target);
+ direction = normal.dot(current) < 0 ? normal.clone().negate() : normal;
+ // Stand the annotation upright: the plane's own Y axis (normal × X)
+ // is up, so its text reads left to right. Z-up would leave a plane
+ // lying flat (normal ±Z) at whatever turn the camera happens to take.
+ const planeUp = new Vector3()
+ .crossVectors(
+ new Vector3(...item.plane.normal),
+ new Vector3(...item.plane.xDirection)
+ )
+ .normalize();
+ if (planeUp.lengthSq() > 0) up = planeUp;
+ }
+ }
+ // Wider than a model fit: the referenced faces sit at the box's edge.
+ frameBox(box, { direction, up, margin: PMI_FOCUS_MARGIN });
+ }, [focusRequest, pmi, controls, scene, camera, frameBox]);
+
+ const allPmiIds = useMemo(
+ () => (pmi ? visibleItemIds(pmi, null) : new Set<string>()),
+ [pmi]
+ );
useEffect(() => {
if (!viewDirectionRef || !controls) return;
@@ -293,7 +437,21 @@ function ModelScene({
};
}, [viewDirectionRef, camera, controls]);
- return <primitive object={scene} />;
+ return (
+ <>
+ <primitive object={scene} />
+ {pmi && pmiVisible && (
+ <PmiLayer
+ doc={pmi}
+ visibleIds={pmiVisibleIds ?? allPmiIds}
+ selectedId={pmiSelectedId}
+ mode={mode}
+ unit={pmiUnit}
+ onSelect={onPmiSelect}
+ />
+ )}
+ </>
+ );
}
/** Bounding-box dimensions (always) + surface area / volume (small meshes). */
diff --git a/packages/viewer/src/ModelPreview.tsx b/packages/viewer/src/ModelPreview.tsx
index c86565b976..ea24ec6097 100644
--- a/packages/viewer/src/ModelPreview.tsx
+++ b/packages/viewer/src/ModelPreview.tsx
@@ -3,19 +3,42 @@
// including ports, remain AGPLv3; serving them over a network requires releasing their source.
import { Button, cn, IconButton } from "@carbon/react";
-import { lazy, Suspense, useEffect, useMemo, useRef, useState } from "react";
+import {
+ lazy,
+ Suspense,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from "react";
import {
LuBox,
LuCamera,
LuChevronDown,
LuDownload,
+ LuEye,
+ LuEyeOff,
LuMaximize,
LuRotateCw,
LuTrash2,
LuTriangleAlert,
LuX
} from "react-icons/lu";
-import type { ModelMetrics, ViewDirection } from "./ModelCanvas";
+import type {
+ ModelMetrics,
+ PmiFocusRequest,
+ ViewDirection
+} from "./ModelCanvas";
+import {
+ formatPmiItem,
+ groupPmiItems,
+ type PmiDisplayUnit,
+ type PmiDocument,
+ type PmiItem,
+ parsePmiDocument,
+ visibleItemIds
+} from "./pmi";
import { isRawRenderable } from "./raw/formats";
// The three.js renderer is code-split: a page with a model ships only this tier
@@ -47,6 +70,9 @@ export type ModelPreviewProps = {
optimizedUrl?: string | null;
/** Lossless assembly GLB — used as the interactive tier if no optimised one. */
glbUrl?: string | null;
+ /** The model's `pmi.json` (PMI read from its STEP AP242 source). When it
+ * holds items, a PMI panel lists them and the server model draws them. */
+ pmiUrl?: string | null;
/** Static poster image (thumbnail PNG) shown before any 3D loads. */
thumbnailUrl?: string | null;
/** The raw uploaded file's auth-proxied URL — the WASM fallback tier renders
@@ -100,6 +126,7 @@ export function ModelPreview({
lodUrl = null,
optimizedUrl = null,
glbUrl = null,
+ pmiUrl = null,
thumbnailUrl = null,
rawUrl = null,
optimizing = false,
@@ -132,6 +159,62 @@ export function ModelPreview({
if (awaitingModel) setWaitDismissed(false);
}, [awaitingModel]);
+ // One display unit for Measurements and PMI. A model whose PMI names its
+ // source unit starts there, unless the user has already picked one.
+ const [unit, setUnit] = useState<UnitSystem>("imperial");
+ const unitPickedRef = useRef(false);
+ const changeUnit = useCallback((next: UnitSystem) => {
+ unitPickedRef.current = true;
+ setUnit(next);
+ }, []);
+
+ const pmi = usePmiDocument(pmiUrl);
+ useEffect(() => {
+ if (!pmi?.sourceUnit || unitPickedRef.current) return;
+ setUnit(pmi.sourceUnit === "mm" ? "metric" : "imperial");
+ }, [pmi]);
+
+ const [pmiVisible, setPmiVisible] = useState(true);
+ const [pmiViewId, setPmiViewId] = useState<string | null>(null);
+ const [pmiSelectedId, setPmiSelectedId] = useState<string | null>(null);
+ const [focusRequest, setFocusRequest] = useState<PmiFocusRequest | null>(
+ null
+ );
+ const focusSeqRef = useRef(0);
+ // A new document starts with nothing picked.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: resets on a new document without reading it
+ useEffect(() => {
+ setPmiViewId(null);
+ setPmiSelectedId(null);
+ setFocusRequest(null);
+ }, [pmi]);
+ const pmiVisibleIds = useMemo(
+ () => (pmi ? visibleItemIds(pmi, pmiViewId) : undefined),
+ [pmi, pmiViewId]
+ );
+ // Picking the selected item again clears it; picking another turns to it.
+ const selectPmiItem = useCallback(
+ (id: string) => {
+ if (pmiSelectedId === id) {
+ setPmiSelectedId(null);
+ return;
+ }
+ setPmiSelectedId(id);
+ setPmiVisible(true);
+ focusSeqRef.current += 1;
+ setFocusRequest({ kind: "item", id, seq: focusSeqRef.current });
+ },
+ [pmiSelectedId]
+ );
+ const selectPmiView = useCallback((viewId: string | null) => {
+ setPmiViewId(viewId);
+ setPmiSelectedId(null);
+ if (viewId) {
+ focusSeqRef.current += 1;
+ setFocusRequest({ kind: "view", id: viewId, seq: focusSeqRef.current });
+ }
+ }, []);
+
const interactiveUrl = optimizedUrl ?? glbUrl;
// The instant 3D layer: the LOD if it's distinct from the interactive model
// (else the interactive model is the only 3D layer).
@@ -209,6 +292,13 @@ export function ModelPreview({
viewDirectionRef={viewDirectionRef}
onLoaded={() => setFullLoaded(true)}
onMetrics={setMetrics}
+ pmi={pmi}
+ pmiVisible={pmiVisible}
+ pmiVisibleIds={pmiVisibleIds}
+ pmiSelectedId={pmiSelectedId}
+ pmiUnit={unit === "metric" ? "mm" : "in"}
+ onPmiSelect={selectPmiItem}
+ focusRequest={focusRequest}
/>
)}
</div>
@@ -275,8 +365,34 @@ export function ModelPreview({
</div>
)}
- {/* Measurements + unit toggle (top-left), like the WASM viewer. */}
- {metrics && fullLoaded && <ModelMetricsPanel metrics={metrics} />}
+ {/* Measurements + unit toggle (top-left), like the WASM viewer, and
+ the PMI under it — only over the server model, which draws it. */}
+ {fullLoaded &&
+ (metrics || (hasServerModel && pmi && pmi.items.length > 0)) && (
+ <div className="absolute left-2 top-2 z-20 flex flex-col items-start gap-2">
+ {metrics && (
+ <ModelMetricsPanel
+ metrics={metrics}
+ unit={unit}
+ onUnitChange={changeUnit}
+ />
+ )}
+ {hasServerModel && pmi && pmi.items.length > 0 && (
+ <PmiPanel
+ doc={pmi}
+ unit={unit === "metric" ? "mm" : "in"}
+ visible={pmiVisible}
+ onVisibleChange={setPmiVisible}
+ viewId={pmiViewId}
+ onViewChange={selectPmiView}
+ visibleIds={pmiVisibleIds}
+ selectedId={pmiSelectedId}
+ onSelect={selectPmiItem}
+ onUnitChange={changeUnit}
+ />
+ )}
+ </div>
+ )}
{/* Click-to-interact gate. */}
{fullLoaded && !interactive && (
@@ -418,8 +534,15 @@ type UnitSystem = "metric" | "imperial";
const MM_PER_IN = 25.4;
/** Dimensions + surface area / volume, with an mm/in toggle. Model space is mm. */
-function ModelMetricsPanel({ metrics }: { metrics: ModelMetrics }) {
- const [unit, setUnit] = useState<UnitSystem>("imperial");
+function ModelMetricsPanel({
+ metrics,
+ unit,
+ onUnitChange
+}: {
+ metrics: ModelMetrics;
+ unit: UnitSystem;
+ onUnitChange: (unit: UnitSystem) => void;
+}) {
const [open, setOpen] = useState(false);
const imperial = unit === "imperial";
@@ -443,7 +566,7 @@ function ModelMetricsPanel({ metrics }: { metrics: ModelMetrics }) {
return (
<div
className={cn(
- "absolute left-2 top-2 z-20 rounded-lg border border-border bg-popover p-2.5 text-xs text-popover-foreground shadow-md",
+ "rounded-lg border border-border bg-popover p-2.5 text-xs text-popover-foreground shadow-md",
open ? "w-56" : "w-auto"
)}
>
@@ -459,7 +582,7 @@ function ModelMetricsPanel({ metrics }: { metrics: ModelMetrics }) {
/>
Measurements
</button>
- {open && <UnitToggle unit={unit} onChange={setUnit} />}
+ {open && <UnitToggle unit={unit} onChange={onUnitChange} />}
</div>
{open && (
@@ -508,6 +631,201 @@ function ModelMetricsPanel({ metrics }: { metrics: ModelMetrics }) {
);
}
+/**
+ * The model's PMI: an eye toggle for the layer, the saved views, and the items
+ * by kind. Picking an item turns it blue and turns the camera to it; picking
+ * it again clears it. Copies the Measurements card.
+ */
+function PmiPanel({
+ doc,
+ unit,
+ visible,
+ onVisibleChange,
+ viewId,
+ onViewChange,
+ visibleIds,
+ selectedId,
+ onSelect,
+ onUnitChange
+}: {
+ doc: PmiDocument;
+ unit: PmiDisplayUnit;
+ visible: boolean;
+ onVisibleChange: (visible: boolean) => void;
+ viewId: string | null;
+ onViewChange: (viewId: string | null) => void;
+ visibleIds: Set<string> | undefined;
+ selectedId: string | null;
+ onSelect: (id: string) => void;
+ onUnitChange: (unit: UnitSystem) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const groups = useMemo(
+ () =>
+ groupPmiItems(doc)
+ .map((group) => ({
+ ...group,
+ items: visibleIds
+ ? group.items.filter((item) => visibleIds.has(item.id))
+ : group.items
+ }))
+ .filter((group) => group.items.length > 0),
+ [doc, visibleIds]
+ );
+
+ return (
+ <div
+ className={cn(
+ "rounded-lg border border-border bg-popover p-2.5 text-xs text-popover-foreground shadow-md",
+ open ? "w-64" : "w-auto"
+ )}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <button
+ type="button"
+ onClick={() => setOpen((o) => !o)}
+ aria-expanded={open}
+ className="flex items-center gap-1 text-[10px] font-medium uppercase tracking-wide text-muted-foreground transition-colors hover:text-foreground"
+ >
+ <LuChevronDown
+ className={cn("size-3 transition-transform", !open && "-rotate-90")}
+ />
+ PMI
+ <span className="tabular-nums">{doc.items.length}</span>
+ </button>
+ <IconButton
+ aria-label={visible ? "Hide PMI" : "Show PMI"}
+ title={visible ? "Hide PMI" : "Show PMI"}
+ className="-my-1 text-muted-foreground"
+ icon={visible ? <LuEye /> : <LuEyeOff />}
+ variant="ghost"
+ size="sm"
+ onClick={() => onVisibleChange(!visible)}
+ />
+ </div>
+
+ {open && (
+ <>
+ <div className="mt-2 flex justify-end">
+ <UnitToggle
+ unit={unit === "mm" ? "metric" : "imperial"}
+ onChange={onUnitChange}
+ />
+ </div>
+ {doc.views.length > 0 && (
+ <select
+ aria-label="Saved view"
+ value={viewId ?? ""}
+ onChange={(event) => onViewChange(event.target.value || null)}
+ className="mt-2 w-full rounded-md border-none bg-muted/60 px-2 py-1 text-[11px] font-medium text-foreground focus:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ <option value="">All PMI</option>
+ {doc.views.map((view) => (
+ <option key={view.id} value={view.id}>
+ {view.name}
+ </option>
+ ))}
+ </select>
+ )}
+
+ <div className="mt-2 flex max-h-64 flex-col gap-2 overflow-y-auto">
+ {groups.map((group) => (
+ <div key={group.kind} className="flex flex-col gap-0.5">
+ <span className="text-[10px] font-medium uppercase tracking-wide text-muted-foreground">
+ {group.title}
+ </span>
+ {group.items.map((item) => (
+ <PmiRow
+ key={item.id}
+ item={item}
+ unit={unit}
+ sourceUnit={doc.sourceUnit}
+ selected={item.id === selectedId}
+ onSelect={onSelect}
+ />
+ ))}
+ </div>
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ );
+}
+
+function PmiRow({
+ item,
+ unit,
+ sourceUnit,
+ selected,
+ onSelect
+}: {
+ item: PmiItem;
+ unit: PmiDisplayUnit;
+ sourceUnit: PmiDisplayUnit | null;
+ selected: boolean;
+ onSelect: (id: string) => void;
+}) {
+ const { label, symbol, title } = formatPmiItem(item, unit, sourceUnit);
+ // A tolerance prints as its frame (`⌖ | ⌀0.1 | A`) and a datum as its
+ // boxed letter, the way the drawing shows them.
+ const cells = item.kind === "tolerance" ? label.split(" | ") : null;
+ return (
+ <button
+ type="button"
+ title={title}
+ aria-pressed={selected}
+ onClick={() => onSelect(item.id)}
+ className={cn(
+ "flex w-full items-center gap-1.5 rounded px-1.5 py-1 text-left font-mono tabular-nums transition-colors hover:bg-accent",
+ selected && "bg-accent text-accent-foreground"
+ )}
+ >
+ {cells ? (
+ <span className="flex min-w-0 divide-x divide-border border border-border">
+ {cells.map((cell, index) => (
+ <span key={index} className="whitespace-nowrap px-1">
+ {cell}
+ </span>
+ ))}
+ </span>
+ ) : item.kind === "datum" ? (
+ <span className="border border-border px-1">{label}</span>
+ ) : (
+ <>
+ {symbol && <span>{symbol}</span>}
+ <span className="truncate">{label}</span>
+ </>
+ )}
+ </button>
+ );
+}
+
+/**
+ * Fetches and parses `pmi.json`. Null while loading, on any failure, or for a
+ * document the viewer cannot read — the preview then simply shows no PMI.
+ */
+function usePmiDocument(url: string | null): PmiDocument | null {
+ const [doc, setDoc] = useState<PmiDocument | null>(null);
+ useEffect(() => {
+ setDoc(null);
+ if (!url) return;
+ const controller = new AbortController();
+ fetch(url, { signal: controller.signal })
+ .then((response) => (response.ok ? response.json() : null))
+ .then((json: unknown) => {
+ if (!controller.signal.aborted) setDoc(parsePmiDocument(json));
+ })
+ .catch(() => {
+ // The preview works without PMI: a failed fetch just shows no panel
+ // (the request itself is in the network log).
+ if (!controller.signal.aborted) setDoc(null);
+ });
+ return () => controller.abort();
+ }, [url]);
+ return doc;
+}
+
/** iOS-style segmented mm/in toggle — lighter than the tab pills. */
function UnitToggle({
unit,
diff --git a/packages/viewer/src/PmiLayer.tsx b/packages/viewer/src/PmiLayer.tsx
new file mode 100644
index 0000000000..4a77baedc7
--- /dev/null
+++ b/packages/viewer/src/PmiLayer.tsx
@@ -0,0 +1,306 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { Html } from "@react-three/drei";
+import { useEffect, useMemo } from "react";
+import {
+ BufferAttribute,
+ BufferGeometry,
+ DoubleSide,
+ Float32BufferAttribute,
+ LineBasicMaterial,
+ MeshBasicMaterial
+} from "three";
+import {
+ formatPmiItem,
+ type PmiDisplayUnit,
+ type PmiDocument,
+ type PmiItem,
+ type PmiMesh,
+ pmiItemBounds
+} from "./pmi";
+import type { Vec3 } from "./types";
+import { cn } from "./utils";
+
+export type PmiLayerProps = {
+ doc: PmiDocument;
+ /** Items to draw; any other item renders nothing. */
+ visibleIds: Set<string>;
+ /** Drawn blue and on top, with its faces and edges highlighted. */
+ selectedId: string | null;
+ mode: "dark" | "light";
+ /** Display unit of the text labels (default mm). */
+ unit?: PmiDisplayUnit;
+ /** Fired when a text label is clicked. */
+ onSelect?: (id: string) => void;
+};
+
+const SELECTED_COLOR = 0x3b82f6;
+const FOREGROUND = { dark: 0xe4e4e7, light: 0x18181b } as const;
+const SELECTED_RENDER_ORDER = 10;
+/** Text labels are DOM nodes; past this they cost more than they show. */
+const MAX_LABELS = 200;
+
+type ItemGeometry = {
+ lines: BufferGeometry | null;
+ mesh: BufferGeometry | null;
+ /** Where a text label goes, for an item with no graphical PMI. */
+ labelAt: Vec3 | null;
+};
+
+/** Each polyline as consecutive segment pairs, merged into one geometry. */
+function segmentsGeometry(polylines: number[][]): BufferGeometry | null {
+ let count = 0;
+ for (const line of polylines) {
+ const points = Math.floor(line.length / 3);
+ if (points >= 2) count += (points - 1) * 6;
+ }
+ if (count === 0) return null;
+ const positions = new Float32Array(count);
+ let o = 0;
+ for (const line of polylines) {
+ const points = Math.floor(line.length / 3);
+ for (let p = 0; p + 1 < points; p++) {
+ for (let k = 0; k < 6; k++) positions[o++] = line[p * 3 + k] ?? 0;
+ }
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
+ return geometry;
+}
+
+/** Triangle meshes merged into one geometry (indexed when every one is). */
+function meshGeometry(meshes: PmiMesh[]): BufferGeometry | null {
+ const parts = meshes.filter((m) => m.positions.length >= 9);
+ if (parts.length === 0) return null;
+ const vertexCount = parts.reduce(
+ (n, m) => n + Math.floor(m.positions.length / 3),
+ 0
+ );
+ const positions = new Float32Array(vertexCount * 3);
+ const indexed = parts.every((m) => m.indices.length > 0);
+ const indices: number[] = [];
+ let base = 0;
+ for (const part of parts) {
+ const vertices = Math.floor(part.positions.length / 3);
+ positions.set(part.positions.slice(0, vertices * 3), base * 3);
+ if (indexed) {
+ for (const index of part.indices) indices.push(index + base);
+ }
+ base += vertices;
+ }
+ const geometry = new BufferGeometry();
+ geometry.setAttribute("position", new Float32BufferAttribute(positions, 3));
+ if (indexed) {
+ geometry.setIndex(
+ new BufferAttribute(
+ vertexCount > 65535
+ ? new Uint32Array(indices)
+ : new Uint16Array(indices),
+ 1
+ )
+ );
+ }
+ return geometry;
+}
+
+function labelAnchor(doc: PmiDocument, item: PmiItem): Vec3 | null {
+ if (item.textPosition) return item.textPosition;
+ const bounds = pmiItemBounds(doc, item, true);
+ if (!bounds) return null;
+ return [
+ (bounds.min[0] + bounds.max[0]) / 2,
+ (bounds.min[1] + bounds.max[1]) / 2,
+ (bounds.min[2] + bounds.max[2]) / 2
+ ];
+}
+
+/**
+ * The model's PMI in the scene: each item's graphical lines and filled text in
+ * the theme's foreground, depth-tested so the model hides what is behind it.
+ * The selected item draws blue on top, with its referenced faces and edges
+ * highlighted. An item with no graphical PMI gets a text label instead.
+ */
+export function PmiLayer({
+ doc,
+ visibleIds,
+ selectedId,
+ mode,
+ unit = "mm",
+ onSelect
+}: PmiLayerProps) {
+ const geometries = useMemo(() => {
+ const byId = new Map<string, ItemGeometry>();
+ for (const item of doc.items) {
+ const lines = segmentsGeometry(item.lines);
+ const mesh = item.mesh ? meshGeometry([item.mesh]) : null;
+ byId.set(item.id, {
+ lines,
+ mesh,
+ labelAt: lines || mesh ? null : labelAnchor(doc, item)
+ });
+ }
+ return byId;
+ }, [doc]);
+
+ useEffect(
+ () => () => {
+ for (const geometry of geometries.values()) {
+ geometry.lines?.dispose();
+ geometry.mesh?.dispose();
+ }
+ },
+ [geometries]
+ );
+
+ const highlight = useMemo(() => {
+ const item = selectedId
+ ? doc.items.find((candidate) => candidate.id === selectedId)
+ : undefined;
+ if (!item) return { faces: null, edges: null };
+ const faces = item.faces
+ .map((index) => doc.faces[index])
+ .filter((face): face is PmiMesh => Boolean(face));
+ const edges = item.edges
+ .map((index) => doc.edges[index])
+ .filter((edge): edge is number[] => Boolean(edge));
+ return { faces: meshGeometry(faces), edges: segmentsGeometry(edges) };
+ }, [doc, selectedId]);
+
+ useEffect(
+ () => () => {
+ highlight.faces?.dispose();
+ highlight.edges?.dispose();
+ },
+ [highlight]
+ );
+
+ const materials = useMemo(() => {
+ const color = FOREGROUND[mode];
+ return {
+ line: new LineBasicMaterial({ color }),
+ mesh: new MeshBasicMaterial({ color, side: DoubleSide }),
+ // Transparent (at full opacity) so the selection sorts after the
+ // model's own transparent materials too, and draws over them.
+ selectedLine: new LineBasicMaterial({
+ color: SELECTED_COLOR,
+ depthTest: false,
+ depthWrite: false,
+ transparent: true
+ }),
+ selectedMesh: new MeshBasicMaterial({
+ color: SELECTED_COLOR,
+ side: DoubleSide,
+ depthTest: false,
+ depthWrite: false,
+ transparent: true
+ }),
+ face: new MeshBasicMaterial({
+ color: SELECTED_COLOR,
+ side: DoubleSide,
+ transparent: true,
+ opacity: 0.5,
+ depthWrite: false,
+ polygonOffset: true,
+ polygonOffsetFactor: -1,
+ polygonOffsetUnits: -1
+ }),
+ edge: new LineBasicMaterial({
+ color: SELECTED_COLOR,
+ depthTest: false,
+ depthWrite: false,
+ transparent: true
+ })
+ };
+ }, [mode]);
+
+ useEffect(
+ () => () => {
+ for (const material of Object.values(materials)) material.dispose();
+ },
+ [materials]
+ );
+
+ const labels = useMemo(() => {
+ const out: { item: PmiItem; at: Vec3 }[] = [];
+ for (const item of doc.items) {
+ if (out.length >= MAX_LABELS) break;
+ if (!visibleIds.has(item.id)) continue;
+ const at = geometries.get(item.id)?.labelAt;
+ if (at) out.push({ item, at });
+ }
+ return out;
+ }, [doc, visibleIds, geometries]);
+
+ return (
+ <group>
+ {doc.items.map((item) => {
+ if (!visibleIds.has(item.id)) return null;
+ const geometry = geometries.get(item.id);
+ if (!geometry || (!geometry.lines && !geometry.mesh)) return null;
+ const selected = item.id === selectedId;
+ const renderOrder = selected ? SELECTED_RENDER_ORDER : 0;
+ return (
+ <group key={item.id}>
+ {geometry.lines && (
+ <lineSegments
+ geometry={geometry.lines}
+ material={selected ? materials.selectedLine : materials.line}
+ renderOrder={renderOrder}
+ />
+ )}
+ {geometry.mesh && (
+ <mesh
+ geometry={geometry.mesh}
+ material={selected ? materials.selectedMesh : materials.mesh}
+ renderOrder={renderOrder}
+ />
+ )}
+ </group>
+ );
+ })}
+ {selectedId && visibleIds.has(selectedId) && highlight.faces && (
+ <mesh
+ geometry={highlight.faces}
+ material={materials.face}
+ renderOrder={SELECTED_RENDER_ORDER - 1}
+ />
+ )}
+ {selectedId && visibleIds.has(selectedId) && highlight.edges && (
+ <lineSegments
+ geometry={highlight.edges}
+ material={materials.edge}
+ renderOrder={SELECTED_RENDER_ORDER - 1}
+ />
+ )}
+ {labels.map(({ item, at }) => {
+ const { label, title } = formatPmiItem(item, unit, doc.sourceUnit);
+ const selected = item.id === selectedId;
+ return (
+ <Html
+ key={item.id}
+ position={at}
+ center
+ // Below the preview's panels (z-20) and its interact gate (z-10).
+ zIndexRange={[5, 0]}
+ >
+ <button
+ type="button"
+ title={title}
+ onClick={() => onSelect?.(item.id)}
+ className={cn(
+ "whitespace-nowrap rounded-full border px-2 py-0.5 font-mono text-xs tabular-nums shadow-sm",
+ selected
+ ? "border-blue-500 bg-blue-500 text-white"
+ : "border-border bg-popover text-popover-foreground hover:bg-accent"
+ )}
+ >
+ {label}
+ </button>
+ </Html>
+ );
+ })}
+ </group>
+ );
+}
diff --git a/packages/viewer/src/index.ts b/packages/viewer/src/index.ts
index a6b656de54..50eff2ab15 100644
--- a/packages/viewer/src/index.ts
+++ b/packages/viewer/src/index.ts
@@ -31,7 +31,8 @@ export {
export {
ModelCanvas,
type ModelCanvasProps,
- type ModelMetrics
+ type ModelMetrics,
+ type PmiFocusRequest
} from "./ModelCanvas";
export {
type BuildTurn,
@@ -43,6 +44,7 @@ export {
turnOrientation,
upForOrientation
} from "./orientation";
+export { PmiLayer, type PmiLayerProps } from "./PmiLayer";
export {
type AssemblyPlan,
type AssemblyPlanComponent,
@@ -54,6 +56,31 @@ export {
planMotionForComponents,
type StepPhase
} from "./plan";
+export {
+ formatPmiItem,
+ groupPmiItems,
+ PMI_VERSION,
+ type PmiBounds,
+ type PmiDatum,
+ type PmiDimension,
+ type PmiDimensionType,
+ type PmiDisplayUnit,
+ type PmiDocument,
+ type PmiGroup,
+ type PmiGroupTitle,
+ type PmiItem,
+ type PmiItemLabel,
+ type PmiKind,
+ type PmiMesh,
+ type PmiPlane,
+ type PmiTolerance,
+ type PmiToleranceType,
+ type PmiView,
+ parsePmiDocument,
+ pmiItemBounds,
+ pmiViewBounds,
+ visibleItemIds
+} from "./pmi";
export { IDENTITY_QUAT as IDENTITY_ORIENTATION, sameOrientation } from "./quat";
export { hasCustomMotion, isPlanFlagged, isSavedView } from "./step-flags";
export {
diff --git a/packages/viewer/src/pmi.test.ts b/packages/viewer/src/pmi.test.ts
new file mode 100644
index 0000000000..188d48bfaa
--- /dev/null
+++ b/packages/viewer/src/pmi.test.ts
@@ -0,0 +1,444 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import { describe, expect, it } from "vitest";
+import {
+ formatPmiItem,
+ groupPmiItems,
+ type PmiDimension,
+ type PmiDocument,
+ type PmiItem,
+ type PmiTolerance,
+ parsePmiDocument,
+ pmiItemBounds,
+ pmiViewBounds,
+ visibleItemIds
+} from "./pmi";
+
+function item(overrides: Partial<PmiItem> & Pick<PmiItem, "id" | "kind">) {
+ return {
+ name: null,
+ dimension: null,
+ tolerance: null,
+ datum: null,
+ lines: [],
+ mesh: null,
+ plane: null,
+ textPosition: null,
+ faces: [],
+ edges: [],
+ ...overrides
+ } satisfies PmiItem;
+}
+
+function dimension(overrides: Partial<PmiDimension>): PmiItem {
+ return item({
+ id: "d1",
+ kind: "dimension",
+ dimension: {
+ type: "linearDistance",
+ value: 10,
+ upper: null,
+ lower: null,
+ upperBound: null,
+ lowerBound: null,
+ fitClass: null,
+ qualifier: null,
+ decimals: null,
+ modifiers: [],
+ descriptions: [],
+ ...overrides
+ }
+ });
+}
+
+function tolerance(overrides: Partial<PmiTolerance>): PmiItem {
+ return item({
+ id: "t1",
+ kind: "tolerance",
+ tolerance: {
+ type: "position",
+ value: 0.1,
+ zoneShape: null,
+ material: null,
+ zoneModifier: null,
+ zoneModifierValue: null,
+ modifiers: [],
+ maxValue: null,
+ datums: [],
+ ...overrides
+ }
+ });
+}
+
+function doc(overrides: Partial<PmiDocument> = {}): PmiDocument {
+ return {
+ version: 1,
+ unit: "mm",
+ sourceUnit: "mm",
+ items: [],
+ faces: [],
+ edges: [],
+ views: [],
+ ...overrides
+ };
+}
+
+const label = (
+ pmi: PmiItem,
+ unit: "mm" | "in" = "mm",
+ sourceUnit: "mm" | "in" | null = "mm"
+) => formatPmiItem(pmi, unit, sourceUnit).label;
+
+describe("parsePmiDocument", () => {
+ it("accepts a version 1 document and keeps extra fields", () => {
+ const json = {
+ ...doc({
+ items: [
+ dimension({ value: 5 }),
+ item({ id: "a1", kind: "datum", datum: null })
+ ],
+ faces: [{ positions: [0, 0, 0, 1, 0, 0, 0, 1, 0], indices: [0, 1, 2] }],
+ edges: [[0, 0, 0, 1, 1, 1]],
+ views: [
+ {
+ id: "v1",
+ name: "Front",
+ direction: [0, 1, 0],
+ up: [0, 0, 1],
+ projection: "parallel",
+ itemIds: ["d1"]
+ }
+ ]
+ }),
+ future: "field"
+ };
+ const parsed = parsePmiDocument(JSON.parse(JSON.stringify(json)));
+ expect(parsed?.items).toHaveLength(2);
+ expect(parsed?.views[0]?.name).toBe("Front");
+ });
+
+ it("reads a missing source unit as null", () => {
+ const { sourceUnit: _, ...rest } = doc();
+ expect(parsePmiDocument(rest)?.sourceUnit).toBeNull();
+ });
+
+ it("refuses another version or a wrong shape", () => {
+ expect(parsePmiDocument({ ...doc(), version: 2 })).toBeNull();
+ expect(parsePmiDocument({ ...doc(), items: {} })).toBeNull();
+ expect(parsePmiDocument({ ...doc(), views: [{ id: "v1" }] })).toBeNull();
+ expect(
+ parsePmiDocument({ ...doc(), items: [{ id: "x", kind: "weld" }] })
+ ).toBeNull();
+ expect(parsePmiDocument({ ...doc(), sourceUnit: "ft" })).toBeNull();
+ expect(parsePmiDocument(null)).toBeNull();
+ expect(parsePmiDocument("pmi")).toBeNull();
+ });
+});
+
+describe("formatPmiItem — dimensions", () => {
+ it("prints a symmetric tolerance as ±", () => {
+ expect(label(dimension({ value: 10, upper: 0.1, lower: -0.1 }))).toBe(
+ "10 ±0.1"
+ );
+ });
+
+ it("prints an asymmetric tolerance as + / −", () => {
+ expect(label(dimension({ value: 10, upper: 0.1, lower: -0.05 }))).toBe(
+ "10 +0.1 / −0.05"
+ );
+ expect(label(dimension({ value: 10, upper: 0.2, lower: 0 }))).toBe(
+ "10 +0.2 / 0"
+ );
+ });
+
+ it("prints limits instead of a nominal", () => {
+ expect(
+ label(dimension({ value: 10, upperBound: 10.1, lowerBound: 9.9 }))
+ ).toBe("10.1/9.9");
+ });
+
+ it("prints a hole fit class in upper case and a shaft in lower case", () => {
+ expect(
+ label(
+ dimension({
+ type: "diameter",
+ value: 12,
+ fitClass: { hole: true, formVariance: "h", grade: "IT7" }
+ })
+ )
+ ).toBe("⌀12 H7");
+ expect(
+ label(
+ dimension({
+ type: "diameter",
+ value: 12,
+ fitClass: { hole: false, formVariance: "G", grade: "IT6" }
+ })
+ )
+ ).toBe("⌀12 g6");
+ });
+
+ it("prefixes diameters and radii", () => {
+ expect(label(dimension({ type: "diameter", value: 8 }))).toBe("⌀8");
+ expect(label(dimension({ type: "sphericalDiameter", value: 8 }))).toBe(
+ "S⌀8"
+ );
+ expect(label(dimension({ type: "radius", value: 4 }))).toBe("R4");
+ expect(label(dimension({ type: "sphericalRadius", value: 4 }))).toBe("SR4");
+ expect(formatPmiItem(dimension({ type: "diameter" }), "mm", null)).toEqual({
+ label: "⌀10",
+ symbol: null,
+ title: "Diameter"
+ });
+ });
+
+ it("suffixes a MIN or MAX qualifier", () => {
+ expect(label(dimension({ value: 3, qualifier: "min" }))).toBe("3 MIN");
+ expect(label(dimension({ value: 3, qualifier: "max" }))).toBe("3 MAX");
+ });
+
+ it("prints angles in degrees in either unit", () => {
+ const angle = dimension({
+ type: "angular",
+ value: 45,
+ upper: 0.5,
+ lower: -0.5
+ });
+ expect(label(angle, "mm")).toBe("45° ±0.5°");
+ expect(label(angle, "in")).toBe("45° ±0.5°");
+ expect(formatPmiItem(angle, "in", "mm").title).toBe("Angle");
+ });
+
+ it("converts lengths to inches", () => {
+ expect(
+ label(dimension({ value: 25.4, upper: 0.127, lower: -0.127 }), "in", "mm")
+ ).toBe("1 ±0.005");
+ });
+
+ it("uses the file's decimals only in the file's own unit", () => {
+ const inchFile = dimension({
+ value: 25.4,
+ upper: 0.254,
+ lower: -0.254,
+ decimals: { left: 1, right: 3 }
+ });
+ expect(label(inchFile, "in", "in")).toBe("1.000 ±0.010");
+ expect(label(inchFile, "mm", "in")).toBe("25.4 ±0.254");
+
+ const mmFile = dimension({ value: 10, decimals: { left: 2, right: 2 } });
+ expect(label(mmFile, "mm", "mm")).toBe("10.00");
+ expect(label(mmFile, "in", "mm")).toBe("0.3937");
+ });
+
+ it("falls back to 3 decimals in mm and 4 in inches, trimmed", () => {
+ expect(label(dimension({ value: 10.12345 }), "mm", null)).toBe("10.123");
+ expect(label(dimension({ value: 10.5 }), "mm", null)).toBe("10.5");
+ expect(label(dimension({ value: 10 }), "in", null)).toBe("0.3937");
+ });
+
+ it("names a graphic-only annotation", () => {
+ const note = item({
+ id: "d2",
+ kind: "dimension",
+ name: "Surface finish",
+ dimension: {
+ ...(dimension({}).dimension as PmiDimension),
+ type: "presentation"
+ }
+ });
+ expect(label(note)).toBe("Surface finish");
+ });
+});
+
+describe("formatPmiItem — tolerances, datums and notes", () => {
+ it("prints a feature control frame", () => {
+ const result = formatPmiItem(
+ tolerance({
+ type: "position",
+ value: 0.1,
+ zoneShape: "diameter",
+ material: "M",
+ datums: [
+ { name: "A", modifiers: [] },
+ { name: "B", modifiers: ["maximumMaterialRequirement"] },
+ { name: "C", modifiers: [] }
+ ]
+ }),
+ "mm",
+ "mm"
+ );
+ expect(result).toEqual({
+ label: "⌖ | ⌀0.1 Ⓜ | A | B Ⓜ | C",
+ symbol: "⌖",
+ title: "Position"
+ });
+ });
+
+ it("prints a flatness zone in inches with no datums", () => {
+ const result = formatPmiItem(
+ tolerance({ type: "flatness", value: 0.0254 }),
+ "in",
+ "mm"
+ );
+ expect(result.label).toBe("⏥ | 0.001");
+ expect(result.title).toBe("Flatness");
+ });
+
+ it("marks a projected zone", () => {
+ expect(
+ label(tolerance({ type: "perpendicularity", zoneModifier: "projected" }))
+ ).toBe("⟂ | 0.1 Ⓟ");
+ });
+
+ it("prints a datum as its letter", () => {
+ expect(
+ formatPmiItem(
+ item({
+ id: "a1",
+ kind: "datum",
+ datum: { name: "B", modifiers: [], target: null }
+ }),
+ "mm",
+ null
+ )
+ ).toEqual({ label: "B", symbol: null, title: "Datum B" });
+ });
+
+ it("prints a note by its name", () => {
+ expect(label(item({ id: "n1", kind: "note", name: "NOTE 1" }))).toBe(
+ "NOTE 1"
+ );
+ expect(label(item({ id: "n2", kind: "note" }))).toBe("Note 2");
+ });
+
+ it("numbers a note whose name is a CAD exporter's generic one", () => {
+ expect(label(item({ id: "n7", kind: "note", name: "DGT:Dimension" }))).toBe(
+ "Note 7"
+ );
+ });
+});
+
+describe("groupPmiItems", () => {
+ it("groups in panel order and skips empty groups", () => {
+ const groups = groupPmiItems(
+ doc({
+ items: [
+ item({ id: "n1", kind: "note" }),
+ tolerance({}),
+ dimension({}),
+ item({ id: "n2", kind: "note" })
+ ]
+ })
+ );
+ expect(groups.map((g) => g.title)).toEqual([
+ "Dimensions",
+ "Tolerances",
+ "Notes"
+ ]);
+ expect(groups[2]?.items.map((i) => i.id)).toEqual(["n1", "n2"]);
+ });
+});
+
+describe("visibleItemIds", () => {
+ const pmi = doc({
+ items: [dimension({}), tolerance({}), item({ id: "a1", kind: "datum" })],
+ views: [
+ {
+ id: "v1",
+ name: "Front",
+ direction: [0, 1, 0],
+ up: [0, 0, 1],
+ projection: null,
+ itemIds: ["t1", "a1"]
+ },
+ {
+ id: "v2",
+ name: "Camera only",
+ direction: [1, 0, 0],
+ up: [0, 0, 1],
+ projection: null,
+ itemIds: []
+ }
+ ]
+ });
+
+ it("shows every item for no view, an unknown view or an empty view", () => {
+ expect([...visibleItemIds(pmi, null)]).toEqual(["d1", "t1", "a1"]);
+ expect([...visibleItemIds(pmi, "nope")]).toEqual(["d1", "t1", "a1"]);
+ expect([...visibleItemIds(pmi, "v2")]).toEqual(["d1", "t1", "a1"]);
+ });
+
+ it("shows only the view's items", () => {
+ expect([...visibleItemIds(pmi, "v1")]).toEqual(["t1", "a1"]);
+ });
+});
+
+describe("bounds", () => {
+ const withGeometry = doc({
+ items: [
+ item({
+ id: "d1",
+ kind: "dimension",
+ lines: [[0, 0, 0, 10, 0, 0]],
+ textPosition: [5, 2, 0],
+ faces: [0],
+ edges: [0]
+ }),
+ item({
+ id: "t1",
+ kind: "tolerance",
+ mesh: { positions: [20, 20, 20, 21, 21, 21, 20, 21, 20], indices: [] }
+ })
+ ],
+ faces: [{ positions: [0, 0, -5, 1, 1, -5, 0, 1, -5], indices: [0, 1, 2] }],
+ edges: [[0, -3, 0, 0, 3, 0]],
+ views: [
+ {
+ id: "v1",
+ name: "Top",
+ direction: [0, 0, -1],
+ up: [0, 1, 0],
+ projection: null,
+ itemIds: ["t1"]
+ }
+ ]
+ });
+ const [d1, t1] = withGeometry.items as [PmiItem, PmiItem];
+
+ it("spans an item's lines and text anchor", () => {
+ expect(pmiItemBounds(withGeometry, d1, false)).toEqual({
+ min: [0, 0, 0],
+ max: [10, 2, 0]
+ });
+ });
+
+ it("adds the referenced faces and edges on request", () => {
+ expect(pmiItemBounds(withGeometry, d1, true)).toEqual({
+ min: [0, -3, -5],
+ max: [10, 3, 0]
+ });
+ });
+
+ it("spans a mesh, and is null with no geometry", () => {
+ expect(pmiItemBounds(withGeometry, t1, false)).toEqual({
+ min: [20, 20, 20],
+ max: [21, 21, 21]
+ });
+ expect(
+ pmiItemBounds(withGeometry, item({ id: "x", kind: "note" }), true)
+ ).toBeNull();
+ });
+
+ it("spans a view's items, or every item with no view", () => {
+ expect(pmiViewBounds(withGeometry, "v1")).toEqual({
+ min: [20, 20, 20],
+ max: [21, 21, 21]
+ });
+ expect(pmiViewBounds(withGeometry, null)).toEqual({
+ min: [0, -3, -5],
+ max: [21, 21, 21]
+ });
+ });
+});
diff --git a/packages/viewer/src/pmi.ts b/packages/viewer/src/pmi.ts
new file mode 100644
index 0000000000..901f8b86a5
--- /dev/null
+++ b/packages/viewer/src/pmi.ts
@@ -0,0 +1,752 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,
+// including ports, remain AGPLv3; serving them over a network requires releasing their source.
+
+import type { Vec3 } from "./types";
+
+/**
+ * `pmi.json` — the PMI (Product Manufacturing Information) the assembler's
+ * optimize ingest reads from a STEP AP242 model: dimensions, geometric
+ * tolerances, datums and graphic-only notes, plus the model's saved views.
+ * Written by `crates/converter/src/pmi.rs`; the two must agree field for
+ * field. Every length and coordinate is world mm in the frame of the optimised
+ * GLB; angles are degrees.
+ */
+export type PmiDocument = {
+ version: 1;
+ unit: "mm";
+ /** The STEP file's length unit, when the ingest read the STEP header. */
+ sourceUnit: "mm" | "in" | null;
+ items: PmiItem[];
+ /** Triangles of every face an item references (`PmiItem.faces` indexes this). */
+ faces: PmiMesh[];
+ /** Flat x,y,z polylines of every edge an item references. */
+ edges: number[][];
+ views: PmiView[];
+};
+
+export type PmiKind = "dimension" | "tolerance" | "datum" | "note";
+
+export type PmiMesh = { positions: number[]; indices: number[] };
+
+export type PmiPlane = { origin: Vec3; normal: Vec3; xDirection: Vec3 };
+
+export type PmiItem = {
+ /** `d1`, `t1`, `a1`, `n1`… in document order, per kind. */
+ id: string;
+ kind: PmiKind;
+ /** The CAD author's name for the item (semantic or presentation name). */
+ name: string | null;
+ dimension: PmiDimension | null;
+ tolerance: PmiTolerance | null;
+ datum: PmiDatum | null;
+ /** Graphical PMI: leader lines, frames and stroked text, flat x,y,z polylines. */
+ lines: number[][];
+ /** Graphical PMI: filled (tessellated) text and arrowheads. */
+ mesh: PmiMesh | null;
+ plane: PmiPlane | null;
+ textPosition: Vec3 | null;
+ /** Indices into `PmiDocument.faces`. */
+ faces: number[];
+ /** Indices into `PmiDocument.edges`. */
+ edges: number[];
+};
+
+/**
+ * OCCT `XCAFDimTolObjects_DimensionType` in lower camel case, without the
+ * `Location_` / `Size_` prefix. `angular` is a location angle and
+ * `angularSize` a size angle; both carry degrees.
+ */
+export type PmiDimensionType =
+ | "none"
+ | "curvedDistance"
+ | "linearDistance"
+ | "linearDistanceFromCenterToOuter"
+ | "linearDistanceFromCenterToInner"
+ | "linearDistanceFromOuterToCenter"
+ | "linearDistanceFromOuterToOuter"
+ | "linearDistanceFromOuterToInner"
+ | "linearDistanceFromInnerToCenter"
+ | "linearDistanceFromInnerToOuter"
+ | "linearDistanceFromInnerToInner"
+ | "angular"
+ | "oriented"
+ | "withPath"
+ | "curveLength"
+ | "diameter"
+ | "sphericalDiameter"
+ | "radius"
+ | "sphericalRadius"
+ | "toroidalMinorDiameter"
+ | "toroidalMajorDiameter"
+ | "toroidalMinorRadius"
+ | "toroidalMajorRadius"
+ | "toroidalHighMajorDiameter"
+ | "toroidalLowMajorDiameter"
+ | "toroidalHighMajorRadius"
+ | "toroidalLowMajorRadius"
+ | "thickness"
+ | "angularSize"
+ | "sizeWithPath"
+ | "commonLabel"
+ | "presentation";
+
+export type PmiDimension = {
+ type: PmiDimensionType;
+ /** Nominal (mm, or degrees for an angle). For a range, the midpoint. */
+ value: number | null;
+ /** Plus/minus tolerance: the upper deviation (`+0.1`). */
+ upper: number | null;
+ /** Plus/minus tolerance: the lower deviation, negative (`-0.05`). */
+ lower: number | null;
+ /** Limit dimension: the upper and lower limits. */
+ upperBound: number | null;
+ lowerBound: number | null;
+ /** ISO fit, e.g. hole `H` grade `IT7` reads `H7`. */
+ fitClass: { hole: boolean; formVariance: string; grade: string } | null;
+ qualifier: "min" | "max" | "avg" | null;
+ /** The author's digits left/right of the point, in the source unit. */
+ decimals: { left: number; right: number } | null;
+ /** OCCT `XCAFDimTolObjects_DimensionModif`, lower camel case. */
+ modifiers: string[];
+ descriptions: string[];
+};
+
+/** OCCT `XCAFDimTolObjects_GeomToleranceType`, lower camel case. */
+export type PmiToleranceType =
+ | "none"
+ | "angularity"
+ | "circularRunout"
+ | "circularityOrRoundness"
+ | "coaxiality"
+ | "concentricity"
+ | "cylindricity"
+ | "flatness"
+ | "parallelism"
+ | "perpendicularity"
+ | "position"
+ | "profileOfLine"
+ | "profileOfSurface"
+ | "straightness"
+ | "symmetry"
+ | "totalRunout";
+
+export type PmiTolerance = {
+ type: PmiToleranceType;
+ /** Zone size, mm. */
+ value: number | null;
+ zoneShape: "diameter" | "sphericalDiameter" | null;
+ /** Material condition: Ⓜ maximum, Ⓛ least. */
+ material: "M" | "L" | null;
+ zoneModifier: "projected" | "runout" | "nonUniform" | null;
+ zoneModifierValue: number | null;
+ /** OCCT `XCAFDimTolObjects_GeomToleranceModif`, lower camel case. */
+ modifiers: string[];
+ maxValue: number | null;
+ /** Datum references in precedence order (primary first). */
+ datums: { name: string; modifiers: string[] }[];
+};
+
+export type PmiDatum = {
+ /** The datum letter. */
+ name: string;
+ modifiers: string[];
+ /** Datum target type (`point`, `line`, `rectangle`, `circle`, `area`), or null. */
+ target: string | null;
+};
+
+export type PmiView = {
+ id: string;
+ name: string;
+ /** From the camera towards the model. */
+ direction: Vec3;
+ up: Vec3;
+ projection: "parallel" | "central" | null;
+ itemIds: string[];
+};
+
+export const PMI_VERSION = 1;
+
+const PMI_KINDS: ReadonlySet<string> = new Set<PmiKind>([
+ "dimension",
+ "tolerance",
+ "datum",
+ "note"
+]);
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const isVec3 = (value: unknown): value is Vec3 =>
+ Array.isArray(value) &&
+ value.length === 3 &&
+ value.every((n) => typeof n === "number" && Number.isFinite(n));
+
+const isMesh = (value: unknown): value is PmiMesh =>
+ isRecord(value) &&
+ Array.isArray(value.positions) &&
+ Array.isArray(value.indices);
+
+const isPolylineList = (value: unknown): value is number[][] =>
+ Array.isArray(value) && value.every(Array.isArray);
+
+function isItem(value: unknown): value is PmiItem {
+ if (!isRecord(value)) return false;
+ return (
+ typeof value.id === "string" &&
+ typeof value.kind === "string" &&
+ PMI_KINDS.has(value.kind) &&
+ isPolylineList(value.lines) &&
+ (value.mesh === null || isMesh(value.mesh)) &&
+ (value.textPosition === null || isVec3(value.textPosition)) &&
+ (value.plane === null ||
+ (isRecord(value.plane) &&
+ isVec3(value.plane.origin) &&
+ isVec3(value.plane.normal))) &&
+ (value.dimension === null || isRecord(value.dimension)) &&
+ (value.tolerance === null || isRecord(value.tolerance)) &&
+ (value.datum === null || isRecord(value.datum)) &&
+ Array.isArray(value.faces) &&
+ Array.isArray(value.edges)
+ );
+}
+
+function isView(value: unknown): value is PmiView {
+ return (
+ isRecord(value) &&
+ typeof value.id === "string" &&
+ typeof value.name === "string" &&
+ isVec3(value.direction) &&
+ isVec3(value.up) &&
+ Array.isArray(value.itemIds)
+ );
+}
+
+/**
+ * Reads a fetched `pmi.json`. Null when the version is not
+ * {@link PMI_VERSION} or the shape is wrong — the viewer then shows no PMI.
+ * Extra fields are kept and ignored, so a later additive change on the
+ * converter side does not break an older viewer.
+ */
+export function parsePmiDocument(json: unknown): PmiDocument | null {
+ if (!isRecord(json) || json.version !== PMI_VERSION) return null;
+ if (json.unit !== "mm") return null;
+ const sourceUnit = json.sourceUnit ?? null;
+ if (sourceUnit !== null && sourceUnit !== "mm" && sourceUnit !== "in") {
+ return null;
+ }
+ if (
+ !Array.isArray(json.items) ||
+ !json.items.every(isItem) ||
+ !Array.isArray(json.faces) ||
+ !json.faces.every(isMesh) ||
+ !isPolylineList(json.edges) ||
+ !Array.isArray(json.views) ||
+ !json.views.every(isView)
+ ) {
+ return null;
+ }
+ return { ...(json as PmiDocument), sourceUnit };
+}
+
+// ---------------------------------------------------------------------------
+// Label formatting
+// ---------------------------------------------------------------------------
+
+export type PmiDisplayUnit = "mm" | "in";
+
+export type PmiItemLabel = {
+ /** What the drawing would print: `⌀10 ±0.1`, `⌖ | ⌀0.1 Ⓜ | A | B`, `A`. */
+ label: string;
+ /** The geometric characteristic symbol of a tolerance, else null. */
+ symbol: string | null;
+ /** A human name: "Position", "Diameter", "Datum A". */
+ title: string;
+};
+
+const MM_PER_IN = 25.4;
+const MINUS = "−";
+const DIAMETER = "⌀";
+
+/** Digits when the display unit is not the file's own (or the file has none). */
+const DEFAULT_DECIMALS: Record<PmiDisplayUnit, number> = { mm: 3, in: 4 };
+
+const TOLERANCE_SYMBOLS: Record<PmiToleranceType, string | null> = {
+ none: null,
+ straightness: "⏤",
+ flatness: "⏥",
+ circularityOrRoundness: "○",
+ cylindricity: "⌭",
+ profileOfLine: "⌒",
+ profileOfSurface: "⌓",
+ angularity: "∠",
+ perpendicularity: "⟂",
+ parallelism: "∥",
+ position: "⌖",
+ concentricity: "◎",
+ coaxiality: "◎",
+ symmetry: "⌯",
+ circularRunout: "↗",
+ totalRunout: "⌰"
+};
+
+const TOLERANCE_TITLES: Record<PmiToleranceType, string> = {
+ none: "Geometric tolerance",
+ straightness: "Straightness",
+ flatness: "Flatness",
+ circularityOrRoundness: "Circularity",
+ cylindricity: "Cylindricity",
+ profileOfLine: "Profile of a line",
+ profileOfSurface: "Profile of a surface",
+ angularity: "Angularity",
+ perpendicularity: "Perpendicularity",
+ parallelism: "Parallelism",
+ position: "Position",
+ concentricity: "Concentricity",
+ coaxiality: "Coaxiality",
+ symmetry: "Symmetry",
+ circularRunout: "Circular runout",
+ totalRunout: "Total runout"
+};
+
+const DIMENSION_PREFIXES: Partial<Record<PmiDimensionType, string>> = {
+ diameter: DIAMETER,
+ toroidalMinorDiameter: DIAMETER,
+ toroidalMajorDiameter: DIAMETER,
+ toroidalHighMajorDiameter: DIAMETER,
+ toroidalLowMajorDiameter: DIAMETER,
+ sphericalDiameter: `S${DIAMETER}`,
+ radius: "R",
+ toroidalMinorRadius: "R",
+ toroidalMajorRadius: "R",
+ toroidalHighMajorRadius: "R",
+ toroidalLowMajorRadius: "R",
+ sphericalRadius: "SR"
+};
+
+function dimensionTitle(type: PmiDimensionType): string {
+ if (type.startsWith("linearDistance")) return "Linear distance";
+ if (type.startsWith("toroidal")) {
+ return type.endsWith("Diameter") ? "Toroidal diameter" : "Toroidal radius";
+ }
+ switch (type) {
+ case "diameter":
+ return "Diameter";
+ case "sphericalDiameter":
+ return "Spherical diameter";
+ case "radius":
+ return "Radius";
+ case "sphericalRadius":
+ return "Spherical radius";
+ case "angular":
+ return "Angle";
+ case "angularSize":
+ return "Angular size";
+ case "curvedDistance":
+ return "Curved distance";
+ case "curveLength":
+ return "Curve length";
+ case "thickness":
+ return "Thickness";
+ case "oriented":
+ return "Oriented distance";
+ case "withPath":
+ return "Distance along path";
+ case "sizeWithPath":
+ return "Size along path";
+ default:
+ return "Dimension";
+ }
+}
+
+const isAngular = (type: PmiDimensionType) =>
+ type === "angular" || type === "angularSize";
+
+const formatters = new Map<string, Intl.NumberFormat>();
+
+/** Locale-free (`.` decimal, no grouping): labels read like the drawing. */
+function formatNumber(
+ value: number,
+ minimumFractionDigits: number,
+ maximumFractionDigits: number
+): string {
+ const key = `${minimumFractionDigits}:${maximumFractionDigits}`;
+ let formatter = formatters.get(key);
+ if (!formatter) {
+ formatter = new Intl.NumberFormat("en-US", {
+ useGrouping: false,
+ minimumFractionDigits,
+ maximumFractionDigits
+ });
+ formatters.set(key, formatter);
+ }
+ // `-0` would print as "-0".
+ const text = formatter.format(value);
+ return text === "-0" ? "0" : text;
+}
+
+/**
+ * How a number is printed: the author's digits (padded, as on the drawing)
+ * when the display unit is the file's own unit, else a fixed precision per
+ * unit with trailing zeros trimmed. `tolerance` widens the author's digits
+ * rather than cutting them, so `±0.05` on a `0` decimal nominal still reads.
+ */
+type NumberStyle = { min: number; max: number };
+
+function lengthStyle(
+ decimals: PmiDimension["decimals"] | null,
+ unit: PmiDisplayUnit,
+ sourceUnit: PmiDisplayUnit | null,
+ tolerance: boolean
+): NumberStyle {
+ const fallback = DEFAULT_DECIMALS[unit];
+ if (decimals && unit === sourceUnit) {
+ const right = Math.max(0, Math.min(decimals.right, 10));
+ return { min: right, max: tolerance ? Math.max(right, fallback) : right };
+ }
+ return { min: 0, max: fallback };
+}
+
+function angleStyle(
+ decimals: PmiDimension["decimals"] | null,
+ tolerance: boolean
+): NumberStyle {
+ // Degrees are the same in either display unit, so the author's digits
+ // always apply.
+ const fallback = DEFAULT_DECIMALS.mm;
+ if (decimals) {
+ const right = Math.max(0, Math.min(decimals.right, 10));
+ return { min: right, max: tolerance ? Math.max(right, fallback) : right };
+ }
+ return { min: 0, max: fallback };
+}
+
+const EPSILON = 1e-9;
+
+function signed(value: number, style: NumberStyle, suffix: string): string {
+ const magnitude = formatNumber(Math.abs(value), style.min, style.max);
+ if (Math.abs(value) < EPSILON || /^0(\.0*)?$/.test(magnitude)) {
+ return `${magnitude}${suffix}`;
+ }
+ return `${value < 0 ? MINUS : "+"}${magnitude}${suffix}`;
+}
+
+function fitClassLabel(fit: NonNullable<PmiDimension["fitClass"]>): string {
+ const letter = fit.hole
+ ? fit.formVariance.toUpperCase()
+ : fit.formVariance.toLowerCase();
+ const grade = fit.grade.replace(/^IT/i, "");
+ return `${letter}${grade}`;
+}
+
+function formatDimension(
+ item: PmiItem,
+ dimension: PmiDimension,
+ unit: PmiDisplayUnit,
+ sourceUnit: PmiDisplayUnit | null
+): PmiItemLabel {
+ const title = dimensionTitle(dimension.type);
+ if (dimension.type === "commonLabel" || dimension.type === "presentation") {
+ return { label: noteLabel(item), symbol: null, title };
+ }
+
+ const angular = isAngular(dimension.type);
+ const suffix = angular ? "°" : "";
+ const convert = (mm: number) =>
+ angular || unit === "mm" ? mm : mm / MM_PER_IN;
+ const nominalStyle = angular
+ ? angleStyle(dimension.decimals, false)
+ : lengthStyle(dimension.decimals, unit, sourceUnit, false);
+ const toleranceStyle = angular
+ ? angleStyle(dimension.decimals, true)
+ : lengthStyle(dimension.decimals, unit, sourceUnit, true);
+ const prefix = DIMENSION_PREFIXES[dimension.type] ?? "";
+
+ const parts: string[] = [];
+ const hasDeviation = dimension.upper !== null || dimension.lower !== null;
+ const hasLimits =
+ dimension.upperBound !== null && dimension.lowerBound !== null;
+
+ if (hasLimits && !hasDeviation) {
+ // A limit dimension prints its two limits instead of a nominal.
+ const upper = formatNumber(
+ convert(dimension.upperBound as number),
+ nominalStyle.min,
+ nominalStyle.max
+ );
+ const lower = formatNumber(
+ convert(dimension.lowerBound as number),
+ nominalStyle.min,
+ nominalStyle.max
+ );
+ parts.push(`${prefix}${upper}${suffix}/${lower}${suffix}`);
+ } else if (dimension.value !== null) {
+ parts.push(
+ `${prefix}${formatNumber(
+ convert(dimension.value),
+ nominalStyle.min,
+ nominalStyle.max
+ )}${suffix}`
+ );
+ } else {
+ parts.push(item.name ?? title);
+ }
+
+ if (dimension.fitClass) parts.push(fitClassLabel(dimension.fitClass));
+
+ if (hasDeviation) {
+ const upper = convert(dimension.upper ?? 0);
+ const lower = convert(dimension.lower ?? 0);
+ if (Math.abs(upper + lower) < EPSILON) {
+ if (Math.abs(upper) >= EPSILON) {
+ parts.push(
+ `±${formatNumber(
+ Math.abs(upper),
+ toleranceStyle.min,
+ toleranceStyle.max
+ )}${suffix}`
+ );
+ }
+ } else {
+ parts.push(
+ `${signed(upper, toleranceStyle, suffix)} / ${signed(
+ lower,
+ toleranceStyle,
+ suffix
+ )}`
+ );
+ }
+ }
+
+ if (dimension.qualifier === "min") parts.push("MIN");
+ if (dimension.qualifier === "max") parts.push("MAX");
+
+ return { label: parts.join(" "), symbol: null, title };
+}
+
+const MATERIAL_SYMBOLS = { M: "Ⓜ", L: "Ⓛ" } as const;
+
+function datumModifierSymbol(modifiers: string[]): string {
+ if (modifiers.includes("maximumMaterialRequirement")) {
+ return ` ${MATERIAL_SYMBOLS.M}`;
+ }
+ if (modifiers.includes("leastMaterialRequirement")) {
+ return ` ${MATERIAL_SYMBOLS.L}`;
+ }
+ return "";
+}
+
+function formatTolerance(
+ tolerance: PmiTolerance,
+ unit: PmiDisplayUnit
+): PmiItemLabel {
+ const symbol = TOLERANCE_SYMBOLS[tolerance.type] ?? null;
+ const title = TOLERANCE_TITLES[tolerance.type] ?? "Geometric tolerance";
+ const cells: string[] = [];
+ if (symbol) cells.push(symbol);
+
+ if (tolerance.value !== null) {
+ const value = unit === "mm" ? tolerance.value : tolerance.value / MM_PER_IN;
+ const zone =
+ tolerance.zoneShape === "diameter"
+ ? DIAMETER
+ : tolerance.zoneShape === "sphericalDiameter"
+ ? `S${DIAMETER}`
+ : "";
+ let cell = `${zone}${formatNumber(value, 0, DEFAULT_DECIMALS[unit])}`;
+ if (tolerance.material) cell += ` ${MATERIAL_SYMBOLS[tolerance.material]}`;
+ if (tolerance.zoneModifier === "projected") cell += " Ⓟ";
+ cells.push(cell);
+ }
+
+ for (const datum of tolerance.datums) {
+ cells.push(`${datum.name}${datumModifierSymbol(datum.modifiers)}`);
+ }
+
+ return {
+ label: cells.length > 0 ? cells.join(" | ") : title,
+ symbol,
+ title
+ };
+}
+
+/**
+ * The text a PMI item shows in the panel and as a 3D label, in the display
+ * unit. Lengths are stored mm and convert to inches; angles stay degrees.
+ */
+export function formatPmiItem(
+ item: PmiItem,
+ unit: PmiDisplayUnit,
+ sourceUnit: PmiDisplayUnit | null
+): PmiItemLabel {
+ if (item.kind === "dimension" && item.dimension) {
+ return formatDimension(item, item.dimension, unit, sourceUnit);
+ }
+ if (item.kind === "tolerance" && item.tolerance) {
+ return formatTolerance(item.tolerance, unit);
+ }
+ if (item.kind === "datum") {
+ const letter = item.datum?.name || item.name || "?";
+ return { label: letter, symbol: null, title: `Datum ${letter}` };
+ }
+ if (item.kind === "dimension") {
+ return {
+ label: item.name ?? "Dimension",
+ symbol: null,
+ title: "Dimension"
+ };
+ }
+ if (item.kind === "tolerance") {
+ return {
+ label: item.name ?? "Geometric tolerance",
+ symbol: null,
+ title: "Geometric tolerance"
+ };
+ }
+ return { label: noteLabel(item), symbol: null, title: "Note" };
+}
+
+/**
+ * A graphic-only note's label. CAD exporters name these generically (CATIA's
+ * "DGT:Dimension"), which tells the reader nothing and repeats on every row,
+ * so a generic name gives way to the note's number.
+ */
+function noteLabel(item: PmiItem): string {
+ const name = item.name?.trim();
+ if (name && !/^DGT:/i.test(name) && !/^(note|annotation)$/i.test(name)) {
+ return name;
+ }
+ const number = item.id.replace(/^\D+/, "");
+ return number ? `Note ${number}` : "Note";
+}
+
+// ---------------------------------------------------------------------------
+// Grouping and views
+// ---------------------------------------------------------------------------
+
+export type PmiGroupTitle = "Dimensions" | "Tolerances" | "Datums" | "Notes";
+
+export type PmiGroup = {
+ kind: PmiKind;
+ title: PmiGroupTitle;
+ items: PmiItem[];
+};
+
+const GROUPS: { kind: PmiKind; title: PmiGroupTitle }[] = [
+ { kind: "dimension", title: "Dimensions" },
+ { kind: "tolerance", title: "Tolerances" },
+ { kind: "datum", title: "Datums" },
+ { kind: "note", title: "Notes" }
+];
+
+/** Items by kind, in panel order, empty groups left out. */
+export function groupPmiItems(doc: PmiDocument): PmiGroup[] {
+ return GROUPS.map(({ kind, title }) => ({
+ kind,
+ title,
+ items: doc.items.filter((item) => item.kind === kind)
+ })).filter((group) => group.items.length > 0);
+}
+
+/**
+ * The ids a saved view shows. Every item for no view, an unknown view or a
+ * view that lists none (a camera-only view still shows the PMI).
+ */
+export function visibleItemIds(
+ doc: PmiDocument,
+ viewId: string | null
+): Set<string> {
+ const view =
+ viewId === null ? undefined : doc.views.find((v) => v.id === viewId);
+ if (!view || view.itemIds.length === 0) {
+ return new Set(doc.items.map((item) => item.id));
+ }
+ return new Set(view.itemIds);
+}
+
+// ---------------------------------------------------------------------------
+// Bounds
+// ---------------------------------------------------------------------------
+
+export type PmiBounds = { min: Vec3; max: Vec3 };
+
+class BoundsBuilder {
+ min: Vec3 = [Infinity, Infinity, Infinity];
+ max: Vec3 = [-Infinity, -Infinity, -Infinity];
+ empty = true;
+
+ point(x: number, y: number, z: number) {
+ if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) {
+ return;
+ }
+ this.empty = false;
+ if (x < this.min[0]) this.min[0] = x;
+ if (y < this.min[1]) this.min[1] = y;
+ if (z < this.min[2]) this.min[2] = z;
+ if (x > this.max[0]) this.max[0] = x;
+ if (y > this.max[1]) this.max[1] = y;
+ if (z > this.max[2]) this.max[2] = z;
+ }
+
+ flat(values: number[]) {
+ for (let i = 0; i + 2 < values.length; i += 3) {
+ // In range by the loop bound; NaN is skipped by `point` anyway.
+ this.point(
+ values[i] ?? Number.NaN,
+ values[i + 1] ?? Number.NaN,
+ values[i + 2] ?? Number.NaN
+ );
+ }
+ }
+
+ result(): PmiBounds | null {
+ return this.empty ? null : { min: this.min, max: this.max };
+ }
+}
+
+function addItem(
+ builder: BoundsBuilder,
+ doc: PmiDocument,
+ item: PmiItem,
+ includeFaces: boolean
+) {
+ for (const line of item.lines) builder.flat(line);
+ if (item.mesh) builder.flat(item.mesh.positions);
+ if (item.textPosition) builder.point(...item.textPosition);
+ if (!includeFaces) return;
+ for (const index of item.faces) {
+ const face = doc.faces[index];
+ if (face) builder.flat(face.positions);
+ }
+ for (const index of item.edges) {
+ const edge = doc.edges[index];
+ if (edge) builder.flat(edge);
+ }
+}
+
+/**
+ * Axis-aligned box over an item's graphical PMI and text anchor, and with
+ * `includeFaces` its referenced faces and edges. Null when it has none.
+ */
+export function pmiItemBounds(
+ doc: PmiDocument,
+ item: PmiItem,
+ includeFaces: boolean
+): PmiBounds | null {
+ const builder = new BoundsBuilder();
+ addItem(builder, doc, item, includeFaces);
+ return builder.result();
+}
+
+/** The box over every item a view shows (all items for no or an unknown view). */
+export function pmiViewBounds(
+ doc: PmiDocument,
+ viewId: string | null
+): PmiBounds | null {
+ const ids = visibleItemIds(doc, viewId);
+ const builder = new BoundsBuilder();
+ for (const item of doc.items) {
+ if (ids.has(item.id)) addItem(builder, doc, item, true);
+ }
+ return builder.result();
+}
diff --git a/packages/viewer/src/useOptimizedModel.ts b/packages/viewer/src/useOptimizedModel.ts
index 384c3c4921..d121fb8429 100644
--- a/packages/viewer/src/useOptimizedModel.ts
+++ b/packages/viewer/src/useOptimizedModel.ts
@@ -20,6 +20,10 @@ export type ModelArtifacts = {
lodPath: string | null;
glbPath: string | null;
thumbnailPath: string | null;
+ /** The model's `pmi.json` (PMI read from a STEP AP242 source by the
+ * optimise ingest), or null when the model has none. Absent (older
+ * server) → treat as null. */
+ pmiPath?: string | null;
/** Raw upload (non-`.zst`) for the viewer's WASM fallback tier, with its
* resolved bucket (temp-staging for current uploads, private for old rows). */
rawPath: string | null;