brep_kernel/io/step/export_tree.rs
1//! Build the STRUCTURED STEP export tree out of the document's parts library.
2//!
3//! [`assembly_export_tree`] is the consumer half of `assembly.rs`: it turns the
4//! app's assembly model — a parts library of unique parts plus ACOMP instances
5//! that place them — into the [`StepAssemblyExport`] the writer emits.
6//!
7//! # Where each half comes from
8//!
9//! * **Structure** is read from the DOCUMENTS. The root's occurrences are passed
10//! in (the app holds the live, post-solve component poses); every level below
11//! comes from that part's own embedded document, whose ACOMP features carry
12//! `partName` and the `{translate, rotateEulerDeg}` pose. Those values are
13//! expression-capable, so they are evaluated through the part document's OWN
14//! [`Env`] and composed by [`compose_trs_matrix`] — the same two calls the
15//! ACOMP feature makes, never a re-derived convention.
16//! * **Geometry** is read from the SNAPSHOTS. A library entry's snapshot is the
17//! evaluated part in its OWN LOCAL FRAME, which is exactly what a STEP product
18//! must carry. Nothing is re-executed and nothing is un-posed: taking the
19//! scene's placed members and multiplying by the inverse pose would reproduce
20//! the snapshot only to rounding, and would not separate a sub-assembly's own
21//! bodies from its children's.
22//!
23//! # Splitting a sub-assembly's snapshot
24//!
25//! A sub-assembly's snapshot holds its children's bodies too, because the ACOMP
26//! features inside it ran when the snapshot was built — and those arrive
27//! NAMESPACED (`ACOMP1:Extrude1`, chaining further down). So a product's OWN
28//! bodies are the snapshot solids whose name carries no `ACOMP<digits>:` prefix;
29//! the prefixed ones are the child products' business and are dropped here, to
30//! be written once, unposed, in the child's own product.
31//!
32//! # Dedup
33//!
34//! One product per library entry PER DOCUMENT LEVEL: two instances of `bolt` in
35//! one assembly share a product and get two occurrences, which is the whole
36//! point. A part reached from two different parents gets a product each — the
37//! rigid-nesting model already stores it once per level, so there is no content
38//! identity to dedup across levels.
39//!
40//! # Identity
41//!
42//! `PRODUCT.name` is the parts-library entry name. `PRODUCT.id` is the part's
43//! BOM part number — the `Part_Number` field of the embedded document's
44//! top-level [`PART_ATTRIBUTES`] record, the same record the BOM panel's
45//! `part.` columns and the Part Properties dialog read and write — because that
46//! is the identity a downstream PDM keys on. A part with no part number falls
47//! back to the library entry's `sourceKey` (the file it was imported from), and
48//! a part with neither writes an empty id, which the writer fills with the
49//! name. The ROOT product's id is empty: [`assembly_export_tree`] never sees
50//! the root document, only its name.
51
52use std::collections::BTreeMap;
53
54use super::assembly::{StepAssemblyExport, StepExportOccurrence, StepExportProduct};
55use super::Mat4;
56use crate::feature_pipeline::features::common::{compose_trs_matrix, vec3_from_value};
57use crate::feature_pipeline::parts_library::{self, PartsLibraryEntry, PartsLibraryMap};
58use crate::feature_pipeline::{Env, HistoryRequest};
59use crate::{is_component_reference, restore_solids, BrepSolid};
60
61/// How deep the recursion will go before it refuses. Matches the import side's
62/// own cap (`model_io.rs::MAX_NESTED_DEPTH`): sixty-four levels of embedded
63/// documents is far past anything a real assembly carries, and the guard is
64/// what keeps a malformed (but acyclic) document off the native stack.
65const MAX_DEPTH: usize = 64;
66
67/// The top-level document key holding a part's own BOM attribute record
68/// (`{ "Part_Number": "PN-7", "Material": "6061", ... }`). Owned by the app's
69/// document model; the kernel reads it only to stamp `PRODUCT.id`.
70pub const PART_ATTRIBUTES: &str = "partAttributes";
71/// The BOM part-number field inside [`PART_ATTRIBUTES`].
72pub const PART_NUMBER: &str = "Part_Number";
73
74/// A part document's BOM part number: `partAttributes.Part_Number`, trimmed;
75/// `None` when the record, the field, or its text is absent or blank.
76fn part_number(document: &serde_json::Value) -> Option<String> {
77 document
78 .get(PART_ATTRIBUTES)?
79 .get(PART_NUMBER)?
80 .as_str()
81 .map(str::trim)
82 .filter(|text| !text.is_empty())
83 .map(str::to_string)
84}
85
86/// The component namespace prefix a scene name opens with, if any:
87/// `ACOMP3:Extrude1` -> `Some("ACOMP3")`, `Extrude1` -> `None`.
88fn component_prefix(name: &str) -> Option<&str> {
89 let (head, _) = name.split_once(':')?;
90 is_component_reference(head).then_some(head)
91}
92
93/// Build the export tree for a document with components.
94///
95/// * `document_name` names the ROOT product.
96/// * `root_bodies` is every resident solid of the document with its scene name;
97/// the component-owned ones are filtered out here, so the caller passes the
98/// scene exactly as it has it.
99/// * `root_components` is one entry per ACOMP instance of the ROOT document:
100/// `(component id, parts-library entry name, instance pose)`. The pose is the
101/// live one, so a solved or gizmo-moved instance exports where it sits.
102pub fn assembly_export_tree(
103 document_name: &str,
104 root_bodies: Vec<(String, BrepSolid)>,
105 root_components: &[(String, String, Mat4)],
106) -> Result<StepAssemblyExport, String> {
107 let (own, placed): (Vec<(String, BrepSolid)>, Vec<(String, BrepSolid)>) = root_bodies
108 .into_iter()
109 .partition(|(name, _)| component_prefix(name).is_none());
110 let mut assembly = StepAssemblyExport {
111 products: vec![StepExportProduct {
112 name: document_name.to_string(),
113 id: String::new(),
114 bodies: own,
115 // The ROOT document's own PMI is not a product's: it rides the
116 // export's `pmi` argument, resolved against the live scene, and is
117 // written through the occurrence paths (`assembly.rs` step 7b).
118 pmi: None,
119 }],
120 occurrences: Vec::new(),
121 };
122 let library = parts_library::parts_library_map();
123 // An instance a weld prepared in context is no longer the shared part: it
124 // is written from its own as-welded bodies, a product of its own, while
125 // the part's other instances keep sharing the library's product.
126 let prepared = crate::feature_pipeline::assembly::context_prepared_components();
127 let (own_body, shared): (Vec<_>, Vec<_>) = root_components
128 .iter()
129 .cloned()
130 .partition(|(designator, _, _)| prepared.contains_key(designator));
131 place_children(&mut assembly, 0, &library, &shared, 0)?;
132 for (designator, part_name, placement) in own_body {
133 let local = crate::AffineTransform::new(placement)
134 .and_then(|pose| pose.rigid_inverse())
135 .map_err(|error| format!("export_step: {designator}: {error}"))?;
136 let prefix = format!("{designator}:");
137 let mut bodies = Vec::new();
138 for (name, solid) in &placed {
139 let Some(local_name) = name.strip_prefix(&prefix) else { continue };
140 let mut body = crate::transform_brep(solid, local, false)
141 .map_err(|error| format!("export_step: {name}: {error}"))?;
142 // Part-local names, as the shared product's bodies carry them (and
143 // as the part's PMI names its faces).
144 let strip = |name: &mut Option<String>| {
145 if let Some(local) = name.as_deref().and_then(|name| name.strip_prefix(&prefix)) {
146 *name = Some(local.to_string());
147 }
148 };
149 for face in body.shells.iter_mut().flat_map(|shell| &mut shell.faces) { strip(&mut face.name); }
150 for edge in &mut body.edges { strip(&mut edge.name); }
151 bodies.push((local_name.to_string(), body));
152 }
153 let id = library.get(&part_name).and_then(|entry| part_number(&entry.document)
154 .or_else(|| Some(entry.source_key.clone()))).unwrap_or_default();
155 let welds = prepared.get(&designator).map(|welds| welds.join(", ")).unwrap_or_default();
156 // The part's own PMI rides along: the annotations on faces the weld
157 // did not cut name the same faces in the as-welded body.
158 let pmi = library.get(&part_name).and_then(|entry| parts_library::document_pmi(&entry.document));
159 let child = assembly.products.len();
160 assembly.products.push(StepExportProduct {
161 name: format!("{part_name} (as welded by {welds})"),
162 id,
163 bodies,
164 pmi,
165 });
166 assembly.occurrences.push(StepExportOccurrence { designator, parent: 0, child, placement, color: None });
167 }
168 Ok(assembly)
169}
170
171/// Add one occurrence per instance, building each distinct part ONCE at this
172/// level (`seen`) so repeated placements share a product.
173fn place_children(
174 assembly: &mut StepAssemblyExport,
175 parent: usize,
176 library: &PartsLibraryMap,
177 instances: &[(String, String, Mat4)],
178 depth: usize,
179) -> Result<(), String> {
180 let mut seen: BTreeMap<&str, usize> = BTreeMap::new();
181 for (designator, part_name, placement) in instances {
182 let child = match seen.get(part_name.as_str()) {
183 Some(index) => *index,
184 None => {
185 let entry = library.get(part_name).ok_or_else(|| {
186 format!(
187 "export_step: part '{part_name}' (placed by {designator}) is not in \
188 the parts library of '{}'",
189 assembly.products[parent].name
190 )
191 })?;
192 let index = add_part(assembly, part_name, entry, depth)?;
193 seen.insert(part_name.as_str(), index);
194 index
195 }
196 };
197 assembly.occurrences.push(StepExportOccurrence {
198 designator: designator.clone(),
199 parent,
200 child,
201 placement: *placement,
202 color: None,
203 });
204 }
205 Ok(())
206}
207
208/// Add one parts-library entry as a product, then recurse into the components
209/// ITS document places. Returns the new product's index.
210fn add_part(
211 assembly: &mut StepAssemblyExport,
212 part_name: &str,
213 entry: &PartsLibraryEntry,
214 depth: usize,
215) -> Result<usize, String> {
216 if depth >= MAX_DEPTH {
217 return Err(format!(
218 "export_step: assembly nests deeper than {MAX_DEPTH} levels at part '{part_name}'"
219 ));
220 }
221 // The snapshot is the fast lane the ACOMP feature itself takes; a stale or
222 // unreadable one heals the same way, by re-executing the embedded document.
223 let restored = match restore_solids(&entry.snapshot) {
224 Ok(restored) if !entry.dirty => restored,
225 _ => {
226 let (snapshot, _) = parts_library::rebuild_snapshot(&entry.document)
227 .map_err(|error| format!("export_step: part '{part_name}': {error}"))?;
228 restore_solids(&snapshot)
229 .map_err(|error| format!("export_step: part '{part_name}': {error}"))?
230 }
231 };
232 // This product's OWN bodies: the snapshot solids that no nested component
233 // contributed. The namespaced ones are written in the child's product.
234 // A sub-assembly whose own groove welds prepare its components in context
235 // holds those components as welded, not as the shared parts: it is
236 // written flat, every snapshot body its own, with no child products.
237 let flat = prepared_in_context(&restored.solids);
238 let bodies: Vec<(String, BrepSolid)> = restored
239 .solids
240 .into_iter()
241 .filter(|solid| flat || component_prefix(&solid.name).is_none())
242 .map(|solid| (solid.name, solid.solid))
243 .collect();
244 let index = assembly.products.len();
245 // The BOM part number is the identity a PDM reads; a part that was never
246 // given one is still identified by the file it came from.
247 let id = part_number(&entry.document).unwrap_or_else(|| entry.source_key.clone());
248 // The part's OWN PMI, resolved against the part's own geometry. Read from
249 // the embedded document rather than the snapshot, because an annotation is
250 // a reference plus a value, not geometry — and resolved here, where the
251 // part document is in hand, so the writer can put it in the part's product
252 // instead of the assembly's (`assembly.rs` step 7a).
253 let pmi = parts_library::document_pmi(&entry.document);
254 let requires_plugin_pmi = entry.document.get("pmi")
255 .and_then(|v| serde_json::from_value::<crate::feature_pipeline::pmi::PmiState>(v.clone()).ok())
256 .is_some_and(|state| state.views.iter().flat_map(|v| &v.annotations)
257 .any(|a| a.enabled && a.kind.contains('/')));
258 if requires_plugin_pmi && pmi.is_none() {
259 return Err(format!("part '{part_name}': plugin annotation replay unavailable during export"));
260 }
261 assembly.products.push(StepExportProduct {
262 name: part_name.to_string(),
263 id,
264 bodies,
265 pmi,
266 });
267 if !flat {
268 let (library, instances) = document_components(&entry.document, part_name)?;
269 place_children(assembly, index, &library, &instances, depth + 1)?;
270 }
271 Ok(index)
272}
273
274/// Whether a snapshot holds a component member a weld prepared in context:
275/// a namespaced body carrying a face the weld's cut left, which is named under
276/// the member's component (`ACOMP2:{weld}:Prep{side}Face{n}`). Read from the
277/// geometry itself, so a groove that cut nothing (a square or flare groove)
278/// keeps the sub-assembly's structure.
279fn prepared_in_context(solids: &[crate::RestoredSolid]) -> bool {
280 solids.iter().filter(|solid| component_prefix(&solid.name).is_some()).any(|solid| {
281 solid.solid.shells.iter().flat_map(|shell| &shell.faces).any(|face| {
282 face.name.as_deref().is_some_and(|name| component_prefix(name).is_some() && name.contains(":Prep"))
283 })
284 })
285}
286
287/// A part document's own parts library and its ACOMP instances, with each pose
288/// evaluated in THAT document's expression environment and composed through the
289/// one feature-transform convention.
290fn document_components(
291 document: &serde_json::Value,
292 part_name: &str,
293) -> Result<(PartsLibraryMap, Vec<(String, String, Mat4)>), String> {
294 let request: HistoryRequest = serde_json::from_value(document.clone()).map_err(|error| {
295 format!("export_step: part '{part_name}' document does not parse: {error}")
296 })?;
297 let env = Env::build(&request.expressions, &request.configurator).unwrap_or_else(Env::poisoned);
298 let mut instances = Vec::new();
299 for feature in &request.features {
300 if !parts_library::is_acomp_type(&feature.feature_type) {
301 continue;
302 }
303 let params = &feature.input_params;
304 let string = |key: &str| {
305 params
306 .get(key)
307 .and_then(serde_json::Value::as_str)
308 .map(str::trim)
309 .filter(|text| !text.is_empty())
310 .map(str::to_string)
311 };
312 let Some(id) = string("id") else {
313 return Err(format!(
314 "export_step: part '{part_name}' has a component with no id"
315 ));
316 };
317 let Some(child) = string("partName") else {
318 return Err(format!(
319 "export_step: part '{part_name}' component {id} names no part"
320 ));
321 };
322 let transform = params.get("transform");
323 let translate = vec3_from_value(
324 &env,
325 transform.and_then(|value| value.get("translate")),
326 "transform.translate",
327 [0.0, 0.0, 0.0],
328 )?;
329 let rotate_deg = vec3_from_value(
330 &env,
331 transform.and_then(|value| value.get("rotateEulerDeg")),
332 "transform.rotateEulerDeg",
333 [0.0, 0.0, 0.0],
334 )?;
335 let placement = compose_trs_matrix(
336 translate,
337 [
338 rotate_deg[0].to_radians(),
339 rotate_deg[1].to_radians(),
340 rotate_deg[2].to_radians(),
341 ],
342 [1.0, 1.0, 1.0],
343 [0.0, 0.0, 0.0],
344 );
345 instances.push((id, child, placement));
346 }
347 Ok((request.parts_library, instances))
348}
349