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