Skip to main content

brep_kernel/io/
step.rs

1use crate::analytic_surface::curve_scale;
2use crate::analytic_surface::{circumcenter, AnalyticSurface};
3use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
4use crate::{make_arc, KernelTolerances, NurbsCurve, NurbsSurface, Vec3};
5use rustc_hash::FxHashMap as HashMap;
6
7#[path = "step/pcurve.rs"]
8pub(crate) mod pcurve;
9use pcurve::{build_pcurve, EmittedCurve, EmittedFrame, EmittedSurface, Pcurve2d};
10#[path = "step/pmi.rs"]
11pub(crate) mod pmi;
12pub use pmi::StepPmi;
13#[path = "step/assembly.rs"]
14pub mod assembly;
15pub use assembly::{
16    export_step_assembly, export_step_assembly_report, StepAssemblyExport, StepExportOccurrence,
17    StepExportProduct,
18};
19#[path = "step/export_tree.rs"]
20mod export_tree;
21pub use export_tree::{assembly_export_tree, PART_ATTRIBUTES, PART_NUMBER};
22#[path = "step/styles.rs"]
23pub(crate) mod styles;
24pub use styles::StepColors;
25
26pub use crate::step_matrix::Mat4;
27pub(crate) use crate::step_matrix::{mat4_mul, MAT4_IDENTITY};
28
29pub(crate) fn transform_point(matrix: &Mat4, point: Vec3) -> Vec3 {
30    crate::AffineTransform {
31        elements: *matrix,
32    }
33    .point(point)
34}
35
36pub(crate) fn step_string(value: &str) -> String {
37    value.replace('\'', "''")
38}
39
40pub(crate) fn real(value: f64) -> Result<String, String> {
41    if !value.is_finite() {
42        return Err(format!("export_step: non-finite number {value}"));
43    }
44    // Analytic frame axes come from cross products that can round to -0.0;
45    // normalize so directions never print a negative zero component.
46    if value == 0.0 {
47        return Ok("0.".into());
48    }
49    if value.fract() == 0.0 && value.abs() < 1e15 {
50        return Ok(format!("{value:.0}."));
51    }
52    let mut output = format!("{value:.15}");
53    while output.ends_with('0') {
54        output.pop();
55    }
56    if output.ends_with('.') {
57        output.push('0');
58    }
59    if output == "-0.0" {
60        output = "0.0".into();
61    }
62    Ok(output)
63}
64
65fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
66    let mut values = Vec::new();
67    let mut multiplicities = Vec::new();
68    for &knot in knots {
69        if values
70            .last()
71            .is_some_and(|previous: &f64| (*previous - knot).abs() <= 1e-12)
72        {
73            *multiplicities.last_mut().unwrap() += 1;
74        } else {
75            values.push(knot);
76            multiplicities.push(1);
77        }
78    }
79    (values, multiplicities)
80}
81
82pub(crate) fn edge_subcurve(edge: &EdgeRecord) -> Result<NurbsCurve, String> {
83    let [start, end] = edge.curve.domain()?;
84    let epsilon = (1e-9 * (end - start)).max(2e-9);
85    let mut curve = edge.curve.clone();
86    if edge.t0 > start + epsilon && edge.t0 < end - epsilon {
87        curve = curve.split(edge.t0)?.1;
88    }
89    let domain = curve.domain()?;
90    if edge.t1 < domain[1] - epsilon && edge.t1 > domain[0] + epsilon {
91        curve = curve.split(edge.t1)?.0;
92    }
93    Ok(curve)
94}
95
96#[derive(Default)]
97pub(crate) struct StepWriter {
98    lines: Vec<String>,
99}
100
101impl StepWriter {
102    pub(crate) fn add(&mut self, body: impl Into<String>) -> usize {
103        let id = self.lines.len() + 1;
104        self.lines.push(format!("#{id}={};", body.into()));
105        id
106    }
107
108    fn data(&self) -> String {
109        self.lines.join("\n")
110    }
111}
112
113pub(crate) fn write_point(writer: &mut StepWriter, point: Vec3) -> Result<usize, String> {
114    Ok(writer.add(format!(
115        "CARTESIAN_POINT('',({},{},{}))",
116        real(point.x)?,
117        real(point.y)?,
118        real(point.z)?
119    )))
120}
121
122pub(crate) fn id_list(ids: &[usize]) -> String {
123    format!(
124        "({})",
125        ids.iter()
126            .map(|id| format!("#{id}"))
127            .collect::<Vec<_>>()
128            .join(",")
129    )
130}
131
132pub(crate) fn write_direction(writer: &mut StepWriter, direction: Vec3) -> Result<usize, String> {
133    Ok(writer.add(format!(
134        "DIRECTION('',({},{},{}))",
135        real(direction.x)?,
136        real(direction.y)?,
137        real(direction.z)?
138    )))
139}
140
141pub(crate) fn write_placement(
142    writer: &mut StepWriter,
143    origin: Vec3,
144    axis: Vec3,
145    ref_direction: Vec3,
146) -> Result<usize, String> {
147    let origin = write_point(writer, origin)?;
148    let axis = write_direction(writer, axis)?;
149    let ref_direction = write_direction(writer, ref_direction)?;
150    Ok(writer.add(format!(
151        "AXIS2_PLACEMENT_3D('',#{origin},#{axis},#{ref_direction})"
152    )))
153}
154
155/// Emit the analytic AP242 surface entity (PLANE / CYLINDRICAL_SURFACE /
156/// CONICAL_SURFACE / SPHERICAL_SURFACE / TOROIDAL_SURFACE) for a recognized
157/// carrier, or `None` when the surface must stay a B-spline. The second value
158/// reports whether the STEP-standard orientation of the emitted entity (plane
159/// normal along the placement axis; revolution normal outward) is the REVERSE
160/// of the stored NURBS orientation, so ADVANCED_FACE can invert `same_sense`
161/// and the face normal survives the round trip. The third describes the
162/// emitted entity's own (u,v) parameterization for the pcurve writer.
163fn write_analytic_surface(
164    writer: &mut StepWriter,
165    surface: &NurbsSurface,
166) -> Result<Option<(usize, bool, EmittedSurface)>, String> {
167    let Some(analytic) = surface.analytic() else {
168        return Ok(None);
169    };
170    match analytic {
171        AnalyticSurface::Plane {
172            origin,
173            u_dir,
174            v_dir,
175            ..
176        } => {
177            // STEP planes are unbounded; the importer re-sizes the patch from
178            // the face's edges, so only origin/normal/ref matter.
179            let (Ok(normal), Ok(x_axis)) = (u_dir.cross(*v_dir).normalized(), u_dir.normalized())
180            else {
181                return Ok(None);
182            };
183            let placement = write_placement(writer, *origin, normal, x_axis)?;
184            // The reader derives the plane's second parameter axis as
185            // normal × ref_direction, so S(x,y) = origin + x·x̂ + y·ŷ with
186            // those exact vectors — an orthonormal frame regardless of how the
187            // stored patch scaled or sheared its own u_dir/v_dir.
188            Ok(Some((
189                writer.add(format!("PLANE('',#{placement})")),
190                false,
191                EmittedSurface::Plane {
192                    origin: *origin,
193                    x_axis,
194                    y_axis: normal.cross(x_axis),
195                },
196            )))
197        }
198        AnalyticSurface::RuledRevolution {
199            frame,
200            rho0,
201            rho1,
202            height,
203        } => {
204            // The recognizer allows height < 0 (descending generatrix), whose
205            // normal is the reverse of the standard outward convention the
206            // importer reconstructs; report that so the face sense compensates.
207            let flipped = *height < 0.0;
208            let radius_scale = 1.0 + rho0.abs().max(rho1.abs());
209            if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
210                if *rho0 <= 0.0 {
211                    return Ok(None);
212                }
213                let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
214                return Ok(Some((
215                    writer.add(format!(
216                        "CYLINDRICAL_SURFACE('',#{placement},{})",
217                        real(*rho0)?
218                    )),
219                    flipped,
220                    EmittedSurface::Cylinder {
221                        frame: EmittedFrame {
222                            origin: frame.origin,
223                            x_axis: frame.x_axis,
224                            y_axis: frame.y_axis,
225                            axis: frame.axis,
226                            azimuth_sign: 1.0,
227                        },
228                        radius: *rho0,
229                    },
230                )));
231            }
232            // Cone. The importer re-sizes the carrier from edge samples with a
233            // 1e-4-scaled axial margin and clamps a negative extended-end
234            // radius to zero — which BENDS the rebuilt slope when the apex sits
235            // at an end of the face's axial range. Keep apex-touching cones as
236            // exact NURBS instead of exporting a distorted carrier.
237            let slope = (rho1 - rho0) / height;
238            let apex_margin = 2.0 * (1e-4 * height.abs().max(1.0) + 1e-9) * slope.abs();
239            if rho0.min(*rho1) <= apex_margin {
240                return Ok(None);
241            }
242            // Orient the placement axis so the radius grows along +axis: STEP
243            // semi-angles are positive. Radius at the placement origin stays
244            // rho0 either way because the origin is on-axis at the v = 0 base.
245            let axis = if slope >= 0.0 {
246                frame.axis
247            } else {
248                frame.axis.scale(-1.0)
249            };
250            let placement = write_placement(writer, frame.origin, axis, frame.x_axis)?;
251            Ok(Some((
252                writer.add(format!(
253                    "CONICAL_SURFACE('',#{placement},{},{})",
254                    real(*rho0)?,
255                    real(slope.abs().atan())?
256                )),
257                flipped,
258                EmittedSurface::Cone {
259                    frame: EmittedFrame {
260                        origin: frame.origin,
261                        x_axis: frame.x_axis,
262                        // Reversing the placement axis reverses the derived
263                        // second axis with it, so the emitted azimuth runs
264                        // opposite the stored carrier's u.
265                        y_axis: axis.cross(frame.x_axis),
266                        axis,
267                        azimuth_sign: if slope >= 0.0 { 1.0 } else { -1.0 },
268                    },
269                    radius: *rho0,
270                    semi_angle: slope.abs().atan(),
271                },
272            )))
273        }
274        AnalyticSurface::Sphere { frame, radius } => {
275            // Recognition template and importer reconstruction share the same
276            // south-to-north meridian construction, so the rebuild is exact.
277            let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
278            Ok(Some((
279                writer.add(format!(
280                    "SPHERICAL_SURFACE('',#{placement},{})",
281                    real(*radius)?
282                )),
283                false,
284                EmittedSurface::Sphere {
285                    frame: EmittedFrame {
286                        origin: frame.origin,
287                        x_axis: frame.x_axis,
288                        y_axis: frame.y_axis,
289                        axis: frame.axis,
290                        azimuth_sign: 1.0,
291                    },
292                    radius: *radius,
293                },
294            )))
295        }
296        AnalyticSurface::Torus {
297            frame,
298            major_radius,
299            minor_radius,
300        } => {
301            let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
302            Ok(Some((
303                writer.add(format!(
304                    "TOROIDAL_SURFACE('',#{placement},{},{})",
305                    real(*major_radius)?,
306                    real(*minor_radius)?
307                )),
308                false,
309                EmittedSurface::Torus {
310                    frame: EmittedFrame {
311                        origin: frame.origin,
312                        x_axis: frame.x_axis,
313                        y_axis: frame.y_axis,
314                        axis: frame.axis,
315                        azimuth_sign: 1.0,
316                    },
317                    major_radius: *major_radius,
318                    minor_radius: *minor_radius,
319                },
320            )))
321        }
322        // No SURFACE_OF_REVOLUTION reader exists yet; general revolutions keep
323        // their exact NURBS form — except a sphere, which a reader knows.
324        AnalyticSurface::Revolution { frame, generatrix, .. } => {
325            let Some((center, radius, reversed)) = polar_meridian_sphere(frame, generatrix) else {
326                return Ok(None);
327            };
328            let placement = write_placement(writer, center, frame.axis, frame.x_axis)?;
329            Ok(Some((
330                writer.add(format!(
331                    "SPHERICAL_SURFACE('',#{placement},{})",
332                    real(radius)?
333                )),
334                reversed,
335                EmittedSurface::Sphere {
336                    frame: EmittedFrame {
337                        origin: center,
338                        x_axis: frame.x_axis,
339                        y_axis: frame.y_axis,
340                        axis: frame.axis,
341                        azimuth_sign: 1.0,
342                    },
343                    radius,
344                },
345            )))
346        }
347    }
348}
349
350/// `BREP_STEP_SPHERE_OF_REVOLUTION` (default on, `=0` restores the B-spline):
351/// a revolution whose generatrix is an arc of a circle centred on the axis is
352/// written as a SPHERICAL_SURFACE, whatever its sweep, whichever way the arc
353/// runs and whether or not it reaches a pole.
354fn sphere_of_revolution_on() -> bool {
355    crate::switch!("BREP_STEP_SPHERE_OF_REVOLUTION", true)
356}
357
358/// The centre and radius of the sphere a general revolution lies on when its
359/// generatrix is an arc of a circle centred on the axis, in the meridian
360/// half-plane, and whether the arc runs north to south there, which makes the
361/// stored normal point inward. A part turn of a half circle about its own
362/// chord is such a surface: a lune between the two poles, which a reader can
363/// bound on a sphere but not on a B-spline patch whose two pole sides have no
364/// length.
365///
366/// The arc is read span by span, so a piece split out of a longer circle
367/// (knots and end weights no longer `make_arc`'s) is taken too: each rational
368/// quadratic span is a circular arc about `centre` exactly when its ends are
369/// at the radius, its middle control point is where the end tangents meet,
370/// and its weights satisfy w1² = w0·w2·cos²(half the span's angle).
371fn polar_meridian_sphere(
372    frame: &crate::analytic_surface::RevolutionFrame,
373    generatrix: &NurbsCurve,
374) -> Option<(Vec3, f64, bool)> {
375    if !sphere_of_revolution_on() {
376        return None;
377    }
378    let controls = &generatrix.control_points;
379    let count = controls.len();
380    if generatrix.degree != 2 || count < 3 || count % 2 == 0 || generatrix.knots.len() != count + 3 {
381        return None;
382    }
383    // Bezier spans: every interior knot twice.
384    let knots = &generatrix.knots;
385    let span_knots = (count - 1) / 2;
386    for span in 1..span_knots {
387        if (knots[1 + 2 * span] - knots[2 + 2 * span]).abs() > 1e-12 {
388            return None;
389        }
390    }
391    let scale = curve_scale(generatrix);
392    let tolerance = 1e-9 * scale.max(1.0);
393    let mut points = Vec::with_capacity(count);
394    for control in controls {
395        if control.w <= 0.0 {
396            return None;
397        }
398        let point = control.point().ok()?;
399        // in the meridian half-plane the frame's x axis and its axis span
400        let d = point.sub(frame.origin);
401        if d.dot(frame.y_axis).abs() > tolerance || d.dot(frame.x_axis) < -tolerance {
402            return None;
403        }
404        points.push(point);
405    }
406    // The centre is on the axis at height `t` above the frame's origin; every
407    // span gives linear conditions on it (ends equidistant, end tangents
408    // square to the radii).
409    let (mut num, mut den) = (0.0, 0.0);
410    for span in 0..span_knots {
411        let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
412        for (direction, through) in [
413            (p2.sub(p0), p0.add(p2).scale(0.5)),
414            (p1.sub(p0), p0),
415            (p1.sub(p2), p2),
416        ] {
417            // direction · (through − origin − t·axis) = 0
418            let a = direction.dot(frame.axis);
419            let b = direction.dot(through.sub(frame.origin));
420            num += a * b;
421            den += a * a;
422        }
423    }
424    if den <= tolerance * tolerance {
425        return None;
426    }
427    let center = frame.origin.add(frame.axis.scale(num / den));
428    let radius = points[0].sub(center).length();
429    if radius <= tolerance {
430        return None;
431    }
432    let mut turn = 0.0;
433    for span in 0..span_knots {
434        let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
435        let (r0, r1, r2) = (p0.sub(center), p1.sub(center), p2.sub(center));
436        if (r0.length() - radius).abs() > tolerance
437            || (r2.length() - radius).abs() > tolerance
438            || p1.sub(p0).dot(r0).abs() > tolerance * radius
439            || p1.sub(p2).dot(r2).abs() > tolerance * radius
440        {
441            return None;
442        }
443        // cos(half the span's angle) = radius / |r1|
444        let cos_half = radius / r1.length();
445        let (w0, w1, w2) = (controls[2 * span].w, controls[2 * span + 1].w, controls[2 * span + 2].w);
446        if !(cos_half > 1e-6) || (w1 * w1 / (w0 * w2) - cos_half * cos_half).abs() > 1e-9 {
447            return None;
448        }
449        // which way the span turns in the (x, axis) half-plane
450        let cross = r0.dot(frame.x_axis) * r2.dot(frame.axis) - r0.dot(frame.axis) * r2.dot(frame.x_axis);
451        if cross.abs() <= tolerance * radius || (turn != 0.0 && cross.signum() != turn) {
452            return None;
453        }
454        turn = cross.signum();
455    }
456    Some((center, radius, turn < 0.0))
457}
458
459/// A curve recognized as an exact `make_arc` product: a circular arc of
460/// `radius` about `axis`, starting at angle 0 on `x_axis` and travelling
461/// counterclockwise through `sweep` — exactly the CIRCLE parameterization the
462/// importer trims between the edge's vertices.
463struct CircularArc {
464    center: Vec3,
465    axis: Vec3,
466    x_axis: Vec3,
467    /// axis × x_axis — the second placement axis a STEP reader derives, so the
468    /// emitted parameterization is C(a) = center + r(cos a·x̂ + sin a·ŷ).
469    y_axis: Vec3,
470    radius: f64,
471    /// Total swept angle: the emitted entity's parameter range is [0, sweep].
472    sweep: f64,
473    /// Rational-quadratic span count of the kernel arc this was recognized
474    /// from — the bridge from the emitted ANGLE back to the kernel's own
475    /// parameter, which a fitted pcurve on a B-spline carrier needs.
476    spans: usize,
477}
478
479
480
481/// Homogeneous-net equality to a scale-relative tolerance (the same
482/// reconstruction contract analytic_surface.rs uses): matching nets mean the
483/// curves are the SAME exact rational arc, not merely close.
484fn curves_match(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
485    if a.degree != b.degree
486        || a.knots.len() != b.knots.len()
487        || a.control_points.len() != b.control_points.len()
488    {
489        return false;
490    }
491    if a.knots
492        .iter()
493        .zip(&b.knots)
494        .any(|(x, y)| (x - y).abs() > 1e-12)
495    {
496        return false;
497    }
498    let tolerance = 1e-9 * scale.max(1.0);
499    a.control_points
500        .iter()
501        .zip(&b.control_points)
502        .all(|(p, q)| {
503            (p.x - q.x).abs() <= tolerance
504                && (p.y - q.y).abs() <= tolerance
505                && (p.z - q.z).abs() <= tolerance
506                && (p.w - q.w).abs() <= 1e-9
507        })
508}
509
510/// Recognition by exact reconstruction: extract a candidate circle from three
511/// curve points, rebuild it with `make_arc`, and demand the identical net.
512/// Split subranges of a circle (whose knots are no longer the pristine
513/// make_arc pattern) are rejected and honestly stay NURBS.
514fn recognize_circular_arc(curve: &NurbsCurve) -> Option<CircularArc> {
515    if curve.degree != 2
516        || curve.control_points.len() < 3
517        || curve.control_points.len() % 2 == 0
518        || (curve.control_points.len() - 1) / 2 > 4
519    {
520        return None;
521    }
522    let [t0, t1] = curve.domain().ok()?;
523    let at = |fraction: f64| curve.evaluate(t0 + (t1 - t0) * fraction);
524    // Three points at < 74% of the sweep apart, so consecutive pairs subtend
525    // less than pi and the cross product below gives the travel direction.
526    let p0 = at(0.0).ok()?;
527    let pa = at(0.35).ok()?;
528    let pb = at(0.7).ok()?;
529    let center = circumcenter(p0, pa, pb)?;
530    let radial = p0.sub(center);
531    let radius = radial.length();
532    let scale = curve_scale(curve);
533    if radius <= 1e-9 * scale.max(1.0) {
534        return None;
535    }
536    let x_axis = radial.scale(1.0 / radius);
537    let axis = radial.cross(pa.sub(center)).normalized().ok()?;
538    let y_axis = axis.cross(x_axis);
539    let p_end = at(1.0).ok()?;
540    let sweep = if p_end.sub(p0).length() <= 1e-9 * (1.0 + radius) {
541        std::f64::consts::TAU
542    } else {
543        let closing = p_end.sub(center);
544        let mut angle = closing.dot(y_axis).atan2(closing.dot(x_axis));
545        if angle < 0.0 {
546            angle += std::f64::consts::TAU;
547        }
548        angle
549    };
550    let rebuilt = make_arc(center, x_axis, y_axis, radius, 0.0, sweep).ok()?;
551    curves_match(curve, &rebuilt, scale).then_some(CircularArc {
552        center,
553        axis,
554        x_axis,
555        y_axis,
556        radius,
557        sweep,
558        spans: (curve.control_points.len() - 1) / 2,
559    })
560}
561
562/// Emit LINE or CIRCLE for a recognized analytic edge curve (already oriented
563/// start-to-end by `edge_subcurve`), or `None` for the B-spline fallback.
564///
565/// The second value describes the parameterization ISO 10303-42 gives the
566/// entity that was written, because a pcurve on this edge has to share THAT
567/// parameter — not the kernel's knot values (see `step/pcurve.rs`).
568fn write_analytic_curve(
569    writer: &mut StepWriter,
570    curve: &NurbsCurve,
571) -> Result<Option<(usize, EmittedCurve)>, String> {
572    if curve.degree == 1
573        && curve.control_points.len() == 2
574        && curve
575            .control_points
576            .iter()
577            .all(|control| (control.w - 1.0).abs() <= 1e-12)
578    {
579        let start = curve.control_points[0].point()?;
580        let end = curve.control_points[1].point()?;
581        let Ok(direction) = end.sub(start).normalized() else {
582            return Ok(None);
583        };
584        let point = write_point(writer, start)?;
585        let step_direction = write_direction(writer, direction)?;
586        let vector = writer.add(format!(
587            "VECTOR('',#{step_direction},{})",
588            real(end.sub(start).length())?
589        ));
590        return Ok(Some((
591            writer.add(format!("LINE('',#{point},#{vector})")),
592            // The VECTOR carries the full chord length, so the STEP parameter
593            // of this line is the fraction along the chord: C(s) = start +
594            // s·(end − start) over [0, 1].
595            EmittedCurve::Line { start, end },
596        )));
597    }
598    if let Some(arc) = recognize_circular_arc(curve) {
599        // ref_direction points at the edge's start vertex and the arc runs
600        // counterclockwise about the axis, so the importer's vertex-trimmed
601        // CCW rebuild reproduces the same directed curve with sense .T.
602        let placement = write_placement(writer, arc.center, arc.axis, arc.x_axis)?;
603        return Ok(Some((
604            writer.add(format!("CIRCLE('',#{placement},{})", real(arc.radius)?)),
605            EmittedCurve::Circle {
606                center: arc.center,
607                x_axis: arc.x_axis,
608                y_axis: arc.y_axis,
609                radius: arc.radius,
610                sweep: arc.sweep,
611                spans: arc.spans,
612            },
613        )));
614    }
615    Ok(None)
616}
617
618fn write_curve(writer: &mut StepWriter, curve: &NurbsCurve) -> Result<usize, String> {
619    let points = curve
620        .control_points
621        .iter()
622        .map(|control| write_point(writer, control.point()?))
623        .collect::<Result<Vec<_>, _>>()?;
624    write_bspline_curve(writer, curve, &points)
625}
626
627/// The B_SPLINE_CURVE_WITH_KNOTS entity (or its rational complex form) over
628/// control points that have ALREADY been written — shared by the 3D edge
629/// curves and by the 2D pcurves, whose CARTESIAN_POINTs carry two coordinates
630/// instead of three but whose degree/knots/weights are written identically.
631fn write_bspline_curve(
632    writer: &mut StepWriter,
633    curve: &NurbsCurve,
634    points: &[usize],
635) -> Result<usize, String> {
636    let (knot_values, multiplicities) = knot_runs(&curve.knots);
637    let multiplicities = format!(
638        "({})",
639        multiplicities
640            .iter()
641            .map(usize::to_string)
642            .collect::<Vec<_>>()
643            .join(",")
644    );
645    let knots = format!(
646        "({})",
647        knot_values
648            .iter()
649            .map(|value| real(*value))
650            .collect::<Result<Vec<_>, _>>()?
651            .join(",")
652    );
653    let rational = curve
654        .control_points
655        .iter()
656        .any(|control| (control.w - 1.0).abs() > 1e-12);
657    if !rational {
658        return Ok(writer.add(format!(
659            "B_SPLINE_CURVE_WITH_KNOTS('',{},{},.UNSPECIFIED.,.F.,.F.,{multiplicities},{knots},.UNSPECIFIED.)",
660            curve.degree,
661            id_list(points),
662        )));
663    }
664    let weights = format!(
665        "({})",
666        curve
667            .control_points
668            .iter()
669            .map(|control| real(control.w))
670            .collect::<Result<Vec<_>, _>>()?
671            .join(",")
672    );
673    Ok(writer.add(format!(
674        "(BOUNDED_CURVE()B_SPLINE_CURVE({},{},.UNSPECIFIED.,.F.,.F.)\
675         B_SPLINE_CURVE_WITH_KNOTS({multiplicities},{knots},.UNSPECIFIED.)\
676         CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({weights})\
677         REPRESENTATION_ITEM(''))",
678        curve.degree,
679        id_list(points),
680    )))
681}
682
683fn write_point_2d(writer: &mut StepWriter, point: [f64; 2]) -> Result<usize, String> {
684    Ok(writer.add(format!(
685        "CARTESIAN_POINT('',({},{}))",
686        real(point[0])?,
687        real(point[1])?
688    )))
689}
690
691fn write_direction_2d(writer: &mut StepWriter, direction: [f64; 2]) -> Result<usize, String> {
692    Ok(writer.add(format!(
693        "DIRECTION('',({},{}))",
694        real(direction[0])?,
695        real(direction[1])?
696    )))
697}
698
699/// Write the 2D geometry of one pcurve.
700///
701/// The `VECTOR` of a 2D LINE carries its TRUE magnitude rather than being
702/// normalized to 1: ISO 10303-42 parameterizes a line as pnt + u·(magnitude ×
703/// orientation), so the magnitude is what makes the 2D parameter equal the 3D
704/// entity's parameter exactly.  (OpenCASCADE normalizes every VECTOR it writes
705/// and then loses that agreement wherever the two speeds differ — its own cone
706/// ruling pcurves are off by cos(semi-angle) — so this is strictly the more
707/// faithful of the two conventions, and identical wherever the speeds agree.)
708fn write_pcurve_geometry(writer: &mut StepWriter, curve: &Pcurve2d) -> Result<usize, String> {
709    match curve {
710        Pcurve2d::Line { point, vector } => {
711            let magnitude = vector[0].hypot(vector[1]);
712            if magnitude <= 0.0 {
713                return Err("export_step: degenerate 2D line pcurve".into());
714            }
715            let point_id = write_point_2d(writer, *point)?;
716            let direction =
717                write_direction_2d(writer, [vector[0] / magnitude, vector[1] / magnitude])?;
718            let vector_id = writer.add(format!(
719                "VECTOR('',#{direction},{})",
720                real(magnitude)?
721            ));
722            Ok(writer.add(format!("LINE('',#{point_id},#{vector_id})")))
723        }
724        Pcurve2d::Circle {
725            center,
726            ref_direction,
727            radius,
728        } => {
729            let center_id = write_point_2d(writer, *center)?;
730            let direction = write_direction_2d(writer, *ref_direction)?;
731            let placement = writer.add(format!(
732                "AXIS2_PLACEMENT_2D('',#{center_id},#{direction})"
733            ));
734            Ok(writer.add(format!("CIRCLE('',#{placement},{})", real(*radius)?)))
735        }
736        Pcurve2d::Spline(spline) => {
737            let points = spline
738                .control_points
739                .iter()
740                .map(|control| {
741                    let point = control.point()?;
742                    write_point_2d(writer, [point.x, point.y])
743                })
744                .collect::<Result<Vec<_>, String>>()?;
745            write_bspline_curve(writer, spline, &points)
746        }
747    }
748}
749
750/// `PCURVE('', surface, DEFINITIONAL_REPRESENTATION('', (2d curve), ctx))` —
751/// the association of one 2D curve with the surface it parameterizes.
752fn write_pcurve_entity(
753    writer: &mut StepWriter,
754    surface_id: usize,
755    context_2d: usize,
756    curve: &Pcurve2d,
757) -> Result<usize, String> {
758    let geometry = write_pcurve_geometry(writer, curve)?;
759    let representation = writer.add(format!(
760        "DEFINITIONAL_REPRESENTATION('',(#{geometry}),#{context_2d})"
761    ));
762    Ok(writer.add(format!("PCURVE('',#{surface_id},#{representation})")))
763}
764
765fn write_surface(writer: &mut StepWriter, surface: &NurbsSurface) -> Result<usize, String> {
766    let rows = surface
767        .control_points
768        .iter()
769        .map(|row| {
770            row.iter()
771                .map(|control| write_point(writer, control.point()?))
772                .collect::<Result<Vec<_>, _>>()
773                .map(|ids| id_list(&ids))
774        })
775        .collect::<Result<Vec<_>, _>>()?;
776    let grid = format!("({})", rows.join(","));
777    let (u_values, u_multiplicities) = knot_runs(&surface.knots_u);
778    let (v_values, v_multiplicities) = knot_runs(&surface.knots_v);
779    let multiplicities = |values: &[usize]| {
780        format!(
781            "({})",
782            values
783                .iter()
784                .map(usize::to_string)
785                .collect::<Vec<_>>()
786                .join(",")
787        )
788    };
789    let knots = |values: &[f64]| -> Result<String, String> {
790        Ok(format!(
791            "({})",
792            values
793                .iter()
794                .map(|value| real(*value))
795                .collect::<Result<Vec<_>, _>>()?
796                .join(",")
797        ))
798    };
799    let u_mults = multiplicities(&u_multiplicities);
800    let v_mults = multiplicities(&v_multiplicities);
801    let u_knots = knots(&u_values)?;
802    let v_knots = knots(&v_values)?;
803    let rational = surface
804        .control_points
805        .iter()
806        .flatten()
807        .any(|control| (control.w - 1.0).abs() > 1e-12);
808    if !rational {
809        return Ok(writer.add(format!(
810            "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.,\
811             {u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)",
812            surface.degree_u, surface.degree_v,
813        )));
814    }
815    let weights = format!(
816        "({})",
817        surface
818            .control_points
819            .iter()
820            .map(|row| {
821                row.iter()
822                    .map(|control| real(control.w))
823                    .collect::<Result<Vec<_>, _>>()
824                    .map(|values| format!("({})", values.join(",")))
825            })
826            .collect::<Result<Vec<_>, _>>()?
827            .join(",")
828    );
829    Ok(writer.add(format!(
830        "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.)\
831         B_SPLINE_SURFACE_WITH_KNOTS({u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)\
832         GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE({weights})\
833         REPRESENTATION_ITEM('')SURFACE())",
834        surface.degree_u, surface.degree_v,
835    )))
836}
837
838fn write_length_unit(writer: &mut StepWriter, unit: &str) -> Result<usize, String> {
839    let normalized = unit.to_lowercase();
840    if normalized == "meter" || normalized == "metre" {
841        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))"));
842    }
843    if normalized == "centimeter" || normalized == "centimetre" {
844        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"));
845    }
846    if matches!(normalized.as_str(), "micron" | "micrometer" | "micrometre") {
847        return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MICRO.,.METRE.))"));
848    }
849    if normalized == "inch" || normalized == "foot" {
850        let metre = writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))");
851        let (factor, name) = if normalized == "inch" {
852            (0.0254, "INCH")
853        } else {
854            (0.3048, "FOOT")
855        };
856        let measure = writer.add(format!(
857            "LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{metre})",
858            real(factor)?
859        ));
860        return Ok(writer.add(format!(
861            "(CONVERSION_BASED_UNIT('{name}',#{measure})LENGTH_UNIT()NAMED_UNIT(*))"
862        )));
863    }
864    Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"))
865}
866
867/// The outward shell (an index into `shells`, one of `outer`) that owns the
868/// void `void`: the smallest by volume of those its shell lies inside. The
869/// shells of a valid solid do not meet, so one point of the void (the middle
870/// of its first proper edge) is inside or outside each of them throughout.
871fn void_owner(
872    solid: &BrepSolid,
873    void: usize,
874    outer: &[usize],
875    shells: &[(usize, bool, f64)],
876) -> Result<usize, String> {
877    let probe = solid.shells[void]
878        .faces
879        .iter()
880        .flat_map(|face| &face.loops)
881        .flat_map(|lp| &lp.coedges)
882        .find_map(|coedge| {
883            let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
884            (!edge.degenerate).then(|| edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).ok()).flatten()
885        })
886        .ok_or("export_step: a void shell with no edge to place it by")?;
887    let mut best: Option<usize> = None;
888    for &candidate in outer {
889        let alone = BrepSolid {
890            shells: vec![solid.shells[candidate].clone()],
891            ..solid.clone()
892        };
893        let class = crate::classify_point(probe, &alone, 1e-7)?.class;
894        if class == crate::PointClass::In && best.is_none_or(|b| shells[candidate].2 < shells[b].2) {
895            best = Some(candidate);
896        }
897    }
898    best.ok_or_else(|| "export_step: a void shell lies inside no outward shell".into())
899}
900
901fn vertex_for(solid: &BrepSolid, id: u64) -> Result<&VertexRecord, String> {
902    solid
903        .vertices
904        .iter()
905        .find(|vertex| vertex.id == id)
906        .ok_or_else(|| format!("export_step: missing vertex {id}"))
907}
908
909fn edge_for(solid: &BrepSolid, id: u64) -> Result<&EdgeRecord, String> {
910    solid
911        .edges
912        .iter()
913        .find(|edge| edge.id == id)
914        .ok_or_else(|| format!("export_step: missing edge {id}"))
915}
916
917fn surface_key(face: &FaceRecord) -> usize {
918    face as *const FaceRecord as usize
919}
920
921/// One use of an edge by a face's loop.  Curve-on-surface geometry is written
922/// per USE — a pcurve names the surface it lives on — so the writer needs the
923/// full adjacency of an edge before it can emit that edge.
924struct CoedgeUse<'a> {
925    surface_key: usize,
926    face: &'a FaceRecord,
927    coedge: &'a CoedgeRecord,
928}
929
930/// The AP242 document plus what the writer measured while producing it.
931///
932/// The pcurve counters are the honest half of the verify-or-omit contract in
933/// `step/pcurve.rs`: a pcurve is written only when the emitted 2D geometry was
934/// proved to reproduce the emitted 3D curve, and every one that could not be
935/// proved is COUNTED here rather than guessed into the file.  A reader
936/// reprojects an omitted pcurve exactly as it must reproject every pcurve in
937/// the files this exporter wrote before curve-on-surface geometry existed.
938#[derive(Clone, Debug, Default)]
939pub struct StepExportReport {
940    /// The Part 21 text.
941    pub text: String,
942    /// `PCURVE` entities written — at most one per coedge use of a
943    /// non-degenerate edge.
944    pub pcurves_written: usize,
945    /// Coedge uses left without a pcurve because no candidate 2D geometry
946    /// verified inside the export band.
947    pub pcurves_omitted: usize,
948    /// Edges written as `SURFACE_CURVE` (their two uses sit on two surfaces).
949    pub surface_curves: usize,
950    /// Edges written as `SEAM_CURVE` (both uses on ONE surface — a periodic
951    /// seam, the case an importer otherwise has to re-detect geometrically).
952    pub seam_curves: usize,
953    /// Edges that kept a bare 3D curve for `edge_geometry`, because no pcurve
954    /// survived (or a seam lost one of the pair it is required to carry).
955    pub bare_curves: usize,
956    /// Collapsed face boundaries written as `VERTEX_LOOP` — cone apexes and
957    /// sphere poles, which this writer used to drop entirely.
958    pub vertex_loops: usize,
959    /// Largest verified ‖S(c₂d(s)) − c₃d(s)‖ among the pcurves actually
960    /// written, in model units.
961    pub max_pcurve_deviation: f64,
962    /// Largest deviation among the BEST candidate for each OMITTED pcurve —
963    /// how far the closest miss was, so an omission can be diagnosed as "a
964    /// candidate applied and missed the band by this much" rather than only
965    /// counted. Zero when nothing was omitted.
966    ///
967    /// It is infinite when ANY omission had no candidate proposed at all, which
968    /// then hides the finite misses behind it — the two omission classes share
969    /// one counter. Splitting them is a follow-up; the max is the useful half,
970    /// because it is the finite value that says whether widening the band would
971    /// have helped.
972    pub worst_omitted_deviation: f64,
973    /// DISTINCT PMI reference names (`{body}`, `{body}:face`, `{body}@x,y,z`)
974    /// that named no entity in the written file, so every annotation on them
975    /// was skipped. Zero for a file whose PMI all resolved. The structured
976    /// (assembly) lane is what can move a reference: a component's geometry is
977    /// written into the PART's product, and a stale reference to a body that no
978    /// longer exists is counted here rather than dropped in silence.
979    pub pmi_unresolved_references: usize,
980    /// PRODUCTs written. `1` for the flat lane; the structured lane writes one
981    /// per distinct part plus one for the root document.
982    pub products: usize,
983    /// `NEXT_ASSEMBLY_USAGE_OCCURRENCE` edges written — the placed component
984    /// instances. Zero for the flat lane.
985    pub occurrences: usize,
986    /// `STYLED_ITEM`s written for GEOMETRY colour — one per coloured body and
987    /// per coloured face (`step/styles.rs`). Zero when the caller passed no
988    /// colours, or when none of the names it passed named written geometry;
989    /// the PMI block's own styled item is not counted here.
990    pub styled_items: usize,
991}
992
993/// Serialize exact NURBS BREP topology as an AP242 STEP Part 21 document.
994///
995/// `unit` LABELS the caller's coordinates (`SI_UNIT($,.METRE.)`, `.MILLI.`,
996/// inch and foot conversion factors): the writer does not scale them. A
997/// kernel body is in millimetres, so a metre-unit file wants the body
998/// pre-scaled by 1e-3 (`transform_brep` with a uniform scale) first; a
999/// millimetre body written under `"meter"` re-imports at 1e9 × its volume
1000/// (measured 2026-10-03).
1001pub fn export_step(
1002    solids: &[BrepSolid],
1003    name: &str,
1004    unit: &str,
1005    timestamp: &str,
1006) -> Result<String, String> {
1007    export_step_report(solids, name, unit, timestamp).map(|report| report.text)
1008}
1009
1010/// [`export_step`] plus the pcurve-coverage measurements behind the file.
1011/// Every body is written under the part name; no PMI.
1012pub fn export_step_report(
1013    solids: &[BrepSolid],
1014    name: &str,
1015    unit: &str,
1016    timestamp: &str,
1017) -> Result<StepExportReport, String> {
1018    let named: Vec<(String, &BrepSolid)> = solids
1019        .iter()
1020        .map(|solid| (name.to_string(), solid))
1021        .collect();
1022    export_step_report_named(&named, name, unit, timestamp, None, None)
1023}
1024
1025/// The full writer: each body carries its SCENE NAME (`MANIFOLD_SOLID_BREP`
1026/// name — and the key the PMI references resolve through), and an optional
1027/// PMI block is written as AP242 semantic representation + polyline
1028/// presentation + saved views ([`pmi`]).
1029/// Where an exported geometry entity lives: the product whose shape it helps
1030/// define, and the representation that carries it. PMI attaches a shape aspect
1031/// to the OWNING product, which in a structured (assembly) export is the part's
1032/// own product, not the root document's.
1033#[derive(Clone, Copy)]
1034pub(crate) struct StepItemOwner {
1035    pub product_shape: usize,
1036    pub representation: usize,
1037}
1038
1039/// One product's geometry, written but not yet bound to a product definition.
1040/// The name lists are flat (not maps) because the same part can be reachable
1041/// under several occurrence paths, and each path registers its own alias.
1042#[derive(Default)]
1043pub(crate) struct ProductGeometry {
1044    /// Body name -> its STEP solid entity, in emission order. Inward shells
1045    /// belong to one `BREP_WITH_VOIDS`; independent outward shells each emit a
1046    /// `MANIFOLD_SOLID_BREP`. A coloured body is styled on this entity
1047    /// (`step/styles.rs`), and the representation's item list is the ids alone.
1048    pub solids: Vec<(String, usize)>,
1049    /// Face name -> its `ADVANCED_FACE`.
1050    pub faces: Vec<(String, usize)>,
1051    /// Edge name -> its `EDGE_CURVE`.
1052    pub edges: Vec<(String, usize)>,
1053    /// Body name -> that body's `VERTEX_POINT`s (LOCAL point, entity id).
1054    pub vertices: Vec<(String, Vec<(Vec3, usize)>)>,
1055}
1056
1057/// The PMI reference maps, folded from every product's [`ProductGeometry`] once
1058/// its owner is known. A structured export registers each product's entities
1059/// under EVERY occurrence path that reaches it (`ACOMP3:`, `ACOMP5:ACOMP1:`),
1060/// which is exactly how the document names a component's geometry.
1061#[derive(Default)]
1062pub(crate) struct StepNameMaps {
1063    pub faces: HashMap<String, (usize, StepItemOwner)>,
1064    pub edges: HashMap<String, (usize, StepItemOwner)>,
1065    /// Body name -> its owner and its `VERTEX_POINT`s in ROOT (document) space,
1066    /// because that is the frame a `{body}@x,y,z` PMI reference is written in.
1067    pub vertices: HashMap<String, (StepItemOwner, Vec<(Vec3, usize)>)>,
1068}
1069
1070impl StepNameMaps {
1071    /// Register one product's entities under an occurrence path: `prefix` is the
1072    /// chained component namespace (`""` at the root), `world` maps the
1073    /// product's local frame into root space.
1074    pub(crate) fn register(
1075        &mut self,
1076        geometry: &ProductGeometry,
1077        owner: StepItemOwner,
1078        prefix: &str,
1079        world: &Mat4,
1080    ) {
1081        for (name, id) in &geometry.faces {
1082            self.faces
1083                .entry(format!("{prefix}{name}"))
1084                .or_insert((*id, owner));
1085        }
1086        for (name, id) in &geometry.edges {
1087            self.edges
1088                .entry(format!("{prefix}{name}"))
1089                .or_insert((*id, owner));
1090        }
1091        for (name, points) in &geometry.vertices {
1092            let placed = points
1093                .iter()
1094                .map(|(point, id)| (transform_point(world, *point), *id))
1095                .collect();
1096            self.vertices
1097                .entry(format!("{prefix}{name}"))
1098                .or_insert((owner, placed));
1099        }
1100    }
1101}
1102
1103/// The file-wide entities every product's geometry is expressed against. One
1104/// set per FILE, shared by every product a structured export writes.
1105pub(crate) struct StepFileContexts {
1106    pub product_context: usize,
1107    pub definition_context: usize,
1108    pub geometry_context: usize,
1109    pub parametric_context: usize,
1110    pub length_unit: usize,
1111    pub angle_unit: usize,
1112    /// The IDENTITY `AXIS2_PLACEMENT_3D` — the first item of every shape
1113    /// representation, and `item_1` of every assembly placement's
1114    /// `ITEM_DEFINED_TRANSFORMATION` (the child frame's own origin).
1115    pub axis: usize,
1116}
1117
1118/// Write the header entities every AP242 body in this file shares.
1119pub(crate) fn write_file_contexts(
1120    writer: &mut StepWriter,
1121    unit: &str,
1122) -> Result<StepFileContexts, String> {
1123    let application = writer.add("APPLICATION_CONTEXT('managed model based 3d engineering')");
1124    writer.add(format!(
1125        "APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{application})"
1126    ));
1127    let product_context = writer.add(format!("PRODUCT_CONTEXT('',#{application},'mechanical')"));
1128    let definition_context = writer.add(format!(
1129        "PRODUCT_DEFINITION_CONTEXT('part definition',#{application},'design')"
1130    ));
1131    let length_unit = write_length_unit(writer, unit)?;
1132    let angle_unit = writer.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
1133    let solid_angle_unit = writer.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
1134    let uncertainty = writer.add(format!(
1135        "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#{length_unit},'distance_accuracy_value','')"
1136    ));
1137    let geometry_context = writer.add(format!(
1138        "(GEOMETRIC_REPRESENTATION_CONTEXT(3)\
1139         GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{uncertainty}))\
1140         GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length_unit},#{angle_unit},#{solid_angle_unit}))\
1141         REPRESENTATION_CONTEXT('',''))"
1142    ));
1143    // ONE parametric context for every DEFINITIONAL_REPRESENTATION in the file.
1144    // It carries no unit assignment, so the importer's file-scale search
1145    // (`derive_length_scale_mm`, which keys on GLOBAL_UNIT_ASSIGNED_CONTEXT /
1146    // LENGTH_UNIT) cannot mistake it for the geometric context.
1147    let parametric_context = writer.add(
1148        "(GEOMETRIC_REPRESENTATION_CONTEXT(2)\
1149         PARAMETRIC_REPRESENTATION_CONTEXT()\
1150         REPRESENTATION_CONTEXT('2D SPACE',''))",
1151    );
1152    let origin = write_point(writer, Vec3::default())?;
1153    let direction_z = writer.add("DIRECTION('',(0.,0.,1.))");
1154    let direction_x = writer.add("DIRECTION('',(1.,0.,0.))");
1155    let axis = writer.add(format!(
1156        "AXIS2_PLACEMENT_3D('',#{origin},#{direction_z},#{direction_x})"
1157    ));
1158    Ok(StepFileContexts {
1159        product_context,
1160        definition_context,
1161        geometry_context,
1162        parametric_context,
1163        length_unit,
1164        angle_unit,
1165        axis,
1166    })
1167}
1168
1169/// The product-definition chain of ONE product: what a `NEXT_ASSEMBLY_USAGE_
1170/// OCCURRENCE` references and what a `SHAPE_DEFINITION_REPRESENTATION` binds to
1171/// its geometry.
1172pub(crate) struct ProductIds {
1173    pub definition: usize,
1174    pub product_shape: usize,
1175}
1176
1177/// PRODUCT -> PRODUCT_DEFINITION -> PRODUCT_DEFINITION_SHAPE for one product.
1178/// `id` is the vendor part number (`PRODUCT.id`); the name is used when empty.
1179/// `category` is the `PRODUCT_RELATED_PRODUCT_CATEGORY` name — `'part'` for a
1180/// leaf, `'assembly'` for a product that places others, which is the
1181/// distinction a receiving system reads to build its own structure tree.
1182pub(crate) fn write_product(
1183    writer: &mut StepWriter,
1184    contexts: &StepFileContexts,
1185    name: &str,
1186    id: &str,
1187    category: &str,
1188) -> ProductIds {
1189    let safe_name = step_string(name);
1190    let safe_id = step_string(if id.is_empty() { name } else { id });
1191    let product_context = contexts.product_context;
1192    let definition_context = contexts.definition_context;
1193    let product = writer.add(format!(
1194        "PRODUCT('{safe_id}','{safe_name}','',(#{product_context}))"
1195    ));
1196    writer.add(format!(
1197        "PRODUCT_RELATED_PRODUCT_CATEGORY('{}','',(#{product}))",
1198        step_string(category)
1199    ));
1200    let formation = writer.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
1201    let definition = writer.add(format!(
1202        "PRODUCT_DEFINITION('design','',#{formation},#{definition_context})"
1203    ));
1204    let product_shape = writer.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{definition})"));
1205    ProductIds {
1206        definition,
1207        product_shape,
1208    }
1209}
1210
1211/// Validate every body the way the export gate requires, then write each one's
1212/// exact topology as a `MANIFOLD_SOLID_BREP` named by its scene name.
1213///
1214/// This is the whole geometry writer, factored out of the single-product lane so
1215/// the structured (assembly) lane can call it once PER PRODUCT into the same
1216/// file. It appends to `writer` and reads only file-wide entities, so products
1217/// share surfaces with nothing and cannot collide.
1218pub(crate) fn write_product_geometry(
1219    writer: &mut StepWriter,
1220    contexts: &StepFileContexts,
1221    bodies: &[(String, &BrepSolid)],
1222    report: &mut StepExportReport,
1223) -> Result<ProductGeometry, String> {
1224    for (_, solid) in bodies {
1225        let policy = KernelTolerances::for_solid(solid, 1e-7);
1226        let issues = solid.validate_with_tolerances(&KernelTolerances {
1227            pcurve_consistency: policy.export_knit,
1228            ..policy
1229        });
1230        if !issues.is_empty() {
1231            return Err(format!("export_step: invalid solid: {issues:?}"));
1232        }
1233    }
1234    let parametric_context = contexts.parametric_context;
1235    let mut written = ProductGeometry::default();
1236    for (solid_name, solid) in bodies {
1237        let solid = *solid;
1238        let solid_name = solid_name.as_str();
1239        let band = KernelTolerances::for_solid(solid, 1e-7).export_knit;
1240        let mut vertex_ids = HashMap::<u64, usize>::default();
1241        let mut edge_ids = HashMap::<u64, usize>::default();
1242        let mut surfaces = HashMap::<usize, (usize, bool, EmittedSurface)>::default();
1243        let mut emitted_shells = Vec::new();
1244        for shell in &solid.shells {
1245            // Pass 1 — SURFACES. A pcurve references the surface entity it
1246            // parameterizes, so every surface id has to exist before the first
1247            // edge is written. (Before curve-on-surface geometry the writer
1248            // could emit surfaces after the loops; it no longer can.)
1249            for face in &shell.faces {
1250                let key = surface_key(face);
1251                if surfaces.contains_key(&key) {
1252                    continue;
1253                }
1254                let entry = match write_analytic_surface(writer, &face.surface)? {
1255                    Some(triple) => triple,
1256                    None => (
1257                        write_surface(writer, &face.surface)?,
1258                        false,
1259                        EmittedSurface::Spline,
1260                    ),
1261                };
1262                surfaces.insert(key, entry);
1263            }
1264
1265            // Pass 2 — ADJACENCY. Which faces use each edge, in first-encounter
1266            // order so the emitted entity numbering stays deterministic.
1267            let mut edge_uses = HashMap::<u64, Vec<CoedgeUse>>::default();
1268            let mut edge_order: Vec<u64> = Vec::new();
1269            for face in &shell.faces {
1270                for loop_record in &face.loops {
1271                    for coedge in &loop_record.coedges {
1272                        let edge = edge_for(solid, coedge.edge_id)?;
1273                        if edge.degenerate {
1274                            continue;
1275                        }
1276                        let uses = edge_uses.entry(edge.id).or_default();
1277                        if uses.is_empty() {
1278                            edge_order.push(edge.id);
1279                        }
1280                        uses.push(CoedgeUse {
1281                            surface_key: surface_key(face),
1282                            face,
1283                            coedge,
1284                        });
1285                    }
1286                }
1287            }
1288
1289            // Pass 3 — EDGES with their curve-on-surface geometry.
1290            for edge_id in &edge_order {
1291                if edge_ids.contains_key(edge_id) {
1292                    continue;
1293                }
1294                let edge = edge_for(solid, *edge_id)?;
1295                let subcurve = edge_subcurve(edge)?;
1296                let (curve, emitted_curve) = match write_analytic_curve(writer, &subcurve)? {
1297                    Some(pair) => pair,
1298                    None => (
1299                        write_curve(writer, &subcurve)?,
1300                        EmittedCurve::Spline { curve: subcurve },
1301                    ),
1302                };
1303                let uses = &edge_uses[edge_id];
1304                // Two uses on ONE surface is a periodic seam: the two halves of
1305                // the edge sit on opposite domain boundaries and the reader is
1306                // told so explicitly instead of having to rediscover it.
1307                let seam = uses.len() == 2 && uses[0].surface_key == uses[1].surface_key;
1308                let mut pcurves: Vec<(usize, Pcurve2d)> = Vec::new();
1309                let mut omitted = 0usize;
1310                if uses.len() == 2 {
1311                    // Slot order for a seam: the FORWARD-oriented coedge first,
1312                    // the reversed one second — the pairing OpenCASCADE writes
1313                    // and reads (BRep_CurveOnClosedSurface's PCurve1/PCurve2).
1314                    let mut ordered: Vec<&CoedgeUse> = uses.iter().collect();
1315                    if seam && !ordered[0].coedge.forward {
1316                        ordered.swap(0, 1);
1317                    }
1318                    for coedge_use in ordered {
1319                        // The stored pcurve runs in LOOP direction; the edge's
1320                        // geometry runs in EDGE direction. Fraction-synchronised
1321                        // reversal is exact, so a reversed coedge's pcurve is
1322                        // simply flipped before it is expressed.
1323                        let oriented = if coedge_use.coedge.forward {
1324                            coedge_use.coedge.pcurve.clone()
1325                        } else {
1326                            coedge_use.coedge.pcurve.reversed()?
1327                        };
1328                        let (surface_id, _, emitted_surface) = &surfaces[&coedge_use.surface_key];
1329                        let outcome = build_pcurve(
1330                            &coedge_use.face.surface,
1331                            emitted_surface,
1332                            &emitted_curve,
1333                            &oriented,
1334                            band,
1335                        )?;
1336                        match outcome.curve {
1337                            Some(curve_2d) => {
1338                                report.max_pcurve_deviation =
1339                                    report.max_pcurve_deviation.max(outcome.deviation);
1340                                pcurves.push((*surface_id, curve_2d));
1341                            }
1342                            None => {
1343                                omitted += 1;
1344                                if outcome.deviation.is_finite() {
1345                                    report.worst_omitted_deviation =
1346                                        report.worst_omitted_deviation.max(outcome.deviation);
1347                                } else {
1348                                    report.worst_omitted_deviation = f64::INFINITY;
1349                                }
1350                            }
1351                        }
1352                    }
1353                }
1354                // A SEAM_CURVE is required to carry BOTH pcurves on the one
1355                // surface, so a seam that lost one falls all the way back to a
1356                // bare 3D curve rather than to a half-described seam.
1357                if seam && pcurves.len() != 2 {
1358                    omitted += pcurves.len();
1359                    pcurves.clear();
1360                }
1361                report.pcurves_omitted += omitted;
1362                report.pcurves_written += pcurves.len();
1363                let geometry = if pcurves.is_empty() {
1364                    report.bare_curves += 1;
1365                    curve
1366                } else {
1367                    let ids = pcurves
1368                        .iter()
1369                        .map(|(surface_id, curve_2d)| {
1370                            write_pcurve_entity(
1371                                writer,
1372                                *surface_id,
1373                                parametric_context,
1374                                curve_2d,
1375                            )
1376                        })
1377                        .collect::<Result<Vec<_>, String>>()?;
1378                    let keyword = if seam {
1379                        report.seam_curves += 1;
1380                        "SEAM_CURVE"
1381                    } else {
1382                        report.surface_curves += 1;
1383                        "SURFACE_CURVE"
1384                    };
1385                    // master_representation is .CURVE_3D.: our 3D curves are
1386                    // the exact authority the whole kernel and the export gate
1387                    // treat them as, and the pcurves above are verified AGAINST
1388                    // them. Promoting an approximation to master would be the
1389                    // one claim this writer must not make.
1390                    writer.add(format!(
1391                        "{keyword}('',#{curve},{},.CURVE_3D.)",
1392                        id_list(&ids)
1393                    ))
1394                };
1395                let start = vertex_step_id(writer, &mut vertex_ids, solid, edge.start_vertex_id)?;
1396                let end = vertex_step_id(writer, &mut vertex_ids, solid, edge.end_vertex_id)?;
1397                let step_id =
1398                    writer.add(format!("EDGE_CURVE('',#{start},#{end},#{geometry},.T.)"));
1399                edge_ids.insert(edge.id, step_id);
1400                if let Some(edge_name) = edge.name.as_deref() {
1401                    written.edges.push((edge_name.to_string(), step_id));
1402                }
1403            }
1404
1405            // Pass 4 — LOOPS and FACES over the ids the passes above fixed.
1406            let mut face_ids = Vec::new();
1407            for face in &shell.faces {
1408                let mut bound_ids = Vec::new();
1409                for (loop_index, loop_record) in face.loops.iter().enumerate() {
1410                    let mut oriented_edges = Vec::new();
1411                    for coedge in &loop_record.coedges {
1412                        let edge = edge_for(solid, coedge.edge_id)?;
1413                        if edge.degenerate {
1414                            continue;
1415                        }
1416                        let edge_id = *edge_ids
1417                            .get(&edge.id)
1418                            .ok_or_else(|| format!("export_step: unwritten edge {}", edge.id))?;
1419                        let orientation = if coedge.forward { ".T." } else { ".F." };
1420                        oriented_edges.push(
1421                            writer.add(format!("ORIENTED_EDGE('',*,*,#{edge_id},{orientation})")),
1422                        );
1423                    }
1424                    let kind = if loop_index == 0 {
1425                        "FACE_OUTER_BOUND"
1426                    } else {
1427                        "FACE_BOUND"
1428                    };
1429                    if oriented_edges.is_empty() {
1430                        // A bound left empty by the degenerate-edge skip is a
1431                        // COLLAPSED boundary — a cone apex, a sphere pole —
1432                        // and AP242 spells that `VERTEX_LOOP`, not nothing.
1433                        // Dropping it (what this writer did before) deletes the
1434                        // apex from the face's parameter domain, so an imported
1435                        // pointed cone lost its apex bound on re-export and
1436                        // every reader had to re-synthesise it from the
1437                        // surface's own degeneracy. A MIXED loop keeps the
1438                        // skip: that is OCCT's own write convention, both our
1439                        // importer and OCC's ShapeFix rebuild those, and the
1440                        // advanced-face conformance class permits vertex loops
1441                        // but not zero-length edge curves.
1442                        let Some(coedge) = loop_record.coedges.first() else {
1443                            continue;
1444                        };
1445                        let collapsed = edge_for(solid, coedge.edge_id)?;
1446                        let vertex = vertex_step_id(
1447                            writer,
1448                            &mut vertex_ids,
1449                            solid,
1450                            collapsed.start_vertex_id,
1451                        )?;
1452                        let vertex_loop = writer.add(format!("VERTEX_LOOP('',#{vertex})"));
1453                        report.vertex_loops += 1;
1454                        bound_ids.push(writer.add(format!("{kind}('',#{vertex_loop},.T.)")));
1455                        continue;
1456                    }
1457                    let edge_loop =
1458                        writer.add(format!("EDGE_LOOP('',{})", id_list(&oriented_edges)));
1459                    bound_ids.push(writer.add(format!("{kind}('',#{edge_loop},.T.)")));
1460                }
1461                let (surface, flipped, _) = surfaces[&surface_key(face)];
1462                // `flipped` analytic entities are written with the reverse of
1463                // the stored NURBS orientation, so invert the flag to keep the
1464                // face normal identical through the round trip.
1465                let sense = if face.same_sense != flipped {
1466                    ".T."
1467                } else {
1468                    ".F."
1469                };
1470                let face_step_id = writer.add(format!(
1471                    "ADVANCED_FACE('',{},#{surface},{sense})",
1472                    id_list(&bound_ids)
1473                ));
1474                if let Some(face_name) = face.name.as_deref() {
1475                    written.faces.push((face_name.to_string(), face_step_id));
1476                }
1477                face_ids.push(face_step_id);
1478            }
1479            let closed_shell = writer.add(format!("CLOSED_SHELL('',{})", id_list(&face_ids)));
1480            let signed_volume = if solid.shells.len() > 1 {
1481                crate::mass_properties::shell_signed_volume(shell)?
1482            } else {
1483                1.0
1484            };
1485            emitted_shells.push((closed_shell, signed_volume < 0.0, signed_volume.abs()));
1486        }
1487        if emitted_shells.iter().any(|&(_, inward, _)| inward) {
1488            let outer: Vec<usize> = (0..emitted_shells.len()).filter(|&i| !emitted_shells[i].1).collect();
1489            if outer.is_empty() {
1490                return Err("export_step: a solid with voids must have an outward shell".into());
1491            }
1492            // Each void belongs to the smallest outward shell around it: one
1493            // body per outward shell, its voids those it owns (several bodies
1494            // nested in each other's hollows are several solids in STEP).
1495            let mut owned: Vec<Vec<usize>> = vec![Vec::new(); emitted_shells.len()];
1496            for void in (0..emitted_shells.len()).filter(|&i| emitted_shells[i].1) {
1497                let owner = if outer.len() == 1 {
1498                    outer[0]
1499                } else {
1500                    void_owner(solid, void, &outer, &emitted_shells)?
1501                };
1502                owned[owner].push(void);
1503            }
1504            for &shell in &outer {
1505                let closed_shell = emitted_shells[shell].0;
1506                let body_id = if owned[shell].is_empty() {
1507                    writer.add(format!("MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)))
1508                } else {
1509                    let voids = owned[shell].iter()
1510                        .map(|&void| writer.add(format!("ORIENTED_CLOSED_SHELL('',*,#{},.T.)", emitted_shells[void].0)))
1511                        .collect::<Vec<_>>();
1512                    writer.add(format!(
1513                        "BREP_WITH_VOIDS('{}',#{closed_shell},{})", step_string(solid_name), id_list(&voids)
1514                    ))
1515                };
1516                written.solids.push((solid_name.to_string(), body_id));
1517            }
1518        } else {
1519            for (closed_shell, _, _) in emitted_shells {
1520                let body_id = writer.add(format!(
1521                    "MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)
1522                ));
1523                written.solids.push((solid_name.to_string(), body_id));
1524            }
1525        }
1526        // The vertices this solid wrote, for `{solid}@x,y,z` PMI references.
1527        let mut points: Vec<(Vec3, usize)> = Vec::with_capacity(vertex_ids.len());
1528        for (vertex_id, step_id) in &vertex_ids {
1529            points.push((vertex_for(solid, *vertex_id)?.point, *step_id));
1530        }
1531        written.vertices.push((solid_name.to_string(), points));
1532    }
1533    Ok(written)
1534}
1535
1536/// Wrap the written entities in the Part 21 envelope and run the emitted-text
1537/// audits — the last step of every export lane.
1538pub(crate) fn finish_step_file(
1539    writer: StepWriter,
1540    name: &str,
1541    timestamp: &str,
1542    report: &mut StepExportReport,
1543) -> Result<(), String> {
1544    let safe_name = step_string(name);
1545    let safe_timestamp = step_string(timestamp);
1546    let output = [
1547        "ISO-10303-21;".to_string(),
1548        "HEADER;".to_string(),
1549        "FILE_DESCRIPTION((''),'2;1');".to_string(),
1550        format!(
1551            "FILE_NAME('{safe_name}.step','{safe_timestamp}',(''),(''),'brep-kernel-rs','brep-kernel-rs','');"
1552        ),
1553        "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));".to_string(),
1554        "ENDSEC;".to_string(),
1555        "DATA;".to_string(),
1556        writer.data(),
1557        "ENDSEC;".to_string(),
1558        "END-ISO-10303-21;".to_string(),
1559        String::new(),
1560    ]
1561    .join("\n");
1562    let manifold_issues = audit_step_manifold(&output);
1563    if !manifold_issues.is_empty() {
1564        return Err(format!(
1565            "export_step: emitted AP242 manifold audit failed: {}",
1566            manifold_issues.join("; ")
1567        ));
1568    }
1569    let pcurve_issues = audit_step_pcurves(&output);
1570    if !pcurve_issues.is_empty() {
1571        return Err(format!(
1572            "export_step: emitted AP242 pcurve audit failed: {}",
1573            pcurve_issues.join("; ")
1574        ));
1575    }
1576    report.text = output;
1577    Ok(())
1578}
1579
1580/// The full single-product writer: each body carries its SCENE NAME
1581/// (`MANIFOLD_SOLID_BREP` name — and the key the PMI references resolve
1582/// through), and an optional PMI block is written as AP242 semantic
1583/// representation + polyline presentation + saved views (`pmi`).
1584///
1585/// This is the FLAT lane: one `PRODUCT`, every body in it, no assembly
1586/// structure. A document with components goes through
1587/// [`assembly::export_step_assembly_report`] instead.
1588pub fn export_step_report_named(
1589    solids: &[(String, &BrepSolid)],
1590    name: &str,
1591    unit: &str,
1592    timestamp: &str,
1593    pmi: Option<&StepPmi<'_>>,
1594    colors: Option<&StepColors>,
1595) -> Result<StepExportReport, String> {
1596    if solids.is_empty() {
1597        return Err("export_step: at least one solid is required".into());
1598    }
1599    let mut report = StepExportReport {
1600        products: 1,
1601        ..StepExportReport::default()
1602    };
1603    let mut writer = StepWriter::default();
1604    let contexts = write_file_contexts(&mut writer, unit)?;
1605    let geometry = write_product_geometry(&mut writer, &contexts, solids, &mut report)?;
1606    let mut items = vec![contexts.axis];
1607    items.extend(geometry.solids.iter().map(|(_, id)| *id));
1608    let geometry_context = contexts.geometry_context;
1609    let representation = writer.add(format!(
1610        "ADVANCED_BREP_SHAPE_REPRESENTATION('',{},#{geometry_context})",
1611        id_list(&items)
1612    ));
1613    let product = write_product(&mut writer, &contexts, name, "", "part");
1614    let product_shape = product.product_shape;
1615    writer.add(format!(
1616        "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
1617    ));
1618    // Geometry colour, before the PMI block so a file's presentation styles read
1619    // in geometry order. The flat lane's bodies carry their document names with
1620    // no component namespace, so the ONE prefix to resolve through is the empty
1621    // one.
1622    if let Some(colors) = colors.filter(|colors| !colors.is_empty()) {
1623        let items = styles::styled_items(&geometry, colors, &[String::new()]);
1624        report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
1625    }
1626    if let Some(pmi) = pmi {
1627        let mut names = StepNameMaps::default();
1628        names.register(
1629            &geometry,
1630            StepItemOwner {
1631                product_shape,
1632                representation,
1633            },
1634            "",
1635            &MAT4_IDENTITY,
1636        );
1637        let context = pmi::StepContext {
1638            product_shape,
1639            representation,
1640            geometry_context,
1641            length_unit: contexts.length_unit,
1642            angle_unit: contexts.angle_unit,
1643            faces: &names.faces,
1644            edges: &names.edges,
1645            vertices: &names.vertices,
1646        };
1647        report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
1648    }
1649    finish_step_file(writer, name, timestamp, &mut report)?;
1650    Ok(report)
1651}
1652
1653/// VERTEX_POINT for a kernel vertex, written once per solid.
1654fn vertex_step_id(
1655    writer: &mut StepWriter,
1656    vertex_ids: &mut HashMap<u64, usize>,
1657    solid: &BrepSolid,
1658    id: u64,
1659) -> Result<usize, String> {
1660    if let Some(step_id) = vertex_ids.get(&id) {
1661        return Ok(*step_id);
1662    }
1663    let point = write_point(writer, vertex_for(solid, id)?.point)?;
1664    let step_id = writer.add(format!("VERTEX_POINT('',#{point})"));
1665    vertex_ids.insert(id, step_id);
1666    Ok(step_id)
1667}
1668
1669/// Entity id -> body, for the serialized-text audits.  One entity per line is
1670/// this writer's own invariant, so the "parse" is a split.
1671fn step_entity_bodies(step: &str) -> HashMap<u64, &str> {
1672    step.lines()
1673        .filter_map(|line| {
1674            let rest = line.strip_prefix('#')?;
1675            let (digits, body) = rest.split_once('=')?;
1676            Some((
1677                digits.parse::<u64>().ok()?,
1678                body.trim_end().trim_end_matches(';'),
1679            ))
1680        })
1681        .collect()
1682}
1683
1684/// Every `#N` reference in an entity body, in order.  For the entities audited
1685/// below that order IS the attribute order (`SURFACE_CURVE` puts its 3D curve
1686/// first and its pcurves after; `PCURVE` puts its surface first).
1687fn step_entity_refs(body: &str) -> Vec<u64> {
1688    let mut refs = Vec::new();
1689    let bytes = body.as_bytes();
1690    let mut index = 0;
1691    while index < bytes.len() {
1692        if bytes[index] == b'#' {
1693            let start = index + 1;
1694            let mut end = start;
1695            while end < bytes.len() && bytes[end].is_ascii_digit() {
1696                end += 1;
1697            }
1698            if end > start {
1699                if let Ok(id) = body[start..end].parse::<u64>() {
1700                    refs.push(id);
1701                }
1702            }
1703            index = end;
1704        } else {
1705            index += 1;
1706        }
1707    }
1708    refs
1709}
1710
1711/// Audit the curve-on-surface half of the emitted graph, on the serialized
1712/// text, for the same reason `audit_step_manifold` exists: valid in-memory
1713/// intent is not proof of a correctly written file.
1714///
1715/// An `EDGE_CURVE` whose geometry is a bare 3D curve is NOT an issue — that is
1716/// the counted, deliberate outcome of the verify-or-omit gate. What is an
1717/// issue is a malformed bundle: a `SURFACE_CURVE` with no or more than two
1718/// associated geometries, a `SEAM_CURVE` that does not carry exactly two, a
1719/// `SEAM_CURVE` whose two pcurves name DIFFERENT surfaces (it is by definition
1720/// one surface's seam), a `SURFACE_CURVE` whose two pcurves name the SAME
1721/// surface (that is a seam, and must say so), or a `PCURVE` that does not
1722/// point at both a surface and a `DEFINITIONAL_REPRESENTATION`.
1723pub fn audit_step_pcurves(step: &str) -> Vec<String> {
1724    let bodies = step_entity_bodies(step);
1725    let mut issues = Vec::new();
1726    for (id, body) in &bodies {
1727        if !body.starts_with("EDGE_CURVE(") {
1728            continue;
1729        }
1730        let refs = step_entity_refs(body);
1731        let Some(geometry) = refs.get(2) else {
1732            issues.push(format!("EDGE_CURVE #{id} has no edge_geometry"));
1733            continue;
1734        };
1735        let Some(wrapper) = bodies.get(geometry) else {
1736            issues.push(format!("EDGE_CURVE #{id} references missing #{geometry}"));
1737            continue;
1738        };
1739        let seam = wrapper.starts_with("SEAM_CURVE(");
1740        if !seam && !wrapper.starts_with("SURFACE_CURVE(") {
1741            continue;
1742        }
1743        let wrapper_refs = step_entity_refs(wrapper);
1744        let pcurves = &wrapper_refs[wrapper_refs.len().min(1)..];
1745        if pcurves.is_empty() || pcurves.len() > 2 || (seam && pcurves.len() != 2) {
1746            issues.push(format!(
1747                "#{geometry} carries {} associated geometries",
1748                pcurves.len()
1749            ));
1750            continue;
1751        }
1752        let mut surfaces = Vec::new();
1753        for pcurve in pcurves {
1754            let Some(pcurve_body) = bodies.get(pcurve) else {
1755                issues.push(format!("#{geometry} references missing #{pcurve}"));
1756                continue;
1757            };
1758            if !pcurve_body.starts_with("PCURVE(") {
1759                issues.push(format!("#{geometry} associate #{pcurve} is not a PCURVE"));
1760                continue;
1761            }
1762            let pcurve_refs = step_entity_refs(pcurve_body);
1763            let representation = pcurve_refs.get(1).and_then(|id| bodies.get(id));
1764            if !representation.is_some_and(|body| body.starts_with("DEFINITIONAL_REPRESENTATION("))
1765            {
1766                issues.push(format!(
1767                    "PCURVE #{pcurve} has no DEFINITIONAL_REPRESENTATION"
1768                ));
1769            }
1770            if let Some(surface) = pcurve_refs.first() {
1771                surfaces.push(*surface);
1772            }
1773        }
1774        if surfaces.len() == 2 && (surfaces[0] == surfaces[1]) != seam {
1775            issues.push(format!(
1776                "#{geometry} pcurves name {} surface(s) but it is a {}",
1777                if surfaces[0] == surfaces[1] { 1 } else { 2 },
1778                if seam { "SEAM_CURVE" } else { "SURFACE_CURVE" }
1779            ));
1780        }
1781    }
1782    issues.sort();
1783    issues
1784}
1785
1786/// Audit the serialized entity graph rather than assuming that valid
1787/// in-memory topology was necessarily written correctly.  Every EDGE_CURVE
1788/// in a closed shell must have exactly two ORIENTED_EDGE users with opposite
1789/// senses.
1790pub fn audit_step_manifold(step: &str) -> Vec<String> {
1791    let marker = "ORIENTED_EDGE('',*,*,#";
1792    let mut uses = HashMap::<u64, Vec<bool>>::default();
1793    for line in step.lines() {
1794        let Some(offset) = line.find(marker) else {
1795            continue;
1796        };
1797        let rest = &line[offset + marker.len()..];
1798        let digits = rest
1799            .chars()
1800            .take_while(|character| character.is_ascii_digit())
1801            .collect::<String>();
1802        let Ok(edge_id) = digits.parse::<u64>() else {
1803            continue;
1804        };
1805        let suffix = &rest[digits.len()..];
1806        let sense = suffix.starts_with(",.T.");
1807        uses.entry(edge_id).or_default().push(sense);
1808    }
1809    let mut issues = uses
1810        .into_iter()
1811        .filter_map(|(edge, senses)| {
1812            (senses.len() != 2 || senses[0] == senses[1]).then(|| {
1813                format!(
1814                    "EDGE_CURVE #{edge} has {} uses with senses {:?}",
1815                    senses.len(),
1816                    senses
1817                )
1818            })
1819        })
1820        .collect::<Vec<_>>();
1821    issues.sort();
1822    issues
1823}
1824