Skip to main content

brep_kernel/io/step/
assembly.rs

1//! STRUCTURED STEP export: write a product structure, not just bodies.
2//!
3//! The flat writer ([`super::export_step_report_named`]) puts every body of the
4//! document into ONE `PRODUCT`. That is the right answer for a part, and the
5//! wrong one for an assembly: a nested assembly came out as a bag of bodies at
6//! their world positions, with the parts library, the instance count and the
7//! hierarchy all discarded.
8//!
9//! This module is the other answer. It takes a [`StepAssemblyExport`] — one
10//! [`StepExportProduct`] per distinct part holding that part's bodies IN ITS OWN
11//! LOCAL FRAME, plus one [`StepExportOccurrence`] per placement — and writes the
12//! AP242 graph the importer (`io/step_import/`) reads back:
13//!
14//! ```text
15//!   PRODUCT -> PRODUCT_DEFINITION_FORMATION -> PRODUCT_DEFINITION
16//!       -> PRODUCT_DEFINITION_SHAPE -> SHAPE_DEFINITION_REPRESENTATION
17//!       -> ADVANCED_BREP_SHAPE_REPRESENTATION (the part's own bodies)
18//!
19//!   NEXT_ASSEMBLY_USAGE_OCCURRENCE(parent_pd, child_pd)
20//!       <- PRODUCT_DEFINITION_SHAPE('NAUO PRDDFN')
21//!       <- CONTEXT_DEPENDENT_SHAPE_REPRESENTATION
22//!       -> ( REPRESENTATION_RELATIONSHIP(child_rep, parent_rep)
23//!            REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(
24//!              ITEM_DEFINED_TRANSFORMATION(identity_axis, placement_axis) )
25//!            SHAPE_REPRESENTATION_RELATIONSHIP() )
26//! ```
27//!
28//! # The placement convention, and why it is copied rather than chosen
29//!
30//! A reader composes `T = M(item_2) · M(item_1)⁻¹` to map `rep_1` into `rep_2`.
31//! With `rep_1` the CHILD and `item_1` the identity axis, `T` is simply
32//! `M(item_2)` — the child's frame expressed in the parent. That ordering is
33//! taken from the `as1-ug-214` vendor fixture
34//! (`REPRESENTATION_RELATIONSHIP(' ',' ',#213 /* rod */,#219 /* rod_assem */)`
35//! with `ITEM_DEFINED_TRANSFORMATION(' ',' ',#1041 /* identity */,#1109)`), NOT
36//! from our own importer: `resolve_rep_rel_transform` reorients using the
37//! child's known root representation, so a self round-trip would have passed
38//! with the ordering reversed and told us nothing.
39//!
40//! For the same reason `item_1`/`item_2` are ITEMS of the reps they belong to —
41//! the identity axis is the first item of every representation this writer
42//! emits, and each occurrence's placement axis is pushed into its PARENT's item
43//! list. A conformance checker requires exactly that.
44//!
45//! # Naming, and what PMI resolves against
46//!
47//! A part's bodies, faces and edges keep the part's OWN names — `Extrude1_top`,
48//! not `ACOMP3:Extrude1_top` — because they are written into the part's product,
49//! where the component namespace does not apply. The document still refers to
50//! them by the namespaced name, so [`StepAssemblyExport::occurrence_paths`]
51//! walks the graph and registers every entity under EVERY chained occurrence
52//! path that reaches it (`ACOMP3:`, `ACOMP5:ACOMP1:`), with the vertex points
53//! moved into root space so a `{body}@x,y,z` reference still matches. Two
54//! instances of one part share the part's entities, so `ACOMP3:top` and
55//! `ACOMP4:top` resolve to the SAME `ADVANCED_FACE`.
56//!
57//! They are not the same ANNOTATION, though, and PMI is written accordingly:
58//!
59//! - a PART's own annotations ([`StepExportProduct::pmi`], from the part
60//!   document's `pmi` block) are written into that part's product, with the
61//!   part's own names and its own draughting model — once, however many
62//!   instances place it;
63//! - the ROOT document's annotations are written through the occurrence paths,
64//!   and a reference that reaches a part through an occurrence hangs its
65//!   `SHAPE_ASPECT` off THAT occurrence's `PRODUCT_DEFINITION_SHAPE` (the
66//!   `'NAUO PRDDFN'` one), not the part's. The `GEOMETRIC_ITEM_SPECIFIC_USAGE`
67//!   still points at the part's face; only the owner says which instance is
68//!   meant, and it is the only place that can say it.
69//!
70//! `io/step_import/assembly_pmi.rs` reads exactly that distinction back, which
71//! is what makes an assembly's PMI survive export → import unchanged.
72
73use super::{
74    finish_step_file, id_list, mat4_mul, pmi, step_string, styles, write_file_contexts,
75    write_product, write_product_geometry, Mat4, StepColors, StepExportReport, StepItemOwner,
76    StepNameMaps, StepPmi, StepWriter, MAT4_IDENTITY,
77};
78use crate::feature_pipeline::pmi::{PmiReport, PmiState};
79use crate::{BrepSolid, Vec3};
80
81/// One product of an exported structure: a part, a sub-assembly, or the root
82/// document. `bodies` are in the product's OWN local frame — never posed.
83#[derive(Clone, Debug, Default)]
84pub struct StepExportProduct {
85    /// `PRODUCT.name` — the parts-library entry name, or the document name.
86    pub name: String,
87    /// `PRODUCT.id` — the vendor part number: a library part's BOM
88    /// `Part_Number` attribute, else its `sourceKey` (`export_tree.rs`). The
89    /// name is used when empty.
90    pub id: String,
91    /// This product's own solids and their part-local scene names. Empty for a
92    /// pure assembly node, which is then written as a bare `SHAPE_REPRESENTATION`.
93    pub bodies: Vec<(String, BrepSolid)>,
94    /// This product's OWN PMI — the part document's `pmi` block, resolved
95    /// against the part's own geometry (`export_tree.rs` runs it). Written
96    /// into THIS product, with the part's own names and its own draughting
97    /// model, which is where a structured import reads it back from.
98    pub pmi: Option<(PmiState, PmiReport)>,
99}
100
101/// One placement of `child` inside `parent` — a `NEXT_ASSEMBLY_USAGE_OCCURRENCE`.
102#[derive(Clone, Debug)]
103pub struct StepExportOccurrence {
104    /// The instance label: the placing component's id (`ACOMP3`). Written into
105    /// the NAUO's `reference_designator`, which is what the importer reads back
106    /// first, so an instance keeps its identity through the round trip.
107    pub designator: String,
108    /// Index into [`StepAssemblyExport::products`].
109    pub parent: usize,
110    /// Index into [`StepAssemblyExport::products`].
111    pub child: usize,
112    /// child-local -> parent-local, row-major affine. Must be RIGID: a mirrored
113    /// or scaled instance has no `AXIS2_PLACEMENT_3D` and is rejected rather
114    /// than silently written as its rotation part.
115    pub placement: Mat4,
116    /// This instance's own colour, over its part's: written as a
117    /// `CONTEXT_DEPENDENT_OVER_RIDING_STYLED_ITEM` on each of the child's own
118    /// solids in this occurrence's context. Only a child that carries solids
119    /// of its own takes one (a sub-assembly instance's colour would need a
120    /// path of occurrences as its context, which is not written).
121    pub color: Option<[u8; 3]>,
122}
123
124/// A document's product structure, ready to write. Exactly one product must be
125/// a root (never an occurrence child) — the document itself.
126#[derive(Clone, Debug, Default)]
127pub struct StepAssemblyExport {
128    pub products: Vec<StepExportProduct>,
129    pub occurrences: Vec<StepExportOccurrence>,
130}
131
132/// How many occurrence paths the PMI alias walk will register before it stops.
133/// One path per instance is the honest count, and a real assembly has
134/// thousands at most; the cap only bounds a pathological diamond graph, whose
135/// path count is exponential in its depth.
136const MAX_OCCURRENCE_PATHS: usize = 100_000;
137
138impl StepAssemblyExport {
139    /// The single root product's index, with the graph checked on the way: every
140    /// occurrence in range, no self-placement, exactly one root, no cycle, every
141    /// product reachable, every placement rigid.
142    pub fn root(&self) -> Result<usize, String> {
143        if self.products.is_empty() {
144            return Err("export_step: an assembly needs at least one product".into());
145        }
146        let count = self.products.len();
147        let mut is_child = vec![false; count];
148        for occurrence in &self.occurrences {
149            if occurrence.parent >= count || occurrence.child >= count {
150                return Err(format!(
151                    "export_step: occurrence '{}' names a product outside the structure",
152                    occurrence.designator
153                ));
154            }
155            if occurrence.parent == occurrence.child {
156                return Err(format!(
157                    "export_step: occurrence '{}' places a product inside itself",
158                    occurrence.designator
159                ));
160            }
161            rigid(&occurrence.placement).map_err(|error| {
162                format!(
163                    "export_step: occurrence '{}' placement: {error}",
164                    occurrence.designator
165                )
166            })?;
167            is_child[occurrence.child] = true;
168        }
169        let roots: Vec<usize> = (0..count).filter(|index| !is_child[*index]).collect();
170        let [root] = roots.as_slice() else {
171            return Err(format!(
172                "export_step: an assembly needs exactly one root product, found {}",
173                roots.len()
174            ));
175        };
176        // Reachability doubles as the cycle check: a cycle makes every product
177        // on it a child, so an unreached product is either orphaned or looping.
178        let mut reached = vec![false; count];
179        let mut stack = vec![*root];
180        reached[*root] = true;
181        while let Some(product) = stack.pop() {
182            for occurrence in &self.occurrences {
183                if occurrence.parent == product && !reached[occurrence.child] {
184                    reached[occurrence.child] = true;
185                    stack.push(occurrence.child);
186                }
187            }
188        }
189        if let Some(lost) = reached.iter().position(|hit| !hit) {
190            return Err(format!(
191                "export_step: product '{}' is not reachable from the root",
192                self.products[lost].name
193            ));
194        }
195        Ok(*root)
196    }
197
198    /// Each product's occurrence namespaces ("ACOMP3:", "ACOMP3:ACOMP1:", and
199    /// "" for the root), sorted: the prefixes its colours resolve through.
200    pub(crate) fn occurrence_prefixes(&self, root: usize) -> Vec<Vec<String>> {
201        self.occurrence_paths(root)
202            .into_iter()
203            .map(|paths| {
204                let mut prefixes: Vec<String> = paths.into_iter().map(|path| path.prefix).collect();
205                prefixes.sort();
206                prefixes
207            })
208            .collect()
209    }
210
211    /// Every chained occurrence path that reaches each product: the component
212    /// namespace prefix the DOCUMENT knows its entities by, and the transform
213    /// into root space. The root itself gets one empty path at identity.
214    ///
215    /// Depth-first from the root, guarding the path's own ancestors, so a
216    /// structure that somehow still carries a cycle terminates.
217    fn occurrence_paths(&self, root: usize) -> Vec<Vec<OccurrencePath>> {
218        let mut paths: Vec<Vec<OccurrencePath>> = vec![Vec::new(); self.products.len()];
219        let mut total = 0usize;
220        let mut stack: Vec<(usize, OccurrencePath, Vec<usize>)> = vec![(
221            root,
222            OccurrencePath {
223                prefix: String::new(),
224                world: MAT4_IDENTITY,
225                last: None,
226            },
227            vec![root],
228        )];
229        while let Some((product, path, ancestors)) = stack.pop() {
230            if total >= MAX_OCCURRENCE_PATHS {
231                break;
232            }
233            total += 1;
234            for (slot, occurrence) in self.occurrences.iter().enumerate() {
235                if occurrence.parent != product || ancestors.contains(&occurrence.child) {
236                    continue;
237                }
238                let mut ancestors = ancestors.clone();
239                ancestors.push(occurrence.child);
240                stack.push((
241                    occurrence.child,
242                    OccurrencePath {
243                        prefix: format!("{}{}:", path.prefix, occurrence.designator),
244                        world: mat4_mul(&path.world, &occurrence.placement),
245                        last: Some(slot),
246                    },
247                    ancestors,
248                ));
249            }
250            paths[product].push(path);
251        }
252        paths
253    }
254}
255
256/// One way the document's geometry reaches a product: the component namespace
257/// that names it (`ACOMP5:ACOMP1:`, `""` at the root), the transform into root
258/// space, and the LAST occurrence on the way — the instance an annotation
259/// written against this namespace is an annotation on.
260#[derive(Clone)]
261struct OccurrencePath {
262    prefix: String,
263    world: Mat4,
264    /// Index into [`StepAssemblyExport::occurrences`]; `None` at the root.
265    last: Option<usize>,
266}
267
268/// A placement is rigid when its linear block is orthonormal with a positive
269/// determinant — the only kind an `AXIS2_PLACEMENT_3D` can express.
270fn rigid(matrix: &Mat4) -> Result<(), String> {
271    if matrix.iter().any(|value| !value.is_finite()) {
272        return Err("matrix is not finite".into());
273    }
274    let transform = crate::AffineTransform { elements: *matrix };
275    if transform.is_rigid(crate::RIGID_TOL) { return Ok(()); }
276    if transform.determinant3() < 0.0 {
277        return Err("matrix is left-handed (a mirrored instance)".into());
278    }
279    Err("matrix is not a rotation (mirrored or scaled)".into())
280}
281
282/// The `AXIS2_PLACEMENT_3D` expressing a rigid placement's frame: the origin is
283/// its translation, the axis its third linear COLUMN and the reference direction
284/// its first — the exact inverse of the importer's `frame_matrix`.
285fn write_placement_axis(writer: &mut StepWriter, matrix: &Mat4) -> Result<usize, String> {
286    super::write_placement(
287        writer,
288        Vec3::new(matrix[3], matrix[7], matrix[11]),
289        Vec3::new(matrix[2], matrix[6], matrix[10]),
290        Vec3::new(matrix[0], matrix[4], matrix[8]),
291    )
292}
293
294/// [`export_step_assembly_report`] returning just the Part 21 text.
295pub fn export_step_assembly(
296    assembly: &StepAssemblyExport,
297    unit: &str,
298    timestamp: &str,
299) -> Result<String, String> {
300    export_step_assembly_report(assembly, unit, timestamp, None, None).map(|report| report.text)
301}
302
303/// Write a product structure as an AP242 Part 21 document: one product per
304/// distinct part, one `NEXT_ASSEMBLY_USAGE_OCCURRENCE` per placement, exact
305/// B-rep geometry in each part's own frame.
306///
307/// The file is named after the ROOT product, and the optional PMI block rides
308/// on the root exactly as it does in the flat lane — with each shape aspect
309/// attached to the product that actually OWNS the geometry it names.
310pub fn export_step_assembly_report(
311    assembly: &StepAssemblyExport,
312    unit: &str,
313    timestamp: &str,
314    pmi: Option<&StepPmi<'_>>,
315    colors: Option<&StepColors>,
316) -> Result<StepExportReport, String> {
317    let root = assembly.root()?;
318    if assembly
319        .products
320        .iter()
321        .all(|product| product.bodies.is_empty())
322    {
323        return Err("export_step: at least one solid is required".into());
324    }
325    let mut report = StepExportReport {
326        products: assembly.products.len(),
327        occurrences: assembly.occurrences.len(),
328        ..StepExportReport::default()
329    };
330    let mut writer = StepWriter::default();
331    let contexts = write_file_contexts(&mut writer, unit)?;
332
333    // 1 — every product's geometry, each in its own local frame. Written first
334    // because a representation's item list needs the solids it carries.
335    let mut geometries = Vec::with_capacity(assembly.products.len());
336    for product in &assembly.products {
337        let bodies: Vec<(String, &BrepSolid)> = product
338            .bodies
339            .iter()
340            .map(|(name, solid)| (name.clone(), solid))
341            .collect();
342        geometries.push(write_product_geometry(
343            &mut writer,
344            &contexts,
345            &bodies,
346            &mut report,
347        )?);
348    }
349
350    // 2 — each occurrence's placement frame. It is an ITEM of the parent
351    // representation, so it has to exist before that representation is written.
352    let mut placement_axes = Vec::with_capacity(assembly.occurrences.len());
353    for occurrence in &assembly.occurrences {
354        placement_axes.push(write_placement_axis(&mut writer, &occurrence.placement)?);
355    }
356
357    // 3 — the representations: identity axis, own solids, child placements.
358    let geometry_context = contexts.geometry_context;
359    let mut representations = Vec::with_capacity(assembly.products.len());
360    for (index, product) in assembly.products.iter().enumerate() {
361        let mut items = vec![contexts.axis];
362        items.extend(geometries[index].solids.iter().map(|(_, id)| *id));
363        for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
364            if occurrence.parent == index {
365                items.push(placement_axes[slot]);
366            }
367        }
368        // A pure assembly node carries no bodies, and an ADVANCED_BREP shape
369        // representation with no solid in it is not one — say SHAPE_REPRESENTATION,
370        // which is what a vendor writes and what our importer reads for the
371        // structure-only levels of a tree.
372        let keyword = if geometries[index].solids.is_empty() {
373            "SHAPE_REPRESENTATION"
374        } else {
375            "ADVANCED_BREP_SHAPE_REPRESENTATION"
376        };
377        representations.push(writer.add(format!(
378            "{keyword}('{}',{},#{geometry_context})",
379            step_string(&product.name),
380            id_list(&items)
381        )));
382    }
383
384    // 4 — the product definition chains, bound to those representations.
385    let mut definitions = Vec::with_capacity(assembly.products.len());
386    for (index, product) in assembly.products.iter().enumerate() {
387        // 'assembly' vs 'part' is the distinction a receiving system builds its
388        // own structure tree from, so it follows the graph, not the geometry: a
389        // product that places others is an assembly even when it also carries
390        // bodies of its own.
391        let places_others = assembly
392            .occurrences
393            .iter()
394            .any(|occurrence| occurrence.parent == index);
395        let category = if places_others { "assembly" } else { "part" };
396        let ids = write_product(&mut writer, &contexts, &product.name, &product.id, category);
397        let (product_shape, representation) = (ids.product_shape, representations[index]);
398        writer.add(format!(
399            "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
400        ));
401        definitions.push(ids);
402    }
403
404    // 5 — the occurrences themselves. Each one's `PRODUCT_DEFINITION_SHAPE` is
405    // kept: it is what an OCCURRENCE-scoped annotation's shape aspect hangs
406    // off (step 7), and the entity a reader tells "this instance" from "this
407    // part" by.
408    let mut nauo_shapes: Vec<usize> = Vec::with_capacity(assembly.occurrences.len());
409    let mut relationships: Vec<usize> = Vec::with_capacity(assembly.occurrences.len());
410    for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
411        let parent = definitions[occurrence.parent].definition;
412        let child = definitions[occurrence.child].definition;
413        let label = step_string(&occurrence.designator);
414        let nauo = writer.add(format!(
415            "NEXT_ASSEMBLY_USAGE_OCCURRENCE('{label}','{label}','',#{parent},#{child},'{label}')"
416        ));
417        let nauo_shape =
418            writer.add(format!("PRODUCT_DEFINITION_SHAPE('','NAUO PRDDFN',#{nauo})"));
419        nauo_shapes.push(nauo_shape);
420        let identity = contexts.axis;
421        let placement = placement_axes[slot];
422        let transformation = writer.add(format!(
423            "ITEM_DEFINED_TRANSFORMATION('','',#{identity},#{placement})"
424        ));
425        let (child_rep, parent_rep) = (
426            representations[occurrence.child],
427            representations[occurrence.parent],
428        );
429        let relationship = writer.add(format!(
430            "(REPRESENTATION_RELATIONSHIP('','',#{child_rep},#{parent_rep})\
431             REPRESENTATION_RELATIONSHIP_WITH_TRANSFORMATION(#{transformation})\
432             SHAPE_REPRESENTATION_RELATIONSHIP())"
433        ));
434        relationships.push(relationship);
435        writer.add(format!(
436            "CONTEXT_DEPENDENT_SHAPE_REPRESENTATION(#{relationship},#{nauo_shape})"
437        ));
438    }
439
440    // 6 — geometry colour. A product's entities are known to the DOCUMENT under
441    // every occurrence namespace that reaches it, so the colour lookup resolves
442    // through the same paths the PMI references do — sorted, so which of a
443    // repeated part's namespaces supplies the colour does not depend on the
444    // walk's stack order.
445    // ONE walk for both consumers below — each product's occurrence namespaces —
446    // and only when one of them needs it: the walk is capped at
447    // `MAX_OCCURRENCE_PATHS`, so an export that carries neither colour nor PMI
448    // must not pay for it.
449    let colors = colors.filter(|colors| !colors.is_empty());
450    let paths = (pmi.is_some() || colors.is_some())
451        .then(|| assembly.occurrence_paths(root))
452        .unwrap_or_default();
453    let mut base_styles = std::collections::BTreeMap::new();
454    // The colour each item's own style was written with.
455    let mut base_written: std::collections::BTreeMap<usize, [u8; 3]> = std::collections::BTreeMap::new();
456    if let Some(colors) = colors {
457        let mut items = Vec::new();
458        for (index, geometry) in geometries.iter().enumerate() {
459            let mut prefixes: Vec<String> =
460                paths[index].iter().map(|path| path.prefix.clone()).collect();
461            prefixes.sort();
462            // A part placed only by the root: a solid's own colour is the one
463            // every instance gives it, and none where they differ, since step
464            // 6b writes each instance's own solid colour on its occurrence
465            // wherever it differs from that (so neither an uncoloured instance
466            // takes another's colour, nor a coloured one loses its own).
467            // Faces, which 6b does not write, and a part reached through a
468            // sub-assembly keep the first colour any namespace names.
469            let root_only = !paths[index].is_empty()
470                && paths[index]
471                    .iter()
472                    .all(|path| path.last.is_some_and(|slot| assembly.occurrences[slot].parent == root));
473            if root_only {
474                for (name, solid) in &geometry.solids {
475                    let mut shared = prefixes.iter().map(|prefix| colors.resolve(std::slice::from_ref(prefix), name));
476                    let first = shared.next().flatten();
477                    if let Some(rgb) = first.filter(|rgb| shared.all(|other| other == Some(*rgb))) {
478                        items.push((*solid, rgb));
479                    }
480                }
481                items.extend(styles::styled_items_split(geometry, colors, &[], &prefixes));
482            } else {
483                items.extend(styles::styled_items(geometry, colors, &prefixes));
484            }
485        }
486        base_styles = styles::write_geometry_styles_keyed(&mut writer, geometry_context, &items)?;
487        report.styled_items = items.len();
488        for (item, rgb) in &items {
489            base_written.entry(*item).or_insert(*rgb);
490        }
491    }
492    // 6b — each occurrence's own colours, on its child's own solids: the one
493    // the caller set, on every solid; or, for an instance placed directly by
494    // the root, each solid's own colour under that instance's namespace where
495    // the part's shared geometry was written with another (or none). Step 6
496    // could give the shared geometry only its first instance's colours.
497    let mut occurrence_items: Vec<(usize, usize, [u8; 3])> = Vec::new();
498    for (slot, occurrence) in assembly.occurrences.iter().enumerate() {
499        let relationship = relationships[slot];
500        let solids = &geometries[occurrence.child].solids;
501        if let Some(rgb) = occurrence.color {
502            occurrence_items.extend(solids.iter().map(|(_, solid)| (*solid, relationship, rgb)));
503            continue;
504        }
505        let Some(colors) = colors else { continue };
506        if occurrence.parent != root {
507            continue;
508        }
509        let own = [format!("{}:", occurrence.designator)];
510        for (name, solid) in solids {
511            if let Some(rgb) = colors.resolve(&own, name) {
512                if base_written.get(solid) != Some(&rgb) {
513                    occurrence_items.push((*solid, relationship, rgb));
514                }
515            }
516        }
517    }
518    report.styled_items +=
519        styles::write_occurrence_styles(&mut writer, geometry_context, &base_styles, &occurrence_items)?;
520
521    // 7a — each PART's own PMI, written into that part's product with the
522    // part's own names. A part shared by six instances carries its annotations
523    // ONCE, which is the same rule the importer reads them back under.
524    for (index, geometry) in geometries.iter().enumerate() {
525        let Some((state, part_report)) = &assembly.products[index].pmi else {
526            continue;
527        };
528        let mut names = StepNameMaps::default();
529        names.register(
530            geometry,
531            StepItemOwner {
532                product_shape: definitions[index].product_shape,
533                representation: representations[index],
534            },
535            "",
536            &MAT4_IDENTITY,
537        );
538        let context = pmi::StepContext {
539            product_shape: definitions[index].product_shape,
540            representation: representations[index],
541            geometry_context,
542            length_unit: contexts.length_unit,
543            angle_unit: contexts.angle_unit,
544            faces: &names.faces,
545            edges: &names.edges,
546            vertices: &names.vertices,
547        };
548        report.pmi_unresolved_references += pmi::write_pmi(
549            &mut writer,
550            &context,
551            &StepPmi {
552                state,
553                report: part_report,
554            },
555        )?;
556    }
557
558    // 7b — PMI on the ROOT document, resolving through every occurrence path.
559    //
560    // A reference that reaches a part THROUGH an occurrence hangs its shape
561    // aspect off that occurrence's `PRODUCT_DEFINITION_SHAPE`, not the part's:
562    // `ACOMP3:top` and `ACOMP4:top` name the SAME `ADVANCED_FACE` (two
563    // instances share the part's geometry, and the `GEOMETRIC_ITEM_SPECIFIC_-
564    // USAGE` still points at it), but they are annotations on two different
565    // INSTANCES, and the owner is the only place that distinction can live.
566    // It is also what the importer reads the distinction back out of
567    // (`io/step_import/assembly_pmi.rs`), which is what closes the round trip.
568    if let Some(pmi) = pmi {
569        let mut names = StepNameMaps::default();
570        for (index, geometry) in geometries.iter().enumerate() {
571            for path in &paths[index] {
572                let owner = StepItemOwner {
573                    product_shape: match path.last {
574                        Some(slot) => nauo_shapes[slot],
575                        None => definitions[index].product_shape,
576                    },
577                    representation: representations[index],
578                };
579                names.register(geometry, owner, &path.prefix, &path.world);
580            }
581        }
582        let context = pmi::StepContext {
583            product_shape: definitions[root].product_shape,
584            representation: representations[root],
585            geometry_context,
586            length_unit: contexts.length_unit,
587            angle_unit: contexts.angle_unit,
588            faces: &names.faces,
589            edges: &names.edges,
590            vertices: &names.vertices,
591        };
592        report.pmi_unresolved_references += pmi::write_pmi(&mut writer, &context, pmi)?;
593    }
594
595    finish_step_file(
596        writer,
597        &assembly.products[root].name,
598        timestamp,
599        &mut report,
600    )?;
601    Ok(report)
602}
603