Skip to main content

brep_render/engine_state/
model_io.rs

1use super::*;
2
3// ===========================================================================
4// Import / export — the file-interchange lane (the ONE platform exception).
5// STEP/IGES are text; STL/OBJ/3MF bytes are submitted to the background runner for
6// RANSAC reconstruction, then return as validated STEP for IMPORT3D. Exports
7// collect the CURRENT model's resident solids and serialize them.
8// ===========================================================================
9impl EngineState {
10    /// Import an STL triangle mesh through topology-aware RANSAC recognition.
11    /// Unsupported regions remain as validated facets, so every repairable
12    /// source triangle reaches the resulting CAD body.
13    pub fn import_stl_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
14        self.submit_mesh_import(crate::runner::MeshImportFormat::Stl, bytes.to_vec())
15    }
16
17    /// Import a Wavefront OBJ mesh through the same RANSAC reconstruction path.
18    pub fn import_obj_feature(&mut self, text: &str) -> Result<String, String> {
19        self.import_obj_bytes_feature(text.as_bytes())
20    }
21
22    /// Byte-oriented OBJ entry used by the picker so decoding also stays on the
23    /// background runner with parsing and reconstruction.
24    pub fn import_obj_bytes_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
25        self.submit_mesh_import(crate::runner::MeshImportFormat::Obj, bytes.to_vec())
26    }
27
28    /// Import a 3MF package (core specification) through the same chain. The
29    /// package is unzipped and its build flattened on the runner, so a large
30    /// model never decompresses on the UI thread.
31    pub fn import_3mf_bytes_feature(&mut self, bytes: &[u8]) -> Result<String, String> {
32        self.submit_mesh_import(crate::runner::MeshImportFormat::ThreeMf, bytes.to_vec())
33    }
34
35    fn submit_mesh_import(
36        &mut self,
37        format: crate::runner::MeshImportFormat,
38        bytes: Vec<u8>,
39    ) -> Result<String, String> {
40        let id = self.submit_mesh_reconstruction(
41            format, bytes, Default::default(), MeshImportDestination::Document,
42        )?;
43        Ok(serde_json::json!({ "meshImport": "submitted", "id": id }).to_string())
44    }
45
46    /// Reconstruct without editing history. The caller owns confirmation and
47    /// can inspect the exact STEP and diagnostics returned by `take_mesh_preview`.
48    pub fn reconstruct_mesh_preview(
49        &mut self,
50        format: crate::runner::MeshImportFormat,
51        bytes: Vec<u8>,
52        options: crate::runner::StlConversionOptions,
53    ) -> Result<u64, String> {
54        self.submit_mesh_reconstruction(format, bytes, options, MeshImportDestination::Preview)
55    }
56
57    pub fn take_mesh_preview(&mut self) -> Option<crate::runner::MeshImportReply> {
58        self.mesh_preview_results.pop_front()
59    }
60
61    fn submit_mesh_reconstruction(
62        &mut self,
63        format: crate::runner::MeshImportFormat,
64        bytes: Vec<u8>,
65        options: crate::runner::StlConversionOptions,
66        destination: MeshImportDestination,
67    ) -> Result<u64, String> {
68        if bytes.is_empty() {
69            return Err("mesh import failed: file is empty".into());
70        }
71        let id = self.next_mesh_import_id;
72        self.next_mesh_import_id = self.next_mesh_import_id.wrapping_add(1);
73        self.pending_mesh_imports.insert(id, destination);
74        self.runner.submit_mesh_import(crate::runner::MeshImportRequest {
75            id, format, bytes, options,
76        });
77        self.pump();
78        Ok(id)
79    }
80
81    /// Import a STEP document into the model: append an `IMPORT3D` feature whose
82    /// `inputParams.stepText` is the raw ISO-10303-21 text (the exact headless
83    /// source the kernel importer reads — no `fileToImport` data-URL marshaling
84    /// needed), mint it a persistent-counter id, roll to it, and rebuild. Returns the
85    /// build report JSON (imported bodies + any per-feature error). A non-STEP
86    /// payload is refused up front so a bad upload never leaves a dead feature.
87    pub fn import_step_feature(&mut self, step_text: &str) -> Result<String, String> {
88        if !step_text.contains("ISO-10303-21") {
89            return Err("not a STEP file (missing the ISO-10303-21 header)".into());
90        }
91        let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
92        let feature = serde_json::json!({
93            "type": "IMPORT3D",
94            "inputParams": { "id": id, "stepText": step_text },
95            "persistentData": {},
96        });
97        // The file's AP242 PMI, lifted ONCE into the document's pmi block with
98        // references naming the faces / edges / vertices the feature will stamp
99        // (the STEP text is never re-read for it). Read BEFORE the add so the
100        // add's undo checkpoint precedes both writes: one undo removes the
101        // feature and its PMI together.
102        let lifted = brep_kernel::read_step_pmi(step_text, &id).unwrap_or(None);
103        // Frame the imported body once the (possibly async) run lands — see
104        // [`EngineState::pending_fit`]. An immediate fit here would frame the still
105        // empty scene under a background runner (native thread / wasm worker).
106        self.pending_fit = true;
107        let report = self.add_feature(&feature.to_string());
108        if let Some(lifted) = lifted {
109            self.pmi_merge_imported(lifted);
110        }
111        report
112    }
113
114    /// Export the CURRENT model's resident solids to an ISO-10303-21 STEP
115    /// document. Collects the resident handles of the rolled-to model (a warm
116    /// re-run of the same prefix the display scene was built from — see
117    /// [`crate::pipeline::resident_solid_handles`]) and hands them to the kernel's
118    /// [`brep_kernel::export_step_handles`], so the exact NURBS topology is
119    /// serialized (never the display mesh). Errs clearly when the model is empty.
120    pub fn export_step_text(&mut self) -> Result<String, String> {
121        self.export_step_text_named("Part")
122    }
123
124    /// [`Self::export_step_text`] with the document's own name, which becomes
125    /// the root `PRODUCT`'s name (and the file's `FILE_NAME`).
126    ///
127    /// A document with ASSEMBLY COMPONENTS takes the STRUCTURED lane: each
128    /// parts-library entry is written once as its own product, in its own local
129    /// frame, and every instance becomes a `NEXT_ASSEMBLY_USAGE_OCCURRENCE`
130    /// carrying its pose — nested sub-assemblies included. Without components
131    /// the flat single-product writer is used, exactly as before.
132    pub fn export_step_text_named(&mut self, document_name: &str) -> Result<String, String> {
133        // The component projection the structured lane places instances by is
134        // the one the last run shipped (post-solve poses), so nothing has to be
135        // synced here; the resident re-run below registers the geometry.
136        let request: HistoryRequest = serde_json::from_value(self.run_request_value())
137            .map_err(|e| format!("export STEP: history request: {e}"))?;
138        let named = crate::pipeline::resident_solid_handles(&request);
139        // A board document's BOARD — substrate, copper, via barrels — as exact
140        // solids. The viewport's board is display triangles in no registry, so
141        // these are handed to the writer as values, in the ROOT product beside
142        // whatever the history made (`step_solids`).
143        let board = self.board_step_solids().unwrap_or_default();
144        for notice in &board.notices {
145            self.push_notice_as(super::NoticeSeverity::Warning, notice.clone());
146        }
147        if let Some(first) = board.skipped.first() {
148            // The file is still written; the user is told what it lacks.
149            self.push_notice(format!(
150                "STEP export: {} board item(s) could not be made as solids and are missing from the file — first: {first}",
151                board.skipped.len()
152            ));
153        }
154        if named.is_empty() && board.bodies.is_empty() {
155            return Err("nothing to export: the model has no solids".into());
156        }
157        // The document's PMI rides along as AP242 semantic PMI + saved views,
158        // resolved against the same resident solids the file is written from
159        // (the warm re-run above left the tail's report on this thread).
160        let report = request
161            .pmi
162            .as_ref()
163            .map(|_| {
164                let _trace = crate::run_trace::span("export_pmi");
165                brep_kernel::execute_history(&request).pmi
166            })
167            .flatten();
168        let pmi = match (request.pmi.as_ref(), report.as_ref()) {
169            (Some(state), Some(report)) => Some(brep_kernel::StepPmi { state, report }),
170            _ => None,
171        };
172        let mut colors = self.step_export_colors(&named);
173        for (name, rgb) in &board.colors {
174            // A colour the user stored under a board body's name still wins.
175            if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
176                colors.set(name, *rgb);
177            }
178        }
179        // The resident solids by value — read on THIS thread, where the re-run
180        // above registered them — whenever the handle-taking writers cannot
181        // take the whole file: there is a board to add, or a product id to fix.
182        let resident = |named: &[(String, u32)]| -> Result<Vec<(String, brep_kernel::BrepSolid)>, String> {
183            named
184                .iter()
185                .map(|(name, handle)| Ok((name.clone(), brep_kernel::registered_solid_clone(*handle)?)))
186                .collect()
187        };
188        if self.assembly_components.is_empty() && !board.bodies.is_empty() {
189            let mut solids = resident(&named)?;
190            solids.extend(board.bodies);
191            let borrowed: Vec<(String, &brep_kernel::BrepSolid)> =
192                solids.iter().map(|(name, solid)| (name.clone(), solid)).collect();
193            return brep_kernel::export_step_report_named(
194                &borrowed,
195                document_name,
196                "MM",
197                "",
198                pmi.as_ref(),
199                Some(&colors),
200            )
201            .map(|report| report.text);
202        }
203        if self.assembly_components.is_empty() {
204            return brep_kernel::export_step_named_handles(
205                &named,
206                document_name,
207                "MM",
208                "",
209                pmi.as_ref(),
210                Some(&colors),
211            )
212            .map(|report| report.text);
213        }
214        let components: Vec<(String, String, brep_kernel::Mat4)> = self
215            .assembly_components
216            .iter()
217            .map(|record| {
218                (
219                    record.id.clone(),
220                    record.part_name.clone(),
221                    record.transform,
222                )
223            })
224            .collect();
225        let mut assembly =
226            brep_kernel::assembly_export_tree(document_name, resident(&named)?, &components)?;
227        // The board is a product of its own, placed in the root at identity,
228        // so a receiving system's tree lists it by name (`PCB`) beside the
229        // parts. As the root's own geometry it read as an unnamed compound
230        // (OpenCascade: `=>[0:1:1:6]`). Its colours are keyed again under the
231        // occurrence's namespace, which is how the writer resolves them.
232        if !board.bodies.is_empty() {
233            for (name, rgb) in &board.colors {
234                if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
235                    colors.set(&format!("{BOARD_OCCURRENCE}:{name}"), *rgb);
236                }
237            }
238            for (name, rgb) in self.persisted_export_colors() {
239                if name.starts_with(super::board_geometry::BOARD_SOLID_PREFIX) {
240                    colors.set(&format!("{BOARD_OCCURRENCE}:{name}"), rgb);
241                }
242            }
243            assembly.products.push(brep_kernel::StepExportProduct {
244                name: BOARD_OCCURRENCE.to_string(),
245                id: BOARD_OCCURRENCE.to_string(),
246                bodies: board.bodies,
247                pmi: None,
248            });
249            assembly.occurrences.push(brep_kernel::StepExportOccurrence {
250                designator: BOARD_OCCURRENCE.to_string(),
251                parent: 0,
252                child: assembly.products.len() - 1,
253                placement: [
254                    1., 0., 0., 0., //
255                    0., 1., 0., 0., //
256                    0., 0., 1., 0., //
257                    0., 0., 0., 1.,
258                ],
259            });
260        }
261        for product in &mut assembly.products {
262            product.id = portable_product_id(&product.id, &product.name);
263        }
264        if self.history.pcb_block().is_some() && pmi.is_none() {
265            self.label_occurrences_by_reference(&mut assembly, &mut colors, &named);
266        }
267        brep_kernel::export_step_assembly_report(&assembly, "MM", "", pmi.as_ref(), Some(&colors))
268            .map(|report| report.text)
269    }
270
271    /// A BOARD document's placed parts, named in the STEP tree by their
272    /// REFERENCE DESIGNATOR (`U1`, `R3`) instead of the component feature id
273    /// (`ACOMP1`) — the name the engineer on the other end knows the part by.
274    ///
275    /// The occurrence label is also the namespace the writer resolves the
276    /// document's names through (`ACOMP1:IMPORT3D1_Face_0` finds its face under
277    /// the `ACOMP1:` occurrence), so every colour keyed under a relabelled
278    /// component is keyed again under its new label, or the KiCad body colours
279    /// would drop out of the file. PMI resolves through the same namespace,
280    /// which is why the caller only relabels a document that carries none.
281    ///
282    /// A reference is used only when it is unambiguous: non-empty, free of the
283    /// `:` namespace separator, carried by exactly one component, and neither
284    /// some other component's id nor the board's own label
285    /// ([`BOARD_OCCURRENCE`]). Anything else keeps its feature id.
286    fn label_occurrences_by_reference(
287        &self,
288        assembly: &mut brep_kernel::StepAssemblyExport,
289        colors: &mut brep_kernel::StepColors,
290        named: &[(String, u32)],
291    ) {
292        let mut references: std::collections::BTreeMap<String, String> = Default::default();
293        let mut seen: std::collections::BTreeMap<String, usize> = Default::default();
294        let mut ids: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
295        for feature in self.history.features() {
296            let is_component = feature["type"]
297                .as_str()
298                .is_some_and(super::components::is_acomp_feature_type);
299            let params = &feature["inputParams"];
300            let Some(id) = params["id"].as_str().filter(|_| is_component) else {
301                continue;
302            };
303            ids.insert(id.to_string());
304            let reference = params["bom"]["Reference_Designator"].as_str().unwrap_or("").trim();
305            if !reference.is_empty() && !reference.contains(':') {
306                references.insert(id.to_string(), reference.to_string());
307                *seen.entry(reference.to_string()).or_default() += 1;
308            }
309        }
310        references.retain(|_, reference| {
311            seen[reference.as_str()] == 1 && !ids.contains(reference.as_str()) && reference != BOARD_OCCURRENCE
312        });
313        if references.is_empty() {
314            return;
315        }
316        for occurrence in assembly.occurrences.iter_mut().filter(|o| o.parent == 0) {
317            if let Some(reference) = references.get(&occurrence.designator) {
318                occurrence.designator = reference.clone();
319            }
320        }
321        // The same colours `step_export_colors` keyed, keyed again under the
322        // new label: the persisted ones, and the name-hash look's.
323        let hashed = self.settings.face_color_mode == crate::style::FaceColorMode::HashedBySolid;
324        let mut keyed: Vec<(String, [u8; 3])> = self.persisted_export_colors();
325        if hashed {
326            for (name, _) in named {
327                if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
328                    keyed.push((name.clone(), srgb_bytes(crate::color::solid_color_srgb(name))));
329                }
330            }
331        }
332        for (name, rgb) in keyed {
333            let Some((id, rest)) = name.split_once(':') else {
334                continue;
335            };
336            if let Some(reference) = references.get(id) {
337                colors.set(&format!("{reference}:{rest}"), rgb);
338            }
339        }
340    }
341
342    /// The body/face colours the STEP writer should emit as presentation styles.
343    ///
344    /// The METADATA STORE is the authority, exactly as it is for the viewport
345    /// ([`EngineState::sync_colors_from_metadata`]): every `color` attribute the
346    /// document persists — a STEP import's stamped colours, a colour picked in
347    /// the Info window, a colour restored from a saved file — becomes a style on
348    /// the body or face of that name. Spellings are read through
349    /// [`crate::style::parse_css_hex`], the one parser the display uses, so a
350    /// value the viewport shows is a value the file carries.
351    ///
352    /// `override_model_colors` is deliberately NOT honoured: it is a display
353    /// switch whose own contract is that the store is never touched, so a
354    /// document exported with the box ticked still carries all of its colours.
355    ///
356    /// The NAME-DERIVED fallback is the second half, and it is narrow on
357    /// purpose: a body with no persisted colour gets the stable name-hash
358    /// colour ONLY when the viewport is itself colouring by name hash
359    /// ([`crate::style::FaceColorMode::HashedBySolid`] — the artifact look, not
360    /// the default). In the default `Uniform` mode an uncoloured body gets no
361    /// style at all, so an export from a document nobody coloured is
362    /// byte-for-byte the file this writer produced before colour existed rather
363    /// than a model painted in colours the user never saw.
364    ///
365    /// Faces are never name-derived: the renderer hashes per SOLID, so there is
366    /// no per-face colour to match.
367    fn step_export_colors(&self, named: &[(String, u32)]) -> brep_kernel::StepColors {
368        let mut colors = brep_kernel::StepColors::new();
369        for (name, rgb) in self.persisted_export_colors() {
370            colors.set(&name, rgb);
371        }
372        if self.settings.face_color_mode == crate::style::FaceColorMode::HashedBySolid {
373            for (name, _) in named {
374                if self.metadata.attribute(name, brep_kernel::COLOR_METADATA_KEY).is_none() {
375                    colors.set(name, srgb_bytes(crate::color::solid_color_srgb(name)));
376                }
377            }
378        }
379        colors
380    }
381
382    /// Resident handle of the part's target sheet-metal body for a flat-pattern
383    /// export. Enumerates the current resident solids (a warm re-run of the same
384    /// prefix the display scene was built from, like the STEP lane) and keeps the
385    /// ones carrying a sheet-metal tree; uses the SELECTED sheet-metal body if the
386    /// selection names exactly one, else the SOLE sheet-metal body (the same
387    /// auto-target SM.CUTOUT uses). Errs with the exact `"no sheet-metal body in
388    /// the part"` when there is none, and loudly when several are ambiguous.
389    fn flat_pattern_target_handle(&self) -> Result<u32, String> {
390        let request: HistoryRequest = serde_json::from_value(self.run_request_value())
391            .map_err(|e| format!("export flat pattern: history request: {e}"))?;
392        let sheet_metal: Vec<(String, u32)> = crate::pipeline::resident_solid_handles(&request)
393            .into_iter()
394            .filter(|(_, handle)| brep_kernel::is_sheet_metal_handle(*handle))
395            .collect();
396        if sheet_metal.is_empty() {
397            return Err("no sheet-metal body in the part".into());
398        }
399        // Prefer a selected sheet-metal body when the selection names exactly one.
400        let selected: Vec<u32> = sheet_metal
401            .iter()
402            .filter(|(name, _)| self.emphasis.selected_solids.contains(name))
403            .map(|(_, handle)| *handle)
404            .collect();
405        if let [handle] = selected.as_slice() {
406            return Ok(*handle);
407        }
408        match sheet_metal.as_slice() {
409            [(_, handle)] => Ok(*handle),
410            _ => Err(
411                "several sheet-metal bodies in the part — select the one to export".into(),
412            ),
413        }
414    }
415
416    /// Export the part's sheet-metal FLAT PATTERN (the unfold) as a DXF (R12
417    /// ASCII) 2D vector document. Runs the unfold TRANSIENTLY off the target
418    /// body's resident tree — no feature is added and history is not mutated. Errs
419    /// (`"no sheet-metal body in the part"`) when the part carries no sheet metal.
420    pub fn export_flat_pattern_dxf(&self) -> Result<String, String> {
421        brep_kernel::flat_pattern_dxf(self.flat_pattern_target_handle()?)
422    }
423
424    /// Export the part's sheet-metal flat pattern as an SVG — the DXF sibling of
425    /// [`Self::export_flat_pattern_dxf`].
426    pub fn export_flat_pattern_svg(&self) -> Result<String, String> {
427        brep_kernel::flat_pattern_svg(self.flat_pattern_target_handle()?)
428    }
429
430    /// Import an IGES document into the model: append an `IMPORT3D` feature whose
431    /// `inputParams.igesText` is the raw IGES text (the kernel importer reads it
432    /// via [`brep_kernel::import_iges`]), mint an id, roll to it, and rebuild.
433    /// Refuses a non-IGES payload up front so a bad upload never leaves a dead
434    /// feature.
435    pub fn import_iges_feature(&mut self, iges_text: &str) -> Result<String, String> {
436        if iges_text.contains("ISO-10303-21") {
437            return Err("not an IGES file (this looks like a STEP document)".into());
438        }
439        // IGES records carry an S/G/D/P/T section letter in column 73.
440        let looks_like_iges = iges_text.lines().any(|line| {
441            matches!(line.chars().nth(72), Some('S' | 'G' | 'D' | 'P' | 'T'))
442        });
443        if !looks_like_iges {
444            return Err("not an IGES file (no S/G/D/P/T section records found)".into());
445        }
446        let id = self.next_feature_id(&crate::features::feature_short_name("IMPORT3D"));
447        let feature = serde_json::json!({
448            "type": "IMPORT3D",
449            "inputParams": { "id": id, "igesText": iges_text },
450            "persistentData": {},
451        });
452        // Frame the imported body once the (possibly async) run lands — see
453        // [`EngineState::pending_fit`] (mirrors the STEP lane above).
454        self.pending_fit = true;
455        self.add_feature(&feature.to_string())
456    }
457
458    /// Export the CURRENT model's resident solids to an IGES 5.3 document of
459    /// trimmed NURBS surfaces — the IGES analogue of [`Self::export_step_text`],
460    /// handing the resident handles to [`brep_kernel::export_iges_handles`].
461    pub fn export_iges_text(&self) -> Result<String, String> {
462        let request: HistoryRequest = serde_json::from_value(self.run_request_value())
463            .map_err(|e| format!("export IGES: history request: {e}"))?;
464        let handles: Vec<u32> = crate::pipeline::resident_solid_handles(&request)
465            .into_iter()
466            .map(|(_, handle)| handle)
467            .collect();
468        if handles.is_empty() {
469            return Err("nothing to export: the model has no solids".into());
470        }
471        brep_kernel::export_iges_handles(&handles, "Part", "MM", "")
472    }
473
474    /// Export the CURRENT display scene to an ASCII STL string (one `solid` with a
475    /// per-triangle geometric normal for every mesh triangle of every displayed
476    /// solid). STL is a triangle-soup format with no multi-body concept, so all
477    /// solids fold into a single `solid brep … endsolid brep`. String-shaped so it
478    /// crosses the same string `ModelStore` seam the STEP lane uses. Errs when the
479    /// scene has no triangles.
480    pub fn export_stl_text(&self) -> Result<String, String> {
481        let mut out = String::from("solid brep\n");
482        let mut triangles = 0usize;
483        for solid in self.scene.solids() {
484            let positions = &solid.mesh.positions;
485            for tri in solid.mesh.indices.chunks_exact(3) {
486                let a = positions[tri[0] as usize];
487                let b = positions[tri[1] as usize];
488                let c = positions[tri[2] as usize];
489                let normal = triangle_normal(a, b, c);
490                out.push_str(&format!(
491                    "  facet normal {} {} {}\n    outer loop\n",
492                    normal[0], normal[1], normal[2]
493                ));
494                for v in [a, b, c] {
495                    out.push_str(&format!("      vertex {} {} {}\n", v[0], v[1], v[2]));
496                }
497                out.push_str("    endloop\n  endfacet\n");
498                triangles += 1;
499            }
500        }
501        out.push_str("endsolid brep\n");
502        if triangles == 0 {
503            return Err("nothing to export: the scene has no triangles".into());
504        }
505        Ok(out)
506    }
507
508    /// Export the CURRENT display scene as Wavefront OBJ text — the same
509    /// triangles [`Self::export_stl_text`] writes, folded into ONE object `brep`
510    /// with the display normals kept per vertex, through the kernel's
511    /// [`brep_kernel::write_obj`]. Millimetres, like every other export lane.
512    /// Errs when the scene has no triangles.
513    pub fn export_obj_text(&self) -> Result<String, String> {
514        let mut mesh = brep_kernel::Mesh::default();
515        for solid in self.scene.solids() {
516            let base = (mesh.positions.len() / 3) as u32;
517            for (position, normal) in solid.mesh.positions.iter().zip(&solid.mesh.normals) {
518                mesh.positions.extend(position.iter().map(|value| f64::from(*value)));
519                mesh.normals.extend(normal.iter().map(|value| f64::from(*value)));
520            }
521            mesh.indices.extend(solid.mesh.indices.iter().map(|index| base + index));
522        }
523        if mesh.indices.is_empty() {
524            return Err("nothing to export: the scene has no triangles".into());
525        }
526        brep_kernel::write_obj(&mesh, "brep")
527    }
528
529    /// Every `color` attribute the document persists, as 8-bit sRGB keyed by
530    /// scene name. The METADATA STORE is the authority for BOTH export lanes —
531    /// the STEP writer's styles ([`Self::step_export_colors`]) and the GLB
532    /// writer's materials ([`Self::export_glb_bytes`]) — so a colour the Info
533    /// window's Metadata tab shows is the colour either file carries. Spellings
534    /// are read through [`crate::style::parse_css_hex`], the one parser the
535    /// display itself uses.
536    fn persisted_export_colors(&self) -> Vec<(String, [u8; 3])> {
537        self.metadata
538            .all()
539            .iter()
540            .filter_map(|(name, record)| {
541                let value = record.get(brep_kernel::COLOR_METADATA_KEY)?;
542                let rgb = crate::style::parse_css_hex(value)?;
543                Some((name.clone(), srgb_bytes(rgb.map(f64::from))))
544            })
545            .collect()
546    }
547
548    /// The colour the VIEWPORT is showing a body with no persisted colour of
549    /// its own: the uniform `face_color` setting, or the stable name-hash in the
550    /// artifact look. This is the one place the GLB lane parts company with the
551    /// STEP lane, which leaves such a body unstyled — glTF has no "no style"
552    /// state, so a primitive with no material renders in the format's own
553    /// default (white, fully metallic), a colour nobody chose.
554    fn display_body_color(&self, name: &str) -> [u8; 3] {
555        match self.settings.face_color_mode {
556            crate::style::FaceColorMode::HashedBySolid => {
557                srgb_bytes(crate::color::solid_color_srgb(name))
558            }
559            crate::style::FaceColorMode::Uniform => {
560                let face = self.settings.face_color;
561                srgb_bytes([f64::from(face[0]), f64::from(face[1]), f64::from(face[2])])
562            }
563        }
564    }
565
566    /// Export the CURRENT display scene as a binary glTF 2.0 (`.glb`) document —
567    /// the same triangles [`Self::export_stl_text`] and [`Self::export_obj_text`]
568    /// write, through the kernel's [`brep_kernel::write_glb`]. Unlike those two,
569    /// glTF HAS a multi-body concept, so each scene solid becomes its own named
570    /// mesh instead of folding into one object.
571    ///
572    /// BINARY, not text: the bytes cross the store's byte-shaped interchange
573    /// (`export_file_named_bytes`), because base64 through the text lane would
574    /// inflate the file by a third for nothing.
575    ///
576    /// The axis convention (+Y up, which is both glTF's and this application's,
577    /// so the identity) and the millimetre-to-metre unit both ride on the root
578    /// NODE's transform — see the kernel module's doc. COLOURS are the metadata
579    /// store's, the same authority the STEP lane reads, with a face's beating its
580    /// body's; a body the store says nothing about takes the colour the viewport
581    /// shows it in ([`Self::display_body_color`]). `override_model_colors` is not
582    /// honoured, exactly as it is not by the STEP lane: it is a display switch
583    /// whose contract is that the store is never touched.
584    ///
585    /// Errs when the scene has no triangles.
586    pub fn export_glb_bytes(&self, document_name: &str) -> Result<Vec<u8>, String> {
587        let colors: std::collections::BTreeMap<String, [u8; 3]> =
588            self.persisted_export_colors().into_iter().collect();
589        let solids: Vec<brep_kernel::GlbSolid> = self
590            .scene
591            .solids()
592            .iter()
593            .map(|solid| {
594                let mut mesh = brep_kernel::Mesh::default();
595                for (position, normal) in solid.mesh.positions.iter().zip(&solid.mesh.normals) {
596                    mesh.positions.extend(position.iter().map(|value| f64::from(*value)));
597                    mesh.normals.extend(normal.iter().map(|value| f64::from(*value)));
598                }
599                mesh.indices = solid.mesh.indices.clone();
600                // The kernel writer groups by the per-TRIANGLE face id, which is
601                // an index into this solid's own `faces` — the same numbering
602                // `face_colors` is keyed by below.
603                mesh.face_ids = solid.mesh.face_ids.clone();
604                let face_colors = solid
605                    .faces
606                    .iter()
607                    .enumerate()
608                    .filter_map(|(index, face)| {
609                        colors.get(&face.name).map(|rgb| (index as u32, *rgb))
610                    })
611                    .collect();
612                brep_kernel::GlbSolid {
613                    name: solid.name.clone(),
614                    mesh,
615                    color: Some(
616                        colors
617                            .get(&solid.name)
618                            .copied()
619                            .unwrap_or_else(|| self.display_body_color(&solid.name)),
620                    ),
621                    face_colors,
622                }
623            })
624            .collect();
625        brep_kernel::write_glb(
626            &solids,
627            document_name,
628            brep_kernel::GlbUpAxis::YUp,
629            METRES_PER_MILLIMETRE,
630        )
631        .map(|(bytes, _report)| bytes)
632    }
633    /// The solids a 3D PDF shows ([`crate::sheets::pdf3d::Body`]): every
634    /// visible, non-sketch solid with triangles, UN-POSED (an explode the
635    /// active PMI view applies to the viewport is that view's, not the
636    /// model's), coloured by the GLB lane's rule — a face's persisted colour,
637    /// else its body's, else the colour the viewport shows the body in — with
638    /// its real edges (not the auxiliary or centre-line display edges).
639    pub fn pdf3d_bodies(&self) -> Vec<crate::sheets::pdf3d::Body> {
640        let colors: std::collections::BTreeMap<String, [u8; 3]> =
641            self.persisted_export_colors().into_iter().collect();
642        self.scene
643            .solids()
644            .iter()
645            .filter(|solid| solid.visible && !solid.is_sketch && solid.mesh.indices.len() >= 3)
646            .map(|shown| {
647                let solid = self.pmi_explode_originals.get(&shown.name).unwrap_or(shown);
648                let body = colors.get(&solid.name).copied().unwrap_or_else(|| self.display_body_color(&solid.name));
649                let face_colors: Vec<[u8; 3]> = solid
650                    .faces
651                    .iter()
652                    .map(|face| colors.get(&face.name).copied().unwrap_or(body))
653                    .collect();
654                crate::sheets::pdf3d::Body {
655                    name: solid.name.clone(),
656                    positions: solid.mesh.positions.clone(),
657                    normals: solid.mesh.normals.clone(),
658                    indices: solid.mesh.indices.clone(),
659                    triangle_colors: solid
660                        .mesh
661                        .face_ids
662                        .iter()
663                        .map(|face| face_colors.get(*face as usize).copied().unwrap_or(body))
664                        .collect(),
665                    edges: solid
666                        .edges
667                        .iter()
668                        .filter(|edge| !edge.aux && !edge.centerline && edge.polyline.len() >= 2)
669                        .map(|edge| edge.polyline.clone())
670                        .collect(),
671                }
672            })
673            .collect()
674    }
675}
676
677/// The model's unit expressed in glTF's. Every export lane writes millimetres
678/// (the STEP writer's `MM`) and glTF's own linear unit is the METRE, so the GLB
679/// root node carries this as its scale rather than the vertices being rewritten.
680const METRES_PER_MILLIMETRE: f64 = 0.001;
681
682/// Unit (or zero, for a degenerate triangle) geometric normal of triangle
683/// `(a, b, c)` — the per-facet normal an ASCII STL record carries.
684fn triangle_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
685    let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
686    let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
687    let n = [
688        u[1] * v[2] - u[2] * v[1],
689        u[2] * v[0] - u[0] * v[2],
690        u[0] * v[1] - u[1] * v[0],
691    ];
692    let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
693    if len > 0.0 {
694        [n[0] / len, n[1] / len, n[2] / len]
695    } else {
696        [0.0, 0.0, 0.0]
697    }
698}
699
700// ===========================================================================
701// STRUCTURED STEP import — the assembly lane.
702//
703// The flat lane above (`import_step_feature`) appends ONE IMPORT3D holding the
704// raw Part-21 text and lets the kernel bake every occurrence's world transform
705// into its own body: N bodies, no parts, no tree. This lane keeps the structure
706// instead — each unique geometry-bearing PRODUCT_DEFINITION becomes ONE
707// parts-library entry holding a NATIVE payload (`nativeBrep`, no STEP text
708// anywhere past this door), and each occurrence of it becomes an ACOMP instance
709// carrying the composed world pose. Six bolts are then one entry × six
710// instances, which is what makes the BOM, the structure tree, per-component
711// selection and constraints work on imported geometry.
712//
713// # FLAT or NESTED — the user's choice, both correct
714//
715// [`StepAssemblyImport::nested`] picks between two shapes of the same
716// geometry:
717//
718// - **Flat** flattens the occurrence tree to its geometry-bearing leaves: one
719//   ACOMP per leaf occurrence, each carrying the COMPOSED world pose. Every
720//   part is stored once for the whole document.
721// - **Nested** keeps the tree: each assembly-node product becomes a part
722//   document that itself carries `{partsLibrary, features: [ACOMP…,
723//   IMPORT3D…]}`, built bottom-up by the same recursive builder, and the
724//   parent gets ONE ACOMP per sub-assembly occurrence.
725//
726// Neither is the deprecated one. Nested shows the real tree; flat is the right
727// answer for a deep or pathological file, and it stores a part reused at two
728// levels ONCE, where nesting stores it once PER LEVEL. For a depth-1 tree the
729// two lanes produce byte-identical documents — the cheapest correctness check
730// there is, and `nested_matches_flat_for_a_depth_one_tree` asserts exactly it.
731//
732// # PROBE then CONSUME — because the parse is the expensive half
733//
734// The app must know the counts BEFORE it can offer the choice ("7 parts, 23
735// instances — import as assembly or as bodies?"), and re-reading multi-MB
736// Part-21 text after the user clicks would pay the file's single most expensive
737// cost twice. So [`EngineState::probe_step_assembly`] performs the ONE parse and
738// stashes the [`brep_kernel::StepAssembly`] in
739// [`EngineState::pending_step_assembly`];
740// [`EngineState::import_probed_step_assembly`] TAKES it. Cancel
741// ([`EngineState::discard_probed_step_assembly`]), a second probe, and a
742// document switch all drop it, so a user who cancels three imports is holding
743// zero parsed assemblies — a real consideration, since the stash keeps every
744// product's solids resident for as long as the dialog is open.
745//
746// # ONE rebuild for the whole import
747//
748// `add_feature` re-runs the entire history per call, so appending N instances
749// through it is O(N²). This lane appends them all through
750// [`EngineState::add_features`] — one push batch, one rebuild, one undo step.
751// (Not `set_history_json`: that is the document-SWITCH path, which clears the
752// kernel history cache and resets the runner's delta baseline.)
753//
754// # Fallback, never a silent zero
755//
756// No structure at all, or every geometry-bearing product failing to encode, both
757// end at today's flat lane. "A successful import that produces zero components"
758// is a failure wearing a result's clothes, so the zero-component case is an
759// `Err` for the dialog-driven entry point (the app owns the file text and re-runs
760// the flat import) and an automatic fall-back for the text-taking convenience.
761// ===========================================================================
762
763/// What the import dialog needs to describe a STEP file's structure — counts
764/// only, so the probe can answer without building anything.
765#[derive(Debug, Clone, Copy, PartialEq, Eq)]
766pub struct StepAssemblyProbe {
767    /// Unique geometry-bearing products → parts-library entries. The floor, not
768    /// the final count: a non-rigid occurrence bakes its own extra entry (§3.4).
769    pub parts: usize,
770    /// Geometry-bearing occurrences → ACOMP instance features.
771    pub instances: usize,
772    /// Longest root→node chain of occurrences. `1` is a flat assembly; `> 1`
773    /// means sub-assemblies exist, so [`StepAssemblyImport::nested`] changes
774    /// the shape of the result and the dialog's choice is worth offering.
775    pub nested_depth: usize,
776}
777
778/// The choices the import dialog collects.
779#[derive(Debug, Clone, Copy, Default)]
780pub struct StepAssemblyImport {
781    /// Build nested rigid sub-assembly documents instead of flattening the
782    /// tree to its leaf occurrences.
783    ///
784    /// `false` (the `Default`) is the flat lane, byte-for-byte unchanged. On a
785    /// depth-1 tree the two produce the same document, so this flag only ever
786    /// matters for a file that really has sub-assemblies.
787    pub nested: bool,
788}
789
790/// What an import did — the numbers the status line and notice report.
791#[derive(Debug, Clone, Default, PartialEq, Eq)]
792pub struct StepAssemblyReport {
793    /// Parts-library entries this import added or reused — the entries of the
794    /// USER'S document. On a nested import that is the top level only: a
795    /// sub-assembly's own entries live in ITS document's library, which the
796    /// parent never sees.
797    pub parts: usize,
798    /// ACOMP instance features appended to the user's document. Nested: one per
799    /// ROOT-level occurrence (a sub-assembly is one component), not one per
800    /// leaf body.
801    pub instances: usize,
802    /// Occurrences whose non-rigid factor was baked into a distinct part
803    /// (§3.4), summed over every level a nested import built.
804    pub baked_nonrigid: usize,
805    /// Products (or baked non-rigid variants of one) that did not encode to a
806    /// payload — skipped and counted, never fatal: the importer's
807    /// graceful-degradation contract, carried up to this altitude. Summed over
808    /// every level a nested import built.
809    pub failed_products: usize,
810    /// The first thing that went wrong, from the kernel's body-build errors or
811    /// this lane's own encode failures.
812    pub first_error: Option<String>,
813    /// The structured lane did not run: the file carries no usable structure, or
814    /// nothing in it encoded, so the bodies were imported through the flat lane
815    /// exactly as before. Only ever `true` from [`EngineState::import_step_assembly`],
816    /// which holds the text; the dialog-driven entry point returns `Err` instead
817    /// and lets its caller re-run the flat import it already has the text for.
818    pub flat_fallback: bool,
819}
820
821/// The outcome of consuming a parsed assembly, before it is shaped into either
822/// an `Err` (dialog lane) or a flat fallback (text lane) — so neither has to
823/// recognise "nothing imported" by matching an error string.
824enum Consumed {
825    Imported(StepAssemblyReport),
826    /// Every geometry-bearing product failed to encode: no components, so this
827    /// is not an import.
828    NoComponents {
829        failed_products: usize,
830        first_error: Option<String>,
831    },
832}
833
834/// A row-major 4×4 affine, the shape `StepOccurrence::placement` and
835/// `AffineTransform` both use.
836type Mat4 = [f64; 16];
837
838/// One node of the composed occurrence tree — a product at a world pose.
839struct PlacedProduct {
840    /// Index into `StepAssembly::products`.
841    product: usize,
842    /// Composed child-local → world transform.
843    world: Mat4,
844    /// Occurrence edges between a root and this node (`0` at a root).
845    depth: usize,
846    /// Every edge on the path here was rigid, so `world` IS a component pose.
847    /// False means the non-rigid factor must be baked into the part (§3.4).
848    rigid_path: bool,
849    /// The STEP occurrence edges walked to get here, root first — the chain a
850    /// lifted OCCURRENCE-scoped annotation names its geometry through
851    /// (`brep_kernel::rewrite_occurrence_refs`). Empty at a root.
852    chain: Vec<usize>,
853}
854
855/// A parts-library entry this import needs: a product, plus the bits of the
856/// non-rigid factor baked into it (all-zero linear block ⇒ none). Two
857/// occurrences of one product under DIFFERENT non-rigid factors are different
858/// parts — never a wrong-handed reuse.
859type PartKey = (usize, [u64; 9]);
860
861/// The `PartKey` factor slot for a plain rigid instance.
862const NO_FACTOR: [u64; 9] = [0; 9];
863
864impl EngineState {
865    /// Read a STEP file's product structure — THE parse of a structured import.
866    /// Stashes the parsed assembly (with every product's solids) for
867    /// [`Self::import_probed_step_assembly`] and returns the dialog's counts.
868    ///
869    /// `Ok(None)` = no usable structure (no NAUO edges, or none reaching built
870    /// geometry): the caller imports through the flat
871    /// [`Self::import_step_feature`] lane with the text it already holds, which
872    /// is byte-for-byte today's behaviour. `Err` only for text that is not a
873    /// Part 21 file at all — a BROKEN assembly degrades, it does not fail.
874    ///
875    /// Replaces any previously stashed assembly on EVERY outcome, `Ok(None)`
876    /// included: a stale stash surviving a probe of a different file is how a
877    /// consume silently imports the wrong one.
878    pub fn probe_step_assembly(
879        &mut self,
880        step_text: &str,
881    ) -> Result<Option<StepAssemblyProbe>, String> {
882        let id = self.submit_step_probe(step_text);
883        // Inline answers inside `submit`'s own pump; a background runner has
884        // not answered yet and this call must not pretend it has.
885        match self.take_step_probe() {
886            Some((answered, outcome)) if answered == id => match outcome {
887                super::StepProbeOutcome::Structure(probe) => Ok(Some(probe)),
888                super::StepProbeOutcome::Flat => Ok(None),
889                super::StepProbeOutcome::Failed(error) => Err(error),
890            },
891            _ => Err(
892                "the STEP probe is still running on the background runner — use \
893                 submit_step_probe / take_step_probe"
894                    .into(),
895            ),
896        }
897    }
898
899    /// SUBMIT a STEP text to be probed for product structure on the runner
900    /// (the parse builds every product's bodies: seconds for a real assembly,
901    /// which is why it leaves the UI thread). The answer arrives through
902    /// [`Self::take_step_probe`] under the returned id, after a later `pump`;
903    /// a found structure is stashed for [`Self::import_probed_step_assembly`].
904    /// Any earlier stash is dropped now — the probe REPLACES it on every
905    /// outcome, so a stale parse can never be consumed for the wrong file.
906    ///
907    /// The structure test the parse would make is "any NEXT_ASSEMBLY_USAGE_
908    /// OCCURRENCE entity" (`assembly_edges`), so a text with none cannot have
909    /// structure and is answered `Flat` without a trip to the runner: a part
910    /// file — the common upload — no longer pays a full parse only to be told
911    /// to take the flat lane, where the worker parses it anyway. (The text
912    /// test is a superset of the entity test: a stray mention in a comment
913    /// merely runs the parse.)
914    pub fn submit_step_probe(&mut self, step_text: &str) -> u64 {
915        self.pending_step_assembly = None;
916        let id = self.next_step_probe_id;
917        self.next_step_probe_id = self.next_step_probe_id.wrapping_add(1);
918        if !step_text.contains("NEXT_ASSEMBLY_USAGE_OCCURRENCE") {
919            self.step_probe_results
920                .push_back((id, super::StepProbeOutcome::Flat));
921            return id;
922        }
923        self.pending_step_probes.insert(id);
924        self.runner.submit_step_probe(crate::runner::StepProbeRequest {
925            id,
926            text: step_text.to_string(),
927        });
928        self.pump();
929        id
930    }
931
932    /// The oldest answered probe, if any: its submission id and what it found.
933    pub fn take_step_probe(&mut self) -> Option<(u64, super::StepProbeOutcome)> {
934        self.step_probe_results.pop_front()
935    }
936
937    /// Whether a submitted probe has not been answered yet — the app keeps the
938    /// frame loop alive (and the panel its "reading…" status) while it is.
939    pub fn step_probes_pending(&self) -> bool {
940        !self.pending_step_probes.is_empty()
941    }
942
943    /// Import the assembly [`Self::probe_step_assembly`] stashed: one
944    /// parts-library entry per unique product, one ACOMP instance per
945    /// occurrence, ONE rebuild. TAKES the stash, so a double-import is an error
946    /// rather than a double-insert.
947    ///
948    /// `doc_name` names products the file left unnamed (`{doc_name}-part-{id}`).
949    /// `opts.nested` chooses between the flat and nested shapes — see
950    /// [`StepAssemblyImport::nested`]. Errs when nothing is stashed, and when
951    /// every product failed to encode — the latter being the caller's cue to
952    /// re-run the flat import with the file text it holds.
953    /// `sink` receives every unique part document so the app can write it to
954    /// the model store and hand back a real `sourceKey`; pass [`EmbeddedOnly`]
955    /// to keep the parts embedded (what a caller with no store does).
956    pub fn import_probed_step_assembly(
957        &mut self,
958        doc_name: &str,
959        opts: StepAssemblyImport,
960        sink: &mut dyn PartSink,
961    ) -> Result<StepAssemblyReport, String> {
962        let assembly = self.pending_step_assembly.take().ok_or_else(|| {
963            "import STEP assembly: nothing probed (call probe_step_assembly first)".to_string()
964        })?;
965        match self.consume_step_assembly(assembly, doc_name, opts.nested, sink) {
966            Consumed::Imported(report) => Ok(report),
967            Consumed::NoComponents { first_error, .. } => Err(format!(
968                "import STEP assembly: no part of the assembly could be built{}",
969                first_error
970                    .map(|error| format!(" ({error})"))
971                    .unwrap_or_default()
972            )),
973        }
974    }
975
976    /// Drop a probed assembly and the solids it holds resident — the dialog's
977    /// Cancel. Idempotent.
978    pub fn discard_probed_step_assembly(&mut self) {
979        self.pending_step_assembly = None;
980    }
981
982    /// Probe + consume in one call, falling back to the flat lane by itself —
983    /// the HEADLESS/test entry point. The app uses the probe/consume pair
984    /// instead, because it has a dialog between the two halves.
985    ///
986    /// Still exactly one parse: this is `probe_step_assembly` followed by the
987    /// consume of what it stashed.
988    ///
989    /// Parts stay EMBEDDED here ([`EmbeddedOnly`]): this entry point has no
990    /// store handle and no way to ask for a destination. The app uses the
991    /// probe/consume pair with a real sink.
992    pub fn import_step_assembly(
993        &mut self,
994        step_text: &str,
995        doc_name: &str,
996        opts: StepAssemblyImport,
997    ) -> Result<StepAssemblyReport, String> {
998        let structured = self.probe_step_assembly(step_text)?.is_some();
999        let outcome = structured.then(|| {
1000            let assembly = self
1001                .pending_step_assembly
1002                .take()
1003                .expect("a Some probe stashed the assembly it counted");
1004            self.consume_step_assembly(assembly, doc_name, opts.nested, &mut EmbeddedOnly)
1005        });
1006        match outcome {
1007            Some(Consumed::Imported(report)) => Ok(report),
1008            // No structure, or a structure nothing built out of: import the
1009            // bodies exactly as the pre-assembly lane did.
1010            Some(Consumed::NoComponents {
1011                failed_products,
1012                first_error,
1013            }) => {
1014                self.import_step_feature(step_text)?;
1015                Ok(StepAssemblyReport {
1016                    failed_products,
1017                    first_error,
1018                    flat_fallback: true,
1019                    ..StepAssemblyReport::default()
1020                })
1021            }
1022            None => {
1023                self.import_step_feature(step_text)?;
1024                Ok(StepAssemblyReport {
1025                    flat_fallback: true,
1026                    ..StepAssemblyReport::default()
1027                })
1028            }
1029        }
1030    }
1031
1032    /// The import itself, shared by both entry points so neither has to
1033    /// recognise "nothing imported" from an error string.
1034    fn consume_step_assembly(
1035        &mut self,
1036        assembly: brep_kernel::StepAssembly,
1037        doc_name: &str,
1038        nested: bool,
1039        sink: &mut dyn PartSink,
1040    ) -> Consumed {
1041        let mut first_error = assembly.first_error.clone();
1042        // ONE writer for the whole import, so identical content is written to
1043        // the store exactly once however many products or LEVELS share it.
1044        let mut writer = PartWriter::new(sink);
1045
1046        // --- what to build ------------------------------------------------
1047        // One row per component the USER'S document gets, each naming the
1048        // library entry it needs. Flat walks the whole tree to its leaves;
1049        // nested stops at the root's own children and folds everything below
1050        // each of them into that child's part document.
1051        let plan = if nested {
1052            plan_nested(&assembly, doc_name, &mut first_error, &mut writer)
1053        } else {
1054            plan_flat(&assembly, &mut first_error)
1055        };
1056        let Plan {
1057            wanted,
1058            factors,
1059            documents,
1060            mut failed_products,
1061            baked_below_root,
1062        } = plan;
1063
1064        // --- build the library entries -------------------------------------
1065        // In (pd_ref, factor) order so an import is deterministic regardless of
1066        // the tree's emit order, and ONCE per key however many instances use it.
1067        let mut keys: Vec<PartKey> = wanted.iter().map(|(key, _, _)| *key).collect();
1068        keys.sort_unstable();
1069        keys.dedup();
1070        let mut entry_names: std::collections::HashMap<PartKey, String> =
1071            std::collections::HashMap::new();
1072        {
1073            // THE metadata bracket. `native_import_payload` seals whatever record
1074            // this thread's scene-metadata store holds for each name it stamps —
1075            // right for a snapshot of the live scene, catastrophic here: a new
1076            // part whose stamped face names collide with names already in THIS
1077            // document would silently carry the current document's metadata.
1078            // Scoped to the encode alone; the rebuild below stamps records the
1079            // document must keep, and this guard's drop would discard them.
1080            //
1081            // The nested lane's payloads are encoded inside `plan_nested`,
1082            // which holds a bracket of its own for exactly the same reason.
1083            let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
1084            for key in &keys {
1085                // Nested pre-built the whole document (a sub-assembly's is a
1086                // recursive `{partsLibrary, features}`); flat builds the §3.2
1087                // native part document right here.
1088                let built = match documents.get(key) {
1089                    Some((name, document)) => install_part(name, document, &mut writer),
1090                    None => {
1091                        let product = assembly
1092                            .products
1093                            .iter()
1094                            .find(|product| product.pd_ref == key.0)
1095                            .expect("every key names a product of this assembly");
1096                        build_library_entry(product, factors.get(key), doc_name, &mut writer)
1097                    }
1098                };
1099                match built {
1100                    Ok(name) => {
1101                        entry_names.insert(*key, name);
1102                    }
1103                    Err(error) => {
1104                        failed_products += 1;
1105                        note(&mut first_error, error);
1106                    }
1107                }
1108            }
1109        }
1110        if entry_names.is_empty() {
1111            return Consumed::NoComponents {
1112                failed_products,
1113                first_error,
1114            };
1115        }
1116
1117        // --- append every instance in ONE history mutation -----------------
1118        // `insert_component`'s rule, verbatim: ground the FIRST component only
1119        // when the document has none yet. Grounding a second one over-constrains
1120        // the next solve.
1121        let mut ground_next = !(0..self.history.len()).any(|index| {
1122            matches!(
1123                self.history.feature_type(index).as_deref(),
1124                Some("ACOMP") | Some("ASSEMBLY COMPONENT")
1125            )
1126        });
1127        let mut features: Vec<serde_json::Value> = Vec::with_capacity(wanted.len());
1128        let mut baked_nonrigid = 0usize;
1129        // Which component carries the geometry a STEP occurrence chain names —
1130        // the map the file's occurrence-scoped PMI is rewritten through, built
1131        // while the ids are minted because that is the only moment both halves
1132        // exist.
1133        let mut namespaces: std::collections::HashMap<Vec<usize>, String> =
1134            std::collections::HashMap::new();
1135        for (key, pose, chain) in &wanted {
1136            let Some(part_name) = entry_names.get(key) else {
1137                continue; // this product failed to encode; counted above
1138            };
1139            let transform = match brep_kernel::AffineTransform::new(*pose) {
1140                Ok(transform) => transform,
1141                Err(error) => {
1142                    note(&mut first_error, format!("occurrence pose: {error}"));
1143                    continue;
1144                }
1145            };
1146            if key.1 != NO_FACTOR {
1147                baked_nonrigid += 1;
1148            }
1149            let id = self.history.next_feature_id("ACOMP");
1150            namespaces
1151                .entry(chain.clone())
1152                .or_insert_with(|| format!("{id}:"));
1153            features.push(serde_json::json!({
1154                "type": "ACOMP",
1155                "inputParams": {
1156                    "id": id,
1157                    "partName": part_name,
1158                    "transform": brep_kernel::transform_to_pose_params(&transform),
1159                    "isFixed": ground_next,
1160                },
1161                "persistentData": {}
1162            }));
1163            ground_next = false;
1164        }
1165        if features.is_empty() {
1166            return Consumed::NoComponents {
1167                failed_products,
1168                first_error,
1169            };
1170        }
1171
1172        // The library block must ride the request so the display runner ingests
1173        // the new entries on the very next run (as `insert_component` does).
1174        // Written only now that there are components to reference them, so an
1175        // import that produced nothing leaves the document untouched.
1176        if let Ok(library) =
1177            serde_json::from_str::<serde_json::Value>(&brep_kernel::parts_library_json())
1178        {
1179            self.history.set_parts_library(library);
1180        }
1181        // Frame the assembly once the (possibly async) run lands — see
1182        // [`EngineState::pending_fit`], same reasoning as `import_step_feature`.
1183        self.pending_fit = true;
1184        let instances = features.len();
1185        let baked_nonrigid = baked_nonrigid + baked_below_root;
1186        self.add_features(&features);
1187
1188        // The file's ASSEMBLY-level PMI — annotations it pinned to an
1189        // occurrence, annotations spanning two parts, free notes — merged into
1190        // the document's own block with its references rewritten into THIS
1191        // import's component namespaces.
1192        //
1193        // AFTER the features, and with no checkpoint of its own, for the
1194        // reason `import_step_feature` reads its PMI BEFORE its `add_feature`:
1195        // `push_features` checkpoints at its START, so a block written first
1196        // is inside the snapshot undo restores — one undo would take the
1197        // components away and leave the annotations behind, every one of them
1198        // naming a component that no longer exists. Both writes have to fall
1199        // after the one checkpoint.
1200        //
1201        // It costs a second rebuild, which is what the flat lane already pays,
1202        // and only on a file that carries assembly-level PMI at all.
1203        //
1204        // A part's OWN PMI is not here: it rode into that part's document in
1205        // `native_part_document`, once for the part however many instances
1206        // place it — the exporter's rule, which is what makes the round trip
1207        // land the same annotations on the same parts.
1208        let pmi_unplaced = self.merge_assembly_pmi(&assembly, &namespaces);
1209        for line in &assembly.pmi_diagnostics {
1210            note(&mut first_error, line.clone());
1211        }
1212        if pmi_unplaced > 0 {
1213            note(
1214                &mut first_error,
1215                format!(
1216                    "{pmi_unplaced} PMI reference(s) name an occurrence this import placed no \
1217                     component for; the annotations are kept unresolved"
1218                ),
1219            );
1220        }
1221        Consumed::Imported(StepAssemblyReport {
1222            // DISTINCT entries, not distinct keys: `add_part_to_library` reuses
1223            // an entry whose content already matches, so two products that are
1224            // the same geometry collapse to one part (§3.5's free content dedup).
1225            parts: entry_names
1226                .values()
1227                .collect::<std::collections::HashSet<_>>()
1228                .len(),
1229            instances,
1230            baked_nonrigid,
1231            failed_products,
1232            first_error,
1233            flat_fallback: false,
1234        })
1235    }
1236}
1237
1238impl EngineState {
1239    /// Merge a structured import's ASSEMBLY-level PMI into the open document's
1240    /// block, rewriting every occurrence-scoped reference into the component
1241    /// namespace this import minted for that STEP occurrence chain.
1242    ///
1243    /// Returns how many references named a chain with no component — a NESTED
1244    /// import folds everything below a root child into that child's own
1245    /// document, so an annotation the file pinned three levels down has no
1246    /// top-level component to name. Those references keep the chain they came
1247    /// with, so the row reports itself in the panel instead of silently
1248    /// resolving to some other instance.
1249    ///
1250    /// No rerun and no undo checkpoint of its own: the caller writes this
1251    /// before `add_features`, whose single rebuild resolves it.
1252    fn merge_assembly_pmi(
1253        &mut self,
1254        assembly: &brep_kernel::StepAssembly,
1255        namespaces: &std::collections::HashMap<Vec<usize>, String>,
1256    ) -> usize {
1257        let Some(lifted) = assembly.pmi.clone() else {
1258            return 0;
1259        };
1260        let mut unplaced = 0usize;
1261        let mut state = self.pmi_state();
1262        for view in lifted.views {
1263            let id = state.next_id("VIEW");
1264            let mut annotations = Vec::with_capacity(view.annotations.len());
1265            for mut annotation in view.annotations {
1266                unplaced += brep_kernel::rewrite_occurrence_refs(&mut annotation.params, |chain| {
1267                    namespaces.get(chain).cloned()
1268                });
1269                let prefix = brep_kernel::pmi_type(&annotation.kind)
1270                    .map(|def| def.short_name)
1271                    .unwrap_or("PMI");
1272                let fresh = state.next_id(prefix);
1273                if let Some(object) = annotation.params.as_object_mut() {
1274                    object.insert("id".into(), serde_json::Value::String(fresh));
1275                }
1276                annotations.push(annotation);
1277            }
1278            state.views.push(brep_kernel::PmiView {
1279                id,
1280                name: view.name,
1281                camera: view.camera,
1282                display: view.display,
1283                annotations,
1284            });
1285        }
1286        let block = serde_json::to_value(&state).ok();
1287        self.history.set_pmi_block_no_undo(block);
1288        // The tail has to re-resolve the merged block against the components
1289        // the run above created; nothing else in this lane reruns after them.
1290        self.rerun_history();
1291        unplaced
1292    }
1293}
1294
1295/// What one import decided to build, before any of it is installed: the rows
1296/// the user's document gets, and whatever each lane needed to work out on the
1297/// way there.
1298#[derive(Default)]
1299struct Plan {
1300    /// One row per component of the USER'S document, in emit order: the
1301    /// library entry it needs, its pose, and the STEP occurrence chain it
1302    /// stands for — which is how a lifted occurrence-scoped annotation finds
1303    /// the component that carries its geometry.
1304    wanted: Vec<(PartKey, Mat4, Vec<usize>)>,
1305    /// FLAT only: the non-rigid factor a key's part must bake (§3.4). The
1306    /// nested lane bakes inside its own builder and hands the finished document
1307    /// over in `documents` instead.
1308    factors: std::collections::HashMap<PartKey, Mat4>,
1309    /// NESTED only: `(entry name, part document)` per key, already built — a
1310    /// leaf's §3.2 native document, or a sub-assembly's recursive
1311    /// `{partsLibrary, features}`.
1312    documents: std::collections::HashMap<PartKey, (String, serde_json::Value)>,
1313    /// Products that did not encode while planning (nested builds payloads
1314    /// during the plan; flat builds them during the install).
1315    failed_products: usize,
1316    /// Non-rigid occurrences baked BELOW the root — nested only, since the flat
1317    /// lane has no below-the-root and counts its bakes at install time.
1318    baked_below_root: usize,
1319}
1320
1321/// **FLAT**: flatten the occurrence tree to its geometry-bearing nodes, each
1322/// carrying the COMPOSED world pose. Byte-for-byte the lane A6 shipped.
1323fn plan_flat(assembly: &brep_kernel::StepAssembly, first_error: &mut Option<String>) -> Plan {
1324    let mut plan = Plan::default();
1325    for placed in &compose_world_occurrences(assembly) {
1326        let product = &assembly.products[placed.product];
1327        if product.bodies.is_empty() {
1328            continue; // a pure assembly node contributes structure, not a component
1329        }
1330        let (key, pose) = if placed.rigid_path {
1331            ((product.pd_ref, NO_FACTOR), placed.world)
1332        } else {
1333            // §3.4: world = rigid · factor. Bake `factor` into a distinct part
1334            // and give the instance the rigid residue, so a mirrored instance
1335            // never lands on its unmirrored twin.
1336            match split_rigid(&placed.world) {
1337                // Non-rigid edges that cancel out along the path leave an
1338                // identity factor: that is an ordinary instance of the ordinary
1339                // part, not a bake.
1340                Ok((rigid, factor)) if is_identity(&factor) => {
1341                    ((product.pd_ref, NO_FACTOR), rigid)
1342                }
1343                Ok((rigid, factor)) => {
1344                    let key = (product.pd_ref, factor_key(&factor));
1345                    plan.factors.insert(key, factor);
1346                    (key, rigid)
1347                }
1348                Err(error) => {
1349                    note(first_error, error);
1350                    continue;
1351                }
1352            }
1353        };
1354        plan.wanted.push((key, pose, placed.chain.clone()));
1355    }
1356    plan
1357}
1358
1359/// **NESTED**: the live document plays the ROOT, so it gets one component per
1360/// root-level row and nothing deeper —
1361///
1362/// - a root's OWN bodies become a leaf part at identity (exactly the flat
1363///   lane's treatment of interior geometry at the root), and
1364/// - each root-child occurrence becomes ONE component: a leaf part when the
1365///   child has no children of its own, else a rigid sub-assembly whose part
1366///   document carries its own `partsLibrary` and its own ACOMPs.
1367///
1368/// Emit order matches [`plan_flat`]'s DFS pre-order — root before its children,
1369/// children by ascending `edge_ref` — which is what makes the two lanes produce
1370/// the SAME document for a depth-1 tree.
1371fn plan_nested(
1372    assembly: &brep_kernel::StepAssembly,
1373    doc_name: &str,
1374    first_error: &mut Option<String>,
1375    writer: &mut PartWriter<'_>,
1376) -> Plan {
1377    // The same bracket the install loop holds, for the same reason: every
1378    // payload this builder encodes (at every level) must see an empty ambient
1379    // scene-metadata store, or a nested leaf whose stamped face names collide
1380    // with the live document's silently inherits the live document's records.
1381    let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
1382    let mut build = NestedBuild {
1383        assembly,
1384        doc_name,
1385        writer,
1386        memo: std::collections::HashMap::new(),
1387        factors: std::collections::HashMap::new(),
1388        entries: 0,
1389        bytes: 0,
1390        failed_products: 0,
1391        baked_nonrigid: 0,
1392        first_error: None,
1393    };
1394    let mut plan = Plan::default();
1395    for &root in &assembly.roots {
1396        let mut rows: Vec<(DocKey, Mat4, Vec<usize>)> = Vec::new();
1397        // The root's OWN bodies become a leaf part at identity — exactly the
1398        // flat lane's treatment, and the reason a depth-1 tree comes out the
1399        // same either way.
1400        if !assembly.products[root].bodies.is_empty() {
1401            rows.push((
1402                DocKey::Leaf((assembly.products[root].pd_ref, NO_FACTOR)),
1403                MAT4_IDENTITY,
1404                Vec::new(),
1405            ));
1406        }
1407        // Root-level bakes are counted by the install loop's own pass over
1408        // `wanted` (they are ordinary top-level rows); only bakes BELOW the root
1409        // — which never become rows of the user's document — are counted here.
1410        let mut root_level_bakes = 0usize;
1411        build.place_children(root, &[root], &mut rows, &mut root_level_bakes);
1412        for (key, pose, chain) in rows {
1413            let part = match build.document(key, &mut vec![root]) {
1414                Ok(Some(document)) => document,
1415                // A subtree with no geometry anywhere places nothing — the flat
1416                // lane says the same thing by emitting no component for it.
1417                Ok(None) => continue,
1418                Err(error) => {
1419                    build.failed_products += 1;
1420                    note(&mut build.first_error, error);
1421                    continue;
1422                }
1423            };
1424            let part_key = key.part_key(assembly);
1425            plan.documents.insert(part_key, part);
1426            plan.wanted.push((part_key, pose, chain));
1427        }
1428    }
1429    plan.failed_products = build.failed_products;
1430    plan.baked_below_root = build.baked_nonrigid;
1431    if let Some(error) = build.first_error {
1432        note(first_error, error);
1433    }
1434    plan
1435}
1436
1437/// How deep the recursive builder will go before it refuses. `read_step_assembly`
1438/// guards cycles inside its own walk and [`NestedBuild::document`] guards them
1439/// again along the recursion path, so this is the SECOND line: a malformed file
1440/// that is merely pathologically deep (rather than cyclic) must not run the
1441/// native stack out. Sixty-four levels of embedded documents is already far past
1442/// anything a real CAD assembly carries — and each level embeds the whole
1443/// subtree below it, so the document would be unusable long before then.
1444const MAX_NESTED_DEPTH: usize = 64;
1445
1446/// How many DISTINCT part documents a nested import may build. Bounds the
1447/// builder's work; it does NOT bound the result's size — see
1448/// [`MAX_NESTED_BYTES`], which is the guard that matters.
1449const MAX_NESTED_ENTRIES: usize = 10_000;
1450
1451/// How many bytes of part document a nested import may EMBED, summed over every
1452/// `partsLibrary` entry it writes at every level.
1453///
1454/// This is the guard neither the depth cap nor the entry count provides. A
1455/// product reachable at many different depths is stored once PER LEVEL — the
1456/// memo builds its document once, but each parent embeds a COPY, so a
1457/// diamond-shaped structure well inside the depth cap can still multiply out
1458/// geometrically. Charging the embedded bytes is the only place that
1459/// multiplication is visible, so it is charged where it happens.
1460const MAX_NESTED_BYTES: usize = 256 * 1024 * 1024;
1461
1462/// What a nested part document is memoised under. A product is either a leaf
1463/// (no occurrence children) or an assembly node, never both, so the two
1464/// variants can never name the same product — except at a ROOT, whose own
1465/// bodies become a leaf part while the root itself is an assembly node. That
1466/// case is exactly why this is an enum and not a bare [`PartKey`].
1467#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1468enum DocKey {
1469    /// A geometry-bearing product placed as a part: `(pd_ref, baked factor)`.
1470    Leaf(PartKey),
1471    /// A product placed as a rigid sub-assembly, by index into `products`.
1472    Assembly(usize),
1473}
1474
1475impl DocKey {
1476    /// The parts-library identity this document is stored under. Always keyed on
1477    /// the `pd_ref` (never the product INDEX, which lives in a different number
1478    /// space and would collide with some other product's `pd_ref`). An assembly
1479    /// node never carries a baked factor — a non-rigid edge into one is skipped,
1480    /// see [`NestedBuild::place_children`] — so `NO_FACTOR` is exact.
1481    fn part_key(self, assembly: &brep_kernel::StepAssembly) -> PartKey {
1482        match self {
1483            DocKey::Leaf(key) => key,
1484            DocKey::Assembly(product) => (assembly.products[product].pd_ref, NO_FACTOR),
1485        }
1486    }
1487}
1488
1489/// The recursive builder behind [`plan_nested`]: turns one product into the part
1490/// document that represents it, bottom-up, memoised so a product reached from
1491/// several parents is built ONCE however many places embed it.
1492struct NestedBuild<'a, 'w> {
1493    assembly: &'a brep_kernel::StepAssembly,
1494    doc_name: &'a str,
1495    /// Where a CHILD library entry's document is written, shared with the
1496    /// top-level install loop so one part is one file at every level.
1497    writer: &'a mut PartWriter<'w>,
1498    /// `None` = this subtree carries no geometry at all, so nothing places it.
1499    memo: std::collections::HashMap<DocKey, Option<(String, serde_json::Value)>>,
1500    /// The non-rigid factor behind every baked [`DocKey::Leaf`] key, so the
1501    /// builder never has to reconstruct a matrix out of its own hash key.
1502    factors: std::collections::HashMap<PartKey, Mat4>,
1503    entries: usize,
1504    /// Bytes of part document embedded so far — the [`MAX_NESTED_BYTES`] charge.
1505    bytes: usize,
1506    failed_products: usize,
1507    baked_nonrigid: usize,
1508    first_error: Option<String>,
1509}
1510
1511impl NestedBuild<'_, '_> {
1512    /// The part document for `key`, built once and reused. `ancestors` is the
1513    /// recursion path — the cycle guard, and the depth the cap is measured on.
1514    ///
1515    /// A cyclic file gets ONE deterministic truncation: the memo keeps whichever
1516    /// path reached a node first, and that path's skipped back-edge is the one
1517    /// every embedding sees. Deterministic and finite is the whole contract for
1518    /// input that is malformed by construction.
1519    fn document(
1520        &mut self,
1521        key: DocKey,
1522        ancestors: &mut Vec<usize>,
1523    ) -> Result<Option<(String, serde_json::Value)>, String> {
1524        if let Some(hit) = self.memo.get(&key) {
1525            return Ok(hit.clone());
1526        }
1527        if ancestors.len() >= MAX_NESTED_DEPTH {
1528            return Err(format!(
1529                "nested import: sub-assembly nesting deeper than {MAX_NESTED_DEPTH} levels \
1530                 (import as bodies, or import flat)"
1531            ));
1532        }
1533        let built = match key {
1534            DocKey::Leaf(part) => self.leaf_document(part),
1535            DocKey::Assembly(product) => {
1536                ancestors.push(product);
1537                let built = self.assembly_document(product, ancestors);
1538                ancestors.pop();
1539                built
1540            }
1541        }?;
1542        self.memo.insert(key, built.clone());
1543        Ok(built)
1544    }
1545
1546    /// A geometry-bearing product as the §3.2 part document — the same one the
1547    /// flat lane installs, built by the same helper, so a depth-1 nested import
1548    /// and a flat one store byte-identical entries.
1549    fn leaf_document(
1550        &mut self,
1551        key: PartKey,
1552    ) -> Result<Option<(String, serde_json::Value)>, String> {
1553        let product = self
1554            .assembly
1555            .products
1556            .iter()
1557            .find(|product| product.pd_ref == key.0)
1558            .expect("every key names a product of this assembly");
1559        if product.bodies.is_empty() {
1560            return Ok(None);
1561        }
1562        let factor = self.factors.get(&key).copied();
1563        self.spend_entry()?;
1564        native_part_document(product, factor.as_ref(), self.doc_name).map(Some)
1565    }
1566
1567    /// An assembly-node product as a rigid sub-assembly document: its OWN bodies
1568    /// as plain native IMPORT3D features (the interior-node geometry Phase 1
1569    /// could only make a SIBLING of its own children), one ACOMP per child
1570    /// occurrence, and the children's documents in this level's own
1571    /// `partsLibrary`.
1572    ///
1573    /// The entries carry NO snapshot. An entry with an unreadable snapshot heals
1574    /// from its embedded document (`assembly_component.rs`'s SELF-HEAL lane),
1575    /// and for a native part that heal is a decode + re-encode — so the level
1576    /// above bakes this whole subtree into ITS snapshot on insert, and these
1577    /// inner caches would only ever be rebuilt to be thrown away.
1578    fn assembly_document(
1579        &mut self,
1580        product: usize,
1581        ancestors: &mut Vec<usize>,
1582    ) -> Result<Option<(String, serde_json::Value)>, String> {
1583        let node = &self.assembly.products[product];
1584        let mut library = serde_json::Map::new();
1585        let mut features: Vec<serde_json::Value> = Vec::new();
1586
1587        // The node's own bodies first, matching the flat lane's "a node before
1588        // its children" emit order.
1589        if !node.bodies.is_empty() {
1590            let payload = brep_kernel::native_import_payload_with_appearance(
1591                "IMPORT3D1",
1592                &node.bodies,
1593                &node.appearances,
1594            )
1595            .map_err(|error| format!("part '{}': {error}", part_name(node, self.doc_name)))?;
1596            features.push(serde_json::json!({
1597                "type": "IMPORT3D",
1598                "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
1599                "persistentData": {},
1600            }));
1601        }
1602
1603        // One ACOMP per child occurrence, children by ascending `edge_ref`.
1604        let mut rows: Vec<(DocKey, Mat4, Vec<usize>)> = Vec::new();
1605        let mut bakes = 0usize;
1606        self.place_children(product, ancestors, &mut rows, &mut bakes);
1607        self.baked_nonrigid += bakes;
1608        let mut names: std::collections::HashMap<DocKey, String> =
1609            std::collections::HashMap::new();
1610        // `add_part_to_library`'s content reuse, applied to this level's block:
1611        // two products that are the SAME geometry collapse to one entry (§3.5's
1612        // free dedup), and every instance of either references it.
1613        let mut by_signature: std::collections::HashMap<String, String> =
1614            std::collections::HashMap::new();
1615        let mut components = 0usize;
1616        // The occurrence chain is not needed at this level: a sub-assembly's
1617        // own ACOMPs live in ITS document, which the open document's PMI never
1618        // names (an annotation pinned below a root child has no top-level
1619        // component — `merge_assembly_pmi` reports it).
1620        for (key, pose, _chain) in rows {
1621            let name = match names.get(&key) {
1622                Some(name) => name.clone(),
1623                None => {
1624                    let built = match self.document(key, ancestors) {
1625                        Ok(Some(built)) => built,
1626                        Ok(None) => continue,
1627                        Err(error) => {
1628                            self.failed_products += 1;
1629                            note(&mut self.first_error, error);
1630                            continue;
1631                        }
1632                    };
1633                    let serialized = built.1.to_string();
1634                    let signature = document_signature(&serialized);
1635                    let name = match by_signature.get(&signature) {
1636                        Some(name) => name.clone(),
1637                        None => {
1638                            // Charged HERE, at the embedding, because that is
1639                            // where a product stored once per level multiplies.
1640                            self.spend_bytes(serialized.len())?;
1641                            // Unique WITHIN this level's library — parent and
1642                            // child libraries are independent, so a name
1643                            // taken upstairs is free down here.
1644                            let name = unique_entry_name(&library, &built.0);
1645                            // A nested child is a part like any other: it gets
1646                            // its own store document and a REAL sourceKey, so
1647                            // Open Part and update-components work the same way
1648                            // however deep it sits.
1649                            let source_key =
1650                                self.writer.key_for(&name, &serialized, &signature);
1651                            library.insert(
1652                                name.clone(),
1653                                serde_json::json!({
1654                                    "sourceKey": source_key,
1655                                    "sourceSignature": signature.clone(),
1656                                    "document": built.1,
1657                                    "snapshot": "",
1658                                }),
1659                            );
1660                            by_signature.insert(signature, name.clone());
1661                            name
1662                        }
1663                    };
1664                    names.insert(key, name.clone());
1665                    name
1666                }
1667            };
1668            let Ok(transform) = brep_kernel::AffineTransform::new(pose) else {
1669                note(
1670                    &mut self.first_error,
1671                    format!("sub-assembly '{name}': occurrence pose is not an affine"),
1672                );
1673                continue;
1674            };
1675            components += 1;
1676            features.push(serde_json::json!({
1677                "type": "ACOMP",
1678                "inputParams": {
1679                    // Its OWN counter, so the ids read `ACOMP1..n` whether or
1680                    // not this node also owns bodies. (The id must match
1681                    // `ACOMP<digits>`: it IS the namespace prefix.)
1682                    "id": format!("ACOMP{components}"),
1683                    "partName": name,
1684                    "transform": brep_kernel::transform_to_pose_params(&transform),
1685                    // Written EXPLICITLY rather than left to the kernel's
1686                    // auto-ground rule, which keys on ABSENCE: the first
1687                    // component of an assembly is grounded, and every other one
1688                    // must not be, or the next solve is over-constrained.
1689                    "isFixed": components == 1,
1690                },
1691                "persistentData": {},
1692            }));
1693        }
1694
1695        // A node whose whole subtree failed to produce geometry places nothing.
1696        // Returning `None` rather than a feature-less document matters: an empty
1697        // document is a hard error inside `add_part_to_library`, which would turn
1698        // "there was nothing here" into "the import failed".
1699        if features.is_empty() {
1700            return Ok(None);
1701        }
1702        self.spend_entry()?;
1703        let mut document =
1704            serde_json::json!({ "partsLibrary": library, "features": features });
1705        // A sub-assembly is a part too: its own `PRODUCT.id` is the part number
1706        // the level above exports it under, and its own PMI — the annotations
1707        // on the bodies IT owns, not its children's — is its document's.
1708        if let Some(attributes) = part_attributes(node) {
1709            document[PART_ATTRIBUTES] = attributes;
1710        }
1711        if let Some(pmi) = &node.pmi {
1712            if let Ok(block) = serde_json::to_value(pmi) {
1713                document["pmi"] = block;
1714            }
1715        }
1716        Ok(Some((part_name(node, self.doc_name), document)))
1717    }
1718
1719    /// The child occurrences of `product`, as `(document key, pose, occurrence
1720    /// chain)` rows in the kernel walk's order — ascending `edge_ref`, with the
1721    /// same ancestor cycle guard. The pose is the occurrence's own child→parent
1722    /// placement: nesting is precisely what stops it having to be composed.
1723    ///
1724    /// The chain is one edge long here by construction: a nested import's rows
1725    /// are the ROOT's own children, and everything below one of them is folded
1726    /// into that child's document.
1727    fn place_children(
1728        &mut self,
1729        product: usize,
1730        ancestors: &[usize],
1731        rows: &mut Vec<(DocKey, Mat4, Vec<usize>)>,
1732        bakes: &mut usize,
1733    ) {
1734        let mut children: Vec<&brep_kernel::StepOccurrence> = self
1735            .assembly
1736            .occurrences
1737            .iter()
1738            .filter(|occurrence| occurrence.parent == product)
1739            .collect();
1740        children.sort_by_key(|occurrence| occurrence.edge_ref);
1741        for occurrence in children {
1742            if ancestors.contains(&occurrence.child) {
1743                note(
1744                    &mut self.first_error,
1745                    format!(
1746                        "occurrence #{} closes a cycle in the product structure and was skipped",
1747                        occurrence.edge_ref
1748                    ),
1749                );
1750                continue;
1751            }
1752            let child = &self.assembly.products[occurrence.child];
1753            let is_assembly = self
1754                .assembly
1755                .occurrences
1756                .iter()
1757                .any(|edge| edge.parent == occurrence.child);
1758            if occurrence.rigid {
1759                let key = if is_assembly {
1760                    DocKey::Assembly(occurrence.child)
1761                } else {
1762                    DocKey::Leaf((child.pd_ref, NO_FACTOR))
1763                };
1764                rows.push((key, occurrence.placement, vec![occurrence.edge_ref]));
1765                continue;
1766            }
1767            // §3.4 on a single edge: a leaf bakes its non-rigid factor into its
1768            // own part, exactly as the flat lane does with the composed pose.
1769            match split_rigid(&occurrence.placement) {
1770                Ok((rigid, factor)) if is_identity(&factor) => {
1771                    let key = if is_assembly {
1772                        DocKey::Assembly(occurrence.child)
1773                    } else {
1774                        DocKey::Leaf((child.pd_ref, NO_FACTOR))
1775                    };
1776                    rows.push((key, rigid, vec![occurrence.edge_ref]));
1777                }
1778                // A mirrored/scaled SUB-ASSEMBLY would have to push its factor
1779                // down through a whole document tree, rewriting every level's
1780                // poses. Nothing in the corpus does it, and a wrong answer here
1781                // would be a silently mis-handed assembly: skip and say so, so
1782                // the user can re-import flat (which bakes it correctly).
1783                Ok(_) if is_assembly => {
1784                    note(
1785                        &mut self.first_error,
1786                        format!(
1787                            "occurrence #{} places sub-assembly '{}' with a non-rigid transform, \
1788                             which a nested import cannot represent — import flat instead",
1789                            occurrence.edge_ref,
1790                            part_name(child, self.doc_name)
1791                        ),
1792                    );
1793                }
1794                Ok((rigid, factor)) => {
1795                    *bakes += 1;
1796                    let key = (child.pd_ref, factor_key(&factor));
1797                    self.factors.insert(key, factor);
1798                    rows.push((DocKey::Leaf(key), rigid, vec![occurrence.edge_ref]));
1799                }
1800                Err(error) => note(&mut self.first_error, error),
1801            }
1802        }
1803    }
1804
1805    /// Charge one built part document against [`MAX_NESTED_ENTRIES`].
1806    fn spend_entry(&mut self) -> Result<(), String> {
1807        self.entries += 1;
1808        if self.entries > MAX_NESTED_ENTRIES {
1809            return Err(format!(
1810                "nested import: more than {MAX_NESTED_ENTRIES} distinct parts \
1811                 (import as bodies, or import flat)"
1812            ));
1813        }
1814        Ok(())
1815    }
1816
1817    /// Charge one embedded part document against [`MAX_NESTED_BYTES`].
1818    fn spend_bytes(&mut self, bytes: usize) -> Result<(), String> {
1819        self.bytes = self.bytes.saturating_add(bytes);
1820        if self.bytes > MAX_NESTED_BYTES {
1821            return Err(format!(
1822                "nested import: the embedded sub-assembly documents exceed \
1823                 {} MB (import as bodies, or import flat)",
1824                MAX_NESTED_BYTES / (1024 * 1024)
1825            ));
1826        }
1827        Ok(())
1828    }
1829}
1830
1831/// A part name not yet used in THIS level's library: `requested`, else
1832/// `requested-2`, `requested-3`, … — the kernel `parts_library::unique_name`
1833/// convention, applied to an embedded block the kernel never sees inserted.
1834fn unique_entry_name(library: &serde_json::Map<String, serde_json::Value>, requested: &str) -> String {
1835    if !library.contains_key(requested) {
1836        return requested.to_string();
1837    }
1838    (2..)
1839        .map(|counter| format!("{requested}-{counter}"))
1840        .find(|candidate| !library.contains_key(candidate))
1841        .expect("the counter loop is unbounded")
1842}
1843
1844/// Keep the FIRST thing that went wrong (the report carries one, and the first
1845/// is the one that explains the rest).
1846fn note(slot: &mut Option<String>, error: String) {
1847    if slot.is_none() {
1848        *slot = Some(error);
1849    }
1850}
1851
1852/// Encode one product as a parts-library entry and return the EFFECTIVE entry
1853/// name the instances must reference (`add_part_to_library` disambiguates a name
1854/// clash and REUSES an entry with identical content, which is where cross-import
1855/// dedup comes from).
1856///
1857/// `factor`, when present, is the non-rigid part of an occurrence's placement:
1858/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
1859fn build_library_entry(
1860    product: &brep_kernel::StepProduct,
1861    factor: Option<&Mat4>,
1862    doc_name: &str,
1863    writer: &mut PartWriter<'_>,
1864) -> Result<String, String> {
1865    let (name, document) = native_part_document(product, factor, doc_name)?;
1866    install_part(&name, &document, writer)
1867}
1868
1869/// The §3.2 part document for one product's OWN bodies: ONE IMPORT3D whose only
1870/// input is the native payload, plus the library name it wants. No STEP text is
1871/// stored anywhere — a rebuild of this part is a base64 decode, not a re-parse.
1872///
1873/// `factor`, when present, is the non-rigid part of an occurrence's placement:
1874/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
1875///
1876/// Split out from [`build_library_entry`] because the nested lane needs the
1877/// DOCUMENT before it installs anything — a leaf's document is embedded in its
1878/// parent's `partsLibrary`, where there is no `add_part_to_library` to call.
1879/// One producer, so a leaf part is byte-identical however deep it lands.
1880fn native_part_document(
1881    product: &brep_kernel::StepProduct,
1882    factor: Option<&Mat4>,
1883    doc_name: &str,
1884) -> Result<(String, serde_json::Value), String> {
1885    let mut name = part_name(product, doc_name);
1886    let bodies = match factor {
1887        None => product.bodies.clone(),
1888        Some(factor) => {
1889            let transform = brep_kernel::AffineTransform::new(*factor)
1890                .map_err(|error| format!("part '{name}': non-rigid factor: {error}"))?;
1891            let mirrored = transform.determinant3() < 0.0;
1892            name.push_str(if mirrored { " (mirrored)" } else { " (scaled)" });
1893            product
1894                .bodies
1895                .iter()
1896                .map(|body| {
1897                    // A mirror MUST reverse orientation or `transform_brep`
1898                    // refuses it (an unreversed reflection inverts the solid).
1899                    brep_kernel::transform_brep(body, transform, mirrored)
1900                        .map_err(|error| format!("part '{name}': {error}"))
1901                })
1902                .collect::<Result<Vec<_>, _>>()?
1903        }
1904    };
1905    // The product's STEP colours ride into the payload with the geometry (the
1906    // snapshot captures the records the stamp writes), so a coloured part keeps
1907    // its colour through the parts library and every reload.
1908    let payload = brep_kernel::native_import_payload_with_appearance(
1909        "IMPORT3D1",
1910        &bodies,
1911        &product.appearances,
1912    )
1913    .map_err(|error| format!("part '{name}': {error}"))?;
1914    let mut document = serde_json::json!({
1915        "features": [{
1916            "type": "IMPORT3D",
1917            "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
1918            "persistentData": {},
1919        }]
1920    });
1921    if let Some(attributes) = part_attributes(product) {
1922        document[PART_ATTRIBUTES] = attributes;
1923    }
1924    // The part's own PMI, lifted once for the PART (`assembly_pmi.rs`). Its
1925    // references already name what the `IMPORT3D1` feature above stamps, and a
1926    // baked factor transforms the bodies without reordering their faces, so a
1927    // mirrored variant's names hold too.
1928    if let Some(pmi) = &product.pmi {
1929        if let Ok(block) = serde_json::to_value(pmi) {
1930            document["pmi"] = block;
1931        }
1932    }
1933    Ok((name, document))
1934}
1935
1936/// The BOM attribute record an imported product's document carries: its STEP
1937/// `PRODUCT.id` as `Part_Number`, or `None` when the file gave it none.
1938///
1939/// This is the OTHER half of `io/step/export_tree.rs`, which writes a part's
1940/// `partAttributes.Part_Number` back out as `PRODUCT.id` — the identity a
1941/// downstream PDM keys on. Without it an imported id died at the import: the
1942/// document had no part number, so a re-export fell back to the library entry's
1943/// `sourceKey` and the vendor's own part numbers were replaced by our file
1944/// names on the first round trip.
1945///
1946/// It is only ever set on a document being MINTED here (a fresh part document
1947/// for one product), so it cannot overwrite a part number a user typed: a part
1948/// document that already exists is reused by
1949/// [`add_part_to_library`](brep_kernel::add_part_to_library)'s content match and
1950/// never rebuilt through this path.
1951///
1952/// Trimmed and blank-filtered to match the reader's own `part_number`, so a
1953/// `PRODUCT('  ','bolt',…)` does not mint a whitespace part number that would
1954/// then export as one.
1955fn part_attributes(product: &brep_kernel::StepProduct) -> Option<serde_json::Value> {
1956    let number = product.id.trim();
1957    if number.is_empty() {
1958        return None;
1959    }
1960    Some(serde_json::json!({ brep_kernel::PART_NUMBER: number }))
1961}
1962
1963/// Install a part document as a parts-library entry of the OPEN document and
1964/// return the EFFECTIVE entry name the instances must reference
1965/// (`add_part_to_library` disambiguates a name clash and REUSES an entry with
1966/// identical content, which is where cross-import dedup comes from).
1967///
1968/// The `sourceKey` comes from the [`PartSink`]: an imported part is written to
1969/// the store as its own document and carries a REAL key, exactly like a part
1970/// inserted from the parts library, so there is no second kind of part. A sink
1971/// that declines (no store, or a failed write) yields `""` — the embedded-only
1972/// entry this lane used to produce unconditionally, and the case
1973/// `UpdateComponents` already skips.
1974fn install_part(
1975    name: &str,
1976    document: &serde_json::Value,
1977    writer: &mut PartWriter<'_>,
1978) -> Result<String, String> {
1979    let document = document.to_string();
1980    let signature = document_signature(&document);
1981    let source_key = writer.key_for(name, &document, &signature);
1982    brep_kernel::add_part_to_library_impl(name, &source_key, &signature, &document)
1983        .map_err(|error| format!("part '{name}': {error}"))
1984}
1985
1986/// Where an imported assembly's unique parts are written, so each becomes a
1987/// document in its own right rather than a payload embedded in one assembly.
1988///
1989/// A trait, and not a `&dyn ModelStore`, because the store lives in `BREP_app`
1990/// and this crate is BELOW it — `BREP_app` depends on `BREP_render`, so naming
1991/// the store here would be a dependency cycle. The import therefore asks for a
1992/// key and the app answers with one, which is also what keeps the destination
1993/// (and any prompt for it) entirely the app's business.
1994pub trait PartSink {
1995    /// Store `document_json` under a name derived from `part_name` and return
1996    /// the stable key it can be read back by. `None` declines — no store, or a
1997    /// write that failed — and the entry stays embedded-only.
1998    fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String>;
1999}
2000
2001/// The sink that stores nothing: every entry stays embedded-only. The default
2002/// for headless callers and tests, which have no store to write to.
2003pub struct EmbeddedOnly;
2004
2005impl PartSink for EmbeddedOnly {
2006    fn store_part(&mut self, _part_name: &str, _document_json: &str) -> Option<String> {
2007        None
2008    }
2009}
2010
2011/// A [`PartSink`] plus the CONTENT DEDUP that must ride with it.
2012///
2013/// `add_part_to_library` reuses an entry whose `(sourceKey, sourceSignature)`
2014/// both match, which is where §3.5's free dedup came from while every imported
2015/// part carried the same empty key. Give each part its own key and that reuse
2016/// stops: the same product under two `PRODUCT_DEFINITION`s would become two
2017/// entries AND two identical files.
2018///
2019/// So the dedup moves in front of the write, keyed on the document signature
2020/// alone. Identical content is written ONCE and every occurrence of it gets the
2021/// SAME key — which then makes `add_part_to_library`'s own `(key, signature)`
2022/// reuse fire exactly as before. Dedup ACROSS imports keeps working for the
2023/// same reason: a re-import derives the same file name, so the same key and
2024/// signature come back and the resident entry is reused.
2025struct PartWriter<'a> {
2026    sink: &'a mut dyn PartSink,
2027    by_signature: std::collections::HashMap<String, String>,
2028}
2029
2030impl<'a> PartWriter<'a> {
2031    fn new(sink: &'a mut dyn PartSink) -> Self {
2032        Self {
2033            sink,
2034            by_signature: std::collections::HashMap::new(),
2035        }
2036    }
2037
2038    /// The `sourceKey` for a part with this content — writing it exactly once
2039    /// however many products share it.
2040    fn key_for(&mut self, name: &str, document_json: &str, signature: &str) -> String {
2041        if let Some(key) = self.by_signature.get(signature) {
2042            return key.clone();
2043        }
2044        let key = self
2045            .sink
2046            .store_part(name, document_json)
2047            .unwrap_or_default();
2048        self.by_signature.insert(signature.to_string(), key.clone());
2049        key
2050    }
2051}
2052
2053/// An sRGB triple in 0..=1 as the 8-bit channels `#RRGGBB` holds — the form
2054/// [`brep_kernel::StepColors`] takes, and the same `round(c * 255)` conversion
2055/// `brep_kernel::ImportedColor::to_hex` uses, so a colour written to a STEP file
2056/// is the colour the metadata record spells.
2057fn srgb_bytes(rgb: [f64; 3]) -> [u8; 3] {
2058    rgb.map(|channel| (channel.clamp(0.0, 1.0) * 255.0).round() as u8)
2059}
2060
2061/// The library name for a product: its `PRODUCT.name`, else a stem built from
2062/// the imported document's name so an unnamed product is still identifiable.
2063fn part_name(product: &brep_kernel::StepProduct, doc_name: &str) -> String {
2064    let named = product.name.trim();
2065    if !named.is_empty() {
2066        return named.to_string();
2067    }
2068    match doc_name.trim() {
2069        "" => format!("part-{}", product.pd_ref),
2070        stem => format!("{stem}-part-{}", product.pd_ref),
2071    }
2072}
2073
2074/// The dialog's counts, taken from the SAME walk the import runs, so the numbers
2075/// the user was shown are the numbers they get (bar an encode failure, and bar
2076/// the extra entry a non-rigid occurrence bakes).
2077pub(super) fn probe_counts(assembly: &brep_kernel::StepAssembly) -> StepAssemblyProbe {
2078    let mut parts = std::collections::HashSet::new();
2079    let mut instances = 0usize;
2080    let mut nested_depth = 0usize;
2081    for placed in compose_world_occurrences(assembly) {
2082        let product = &assembly.products[placed.product];
2083        if product.bodies.is_empty() {
2084            continue;
2085        }
2086        parts.insert(product.pd_ref);
2087        instances += 1;
2088        nested_depth = nested_depth.max(placed.depth);
2089    }
2090    StepAssemblyProbe {
2091        parts: parts.len(),
2092        instances,
2093        nested_depth,
2094    }
2095}
2096
2097/// Depth-first from the roots, composing each occurrence's child→parent
2098/// placement into a world transform — the consumer half of `read_step_assembly`,
2099/// which deliberately transforms nothing.
2100///
2101/// Emit order, child ordering (by `edge_ref`) and the ancestor cycle guard mirror
2102/// the kernel's own `walk_occurrences`, which is what makes the components this
2103/// lane produces the same solids, in the same order, as the flat lane's — the
2104/// kernel asserts that equivalence BIT-for-bit
2105/// (`step_import/tests/assembly_structure.rs`), and
2106/// `structured_import_matches_the_flat_lane_geometry` below re-asserts it from
2107/// this side, where a divergence would actually land.
2108fn compose_world_occurrences(assembly: &brep_kernel::StepAssembly) -> Vec<PlacedProduct> {
2109    struct Node {
2110        placed: PlacedProduct,
2111        ancestors: Vec<usize>,
2112    }
2113    let mut out = Vec::new();
2114    let mut stack: Vec<Node> = assembly
2115        .roots
2116        .iter()
2117        .rev()
2118        .map(|&product| Node {
2119            placed: PlacedProduct {
2120                product,
2121                world: MAT4_IDENTITY,
2122                depth: 0,
2123                rigid_path: true,
2124                chain: Vec::new(),
2125            },
2126            ancestors: vec![product],
2127        })
2128        .collect();
2129    while let Some(node) = stack.pop() {
2130        let (product, world, depth, rigid_path, chain) = (
2131            node.placed.product,
2132            node.placed.world,
2133            node.placed.depth,
2134            node.placed.rigid_path,
2135            node.placed.chain.clone(),
2136        );
2137        out.push(node.placed);
2138        let mut children: Vec<&brep_kernel::StepOccurrence> = assembly
2139            .occurrences
2140            .iter()
2141            .filter(|occurrence| occurrence.parent == product)
2142            .collect();
2143        children.sort_by_key(|occurrence| occurrence.edge_ref);
2144        for occurrence in children.into_iter().rev() {
2145            if node.ancestors.contains(&occurrence.child) {
2146                continue; // the cycle guard the kernel's walk applies
2147            }
2148            let mut ancestors = node.ancestors.clone();
2149            ancestors.push(occurrence.child);
2150            let mut child_chain = chain.clone();
2151            child_chain.push(occurrence.edge_ref);
2152            stack.push(Node {
2153                placed: PlacedProduct {
2154                    product: occurrence.child,
2155                    world: mat4_mul(&world, &occurrence.placement),
2156                    depth: depth + 1,
2157                    // The kernel's per-edge rigidity flag, carried down the path:
2158                    // a composed pose is a component pose only when every edge
2159                    // on the way to it was one.
2160                    rigid_path: rigid_path && occurrence.rigid,
2161                    chain: child_chain,
2162                },
2163                ancestors,
2164            });
2165        }
2166    }
2167    out
2168}
2169
2170const MAT4_IDENTITY: Mat4 = [
2171    1.0, 0.0, 0.0, 0.0, //
2172    0.0, 1.0, 0.0, 0.0, //
2173    0.0, 0.0, 1.0, 0.0, //
2174    0.0, 0.0, 0.0, 1.0,
2175];
2176
2177/// Row-major 4×4 product `a · b`.
2178fn mat4_mul(a: &Mat4, b: &Mat4) -> Mat4 {
2179    let mut out = [0.0; 16];
2180    for row in 0..4 {
2181        for column in 0..4 {
2182            out[row * 4 + column] = (0..4)
2183                .map(|k| a[row * 4 + k] * b[k * 4 + column])
2184                .sum();
2185        }
2186    }
2187    out
2188}
2189
2190/// Split a non-rigid world placement into `world = rigid · factor`, where
2191/// `rigid` is a component pose (rotation + translation, det +1) and `factor` is
2192/// a purely linear residue carrying the mirror/scale/shear.
2193///
2194/// Gram-Schmidt on the linear block's columns gives `A = Q·U` with `U` upper
2195/// triangular and positively-diagonalled; when `Q` came out left-handed the pair
2196/// is re-signed through `D = diag(-1, 1, 1)` (`Q' = Q·D`, `U' = D·U`, still
2197/// `Q'U' = A`) so the ROTATION is a rotation and the reflection rides in the
2198/// factor. A mirror composed with a rotation therefore yields the same factor
2199/// whatever the rotation, which keeps every such instance on ONE baked part.
2200fn split_rigid(world: &Mat4) -> Result<(Mat4, Mat4), String> {
2201    let column = |index: usize| [world[index], world[4 + index], world[8 + index]];
2202    let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2203    let axpy = |a: [f64; 3], scale: f64, b: [f64; 3]| {
2204        [a[0] - scale * b[0], a[1] - scale * b[1], a[2] - scale * b[2]]
2205    };
2206    let (a1, a2, a3) = (column(0), column(1), column(2));
2207
2208    let r11 = dot(a1, a1).sqrt();
2209    let mut q1 = normalize(a1, r11)?;
2210    let r12 = dot(q1, a2);
2211    let v2 = axpy(a2, r12, q1);
2212    let r22 = dot(v2, v2).sqrt();
2213    let q2 = normalize(v2, r22)?;
2214    let r13 = dot(q1, a3);
2215    let r23 = dot(q2, a3);
2216    let v3 = axpy(axpy(a3, r13, q1), r23, q2);
2217    let r33 = dot(v3, v3).sqrt();
2218    let q3 = normalize(v3, r33)?;
2219
2220    // det Q = q1 · (q2 × q3); -1 means Q is a reflection, not a rotation.
2221    let cross = [
2222        q2[1] * q3[2] - q2[2] * q3[1],
2223        q2[2] * q3[0] - q2[0] * q3[2],
2224        q2[0] * q3[1] - q2[1] * q3[0],
2225    ];
2226    let (mut r11, mut r12, mut r13) = (r11, r12, r13);
2227    if dot(q1, cross) < 0.0 {
2228        q1 = [-q1[0], -q1[1], -q1[2]];
2229        r11 = -r11;
2230        r12 = -r12;
2231        r13 = -r13;
2232    }
2233    let rigid = [
2234        q1[0], q2[0], q3[0], world[3], //
2235        q1[1], q2[1], q3[1], world[7], //
2236        q1[2], q2[2], q3[2], world[11], //
2237        0.0, 0.0, 0.0, 1.0,
2238    ];
2239    let factor = [
2240        r11, r12, r13, 0.0, //
2241        0.0, r22, r23, 0.0, //
2242        0.0, 0.0, r33, 0.0, //
2243        0.0, 0.0, 0.0, 1.0,
2244    ];
2245    Ok((rigid, factor))
2246}
2247
2248/// Unit vector, or a clear error for the degenerate column a near-singular
2249/// placement produces (skipped and counted, never fatal).
2250fn normalize(vector: [f64; 3], length: f64) -> Result<[f64; 3], String> {
2251    if !(length > 1e-12) || !length.is_finite() {
2252        return Err("occurrence placement is singular (a degenerate axis)".into());
2253    }
2254    Ok([vector[0] / length, vector[1] / length, vector[2] / length])
2255}
2256
2257/// Is this affine the identity to 1e-9 — the tolerance the kernel's own
2258/// rigidity gate uses?
2259fn is_identity(matrix: &Mat4) -> bool {
2260    matrix
2261        .iter()
2262        .zip(MAT4_IDENTITY.iter())
2263        .all(|(value, want)| (value - want).abs() <= 1e-9)
2264}
2265
2266/// The linear block of a baked factor as an exact bit key — two occurrences
2267/// share a baked part only when their factor is bit-identical, so a wrong-handed
2268/// reuse is not reachable through rounding.
2269fn factor_key(factor: &Mat4) -> [u64; 9] {
2270    let mut key = [0u64; 9];
2271    for (slot, index) in key.iter_mut().zip([0, 1, 2, 4, 5, 6, 8, 9, 10]) {
2272        *slot = factor[index].to_bits();
2273    }
2274    key
2275}
2276
2277/// The product, and the placement of it, that holds a board document's board
2278/// in a STRUCTURED export. The board's bodies keep their own names inside it
2279/// (`PCB_Board`, `PCB_F.Cu/GND#3`). A component's reference designator is
2280/// never taken for an occurrence label when it is this word.
2281const BOARD_OCCURRENCE: &str = "PCB";
2282
2283/// A `PRODUCT.id` a receiving system can use. A library part with no BOM part
2284/// number is identified by the `sourceKey` it was imported from, which is an
2285/// ABSOLUTE path on the exporting machine (`/tmp/…/kicad/symbols/lm358.nbrep`):
2286/// meaningless anywhere else, and a leak of the user's directory layout into
2287/// every file they send. Such an id becomes the file's stem (`lm358`), or the
2288/// product's name when the path has no usable stem. An id with no path
2289/// separator — a real part number — is kept as it is.
2290fn portable_product_id(id: &str, name: &str) -> String {
2291    const SEPARATORS: [char; 2] = ['/', '\\'];
2292    if !id.contains(SEPARATORS) {
2293        return id.to_string();
2294    }
2295    let file = id.rsplit(SEPARATORS).next().unwrap_or_default();
2296    let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem);
2297    if stem.is_empty() {
2298        name.to_string()
2299    } else {
2300        stem.to_string()
2301    }
2302}
2303