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