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