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 lane, which leaves such a body unstyled — glTF has no "no style"
562 /// state, so a primitive with no material renders in the format's own
563 /// 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 /// The solids a 3D PDF shows ([`crate::sheets::pdf3d::Body`]): every
645 /// visible, non-sketch solid with triangles, UN-POSED (an explode the
646 /// active PMI view applies to the viewport is that view's, not the
647 /// model's), coloured by the GLB lane's rule — a face's persisted colour,
648 /// else its body's, else the colour the viewport shows the body in — with
649 /// its real edges (not the auxiliary or centre-line display edges).
650 pub fn pdf3d_bodies(&self) -> Vec<crate::sheets::pdf3d::Body> {
651 let colors: std::collections::BTreeMap<String, [u8; 3]> =
652 self.persisted_export_colors().into_iter().collect();
653 self.scene
654 .solids()
655 .iter()
656 .filter(|solid| solid.visible && !solid.is_sketch && solid.mesh.indices.len() >= 3)
657 .map(|shown| {
658 let solid = self.pmi_explode_originals.get(&shown.name).unwrap_or(shown);
659 let body = colors.get(&solid.name).copied().unwrap_or_else(|| self.display_body_color(&solid.name));
660 let face_colors: Vec<[u8; 3]> = solid
661 .faces
662 .iter()
663 .map(|face| colors.get(&face.name).copied().unwrap_or(body))
664 .collect();
665 crate::sheets::pdf3d::Body {
666 name: solid.name.clone(),
667 positions: solid.mesh.positions.clone(),
668 normals: solid.mesh.normals.clone(),
669 indices: solid.mesh.indices.clone(),
670 triangle_colors: solid
671 .mesh
672 .face_ids
673 .iter()
674 .map(|face| face_colors.get(*face as usize).copied().unwrap_or(body))
675 .collect(),
676 edges: solid
677 .edges
678 .iter()
679 .filter(|edge| !edge.aux && !edge.centerline && edge.polyline.len() >= 2)
680 .map(|edge| edge.polyline.clone())
681 .collect(),
682 }
683 })
684 .collect()
685 }
686}
687
688/// The model's unit expressed in glTF's. Every export lane writes millimetres
689/// (the STEP writer's `MM`) and glTF's own linear unit is the METRE, so the GLB
690/// root node carries this as its scale rather than the vertices being rewritten.
691const METRES_PER_MILLIMETRE: f64 = 0.001;
692
693/// Unit (or zero, for a degenerate triangle) geometric normal of triangle
694/// `(a, b, c)` — the per-facet normal an ASCII STL record carries.
695fn triangle_normal(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> [f32; 3] {
696 let u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
697 let v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
698 let n = [
699 u[1] * v[2] - u[2] * v[1],
700 u[2] * v[0] - u[0] * v[2],
701 u[0] * v[1] - u[1] * v[0],
702 ];
703 let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt();
704 if len > 0.0 {
705 [n[0] / len, n[1] / len, n[2] / len]
706 } else {
707 [0.0, 0.0, 0.0]
708 }
709}
710
711// ===========================================================================
712// STRUCTURED STEP import — the assembly lane.
713//
714// The flat lane above (`import_step_feature`) appends ONE IMPORT3D holding the
715// raw Part-21 text and lets the kernel bake every occurrence's world transform
716// into its own body: N bodies, no parts, no tree. This lane keeps the structure
717// instead — each unique geometry-bearing PRODUCT_DEFINITION becomes ONE
718// parts-library entry holding a NATIVE payload (`nativeBrep`, no STEP text
719// anywhere past this door), and each occurrence of it becomes an ACOMP instance
720// carrying the composed world pose. Six bolts are then one entry × six
721// instances, which is what makes the BOM, the structure tree, per-component
722// selection and constraints work on imported geometry.
723//
724// # FLAT or NESTED — the user's choice, both correct
725//
726// [`StepAssemblyImport::nested`] picks between two shapes of the same
727// geometry:
728//
729// - **Flat** flattens the occurrence tree to its geometry-bearing leaves: one
730// ACOMP per leaf occurrence, each carrying the COMPOSED world pose. Every
731// part is stored once for the whole document.
732// - **Nested** keeps the tree: each assembly-node product becomes a part
733// document that itself carries `{partsLibrary, features: [ACOMP…,
734// IMPORT3D…]}`, built bottom-up by the same recursive builder, and the
735// parent gets ONE ACOMP per sub-assembly occurrence.
736//
737// Neither is the deprecated one. Nested shows the real tree; flat is the right
738// answer for a deep or pathological file, and it stores a part reused at two
739// levels ONCE, where nesting stores it once PER LEVEL. For a depth-1 tree the
740// two lanes produce byte-identical documents — the cheapest correctness check
741// there is, and `nested_matches_flat_for_a_depth_one_tree` asserts exactly it.
742//
743// # PROBE then CONSUME — because the parse is the expensive half
744//
745// The app must know the counts BEFORE it can offer the choice ("7 parts, 23
746// instances — import as assembly or as bodies?"), and re-reading multi-MB
747// Part-21 text after the user clicks would pay the file's single most expensive
748// cost twice. So [`EngineState::probe_step_assembly`] performs the ONE parse and
749// stashes the [`brep_kernel::StepAssembly`] in
750// [`EngineState::pending_step_assembly`];
751// [`EngineState::import_probed_step_assembly`] TAKES it. Cancel
752// ([`EngineState::discard_probed_step_assembly`]), a second probe, and a
753// document switch all drop it, so a user who cancels three imports is holding
754// zero parsed assemblies — a real consideration, since the stash keeps every
755// product's solids resident for as long as the dialog is open.
756//
757// # ONE rebuild for the whole import
758//
759// `add_feature` re-runs the entire history per call, so appending N instances
760// through it is O(N²). This lane appends them all through
761// [`EngineState::add_features`] — one push batch, one rebuild, one undo step.
762// (Not `set_history_json`: that is the document-SWITCH path, which clears the
763// kernel history cache and resets the runner's delta baseline.)
764//
765// # Fallback, never a silent zero
766//
767// No structure at all, or every geometry-bearing product failing to encode, both
768// end at today's flat lane. "A successful import that produces zero components"
769// is a failure wearing a result's clothes, so the zero-component case is an
770// `Err` for the dialog-driven entry point (the app owns the file text and re-runs
771// the flat import) and an automatic fall-back for the text-taking convenience.
772// ===========================================================================
773
774/// What the import dialog needs to describe a STEP file's structure — counts
775/// only, so the probe can answer without building anything.
776#[derive(Debug, Clone, Copy, PartialEq, Eq)]
777pub struct StepAssemblyProbe {
778 /// Unique geometry-bearing products → parts-library entries. The floor, not
779 /// the final count: a non-rigid occurrence bakes its own extra entry (§3.4).
780 pub parts: usize,
781 /// Geometry-bearing occurrences → ACOMP instance features.
782 pub instances: usize,
783 /// Longest root→node chain of occurrences. `1` is a flat assembly; `> 1`
784 /// means sub-assemblies exist, so [`StepAssemblyImport::nested`] changes
785 /// the shape of the result and the dialog's choice is worth offering.
786 pub nested_depth: usize,
787}
788
789/// The choices the import dialog collects.
790#[derive(Debug, Clone, Copy, Default)]
791pub struct StepAssemblyImport {
792 /// Build nested rigid sub-assembly documents instead of flattening the
793 /// tree to its leaf occurrences.
794 ///
795 /// `false` (the `Default`) is the flat lane, byte-for-byte unchanged. On a
796 /// depth-1 tree the two produce the same document, so this flag only ever
797 /// matters for a file that really has sub-assemblies.
798 pub nested: bool,
799}
800
801/// What an import did — the numbers the status line and notice report.
802#[derive(Debug, Clone, Default, PartialEq, Eq)]
803pub struct StepAssemblyReport {
804 /// Parts-library entries this import added or reused — the entries of the
805 /// USER'S document. On a nested import that is the top level only: a
806 /// sub-assembly's own entries live in ITS document's library, which the
807 /// parent never sees.
808 pub parts: usize,
809 /// ACOMP instance features appended to the user's document. Nested: one per
810 /// ROOT-level occurrence (a sub-assembly is one component), not one per
811 /// leaf body.
812 pub instances: usize,
813 /// Occurrences whose non-rigid factor was baked into a distinct part
814 /// (§3.4), summed over every level a nested import built.
815 pub baked_nonrigid: usize,
816 /// Products (or baked non-rigid variants of one) that did not encode to a
817 /// payload — skipped and counted, never fatal: the importer's
818 /// graceful-degradation contract, carried up to this altitude. Summed over
819 /// every level a nested import built.
820 pub failed_products: usize,
821 /// The first thing that went wrong, from the kernel's body-build errors or
822 /// this lane's own encode failures.
823 pub first_error: Option<String>,
824 /// The structured lane did not run: the file carries no usable structure, or
825 /// nothing in it encoded, so the bodies were imported through the flat lane
826 /// exactly as before. Only ever `true` from [`EngineState::import_step_assembly`],
827 /// which holds the text; the dialog-driven entry point returns `Err` instead
828 /// and lets its caller re-run the flat import it already has the text for.
829 pub flat_fallback: bool,
830}
831
832/// The outcome of consuming a parsed assembly, before it is shaped into either
833/// an `Err` (dialog lane) or a flat fallback (text lane) — so neither has to
834/// recognise "nothing imported" by matching an error string.
835enum Consumed {
836 Imported(StepAssemblyReport),
837 /// Every geometry-bearing product failed to encode: no components, so this
838 /// is not an import.
839 NoComponents {
840 failed_products: usize,
841 first_error: Option<String>,
842 },
843}
844
845/// A row-major 4×4 affine, the shape `StepOccurrence::placement` and
846/// `AffineTransform` both use.
847type Mat4 = [f64; 16];
848
849/// One node of the composed occurrence tree — a product at a world pose.
850struct PlacedProduct {
851 /// Index into `StepAssembly::products`.
852 product: usize,
853 /// Composed child-local → world transform.
854 world: Mat4,
855 /// Occurrence edges between a root and this node (`0` at a root).
856 depth: usize,
857 /// Every edge on the path here was rigid, so `world` IS a component pose.
858 /// False means the non-rigid factor must be baked into the part (§3.4).
859 rigid_path: bool,
860 /// The STEP occurrence edges walked to get here, root first — the chain a
861 /// lifted OCCURRENCE-scoped annotation names its geometry through
862 /// (`brep_kernel::rewrite_occurrence_refs`). Empty at a root.
863 chain: Vec<usize>,
864}
865
866/// A parts-library entry this import needs: a product, plus the bits of the
867/// non-rigid factor baked into it (all-zero linear block ⇒ none). Two
868/// occurrences of one product under DIFFERENT non-rigid factors are different
869/// parts — never a wrong-handed reuse.
870type PartKey = (usize, [u64; 9]);
871
872/// The `PartKey` factor slot for a plain rigid instance.
873const NO_FACTOR: [u64; 9] = [0; 9];
874
875impl EngineState {
876 /// Read a STEP file's product structure — THE parse of a structured import.
877 /// Stashes the parsed assembly (with every product's solids) for
878 /// [`Self::import_probed_step_assembly`] and returns the dialog's counts.
879 ///
880 /// `Ok(None)` = no usable structure (no NAUO edges, or none reaching built
881 /// geometry): the caller imports through the flat
882 /// [`Self::import_step_feature`] lane with the text it already holds, which
883 /// is byte-for-byte today's behaviour. `Err` only for text that is not a
884 /// Part 21 file at all — a BROKEN assembly degrades, it does not fail.
885 ///
886 /// Replaces any previously stashed assembly on EVERY outcome, `Ok(None)`
887 /// included: a stale stash surviving a probe of a different file is how a
888 /// consume silently imports the wrong one.
889 pub fn probe_step_assembly(
890 &mut self,
891 step_text: &str,
892 ) -> Result<Option<StepAssemblyProbe>, String> {
893 let id = self.submit_step_probe(step_text);
894 // Inline answers inside `submit`'s own pump; a background runner has
895 // not answered yet and this call must not pretend it has.
896 match self.take_step_probe() {
897 Some((answered, outcome)) if answered == id => match outcome {
898 super::StepProbeOutcome::Structure(probe) => Ok(Some(probe)),
899 super::StepProbeOutcome::Flat => Ok(None),
900 super::StepProbeOutcome::Failed(error) => Err(error),
901 },
902 _ => Err(
903 "the STEP probe is still running on the background runner — use \
904 submit_step_probe / take_step_probe"
905 .into(),
906 ),
907 }
908 }
909
910 /// SUBMIT a STEP text to be probed for product structure on the runner
911 /// (the parse builds every product's bodies: seconds for a real assembly,
912 /// which is why it leaves the UI thread). The answer arrives through
913 /// [`Self::take_step_probe`] under the returned id, after a later `pump`;
914 /// a found structure is stashed for [`Self::import_probed_step_assembly`].
915 /// Any earlier stash is dropped now — the probe REPLACES it on every
916 /// outcome, so a stale parse can never be consumed for the wrong file.
917 ///
918 /// The structure test the parse would make is "any NEXT_ASSEMBLY_USAGE_
919 /// OCCURRENCE entity" (`assembly_edges`), so a text with none cannot have
920 /// structure and is answered `Flat` without a trip to the runner: a part
921 /// file — the common upload — no longer pays a full parse only to be told
922 /// to take the flat lane, where the worker parses it anyway. (The text
923 /// test is a superset of the entity test: a stray mention in a comment
924 /// merely runs the parse.)
925 pub fn submit_step_probe(&mut self, step_text: &str) -> u64 {
926 self.pending_step_assembly = None;
927 let id = self.next_step_probe_id;
928 self.next_step_probe_id = self.next_step_probe_id.wrapping_add(1);
929 if !step_text.contains("NEXT_ASSEMBLY_USAGE_OCCURRENCE") {
930 self.step_probe_results
931 .push_back((id, super::StepProbeOutcome::Flat));
932 return id;
933 }
934 self.pending_step_probes.insert(id);
935 self.runner.submit_step_probe(crate::runner::StepProbeRequest {
936 id,
937 text: step_text.to_string(),
938 });
939 self.pump();
940 id
941 }
942
943 /// The oldest answered probe, if any: its submission id and what it found.
944 pub fn take_step_probe(&mut self) -> Option<(u64, super::StepProbeOutcome)> {
945 self.step_probe_results.pop_front()
946 }
947
948 /// Whether a submitted probe has not been answered yet — the app keeps the
949 /// frame loop alive (and the panel its "reading…" status) while it is.
950 pub fn step_probes_pending(&self) -> bool {
951 !self.pending_step_probes.is_empty()
952 }
953
954 /// Import the assembly [`Self::probe_step_assembly`] stashed: one
955 /// parts-library entry per unique product, one ACOMP instance per
956 /// occurrence, ONE rebuild. TAKES the stash, so a double-import is an error
957 /// rather than a double-insert.
958 ///
959 /// `doc_name` names products the file left unnamed (`{doc_name}-part-{id}`).
960 /// `opts.nested` chooses between the flat and nested shapes — see
961 /// [`StepAssemblyImport::nested`]. Errs when nothing is stashed, and when
962 /// every product failed to encode — the latter being the caller's cue to
963 /// re-run the flat import with the file text it holds.
964 /// `sink` receives every unique part document so the app can write it to
965 /// the model store and hand back a real `sourceKey`; pass [`EmbeddedOnly`]
966 /// to keep the parts embedded (what a caller with no store does).
967 pub fn import_probed_step_assembly(
968 &mut self,
969 doc_name: &str,
970 opts: StepAssemblyImport,
971 sink: &mut dyn PartSink,
972 ) -> Result<StepAssemblyReport, String> {
973 let assembly = self.pending_step_assembly.take().ok_or_else(|| {
974 "import STEP assembly: nothing probed (call probe_step_assembly first)".to_string()
975 })?;
976 match self.consume_step_assembly(assembly, doc_name, opts.nested, sink) {
977 Consumed::Imported(report) => Ok(report),
978 Consumed::NoComponents { first_error, .. } => Err(format!(
979 "import STEP assembly: no part of the assembly could be built{}",
980 first_error
981 .map(|error| format!(" ({error})"))
982 .unwrap_or_default()
983 )),
984 }
985 }
986
987 /// Drop a probed assembly and the solids it holds resident — the dialog's
988 /// Cancel. Idempotent.
989 pub fn discard_probed_step_assembly(&mut self) {
990 self.pending_step_assembly = None;
991 }
992
993 /// Probe + consume in one call, falling back to the flat lane by itself —
994 /// the HEADLESS/test entry point. The app uses the probe/consume pair
995 /// instead, because it has a dialog between the two halves.
996 ///
997 /// Still exactly one parse: this is `probe_step_assembly` followed by the
998 /// consume of what it stashed.
999 ///
1000 /// Parts stay EMBEDDED here ([`EmbeddedOnly`]): this entry point has no
1001 /// store handle and no way to ask for a destination. The app uses the
1002 /// probe/consume pair with a real sink.
1003 pub fn import_step_assembly(
1004 &mut self,
1005 step_text: &str,
1006 doc_name: &str,
1007 opts: StepAssemblyImport,
1008 ) -> Result<StepAssemblyReport, String> {
1009 let structured = self.probe_step_assembly(step_text)?.is_some();
1010 let outcome = structured.then(|| {
1011 let assembly = self
1012 .pending_step_assembly
1013 .take()
1014 .expect("a Some probe stashed the assembly it counted");
1015 self.consume_step_assembly(assembly, doc_name, opts.nested, &mut EmbeddedOnly)
1016 });
1017 match outcome {
1018 Some(Consumed::Imported(report)) => Ok(report),
1019 // No structure, or a structure nothing built out of: import the
1020 // bodies exactly as the pre-assembly lane did.
1021 Some(Consumed::NoComponents {
1022 failed_products,
1023 first_error,
1024 }) => {
1025 self.import_step_feature(step_text)?;
1026 Ok(StepAssemblyReport {
1027 failed_products,
1028 first_error,
1029 flat_fallback: true,
1030 ..StepAssemblyReport::default()
1031 })
1032 }
1033 None => {
1034 self.import_step_feature(step_text)?;
1035 Ok(StepAssemblyReport {
1036 flat_fallback: true,
1037 ..StepAssemblyReport::default()
1038 })
1039 }
1040 }
1041 }
1042
1043 /// The import itself, shared by both entry points so neither has to
1044 /// recognise "nothing imported" from an error string.
1045 fn consume_step_assembly(
1046 &mut self,
1047 assembly: brep_kernel::StepAssembly,
1048 doc_name: &str,
1049 nested: bool,
1050 sink: &mut dyn PartSink,
1051 ) -> Consumed {
1052 let mut first_error = assembly.first_error.clone();
1053 // ONE writer for the whole import, so identical content is written to
1054 // the store exactly once however many products or LEVELS share it.
1055 let mut writer = PartWriter::new(sink);
1056
1057 // --- what to build ------------------------------------------------
1058 // One row per component the USER'S document gets, each naming the
1059 // library entry it needs. Flat walks the whole tree to its leaves;
1060 // nested stops at the root's own children and folds everything below
1061 // each of them into that child's part document.
1062 let plan = if nested {
1063 plan_nested(&assembly, doc_name, &mut first_error, &mut writer)
1064 } else {
1065 plan_flat(&assembly, &mut first_error)
1066 };
1067 let Plan {
1068 wanted,
1069 factors,
1070 documents,
1071 mut failed_products,
1072 baked_below_root,
1073 } = plan;
1074
1075 // --- build the library entries -------------------------------------
1076 // In (pd_ref, factor) order so an import is deterministic regardless of
1077 // the tree's emit order, and ONCE per key however many instances use it.
1078 let mut keys: Vec<PartKey> = wanted.iter().map(|(key, _, _)| *key).collect();
1079 keys.sort_unstable();
1080 keys.dedup();
1081 let mut entry_names: std::collections::HashMap<PartKey, String> =
1082 std::collections::HashMap::new();
1083 {
1084 // THE metadata bracket. `native_import_payload` seals whatever record
1085 // this thread's scene-metadata store holds for each name it stamps —
1086 // right for a snapshot of the live scene, catastrophic here: a new
1087 // part whose stamped face names collide with names already in THIS
1088 // document would silently carry the current document's metadata.
1089 // Scoped to the encode alone; the rebuild below stamps records the
1090 // document must keep, and this guard's drop would discard them.
1091 //
1092 // The nested lane's payloads are encoded inside `plan_nested`,
1093 // which holds a bracket of its own for exactly the same reason.
1094 let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
1095 for key in &keys {
1096 // Nested pre-built the whole document (a sub-assembly's is a
1097 // recursive `{partsLibrary, features}`); flat builds the §3.2
1098 // native part document right here.
1099 let built = match documents.get(key) {
1100 Some((name, document)) => install_part(name, document, &mut writer),
1101 None => {
1102 let product = assembly
1103 .products
1104 .iter()
1105 .find(|product| product.pd_ref == key.0)
1106 .expect("every key names a product of this assembly");
1107 build_library_entry(product, factors.get(key), doc_name, &mut writer)
1108 }
1109 };
1110 match built {
1111 Ok(name) => {
1112 entry_names.insert(*key, name);
1113 }
1114 Err(error) => {
1115 failed_products += 1;
1116 note(&mut first_error, error);
1117 }
1118 }
1119 }
1120 }
1121 if entry_names.is_empty() {
1122 return Consumed::NoComponents {
1123 failed_products,
1124 first_error,
1125 };
1126 }
1127
1128 // --- append every instance in ONE history mutation -----------------
1129 // `insert_component`'s rule, verbatim: ground the FIRST component only
1130 // when the document has none yet. Grounding a second one over-constrains
1131 // the next solve.
1132 let mut ground_next = !(0..self.history.len()).any(|index| {
1133 matches!(
1134 self.history.feature_type(index).as_deref(),
1135 Some("ACOMP") | Some("ASSEMBLY COMPONENT")
1136 )
1137 });
1138 let mut features: Vec<serde_json::Value> = Vec::with_capacity(wanted.len());
1139 let mut baked_nonrigid = 0usize;
1140 // Which component carries the geometry a STEP occurrence chain names —
1141 // the map the file's occurrence-scoped PMI is rewritten through, built
1142 // while the ids are minted because that is the only moment both halves
1143 // exist.
1144 let mut namespaces: std::collections::HashMap<Vec<usize>, String> =
1145 std::collections::HashMap::new();
1146 for (key, pose, chain) in &wanted {
1147 let Some(part_name) = entry_names.get(key) else {
1148 continue; // this product failed to encode; counted above
1149 };
1150 let transform = match brep_kernel::AffineTransform::new(*pose) {
1151 Ok(transform) => transform,
1152 Err(error) => {
1153 note(&mut first_error, format!("occurrence pose: {error}"));
1154 continue;
1155 }
1156 };
1157 if key.1 != NO_FACTOR {
1158 baked_nonrigid += 1;
1159 }
1160 let id = self.history.next_feature_id("ACOMP");
1161 namespaces
1162 .entry(chain.clone())
1163 .or_insert_with(|| format!("{id}:"));
1164 features.push(serde_json::json!({
1165 "type": "ACOMP",
1166 "inputParams": {
1167 "id": id,
1168 "partName": part_name,
1169 "transform": brep_kernel::transform_to_pose_params(&transform),
1170 "isFixed": ground_next,
1171 },
1172 "persistentData": {}
1173 }));
1174 ground_next = false;
1175 }
1176 if features.is_empty() {
1177 return Consumed::NoComponents {
1178 failed_products,
1179 first_error,
1180 };
1181 }
1182
1183 // The library block must ride the request so the display runner ingests
1184 // the new entries on the very next run (as `insert_component` does).
1185 // Written only now that there are components to reference them, so an
1186 // import that produced nothing leaves the document untouched.
1187 if let Ok(library) =
1188 serde_json::from_str::<serde_json::Value>(&brep_kernel::parts_library_json())
1189 {
1190 self.history.set_parts_library(library);
1191 }
1192 // Frame the assembly once the (possibly async) run lands — see
1193 // [`EngineState::pending_fit`], same reasoning as `import_step_feature`.
1194 self.pending_fit = true;
1195 let instances = features.len();
1196 let baked_nonrigid = baked_nonrigid + baked_below_root;
1197 self.add_features(&features);
1198
1199 // The file's ASSEMBLY-level PMI — annotations it pinned to an
1200 // occurrence, annotations spanning two parts, free notes — merged into
1201 // the document's own block with its references rewritten into THIS
1202 // import's component namespaces.
1203 //
1204 // AFTER the features, and with no checkpoint of its own, for the
1205 // reason `import_step_feature` reads its PMI BEFORE its `add_feature`:
1206 // `push_features` checkpoints at its START, so a block written first
1207 // is inside the snapshot undo restores — one undo would take the
1208 // components away and leave the annotations behind, every one of them
1209 // naming a component that no longer exists. Both writes have to fall
1210 // after the one checkpoint.
1211 //
1212 // It costs a second rebuild, which is what the flat lane already pays,
1213 // and only on a file that carries assembly-level PMI at all.
1214 //
1215 // A part's OWN PMI is not here: it rode into that part's document in
1216 // `native_part_document`, once for the part however many instances
1217 // place it — the exporter's rule, which is what makes the round trip
1218 // land the same annotations on the same parts.
1219 let pmi_unplaced = self.merge_assembly_pmi(&assembly, &namespaces);
1220 for line in &assembly.pmi_diagnostics {
1221 note(&mut first_error, line.clone());
1222 }
1223 if pmi_unplaced > 0 {
1224 note(
1225 &mut first_error,
1226 format!(
1227 "{pmi_unplaced} PMI reference(s) name an occurrence this import placed no \
1228 component for; the annotations are kept unresolved"
1229 ),
1230 );
1231 }
1232 Consumed::Imported(StepAssemblyReport {
1233 // DISTINCT entries, not distinct keys: `add_part_to_library` reuses
1234 // an entry whose content already matches, so two products that are
1235 // the same geometry collapse to one part (§3.5's free content dedup).
1236 parts: entry_names
1237 .values()
1238 .collect::<std::collections::HashSet<_>>()
1239 .len(),
1240 instances,
1241 baked_nonrigid,
1242 failed_products,
1243 first_error,
1244 flat_fallback: false,
1245 })
1246 }
1247}
1248
1249impl EngineState {
1250 /// Merge a structured import's ASSEMBLY-level PMI into the open document's
1251 /// block, rewriting every occurrence-scoped reference into the component
1252 /// namespace this import minted for that STEP occurrence chain.
1253 ///
1254 /// Returns how many references named a chain with no component — a NESTED
1255 /// import folds everything below a root child into that child's own
1256 /// document, so an annotation the file pinned three levels down has no
1257 /// top-level component to name. Those references keep the chain they came
1258 /// with, so the row reports itself in the panel instead of silently
1259 /// resolving to some other instance.
1260 ///
1261 /// No rerun and no undo checkpoint of its own: the caller writes this
1262 /// before `add_features`, whose single rebuild resolves it.
1263 fn merge_assembly_pmi(
1264 &mut self,
1265 assembly: &brep_kernel::StepAssembly,
1266 namespaces: &std::collections::HashMap<Vec<usize>, String>,
1267 ) -> usize {
1268 let Some(lifted) = assembly.pmi.clone() else {
1269 return 0;
1270 };
1271 let mut unplaced = 0usize;
1272 let mut state = self.pmi_state();
1273 for view in lifted.views {
1274 let id = state.next_id("VIEW");
1275 let mut annotations = Vec::with_capacity(view.annotations.len());
1276 for mut annotation in view.annotations {
1277 unplaced += brep_kernel::rewrite_occurrence_refs(&mut annotation.params, |chain| {
1278 namespaces.get(chain).cloned()
1279 });
1280 let prefix = brep_kernel::pmi_type(&annotation.kind)
1281 .map(|def| def.short_name)
1282 .unwrap_or("PMI");
1283 let fresh = state.next_id(prefix);
1284 if let Some(object) = annotation.params.as_object_mut() {
1285 object.insert("id".into(), serde_json::Value::String(fresh));
1286 }
1287 annotations.push(annotation);
1288 }
1289 state.views.push(brep_kernel::PmiView {
1290 id,
1291 name: view.name,
1292 camera: view.camera,
1293 display: view.display,
1294 annotations,
1295 });
1296 }
1297 let block = serde_json::to_value(&state).ok();
1298 self.history.set_pmi_block_no_undo(block);
1299 // The tail has to re-resolve the merged block against the components
1300 // the run above created; nothing else in this lane reruns after them.
1301 self.rerun_history();
1302 unplaced
1303 }
1304}
1305
1306/// What one import decided to build, before any of it is installed: the rows
1307/// the user's document gets, and whatever each lane needed to work out on the
1308/// way there.
1309#[derive(Default)]
1310struct Plan {
1311 /// One row per component of the USER'S document, in emit order: the
1312 /// library entry it needs, its pose, and the STEP occurrence chain it
1313 /// stands for — which is how a lifted occurrence-scoped annotation finds
1314 /// the component that carries its geometry.
1315 wanted: Vec<(PartKey, Mat4, Vec<usize>)>,
1316 /// FLAT only: the non-rigid factor a key's part must bake (§3.4). The
1317 /// nested lane bakes inside its own builder and hands the finished document
1318 /// over in `documents` instead.
1319 factors: std::collections::HashMap<PartKey, Mat4>,
1320 /// NESTED only: `(entry name, part document)` per key, already built — a
1321 /// leaf's §3.2 native document, or a sub-assembly's recursive
1322 /// `{partsLibrary, features}`.
1323 documents: std::collections::HashMap<PartKey, (String, serde_json::Value)>,
1324 /// Products that did not encode while planning (nested builds payloads
1325 /// during the plan; flat builds them during the install).
1326 failed_products: usize,
1327 /// Non-rigid occurrences baked BELOW the root — nested only, since the flat
1328 /// lane has no below-the-root and counts its bakes at install time.
1329 baked_below_root: usize,
1330}
1331
1332/// **FLAT**: flatten the occurrence tree to its geometry-bearing nodes, each
1333/// carrying the COMPOSED world pose. Byte-for-byte the lane A6 shipped.
1334fn plan_flat(assembly: &brep_kernel::StepAssembly, first_error: &mut Option<String>) -> Plan {
1335 let mut plan = Plan::default();
1336 for placed in &compose_world_occurrences(assembly) {
1337 let product = &assembly.products[placed.product];
1338 if product.bodies.is_empty() {
1339 continue; // a pure assembly node contributes structure, not a component
1340 }
1341 let (key, pose) = if placed.rigid_path {
1342 ((product.pd_ref, NO_FACTOR), placed.world)
1343 } else {
1344 // §3.4: world = rigid · factor. Bake `factor` into a distinct part
1345 // and give the instance the rigid residue, so a mirrored instance
1346 // never lands on its unmirrored twin.
1347 match split_rigid(&placed.world) {
1348 // Non-rigid edges that cancel out along the path leave an
1349 // identity factor: that is an ordinary instance of the ordinary
1350 // part, not a bake.
1351 Ok((rigid, factor)) if is_identity(&factor) => {
1352 ((product.pd_ref, NO_FACTOR), rigid)
1353 }
1354 Ok((rigid, factor)) => {
1355 let key = (product.pd_ref, factor_key(&factor));
1356 plan.factors.insert(key, factor);
1357 (key, rigid)
1358 }
1359 Err(error) => {
1360 note(first_error, error);
1361 continue;
1362 }
1363 }
1364 };
1365 plan.wanted.push((key, pose, placed.chain.clone()));
1366 }
1367 plan
1368}
1369
1370/// **NESTED**: the live document plays the ROOT, so it gets one component per
1371/// root-level row and nothing deeper —
1372///
1373/// - a root's OWN bodies become a leaf part at identity (exactly the flat
1374/// lane's treatment of interior geometry at the root), and
1375/// - each root-child occurrence becomes ONE component: a leaf part when the
1376/// child has no children of its own, else a rigid sub-assembly whose part
1377/// document carries its own `partsLibrary` and its own ACOMPs.
1378///
1379/// Emit order matches [`plan_flat`]'s DFS pre-order — root before its children,
1380/// children by ascending `edge_ref` — which is what makes the two lanes produce
1381/// the SAME document for a depth-1 tree.
1382fn plan_nested(
1383 assembly: &brep_kernel::StepAssembly,
1384 doc_name: &str,
1385 first_error: &mut Option<String>,
1386 writer: &mut PartWriter<'_>,
1387) -> Plan {
1388 // The same bracket the install loop holds, for the same reason: every
1389 // payload this builder encodes (at every level) must see an empty ambient
1390 // scene-metadata store, or a nested leaf whose stamped face names collide
1391 // with the live document's silently inherits the live document's records.
1392 let _isolation = brep_kernel::IsolatedSceneMetadata::begin();
1393 let mut build = NestedBuild {
1394 assembly,
1395 doc_name,
1396 writer,
1397 memo: std::collections::HashMap::new(),
1398 factors: std::collections::HashMap::new(),
1399 entries: 0,
1400 bytes: 0,
1401 failed_products: 0,
1402 baked_nonrigid: 0,
1403 first_error: None,
1404 };
1405 let mut plan = Plan::default();
1406 for &root in &assembly.roots {
1407 let mut rows: Vec<(DocKey, Mat4, Vec<usize>)> = Vec::new();
1408 // The root's OWN bodies become a leaf part at identity — exactly the
1409 // flat lane's treatment, and the reason a depth-1 tree comes out the
1410 // same either way.
1411 if !assembly.products[root].bodies.is_empty() {
1412 rows.push((
1413 DocKey::Leaf((assembly.products[root].pd_ref, NO_FACTOR)),
1414 MAT4_IDENTITY,
1415 Vec::new(),
1416 ));
1417 }
1418 // Root-level bakes are counted by the install loop's own pass over
1419 // `wanted` (they are ordinary top-level rows); only bakes BELOW the root
1420 // — which never become rows of the user's document — are counted here.
1421 let mut root_level_bakes = 0usize;
1422 build.place_children(root, &[root], &mut rows, &mut root_level_bakes);
1423 for (key, pose, chain) in rows {
1424 let part = match build.document(key, &mut vec![root]) {
1425 Ok(Some(document)) => document,
1426 // A subtree with no geometry anywhere places nothing — the flat
1427 // lane says the same thing by emitting no component for it.
1428 Ok(None) => continue,
1429 Err(error) => {
1430 build.failed_products += 1;
1431 note(&mut build.first_error, error);
1432 continue;
1433 }
1434 };
1435 let part_key = key.part_key(assembly);
1436 plan.documents.insert(part_key, part);
1437 plan.wanted.push((part_key, pose, chain));
1438 }
1439 }
1440 plan.failed_products = build.failed_products;
1441 plan.baked_below_root = build.baked_nonrigid;
1442 if let Some(error) = build.first_error {
1443 note(first_error, error);
1444 }
1445 plan
1446}
1447
1448/// How deep the recursive builder will go before it refuses. `read_step_assembly`
1449/// guards cycles inside its own walk and [`NestedBuild::document`] guards them
1450/// again along the recursion path, so this is the SECOND line: a malformed file
1451/// that is merely pathologically deep (rather than cyclic) must not run the
1452/// native stack out. Sixty-four levels of embedded documents is already far past
1453/// anything a real CAD assembly carries — and each level embeds the whole
1454/// subtree below it, so the document would be unusable long before then.
1455const MAX_NESTED_DEPTH: usize = 64;
1456
1457/// How many DISTINCT part documents a nested import may build. Bounds the
1458/// builder's work; it does NOT bound the result's size — see
1459/// [`MAX_NESTED_BYTES`], which is the guard that matters.
1460const MAX_NESTED_ENTRIES: usize = 10_000;
1461
1462/// How many bytes of part document a nested import may EMBED, summed over every
1463/// `partsLibrary` entry it writes at every level.
1464///
1465/// This is the guard neither the depth cap nor the entry count provides. A
1466/// product reachable at many different depths is stored once PER LEVEL — the
1467/// memo builds its document once, but each parent embeds a COPY, so a
1468/// diamond-shaped structure well inside the depth cap can still multiply out
1469/// geometrically. Charging the embedded bytes is the only place that
1470/// multiplication is visible, so it is charged where it happens.
1471const MAX_NESTED_BYTES: usize = 256 * 1024 * 1024;
1472
1473/// What a nested part document is memoised under. A product is either a leaf
1474/// (no occurrence children) or an assembly node, never both, so the two
1475/// variants can never name the same product — except at a ROOT, whose own
1476/// bodies become a leaf part while the root itself is an assembly node. That
1477/// case is exactly why this is an enum and not a bare [`PartKey`].
1478#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Debug)]
1479enum DocKey {
1480 /// A geometry-bearing product placed as a part: `(pd_ref, baked factor)`.
1481 Leaf(PartKey),
1482 /// A product placed as a rigid sub-assembly, by index into `products`.
1483 Assembly(usize),
1484}
1485
1486impl DocKey {
1487 /// The parts-library identity this document is stored under. Always keyed on
1488 /// the `pd_ref` (never the product INDEX, which lives in a different number
1489 /// space and would collide with some other product's `pd_ref`). An assembly
1490 /// node never carries a baked factor — a non-rigid edge into one is skipped,
1491 /// see [`NestedBuild::place_children`] — so `NO_FACTOR` is exact.
1492 fn part_key(self, assembly: &brep_kernel::StepAssembly) -> PartKey {
1493 match self {
1494 DocKey::Leaf(key) => key,
1495 DocKey::Assembly(product) => (assembly.products[product].pd_ref, NO_FACTOR),
1496 }
1497 }
1498}
1499
1500/// The recursive builder behind [`plan_nested`]: turns one product into the part
1501/// document that represents it, bottom-up, memoised so a product reached from
1502/// several parents is built ONCE however many places embed it.
1503struct NestedBuild<'a, 'w> {
1504 assembly: &'a brep_kernel::StepAssembly,
1505 doc_name: &'a str,
1506 /// Where a CHILD library entry's document is written, shared with the
1507 /// top-level install loop so one part is one file at every level.
1508 writer: &'a mut PartWriter<'w>,
1509 /// `None` = this subtree carries no geometry at all, so nothing places it.
1510 memo: std::collections::HashMap<DocKey, Option<(String, serde_json::Value)>>,
1511 /// The non-rigid factor behind every baked [`DocKey::Leaf`] key, so the
1512 /// builder never has to reconstruct a matrix out of its own hash key.
1513 factors: std::collections::HashMap<PartKey, Mat4>,
1514 entries: usize,
1515 /// Bytes of part document embedded so far — the [`MAX_NESTED_BYTES`] charge.
1516 bytes: usize,
1517 failed_products: usize,
1518 baked_nonrigid: usize,
1519 first_error: Option<String>,
1520}
1521
1522impl NestedBuild<'_, '_> {
1523 /// The part document for `key`, built once and reused. `ancestors` is the
1524 /// recursion path — the cycle guard, and the depth the cap is measured on.
1525 ///
1526 /// A cyclic file gets ONE deterministic truncation: the memo keeps whichever
1527 /// path reached a node first, and that path's skipped back-edge is the one
1528 /// every embedding sees. Deterministic and finite is the whole contract for
1529 /// input that is malformed by construction.
1530 fn document(
1531 &mut self,
1532 key: DocKey,
1533 ancestors: &mut Vec<usize>,
1534 ) -> Result<Option<(String, serde_json::Value)>, String> {
1535 if let Some(hit) = self.memo.get(&key) {
1536 return Ok(hit.clone());
1537 }
1538 if ancestors.len() >= MAX_NESTED_DEPTH {
1539 return Err(format!(
1540 "nested import: sub-assembly nesting deeper than {MAX_NESTED_DEPTH} levels \
1541 (import as bodies, or import flat)"
1542 ));
1543 }
1544 let built = match key {
1545 DocKey::Leaf(part) => self.leaf_document(part),
1546 DocKey::Assembly(product) => {
1547 ancestors.push(product);
1548 let built = self.assembly_document(product, ancestors);
1549 ancestors.pop();
1550 built
1551 }
1552 }?;
1553 self.memo.insert(key, built.clone());
1554 Ok(built)
1555 }
1556
1557 /// A geometry-bearing product as the §3.2 part document — the same one the
1558 /// flat lane installs, built by the same helper, so a depth-1 nested import
1559 /// and a flat one store byte-identical entries.
1560 fn leaf_document(
1561 &mut self,
1562 key: PartKey,
1563 ) -> Result<Option<(String, serde_json::Value)>, String> {
1564 let product = self
1565 .assembly
1566 .products
1567 .iter()
1568 .find(|product| product.pd_ref == key.0)
1569 .expect("every key names a product of this assembly");
1570 if product.bodies.is_empty() {
1571 return Ok(None);
1572 }
1573 let factor = self.factors.get(&key).copied();
1574 self.spend_entry()?;
1575 native_part_document(product, factor.as_ref(), self.doc_name).map(Some)
1576 }
1577
1578 /// An assembly-node product as a rigid sub-assembly document: its OWN bodies
1579 /// as plain native IMPORT3D features (the interior-node geometry Phase 1
1580 /// could only make a SIBLING of its own children), one ACOMP per child
1581 /// occurrence, and the children's documents in this level's own
1582 /// `partsLibrary`.
1583 ///
1584 /// The entries carry NO snapshot. An entry with an unreadable snapshot heals
1585 /// from its embedded document (`assembly_component.rs`'s SELF-HEAL lane),
1586 /// and for a native part that heal is a decode + re-encode — so the level
1587 /// above bakes this whole subtree into ITS snapshot on insert, and these
1588 /// inner caches would only ever be rebuilt to be thrown away.
1589 fn assembly_document(
1590 &mut self,
1591 product: usize,
1592 ancestors: &mut Vec<usize>,
1593 ) -> Result<Option<(String, serde_json::Value)>, String> {
1594 let node = &self.assembly.products[product];
1595 let mut library = serde_json::Map::new();
1596 let mut features: Vec<serde_json::Value> = Vec::new();
1597
1598 // The node's own bodies first, matching the flat lane's "a node before
1599 // its children" emit order.
1600 if !node.bodies.is_empty() {
1601 let payload = brep_kernel::native_import_payload_with_appearance(
1602 "IMPORT3D1",
1603 &node.bodies,
1604 &node.appearances,
1605 )
1606 .map_err(|error| format!("part '{}': {error}", part_name(node, self.doc_name)))?;
1607 features.push(serde_json::json!({
1608 "type": "IMPORT3D",
1609 "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
1610 "persistentData": {},
1611 }));
1612 }
1613
1614 // One ACOMP per child occurrence, children by ascending `edge_ref`.
1615 let mut rows: Vec<(DocKey, Mat4, Vec<usize>)> = Vec::new();
1616 let mut bakes = 0usize;
1617 self.place_children(product, ancestors, &mut rows, &mut bakes);
1618 self.baked_nonrigid += bakes;
1619 let mut names: std::collections::HashMap<DocKey, String> =
1620 std::collections::HashMap::new();
1621 // `add_part_to_library`'s content reuse, applied to this level's block:
1622 // two products that are the SAME geometry collapse to one entry (§3.5's
1623 // free dedup), and every instance of either references it.
1624 let mut by_signature: std::collections::HashMap<String, String> =
1625 std::collections::HashMap::new();
1626 let mut components = 0usize;
1627 // The occurrence chain is not needed at this level: a sub-assembly's
1628 // own ACOMPs live in ITS document, which the open document's PMI never
1629 // names (an annotation pinned below a root child has no top-level
1630 // component — `merge_assembly_pmi` reports it).
1631 for (key, pose, _chain) in rows {
1632 let name = match names.get(&key) {
1633 Some(name) => name.clone(),
1634 None => {
1635 let built = match self.document(key, ancestors) {
1636 Ok(Some(built)) => built,
1637 Ok(None) => continue,
1638 Err(error) => {
1639 self.failed_products += 1;
1640 note(&mut self.first_error, error);
1641 continue;
1642 }
1643 };
1644 let serialized = built.1.to_string();
1645 let signature = document_signature(&serialized);
1646 let name = match by_signature.get(&signature) {
1647 Some(name) => name.clone(),
1648 None => {
1649 // Charged HERE, at the embedding, because that is
1650 // where a product stored once per level multiplies.
1651 self.spend_bytes(serialized.len())?;
1652 // Unique WITHIN this level's library — parent and
1653 // child libraries are independent, so a name
1654 // taken upstairs is free down here.
1655 let name = unique_entry_name(&library, &built.0);
1656 // A nested child is a part like any other: it gets
1657 // its own store document and a REAL sourceKey, so
1658 // Open Part and update-components work the same way
1659 // however deep it sits.
1660 let source_key =
1661 self.writer.key_for(&name, &serialized, &signature);
1662 library.insert(
1663 name.clone(),
1664 serde_json::json!({
1665 "sourceKey": source_key,
1666 "sourceSignature": signature.clone(),
1667 "document": built.1,
1668 "snapshot": "",
1669 }),
1670 );
1671 by_signature.insert(signature, name.clone());
1672 name
1673 }
1674 };
1675 names.insert(key, name.clone());
1676 name
1677 }
1678 };
1679 let Ok(transform) = brep_kernel::AffineTransform::new(pose) else {
1680 note(
1681 &mut self.first_error,
1682 format!("sub-assembly '{name}': occurrence pose is not an affine"),
1683 );
1684 continue;
1685 };
1686 components += 1;
1687 features.push(serde_json::json!({
1688 "type": "ACOMP",
1689 "inputParams": {
1690 // Its OWN counter, so the ids read `ACOMP1..n` whether or
1691 // not this node also owns bodies. (The id must match
1692 // `ACOMP<digits>`: it IS the namespace prefix.)
1693 "id": format!("ACOMP{components}"),
1694 "partName": name,
1695 "transform": brep_kernel::transform_to_pose_params(&transform),
1696 // Written EXPLICITLY rather than left to the kernel's
1697 // auto-ground rule, which keys on ABSENCE: the first
1698 // component of an assembly is grounded, and every other one
1699 // must not be, or the next solve is over-constrained.
1700 "isFixed": components == 1,
1701 },
1702 "persistentData": {},
1703 }));
1704 }
1705
1706 // A node whose whole subtree failed to produce geometry places nothing.
1707 // Returning `None` rather than a feature-less document matters: an empty
1708 // document is a hard error inside `add_part_to_library`, which would turn
1709 // "there was nothing here" into "the import failed".
1710 if features.is_empty() {
1711 return Ok(None);
1712 }
1713 self.spend_entry()?;
1714 let mut document =
1715 serde_json::json!({ "partsLibrary": library, "features": features });
1716 // A sub-assembly is a part too: its own `PRODUCT.id` is the part number
1717 // the level above exports it under, and its own PMI — the annotations
1718 // on the bodies IT owns, not its children's — is its document's.
1719 if let Some(attributes) = part_attributes(node) {
1720 document[PART_ATTRIBUTES] = attributes;
1721 }
1722 if let Some(pmi) = &node.pmi {
1723 if let Ok(block) = serde_json::to_value(pmi) {
1724 document["pmi"] = block;
1725 }
1726 }
1727 Ok(Some((part_name(node, self.doc_name), document)))
1728 }
1729
1730 /// The child occurrences of `product`, as `(document key, pose, occurrence
1731 /// chain)` rows in the kernel walk's order — ascending `edge_ref`, with the
1732 /// same ancestor cycle guard. The pose is the occurrence's own child→parent
1733 /// placement: nesting is precisely what stops it having to be composed.
1734 ///
1735 /// The chain is one edge long here by construction: a nested import's rows
1736 /// are the ROOT's own children, and everything below one of them is folded
1737 /// into that child's document.
1738 fn place_children(
1739 &mut self,
1740 product: usize,
1741 ancestors: &[usize],
1742 rows: &mut Vec<(DocKey, Mat4, Vec<usize>)>,
1743 bakes: &mut usize,
1744 ) {
1745 let mut children: Vec<&brep_kernel::StepOccurrence> = self
1746 .assembly
1747 .occurrences
1748 .iter()
1749 .filter(|occurrence| occurrence.parent == product)
1750 .collect();
1751 children.sort_by_key(|occurrence| occurrence.edge_ref);
1752 for occurrence in children {
1753 if ancestors.contains(&occurrence.child) {
1754 note(
1755 &mut self.first_error,
1756 format!(
1757 "occurrence #{} closes a cycle in the product structure and was skipped",
1758 occurrence.edge_ref
1759 ),
1760 );
1761 continue;
1762 }
1763 let child = &self.assembly.products[occurrence.child];
1764 let is_assembly = self
1765 .assembly
1766 .occurrences
1767 .iter()
1768 .any(|edge| edge.parent == occurrence.child);
1769 if occurrence.rigid {
1770 let key = if is_assembly {
1771 DocKey::Assembly(occurrence.child)
1772 } else {
1773 DocKey::Leaf((child.pd_ref, NO_FACTOR))
1774 };
1775 rows.push((key, occurrence.placement, vec![occurrence.edge_ref]));
1776 continue;
1777 }
1778 // §3.4 on a single edge: a leaf bakes its non-rigid factor into its
1779 // own part, exactly as the flat lane does with the composed pose.
1780 match split_rigid(&occurrence.placement) {
1781 Ok((rigid, factor)) if is_identity(&factor) => {
1782 let key = if is_assembly {
1783 DocKey::Assembly(occurrence.child)
1784 } else {
1785 DocKey::Leaf((child.pd_ref, NO_FACTOR))
1786 };
1787 rows.push((key, rigid, vec![occurrence.edge_ref]));
1788 }
1789 // A mirrored/scaled SUB-ASSEMBLY would have to push its factor
1790 // down through a whole document tree, rewriting every level's
1791 // poses. Nothing in the corpus does it, and a wrong answer here
1792 // would be a silently mis-handed assembly: skip and say so, so
1793 // the user can re-import flat (which bakes it correctly).
1794 Ok(_) if is_assembly => {
1795 note(
1796 &mut self.first_error,
1797 format!(
1798 "occurrence #{} places sub-assembly '{}' with a non-rigid transform, \
1799 which a nested import cannot represent — import flat instead",
1800 occurrence.edge_ref,
1801 part_name(child, self.doc_name)
1802 ),
1803 );
1804 }
1805 Ok((rigid, factor)) => {
1806 *bakes += 1;
1807 let key = (child.pd_ref, factor_key(&factor));
1808 self.factors.insert(key, factor);
1809 rows.push((DocKey::Leaf(key), rigid, vec![occurrence.edge_ref]));
1810 }
1811 Err(error) => note(&mut self.first_error, error),
1812 }
1813 }
1814 }
1815
1816 /// Charge one built part document against [`MAX_NESTED_ENTRIES`].
1817 fn spend_entry(&mut self) -> Result<(), String> {
1818 self.entries += 1;
1819 if self.entries > MAX_NESTED_ENTRIES {
1820 return Err(format!(
1821 "nested import: more than {MAX_NESTED_ENTRIES} distinct parts \
1822 (import as bodies, or import flat)"
1823 ));
1824 }
1825 Ok(())
1826 }
1827
1828 /// Charge one embedded part document against [`MAX_NESTED_BYTES`].
1829 fn spend_bytes(&mut self, bytes: usize) -> Result<(), String> {
1830 self.bytes = self.bytes.saturating_add(bytes);
1831 if self.bytes > MAX_NESTED_BYTES {
1832 return Err(format!(
1833 "nested import: the embedded sub-assembly documents exceed \
1834 {} MB (import as bodies, or import flat)",
1835 MAX_NESTED_BYTES / (1024 * 1024)
1836 ));
1837 }
1838 Ok(())
1839 }
1840}
1841
1842/// A part name not yet used in THIS level's library: `requested`, else
1843/// `requested-2`, `requested-3`, … — the kernel `parts_library::unique_name`
1844/// convention, applied to an embedded block the kernel never sees inserted.
1845fn unique_entry_name(library: &serde_json::Map<String, serde_json::Value>, requested: &str) -> String {
1846 if !library.contains_key(requested) {
1847 return requested.to_string();
1848 }
1849 (2..)
1850 .map(|counter| format!("{requested}-{counter}"))
1851 .find(|candidate| !library.contains_key(candidate))
1852 .expect("the counter loop is unbounded")
1853}
1854
1855/// Keep the FIRST thing that went wrong (the report carries one, and the first
1856/// is the one that explains the rest).
1857fn note(slot: &mut Option<String>, error: String) {
1858 if slot.is_none() {
1859 *slot = Some(error);
1860 }
1861}
1862
1863/// Encode one product as a parts-library entry and return the EFFECTIVE entry
1864/// name the instances must reference (`add_part_to_library` disambiguates a name
1865/// clash and REUSES an entry with identical content, which is where cross-import
1866/// dedup comes from).
1867///
1868/// `factor`, when present, is the non-rigid part of an occurrence's placement:
1869/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
1870fn build_library_entry(
1871 product: &brep_kernel::StepProduct,
1872 factor: Option<&Mat4>,
1873 doc_name: &str,
1874 writer: &mut PartWriter<'_>,
1875) -> Result<String, String> {
1876 let (name, document) = native_part_document(product, factor, doc_name)?;
1877 install_part(&name, &document, writer)
1878}
1879
1880/// The §3.2 part document for one product's OWN bodies: ONE IMPORT3D whose only
1881/// input is the native payload, plus the library name it wants. No STEP text is
1882/// stored anywhere — a rebuild of this part is a base64 decode, not a re-parse.
1883///
1884/// `factor`, when present, is the non-rigid part of an occurrence's placement:
1885/// applied to the geometry HERE, so the instance can carry a rigid pose (§3.4).
1886///
1887/// Split out from [`build_library_entry`] because the nested lane needs the
1888/// DOCUMENT before it installs anything — a leaf's document is embedded in its
1889/// parent's `partsLibrary`, where there is no `add_part_to_library` to call.
1890/// One producer, so a leaf part is byte-identical however deep it lands.
1891fn native_part_document(
1892 product: &brep_kernel::StepProduct,
1893 factor: Option<&Mat4>,
1894 doc_name: &str,
1895) -> Result<(String, serde_json::Value), String> {
1896 let mut name = part_name(product, doc_name);
1897 let bodies = match factor {
1898 None => product.bodies.clone(),
1899 Some(factor) => {
1900 let transform = brep_kernel::AffineTransform::new(*factor)
1901 .map_err(|error| format!("part '{name}': non-rigid factor: {error}"))?;
1902 let mirrored = transform.determinant3() < 0.0;
1903 name.push_str(if mirrored { " (mirrored)" } else { " (scaled)" });
1904 product
1905 .bodies
1906 .iter()
1907 .map(|body| {
1908 // A mirror MUST reverse orientation or `transform_brep`
1909 // refuses it (an unreversed reflection inverts the solid).
1910 brep_kernel::transform_brep(body, transform, mirrored)
1911 .map_err(|error| format!("part '{name}': {error}"))
1912 })
1913 .collect::<Result<Vec<_>, _>>()?
1914 }
1915 };
1916 // The product's STEP colours ride into the payload with the geometry (the
1917 // snapshot captures the records the stamp writes), so a coloured part keeps
1918 // its colour through the parts library and every reload.
1919 let payload = brep_kernel::native_import_payload_with_appearance(
1920 "IMPORT3D1",
1921 &bodies,
1922 &product.appearances,
1923 )
1924 .map_err(|error| format!("part '{name}': {error}"))?;
1925 let mut document = serde_json::json!({
1926 "features": [{
1927 "type": "IMPORT3D",
1928 "inputParams": { "id": "IMPORT3D1", "nativeBrep": payload },
1929 "persistentData": {},
1930 }]
1931 });
1932 if let Some(attributes) = part_attributes(product) {
1933 document[PART_ATTRIBUTES] = attributes;
1934 }
1935 // The part's own PMI, lifted once for the PART (`assembly_pmi.rs`). Its
1936 // references already name what the `IMPORT3D1` feature above stamps, and a
1937 // baked factor transforms the bodies without reordering their faces, so a
1938 // mirrored variant's names hold too.
1939 if let Some(pmi) = &product.pmi {
1940 if let Ok(block) = serde_json::to_value(pmi) {
1941 document["pmi"] = block;
1942 }
1943 }
1944 Ok((name, document))
1945}
1946
1947/// The BOM attribute record an imported product's document carries: its STEP
1948/// `PRODUCT.id` as `Part_Number`, or `None` when the file gave it none.
1949///
1950/// This is the OTHER half of `io/step/export_tree.rs`, which writes a part's
1951/// `partAttributes.Part_Number` back out as `PRODUCT.id` — the identity a
1952/// downstream PDM keys on. Without it an imported id died at the import: the
1953/// document had no part number, so a re-export fell back to the library entry's
1954/// `sourceKey` and the vendor's own part numbers were replaced by our file
1955/// names on the first round trip.
1956///
1957/// It is only ever set on a document being MINTED here (a fresh part document
1958/// for one product), so it cannot overwrite a part number a user typed: a part
1959/// document that already exists is reused by
1960/// [`add_part_to_library`](brep_kernel::add_part_to_library)'s content match and
1961/// never rebuilt through this path.
1962///
1963/// Trimmed and blank-filtered to match the reader's own `part_number`, so a
1964/// `PRODUCT(' ','bolt',…)` does not mint a whitespace part number that would
1965/// then export as one.
1966fn part_attributes(product: &brep_kernel::StepProduct) -> Option<serde_json::Value> {
1967 let number = product.id.trim();
1968 if number.is_empty() {
1969 return None;
1970 }
1971 Some(serde_json::json!({ brep_kernel::PART_NUMBER: number }))
1972}
1973
1974/// Install a part document as a parts-library entry of the OPEN document and
1975/// return the EFFECTIVE entry name the instances must reference
1976/// (`add_part_to_library` disambiguates a name clash and REUSES an entry with
1977/// identical content, which is where cross-import dedup comes from).
1978///
1979/// The `sourceKey` comes from the [`PartSink`]: an imported part is written to
1980/// the store as its own document and carries a REAL key, exactly like a part
1981/// inserted from the parts library, so there is no second kind of part. A sink
1982/// that declines (no store, or a failed write) yields `""` — the embedded-only
1983/// entry this lane used to produce unconditionally, and the case
1984/// `UpdateComponents` already skips.
1985fn install_part(
1986 name: &str,
1987 document: &serde_json::Value,
1988 writer: &mut PartWriter<'_>,
1989) -> Result<String, String> {
1990 let document = document.to_string();
1991 let signature = document_signature(&document);
1992 let source_key = writer.key_for(name, &document, &signature);
1993 brep_kernel::add_part_to_library_impl(name, &source_key, &signature, &document)
1994 .map_err(|error| format!("part '{name}': {error}"))
1995}
1996
1997/// Where an imported assembly's unique parts are written, so each becomes a
1998/// document in its own right rather than a payload embedded in one assembly.
1999///
2000/// A trait, and not a `&dyn ModelStore`, because the store lives in `BREP_app`
2001/// and this crate is BELOW it — `BREP_app` depends on `BREP_render`, so naming
2002/// the store here would be a dependency cycle. The import therefore asks for a
2003/// key and the app answers with one, which is also what keeps the destination
2004/// (and any prompt for it) entirely the app's business.
2005pub trait PartSink {
2006 /// Store `document_json` under a name derived from `part_name` and return
2007 /// the stable key it can be read back by. `None` declines — no store, or a
2008 /// write that failed — and the entry stays embedded-only.
2009 fn store_part(&mut self, part_name: &str, document_json: &str) -> Option<String>;
2010}
2011
2012/// The sink that stores nothing: every entry stays embedded-only. The default
2013/// for headless callers and tests, which have no store to write to.
2014pub struct EmbeddedOnly;
2015
2016impl PartSink for EmbeddedOnly {
2017 fn store_part(&mut self, _part_name: &str, _document_json: &str) -> Option<String> {
2018 None
2019 }
2020}
2021
2022/// A [`PartSink`] plus the CONTENT DEDUP that must ride with it.
2023///
2024/// `add_part_to_library` reuses an entry whose `(sourceKey, sourceSignature)`
2025/// both match, which is where §3.5's free dedup came from while every imported
2026/// part carried the same empty key. Give each part its own key and that reuse
2027/// stops: the same product under two `PRODUCT_DEFINITION`s would become two
2028/// entries AND two identical files.
2029///
2030/// So the dedup moves in front of the write, keyed on the document signature
2031/// alone. Identical content is written ONCE and every occurrence of it gets the
2032/// SAME key — which then makes `add_part_to_library`'s own `(key, signature)`
2033/// reuse fire exactly as before. Dedup ACROSS imports keeps working for the
2034/// same reason: a re-import derives the same file name, so the same key and
2035/// signature come back and the resident entry is reused.
2036struct PartWriter<'a> {
2037 sink: &'a mut dyn PartSink,
2038 by_signature: std::collections::HashMap<String, String>,
2039}
2040
2041impl<'a> PartWriter<'a> {
2042 fn new(sink: &'a mut dyn PartSink) -> Self {
2043 Self {
2044 sink,
2045 by_signature: std::collections::HashMap::new(),
2046 }
2047 }
2048
2049 /// The `sourceKey` for a part with this content — writing it exactly once
2050 /// however many products share it.
2051 fn key_for(&mut self, name: &str, document_json: &str, signature: &str) -> String {
2052 if let Some(key) = self.by_signature.get(signature) {
2053 return key.clone();
2054 }
2055 let key = self
2056 .sink
2057 .store_part(name, document_json)
2058 .unwrap_or_default();
2059 self.by_signature.insert(signature.to_string(), key.clone());
2060 key
2061 }
2062}
2063
2064/// An sRGB triple in 0..=1 as the 8-bit channels `#RRGGBB` holds — the form
2065/// [`brep_kernel::StepColors`] takes, and the same `round(c * 255)` conversion
2066/// `brep_kernel::ImportedColor::to_hex` uses, so a colour written to a STEP file
2067/// is the colour the metadata record spells.
2068fn srgb_bytes(rgb: [f64; 3]) -> [u8; 3] {
2069 rgb.map(|channel| (channel.clamp(0.0, 1.0) * 255.0).round() as u8)
2070}
2071
2072/// The library name for a product: its `PRODUCT.name`, else a stem built from
2073/// the imported document's name so an unnamed product is still identifiable.
2074fn part_name(product: &brep_kernel::StepProduct, doc_name: &str) -> String {
2075 let named = product.name.trim();
2076 if !named.is_empty() {
2077 return named.to_string();
2078 }
2079 match doc_name.trim() {
2080 "" => format!("part-{}", product.pd_ref),
2081 stem => format!("{stem}-part-{}", product.pd_ref),
2082 }
2083}
2084
2085/// The dialog's counts, taken from the SAME walk the import runs, so the numbers
2086/// the user was shown are the numbers they get (bar an encode failure, and bar
2087/// the extra entry a non-rigid occurrence bakes).
2088pub(super) fn probe_counts(assembly: &brep_kernel::StepAssembly) -> StepAssemblyProbe {
2089 let mut parts = std::collections::HashSet::new();
2090 let mut instances = 0usize;
2091 let mut nested_depth = 0usize;
2092 for placed in compose_world_occurrences(assembly) {
2093 let product = &assembly.products[placed.product];
2094 if product.bodies.is_empty() {
2095 continue;
2096 }
2097 parts.insert(product.pd_ref);
2098 instances += 1;
2099 nested_depth = nested_depth.max(placed.depth);
2100 }
2101 StepAssemblyProbe {
2102 parts: parts.len(),
2103 instances,
2104 nested_depth,
2105 }
2106}
2107
2108/// Depth-first from the roots, composing each occurrence's child→parent
2109/// placement into a world transform — the consumer half of `read_step_assembly`,
2110/// which deliberately transforms nothing.
2111///
2112/// Emit order, child ordering (by `edge_ref`) and the ancestor cycle guard mirror
2113/// the kernel's own `walk_occurrences`, which is what makes the components this
2114/// lane produces the same solids, in the same order, as the flat lane's — the
2115/// kernel asserts that equivalence BIT-for-bit
2116/// (`step_import/tests/assembly_structure.rs`), and
2117/// `structured_import_matches_the_flat_lane_geometry` below re-asserts it from
2118/// this side, where a divergence would actually land.
2119fn compose_world_occurrences(assembly: &brep_kernel::StepAssembly) -> Vec<PlacedProduct> {
2120 struct Node {
2121 placed: PlacedProduct,
2122 ancestors: Vec<usize>,
2123 }
2124 let mut out = Vec::new();
2125 let mut stack: Vec<Node> = assembly
2126 .roots
2127 .iter()
2128 .rev()
2129 .map(|&product| Node {
2130 placed: PlacedProduct {
2131 product,
2132 world: MAT4_IDENTITY,
2133 depth: 0,
2134 rigid_path: true,
2135 chain: Vec::new(),
2136 },
2137 ancestors: vec![product],
2138 })
2139 .collect();
2140 while let Some(node) = stack.pop() {
2141 let (product, world, depth, rigid_path, chain) = (
2142 node.placed.product,
2143 node.placed.world,
2144 node.placed.depth,
2145 node.placed.rigid_path,
2146 node.placed.chain.clone(),
2147 );
2148 out.push(node.placed);
2149 let mut children: Vec<&brep_kernel::StepOccurrence> = assembly
2150 .occurrences
2151 .iter()
2152 .filter(|occurrence| occurrence.parent == product)
2153 .collect();
2154 children.sort_by_key(|occurrence| occurrence.edge_ref);
2155 for occurrence in children.into_iter().rev() {
2156 if node.ancestors.contains(&occurrence.child) {
2157 continue; // the cycle guard the kernel's walk applies
2158 }
2159 let mut ancestors = node.ancestors.clone();
2160 ancestors.push(occurrence.child);
2161 let mut child_chain = chain.clone();
2162 child_chain.push(occurrence.edge_ref);
2163 stack.push(Node {
2164 placed: PlacedProduct {
2165 product: occurrence.child,
2166 world: mat4_mul(&world, &occurrence.placement),
2167 depth: depth + 1,
2168 // The kernel's per-edge rigidity flag, carried down the path:
2169 // a composed pose is a component pose only when every edge
2170 // on the way to it was one.
2171 rigid_path: rigid_path && occurrence.rigid,
2172 chain: child_chain,
2173 },
2174 ancestors,
2175 });
2176 }
2177 }
2178 out
2179}
2180
2181const MAT4_IDENTITY: Mat4 = [
2182 1.0, 0.0, 0.0, 0.0, //
2183 0.0, 1.0, 0.0, 0.0, //
2184 0.0, 0.0, 1.0, 0.0, //
2185 0.0, 0.0, 0.0, 1.0,
2186];
2187
2188/// Row-major 4×4 product `a · b`.
2189fn mat4_mul(a: &Mat4, b: &Mat4) -> Mat4 {
2190 let mut out = [0.0; 16];
2191 for row in 0..4 {
2192 for column in 0..4 {
2193 out[row * 4 + column] = (0..4)
2194 .map(|k| a[row * 4 + k] * b[k * 4 + column])
2195 .sum();
2196 }
2197 }
2198 out
2199}
2200
2201/// Split a non-rigid world placement into `world = rigid · factor`, where
2202/// `rigid` is a component pose (rotation + translation, det +1) and `factor` is
2203/// a purely linear residue carrying the mirror/scale/shear.
2204///
2205/// Gram-Schmidt on the linear block's columns gives `A = Q·U` with `U` upper
2206/// triangular and positively-diagonalled; when `Q` came out left-handed the pair
2207/// is re-signed through `D = diag(-1, 1, 1)` (`Q' = Q·D`, `U' = D·U`, still
2208/// `Q'U' = A`) so the ROTATION is a rotation and the reflection rides in the
2209/// factor. A mirror composed with a rotation therefore yields the same factor
2210/// whatever the rotation, which keeps every such instance on ONE baked part.
2211fn split_rigid(world: &Mat4) -> Result<(Mat4, Mat4), String> {
2212 let column = |index: usize| [world[index], world[4 + index], world[8 + index]];
2213 let dot = |a: [f64; 3], b: [f64; 3]| a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
2214 let axpy = |a: [f64; 3], scale: f64, b: [f64; 3]| {
2215 [a[0] - scale * b[0], a[1] - scale * b[1], a[2] - scale * b[2]]
2216 };
2217 let (a1, a2, a3) = (column(0), column(1), column(2));
2218
2219 let r11 = dot(a1, a1).sqrt();
2220 let mut q1 = normalize(a1, r11)?;
2221 let r12 = dot(q1, a2);
2222 let v2 = axpy(a2, r12, q1);
2223 let r22 = dot(v2, v2).sqrt();
2224 let q2 = normalize(v2, r22)?;
2225 let r13 = dot(q1, a3);
2226 let r23 = dot(q2, a3);
2227 let v3 = axpy(axpy(a3, r13, q1), r23, q2);
2228 let r33 = dot(v3, v3).sqrt();
2229 let q3 = normalize(v3, r33)?;
2230
2231 // det Q = q1 · (q2 × q3); -1 means Q is a reflection, not a rotation.
2232 let cross = [
2233 q2[1] * q3[2] - q2[2] * q3[1],
2234 q2[2] * q3[0] - q2[0] * q3[2],
2235 q2[0] * q3[1] - q2[1] * q3[0],
2236 ];
2237 let (mut r11, mut r12, mut r13) = (r11, r12, r13);
2238 if dot(q1, cross) < 0.0 {
2239 q1 = [-q1[0], -q1[1], -q1[2]];
2240 r11 = -r11;
2241 r12 = -r12;
2242 r13 = -r13;
2243 }
2244 let rigid = [
2245 q1[0], q2[0], q3[0], world[3], //
2246 q1[1], q2[1], q3[1], world[7], //
2247 q1[2], q2[2], q3[2], world[11], //
2248 0.0, 0.0, 0.0, 1.0,
2249 ];
2250 let factor = [
2251 r11, r12, r13, 0.0, //
2252 0.0, r22, r23, 0.0, //
2253 0.0, 0.0, r33, 0.0, //
2254 0.0, 0.0, 0.0, 1.0,
2255 ];
2256 Ok((rigid, factor))
2257}
2258
2259/// Unit vector, or a clear error for the degenerate column a near-singular
2260/// placement produces (skipped and counted, never fatal).
2261fn normalize(vector: [f64; 3], length: f64) -> Result<[f64; 3], String> {
2262 if !(length > 1e-12) || !length.is_finite() {
2263 return Err("occurrence placement is singular (a degenerate axis)".into());
2264 }
2265 Ok([vector[0] / length, vector[1] / length, vector[2] / length])
2266}
2267
2268/// Is this affine the identity to 1e-9 — the tolerance the kernel's own
2269/// rigidity gate uses?
2270fn is_identity(matrix: &Mat4) -> bool {
2271 matrix
2272 .iter()
2273 .zip(MAT4_IDENTITY.iter())
2274 .all(|(value, want)| (value - want).abs() <= 1e-9)
2275}
2276
2277/// The linear block of a baked factor as an exact bit key — two occurrences
2278/// share a baked part only when their factor is bit-identical, so a wrong-handed
2279/// reuse is not reachable through rounding.
2280fn factor_key(factor: &Mat4) -> [u64; 9] {
2281 let mut key = [0u64; 9];
2282 for (slot, index) in key.iter_mut().zip([0, 1, 2, 4, 5, 6, 8, 9, 10]) {
2283 *slot = factor[index].to_bits();
2284 }
2285 key
2286}
2287
2288/// The product, and the placement of it, that holds a board document's board
2289/// in a STRUCTURED export. The board's bodies keep their own names inside it
2290/// (`PCB_Board`, `PCB_F.Cu/GND#3`). A component's reference designator is
2291/// never taken for an occurrence label when it is this word.
2292const BOARD_OCCURRENCE: &str = "PCB";
2293
2294/// A `PRODUCT.id` a receiving system can use. A library part with no BOM part
2295/// number is identified by the `sourceKey` it was imported from, which is an
2296/// ABSOLUTE path on the exporting machine (`/tmp/…/kicad/symbols/lm358.nbrep`):
2297/// meaningless anywhere else, and a leak of the user's directory layout into
2298/// every file they send. Such an id becomes the file's stem (`lm358`), or the
2299/// product's name when the path has no usable stem. An id with no path
2300/// separator — a real part number — is kept as it is.
2301fn portable_product_id(id: &str, name: &str) -> String {
2302 const SEPARATORS: [char; 2] = ['/', '\\'];
2303 if !id.contains(SEPARATORS) {
2304 return id.to_string();
2305 }
2306 let file = id.rsplit(SEPARATORS).next().unwrap_or_default();
2307 let stem = file.rsplit_once('.').map_or(file, |(stem, _)| stem);
2308 if stem.is_empty() {
2309 name.to_string()
2310 } else {
2311 stem.to_string()
2312 }
2313}
2314