1use crate::analytic_surface::curve_scale;
2use crate::analytic_surface::{circumcenter, AnalyticSurface};
3use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
4use crate::{make_arc, KernelTolerances, NurbsCurve, NurbsSurface, Vec3};
5use rustc_hash::FxHashMap as HashMap;
6
7#[path = "step/pcurve.rs"]
8pub(crate) mod pcurve;
9use pcurve::{build_pcurve, EmittedCurve, EmittedFrame, EmittedSurface, Pcurve2d};
10#[path = "step/pmi.rs"]
11pub(crate) mod pmi;
12pub use pmi::StepPmi;
13#[path = "step/assembly.rs"]
14pub mod assembly;
15pub use assembly::{
16 export_step_assembly, export_step_assembly_report, StepAssemblyExport, StepExportOccurrence,
17 StepExportProduct,
18};
19#[path = "step/export_tree.rs"]
20mod export_tree;
21pub use export_tree::{assembly_export_tree, PART_ATTRIBUTES, PART_NUMBER};
22#[path = "step/styles.rs"]
23pub(crate) mod styles;
24pub use styles::StepColors;
25
26pub use crate::step_matrix::Mat4;
27pub(crate) use crate::step_matrix::{mat4_mul, MAT4_IDENTITY};
28
29pub(crate) fn transform_point(matrix: &Mat4, point: Vec3) -> Vec3 {
30 crate::AffineTransform {
31 elements: *matrix,
32 }
33 .point(point)
34}
35
36pub(crate) fn step_string(value: &str) -> String {
37 value.replace('\'', "''")
38}
39
40pub(crate) fn real(value: f64) -> Result<String, String> {
41 if !value.is_finite() {
42 return Err(format!("export_step: non-finite number {value}"));
43 }
44 if value == 0.0 {
47 return Ok("0.".into());
48 }
49 if value.fract() == 0.0 && value.abs() < 1e15 {
50 return Ok(format!("{value:.0}."));
51 }
52 let mut output = format!("{value:.15}");
53 while output.ends_with('0') {
54 output.pop();
55 }
56 if output.ends_with('.') {
57 output.push('0');
58 }
59 if output == "-0.0" {
60 output = "0.0".into();
61 }
62 Ok(output)
63}
64
65fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
66 let mut values = Vec::new();
67 let mut multiplicities = Vec::new();
68 for &knot in knots {
69 if values
70 .last()
71 .is_some_and(|previous: &f64| (*previous - knot).abs() <= 1e-12)
72 {
73 *multiplicities.last_mut().unwrap() += 1;
74 } else {
75 values.push(knot);
76 multiplicities.push(1);
77 }
78 }
79 (values, multiplicities)
80}
81pub(crate) use crate::edge_subcurve::edge_subcurve;
82
83
84#[derive(Default)]
85pub(crate) struct StepWriter {
86 lines: Vec<String>,
87}
88
89impl StepWriter {
90 pub(crate) fn add(&mut self, body: impl Into<String>) -> usize {
91 let id = self.lines.len() + 1;
92 self.lines.push(format!("#{id}={};", body.into()));
93 id
94 }
95
96 fn data(&self) -> String {
97 self.lines.join("\n")
98 }
99}
100
101pub(crate) fn write_point(writer: &mut StepWriter, point: Vec3) -> Result<usize, String> {
102 Ok(writer.add(format!(
103 "CARTESIAN_POINT('',({},{},{}))",
104 real(point.x)?,
105 real(point.y)?,
106 real(point.z)?
107 )))
108}
109
110pub(crate) fn id_list(ids: &[usize]) -> String {
111 format!(
112 "({})",
113 ids.iter()
114 .map(|id| format!("#{id}"))
115 .collect::<Vec<_>>()
116 .join(",")
117 )
118}
119
120pub(crate) fn write_direction(writer: &mut StepWriter, direction: Vec3) -> Result<usize, String> {
121 Ok(writer.add(format!(
122 "DIRECTION('',({},{},{}))",
123 real(direction.x)?,
124 real(direction.y)?,
125 real(direction.z)?
126 )))
127}
128
129pub(crate) fn write_placement(
130 writer: &mut StepWriter,
131 origin: Vec3,
132 axis: Vec3,
133 ref_direction: Vec3,
134) -> Result<usize, String> {
135 let origin = write_point(writer, origin)?;
136 let axis = write_direction(writer, axis)?;
137 let ref_direction = write_direction(writer, ref_direction)?;
138 Ok(writer.add(format!(
139 "AXIS2_PLACEMENT_3D('',#{origin},#{axis},#{ref_direction})"
140 )))
141}
142
143fn write_analytic_surface(
152 writer: &mut StepWriter,
153 surface: &NurbsSurface,
154) -> Result<Option<(usize, bool, EmittedSurface)>, String> {
155 let Some(analytic) = surface.analytic() else {
156 return Ok(None);
157 };
158 match analytic {
159 AnalyticSurface::Plane {
160 origin,
161 u_dir,
162 v_dir,
163 ..
164 } => {
165 let (Ok(normal), Ok(x_axis)) = (u_dir.cross(*v_dir).normalized(), u_dir.normalized())
168 else {
169 return Ok(None);
170 };
171 let placement = write_placement(writer, *origin, normal, x_axis)?;
172 Ok(Some((
177 writer.add(format!("PLANE('',#{placement})")),
178 false,
179 EmittedSurface::Plane {
180 origin: *origin,
181 x_axis,
182 y_axis: normal.cross(x_axis),
183 },
184 )))
185 }
186 AnalyticSurface::RuledRevolution {
187 frame,
188 rho0,
189 rho1,
190 height,
191 } => {
192 let flipped = *height < 0.0;
196 let radius_scale = 1.0 + rho0.abs().max(rho1.abs());
197 if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
198 if *rho0 <= 0.0 {
199 return Ok(None);
200 }
201 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
202 return Ok(Some((
203 writer.add(format!(
204 "CYLINDRICAL_SURFACE('',#{placement},{})",
205 real(*rho0)?
206 )),
207 flipped,
208 EmittedSurface::Cylinder {
209 frame: EmittedFrame {
210 origin: frame.origin,
211 x_axis: frame.x_axis,
212 y_axis: frame.y_axis,
213 axis: frame.axis,
214 azimuth_sign: 1.0,
215 },
216 radius: *rho0,
217 },
218 )));
219 }
220 let slope = (rho1 - rho0) / height;
226 let apex_margin = 2.0 * (1e-4 * height.abs().max(1.0) + 1e-9) * slope.abs();
227 if rho0.min(*rho1) <= apex_margin {
228 return Ok(None);
229 }
230 let axis = if slope >= 0.0 {
234 frame.axis
235 } else {
236 frame.axis.scale(-1.0)
237 };
238 let placement = write_placement(writer, frame.origin, axis, frame.x_axis)?;
239 Ok(Some((
240 writer.add(format!(
241 "CONICAL_SURFACE('',#{placement},{},{})",
242 real(*rho0)?,
243 real(slope.abs().atan())?
244 )),
245 flipped,
246 EmittedSurface::Cone {
247 frame: EmittedFrame {
248 origin: frame.origin,
249 x_axis: frame.x_axis,
250 y_axis: axis.cross(frame.x_axis),
254 axis,
255 azimuth_sign: if slope >= 0.0 { 1.0 } else { -1.0 },
256 },
257 radius: *rho0,
258 semi_angle: slope.abs().atan(),
259 },
260 )))
261 }
262 AnalyticSurface::Sphere { frame, radius } => {
263 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
266 Ok(Some((
267 writer.add(format!(
268 "SPHERICAL_SURFACE('',#{placement},{})",
269 real(*radius)?
270 )),
271 false,
272 EmittedSurface::Sphere {
273 frame: EmittedFrame {
274 origin: frame.origin,
275 x_axis: frame.x_axis,
276 y_axis: frame.y_axis,
277 axis: frame.axis,
278 azimuth_sign: 1.0,
279 },
280 radius: *radius,
281 },
282 )))
283 }
284 AnalyticSurface::Torus {
285 frame,
286 major_radius,
287 minor_radius,
288 } => {
289 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
290 Ok(Some((
291 writer.add(format!(
292 "TOROIDAL_SURFACE('',#{placement},{},{})",
293 real(*major_radius)?,
294 real(*minor_radius)?
295 )),
296 false,
297 EmittedSurface::Torus {
298 frame: EmittedFrame {
299 origin: frame.origin,
300 x_axis: frame.x_axis,
301 y_axis: frame.y_axis,
302 axis: frame.axis,
303 azimuth_sign: 1.0,
304 },
305 major_radius: *major_radius,
306 minor_radius: *minor_radius,
307 },
308 )))
309 }
310 AnalyticSurface::Revolution { frame, generatrix, .. } => {
313 let Some((center, radius, reversed)) = polar_meridian_sphere(frame, generatrix) else {
314 return Ok(None);
315 };
316 let placement = write_placement(writer, center, frame.axis, frame.x_axis)?;
317 Ok(Some((
318 writer.add(format!(
319 "SPHERICAL_SURFACE('',#{placement},{})",
320 real(radius)?
321 )),
322 reversed,
323 EmittedSurface::Sphere {
324 frame: EmittedFrame {
325 origin: center,
326 x_axis: frame.x_axis,
327 y_axis: frame.y_axis,
328 axis: frame.axis,
329 azimuth_sign: 1.0,
330 },
331 radius,
332 },
333 )))
334 }
335 }
336}
337
338fn sphere_of_revolution_on() -> bool {
343 crate::switch!("BREP_STEP_SPHERE_OF_REVOLUTION", true)
344}
345
346fn polar_meridian_sphere(
360 frame: &crate::analytic_surface::RevolutionFrame,
361 generatrix: &NurbsCurve,
362) -> Option<(Vec3, f64, bool)> {
363 if !sphere_of_revolution_on() {
364 return None;
365 }
366 let controls = &generatrix.control_points;
367 let count = controls.len();
368 if generatrix.degree != 2 || count < 3 || count % 2 == 0 || generatrix.knots.len() != count + 3 {
369 return None;
370 }
371 let knots = &generatrix.knots;
373 let span_knots = (count - 1) / 2;
374 for span in 1..span_knots {
375 if (knots[1 + 2 * span] - knots[2 + 2 * span]).abs() > 1e-12 {
376 return None;
377 }
378 }
379 let scale = curve_scale(generatrix);
380 let tolerance = 1e-9 * scale.max(1.0);
381 let mut points = Vec::with_capacity(count);
382 for control in controls {
383 if control.w <= 0.0 {
384 return None;
385 }
386 let point = control.point().ok()?;
387 let d = point.sub(frame.origin);
389 if d.dot(frame.y_axis).abs() > tolerance || d.dot(frame.x_axis) < -tolerance {
390 return None;
391 }
392 points.push(point);
393 }
394 let (mut num, mut den) = (0.0, 0.0);
398 for span in 0..span_knots {
399 let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
400 for (direction, through) in [
401 (p2.sub(p0), p0.add(p2).scale(0.5)),
402 (p1.sub(p0), p0),
403 (p1.sub(p2), p2),
404 ] {
405 let a = direction.dot(frame.axis);
407 let b = direction.dot(through.sub(frame.origin));
408 num += a * b;
409 den += a * a;
410 }
411 }
412 if den <= tolerance * tolerance {
413 return None;
414 }
415 let center = frame.origin.add(frame.axis.scale(num / den));
416 let radius = points[0].sub(center).length();
417 if radius <= tolerance {
418 return None;
419 }
420 let mut turn = 0.0;
421 for span in 0..span_knots {
422 let (p0, p1, p2) = (points[2 * span], points[2 * span + 1], points[2 * span + 2]);
423 let (r0, r1, r2) = (p0.sub(center), p1.sub(center), p2.sub(center));
424 if (r0.length() - radius).abs() > tolerance
425 || (r2.length() - radius).abs() > tolerance
426 || p1.sub(p0).dot(r0).abs() > tolerance * radius
427 || p1.sub(p2).dot(r2).abs() > tolerance * radius
428 {
429 return None;
430 }
431 let cos_half = radius / r1.length();
433 let (w0, w1, w2) = (controls[2 * span].w, controls[2 * span + 1].w, controls[2 * span + 2].w);
434 if !(cos_half > 1e-6) || (w1 * w1 / (w0 * w2) - cos_half * cos_half).abs() > 1e-9 {
435 return None;
436 }
437 let cross = r0.dot(frame.x_axis) * r2.dot(frame.axis) - r0.dot(frame.axis) * r2.dot(frame.x_axis);
439 if cross.abs() <= tolerance * radius || (turn != 0.0 && cross.signum() != turn) {
440 return None;
441 }
442 turn = cross.signum();
443 }
444 Some((center, radius, turn < 0.0))
445}
446
447struct CircularArc {
452 center: Vec3,
453 axis: Vec3,
454 x_axis: Vec3,
455 y_axis: Vec3,
458 radius: f64,
459 sweep: f64,
461 spans: usize,
465}
466
467
468
469fn curves_match(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
473 if a.degree != b.degree
474 || a.knots.len() != b.knots.len()
475 || a.control_points.len() != b.control_points.len()
476 {
477 return false;
478 }
479 if a.knots
480 .iter()
481 .zip(&b.knots)
482 .any(|(x, y)| (x - y).abs() > 1e-12)
483 {
484 return false;
485 }
486 let tolerance = 1e-9 * scale.max(1.0);
487 a.control_points
488 .iter()
489 .zip(&b.control_points)
490 .all(|(p, q)| {
491 (p.x - q.x).abs() <= tolerance
492 && (p.y - q.y).abs() <= tolerance
493 && (p.z - q.z).abs() <= tolerance
494 && (p.w - q.w).abs() <= 1e-9
495 })
496}
497
498fn recognize_circular_arc(curve: &NurbsCurve) -> Option<CircularArc> {
503 if curve.degree != 2
504 || curve.control_points.len() < 3
505 || curve.control_points.len() % 2 == 0
506 || (curve.control_points.len() - 1) / 2 > 4
507 {
508 return None;
509 }
510 let [t0, t1] = curve.domain().ok()?;
511 let at = |fraction: f64| curve.evaluate(t0 + (t1 - t0) * fraction);
512 let p0 = at(0.0).ok()?;
515 let pa = at(0.35).ok()?;
516 let pb = at(0.7).ok()?;
517 let center = circumcenter(p0, pa, pb)?;
518 let radial = p0.sub(center);
519 let radius = radial.length();
520 let scale = curve_scale(curve);
521 if radius <= 1e-9 * scale.max(1.0) {
522 return None;
523 }
524 let x_axis = radial.scale(1.0 / radius);
525 let axis = radial.cross(pa.sub(center)).normalized().ok()?;
526 let y_axis = axis.cross(x_axis);
527 let p_end = at(1.0).ok()?;
528 let sweep = if p_end.sub(p0).length() <= 1e-9 * (1.0 + radius) {
529 std::f64::consts::TAU
530 } else {
531 let closing = p_end.sub(center);
532 let mut angle = closing.dot(y_axis).atan2(closing.dot(x_axis));
533 if angle < 0.0 {
534 angle += std::f64::consts::TAU;
535 }
536 angle
537 };
538 let rebuilt = make_arc(center, x_axis, y_axis, radius, 0.0, sweep).ok()?;
539 curves_match(curve, &rebuilt, scale).then_some(CircularArc {
540 center,
541 axis,
542 x_axis,
543 y_axis,
544 radius,
545 sweep,
546 spans: (curve.control_points.len() - 1) / 2,
547 })
548}
549
550fn write_analytic_curve(
557 writer: &mut StepWriter,
558 curve: &NurbsCurve,
559) -> Result<Option<(usize, EmittedCurve)>, String> {
560 if curve.degree == 1
561 && curve.control_points.len() == 2
562 && curve
563 .control_points
564 .iter()
565 .all(|control| (control.w - 1.0).abs() <= 1e-12)
566 {
567 let start = curve.control_points[0].point()?;
568 let end = curve.control_points[1].point()?;
569 let Ok(direction) = end.sub(start).normalized() else {
570 return Ok(None);
571 };
572 let point = write_point(writer, start)?;
573 let step_direction = write_direction(writer, direction)?;
574 let vector = writer.add(format!(
575 "VECTOR('',#{step_direction},{})",
576 real(end.sub(start).length())?
577 ));
578 return Ok(Some((
579 writer.add(format!("LINE('',#{point},#{vector})")),
580 EmittedCurve::Line { start, end },
584 )));
585 }
586 if let Some(arc) = recognize_circular_arc(curve) {
587 let placement = write_placement(writer, arc.center, arc.axis, arc.x_axis)?;
591 return Ok(Some((
592 writer.add(format!("CIRCLE('',#{placement},{})", real(arc.radius)?)),
593 EmittedCurve::Circle {
594 center: arc.center,
595 x_axis: arc.x_axis,
596 y_axis: arc.y_axis,
597 radius: arc.radius,
598 sweep: arc.sweep,
599 spans: arc.spans,
600 },
601 )));
602 }
603 Ok(None)
604}
605
606fn write_curve(writer: &mut StepWriter, curve: &NurbsCurve) -> Result<usize, String> {
607 let points = curve
608 .control_points
609 .iter()
610 .map(|control| write_point(writer, control.point()?))
611 .collect::<Result<Vec<_>, _>>()?;
612 write_bspline_curve(writer, curve, &points)
613}
614
615fn write_bspline_curve(
620 writer: &mut StepWriter,
621 curve: &NurbsCurve,
622 points: &[usize],
623) -> Result<usize, String> {
624 let (knot_values, multiplicities) = knot_runs(&curve.knots);
625 let multiplicities = format!(
626 "({})",
627 multiplicities
628 .iter()
629 .map(usize::to_string)
630 .collect::<Vec<_>>()
631 .join(",")
632 );
633 let knots = format!(
634 "({})",
635 knot_values
636 .iter()
637 .map(|value| real(*value))
638 .collect::<Result<Vec<_>, _>>()?
639 .join(",")
640 );
641 let rational = curve
642 .control_points
643 .iter()
644 .any(|control| (control.w - 1.0).abs() > 1e-12);
645 if !rational {
646 return Ok(writer.add(format!(
647 "B_SPLINE_CURVE_WITH_KNOTS('',{},{},.UNSPECIFIED.,.F.,.F.,{multiplicities},{knots},.UNSPECIFIED.)",
648 curve.degree,
649 id_list(points),
650 )));
651 }
652 let weights = format!(
653 "({})",
654 curve
655 .control_points
656 .iter()
657 .map(|control| real(control.w))
658 .collect::<Result<Vec<_>, _>>()?
659 .join(",")
660 );
661 Ok(writer.add(format!(
662 "(BOUNDED_CURVE()B_SPLINE_CURVE({},{},.UNSPECIFIED.,.F.,.F.)\
663 B_SPLINE_CURVE_WITH_KNOTS({multiplicities},{knots},.UNSPECIFIED.)\
664 CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({weights})\
665 REPRESENTATION_ITEM(''))",
666 curve.degree,
667 id_list(points),
668 )))
669}
670
671fn write_point_2d(writer: &mut StepWriter, point: [f64; 2]) -> Result<usize, String> {
672 Ok(writer.add(format!(
673 "CARTESIAN_POINT('',({},{}))",
674 real(point[0])?,
675 real(point[1])?
676 )))
677}
678
679fn write_direction_2d(writer: &mut StepWriter, direction: [f64; 2]) -> Result<usize, String> {
680 Ok(writer.add(format!(
681 "DIRECTION('',({},{}))",
682 real(direction[0])?,
683 real(direction[1])?
684 )))
685}
686
687fn write_pcurve_geometry(writer: &mut StepWriter, curve: &Pcurve2d) -> Result<usize, String> {
697 match curve {
698 Pcurve2d::Line { point, vector } => {
699 let magnitude = vector[0].hypot(vector[1]);
700 if magnitude <= 0.0 {
701 return Err("export_step: degenerate 2D line pcurve".into());
702 }
703 let point_id = write_point_2d(writer, *point)?;
704 let direction =
705 write_direction_2d(writer, [vector[0] / magnitude, vector[1] / magnitude])?;
706 let vector_id = writer.add(format!(
707 "VECTOR('',#{direction},{})",
708 real(magnitude)?
709 ));
710 Ok(writer.add(format!("LINE('',#{point_id},#{vector_id})")))
711 }
712 Pcurve2d::Circle {
713 center,
714 ref_direction,
715 radius,
716 } => {
717 let center_id = write_point_2d(writer, *center)?;
718 let direction = write_direction_2d(writer, *ref_direction)?;
719 let placement = writer.add(format!(
720 "AXIS2_PLACEMENT_2D('',#{center_id},#{direction})"
721 ));
722 Ok(writer.add(format!("CIRCLE('',#{placement},{})", real(*radius)?)))
723 }
724 Pcurve2d::Spline(spline) => {
725 let points = spline
726 .control_points
727 .iter()
728 .map(|control| {
729 let point = control.point()?;
730 write_point_2d(writer, [point.x, point.y])
731 })
732 .collect::<Result<Vec<_>, String>>()?;
733 write_bspline_curve(writer, spline, &points)
734 }
735 }
736}
737
738fn write_pcurve_entity(
741 writer: &mut StepWriter,
742 surface_id: usize,
743 context_2d: usize,
744 curve: &Pcurve2d,
745) -> Result<usize, String> {
746 let geometry = write_pcurve_geometry(writer, curve)?;
747 let representation = writer.add(format!(
748 "DEFINITIONAL_REPRESENTATION('',(#{geometry}),#{context_2d})"
749 ));
750 Ok(writer.add(format!("PCURVE('',#{surface_id},#{representation})")))
751}
752
753fn write_surface(writer: &mut StepWriter, surface: &NurbsSurface) -> Result<usize, String> {
754 let rows = surface
755 .control_points
756 .iter()
757 .map(|row| {
758 row.iter()
759 .map(|control| write_point(writer, control.point()?))
760 .collect::<Result<Vec<_>, _>>()
761 .map(|ids| id_list(&ids))
762 })
763 .collect::<Result<Vec<_>, _>>()?;
764 let grid = format!("({})", rows.join(","));
765 let (u_values, u_multiplicities) = knot_runs(&surface.knots_u);
766 let (v_values, v_multiplicities) = knot_runs(&surface.knots_v);
767 let multiplicities = |values: &[usize]| {
768 format!(
769 "({})",
770 values
771 .iter()
772 .map(usize::to_string)
773 .collect::<Vec<_>>()
774 .join(",")
775 )
776 };
777 let knots = |values: &[f64]| -> Result<String, String> {
778 Ok(format!(
779 "({})",
780 values
781 .iter()
782 .map(|value| real(*value))
783 .collect::<Result<Vec<_>, _>>()?
784 .join(",")
785 ))
786 };
787 let u_mults = multiplicities(&u_multiplicities);
788 let v_mults = multiplicities(&v_multiplicities);
789 let u_knots = knots(&u_values)?;
790 let v_knots = knots(&v_values)?;
791 let rational = surface
792 .control_points
793 .iter()
794 .flatten()
795 .any(|control| (control.w - 1.0).abs() > 1e-12);
796 if !rational {
797 return Ok(writer.add(format!(
798 "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.,\
799 {u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)",
800 surface.degree_u, surface.degree_v,
801 )));
802 }
803 let weights = format!(
804 "({})",
805 surface
806 .control_points
807 .iter()
808 .map(|row| {
809 row.iter()
810 .map(|control| real(control.w))
811 .collect::<Result<Vec<_>, _>>()
812 .map(|values| format!("({})", values.join(",")))
813 })
814 .collect::<Result<Vec<_>, _>>()?
815 .join(",")
816 );
817 Ok(writer.add(format!(
818 "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.)\
819 B_SPLINE_SURFACE_WITH_KNOTS({u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)\
820 GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE({weights})\
821 REPRESENTATION_ITEM('')SURFACE())",
822 surface.degree_u, surface.degree_v,
823 )))
824}
825
826fn write_length_unit(writer: &mut StepWriter, unit: &str) -> Result<usize, String> {
827 let normalized = unit.to_lowercase();
828 if normalized == "meter" || normalized == "metre" {
829 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))"));
830 }
831 if normalized == "centimeter" || normalized == "centimetre" {
832 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"));
833 }
834 if matches!(normalized.as_str(), "micron" | "micrometer" | "micrometre") {
835 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MICRO.,.METRE.))"));
836 }
837 if normalized == "inch" || normalized == "foot" {
838 let metre = writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))");
839 let (factor, name) = if normalized == "inch" {
840 (0.0254, "INCH")
841 } else {
842 (0.3048, "FOOT")
843 };
844 let measure = writer.add(format!(
845 "LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{metre})",
846 real(factor)?
847 ));
848 return Ok(writer.add(format!(
849 "(CONVERSION_BASED_UNIT('{name}',#{measure})LENGTH_UNIT()NAMED_UNIT(*))"
850 )));
851 }
852 Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"))
853}
854
855fn void_owner(
860 solid: &BrepSolid,
861 void: usize,
862 outer: &[usize],
863 shells: &[(usize, bool, f64)],
864) -> Result<usize, String> {
865 let probe = solid.shells[void]
866 .faces
867 .iter()
868 .flat_map(|face| &face.loops)
869 .flat_map(|lp| &lp.coedges)
870 .find_map(|coedge| {
871 let edge = solid.edges.iter().find(|edge| edge.id == coedge.edge_id)?;
872 (!edge.degenerate).then(|| edge.curve.evaluate(0.5 * (edge.t0 + edge.t1)).ok()).flatten()
873 })
874 .ok_or("export_step: a void shell with no edge to place it by")?;
875 let mut best: Option<usize> = None;
876 for &candidate in outer {
877 let alone = BrepSolid {
878 shells: vec![solid.shells[candidate].clone()],
879 ..solid.clone()
880 };
881 let class = crate::classify_point(probe, &alone, 1e-7)?.class;
882 if class == crate::PointClass::In && best.is_none_or(|b| shells[candidate].2 < shells[b].2) {
883 best = Some(candidate);
884 }
885 }
886 best.ok_or_else(|| "export_step: a void shell lies inside no outward shell".into())
887}
888
889fn vertex_for(solid: &BrepSolid, id: u64) -> Result<&VertexRecord, String> {
890 solid
891 .vertices
892 .iter()
893 .find(|vertex| vertex.id == id)
894 .ok_or_else(|| format!("export_step: missing vertex {id}"))
895}
896
897fn edge_for(solid: &BrepSolid, id: u64) -> Result<&EdgeRecord, String> {
898 solid
899 .edges
900 .iter()
901 .find(|edge| edge.id == id)
902 .ok_or_else(|| format!("export_step: missing edge {id}"))
903}
904
905fn surface_key(face: &FaceRecord) -> usize {
906 face as *const FaceRecord as usize
907}
908
909struct CoedgeUse<'a> {
913 surface_key: usize,
914 face: &'a FaceRecord,
915 coedge: &'a CoedgeRecord,
916}
917
918#[derive(Clone, Debug, Default)]
927pub struct StepExportReport {
928 pub text: String,
930 pub pcurves_written: usize,
933 pub pcurves_omitted: usize,
936 pub surface_curves: usize,
938 pub seam_curves: usize,
941 pub bare_curves: usize,
944 pub vertex_loops: usize,
947 pub max_pcurve_deviation: f64,
950 pub worst_omitted_deviation: f64,
961 pub pmi_unresolved_references: usize,
968 pub products: usize,
971 pub occurrences: usize,
974 pub styled_items: usize,
979}
980
981pub fn export_step(
990 solids: &[BrepSolid],
991 name: &str,
992 unit: &str,
993 timestamp: &str,
994) -> Result<String, String> {
995 export_step_report(solids, name, unit, timestamp).map(|report| report.text)
996}
997
998pub fn export_step_report(
1001 solids: &[BrepSolid],
1002 name: &str,
1003 unit: &str,
1004 timestamp: &str,
1005) -> Result<StepExportReport, String> {
1006 let named: Vec<(String, &BrepSolid)> = solids
1007 .iter()
1008 .map(|solid| (name.to_string(), solid))
1009 .collect();
1010 export_step_report_named(&named, name, unit, timestamp, None, None)
1011}
1012
1013#[derive(Clone, Copy)]
1022pub(crate) struct StepItemOwner {
1023 pub product_shape: usize,
1024 pub representation: usize,
1025}
1026
1027#[derive(Default)]
1031pub(crate) struct ProductGeometry {
1032 pub solids: Vec<(String, usize)>,
1037 pub faces: Vec<(String, usize)>,
1039 pub edges: Vec<(String, usize)>,
1041 pub vertices: Vec<(String, Vec<(Vec3, usize)>)>,
1043}
1044
1045#[derive(Default)]
1050pub(crate) struct StepNameMaps {
1051 pub faces: HashMap<String, (usize, StepItemOwner)>,
1052 pub edges: HashMap<String, (usize, StepItemOwner)>,
1053 pub vertices: HashMap<String, (StepItemOwner, Vec<(Vec3, usize)>)>,
1056}
1057
1058impl StepNameMaps {
1059 pub(crate) fn register(
1063 &mut self,
1064 geometry: &ProductGeometry,
1065 owner: StepItemOwner,
1066 prefix: &str,
1067 world: &Mat4,
1068 ) {
1069 for (name, id) in &geometry.faces {
1070 self.faces
1071 .entry(format!("{prefix}{name}"))
1072 .or_insert((*id, owner));
1073 }
1074 for (name, id) in &geometry.edges {
1075 self.edges
1076 .entry(format!("{prefix}{name}"))
1077 .or_insert((*id, owner));
1078 }
1079 for (name, points) in &geometry.vertices {
1080 let placed = points
1081 .iter()
1082 .map(|(point, id)| (transform_point(world, *point), *id))
1083 .collect();
1084 self.vertices
1085 .entry(format!("{prefix}{name}"))
1086 .or_insert((owner, placed));
1087 }
1088 }
1089}
1090
1091pub(crate) struct StepFileContexts {
1094 pub product_context: usize,
1095 pub definition_context: usize,
1096 pub geometry_context: usize,
1097 pub parametric_context: usize,
1098 pub length_unit: usize,
1099 pub angle_unit: usize,
1100 pub axis: usize,
1104}
1105
1106pub(crate) fn write_file_contexts(
1108 writer: &mut StepWriter,
1109 unit: &str,
1110) -> Result<StepFileContexts, String> {
1111 let application = writer.add("APPLICATION_CONTEXT('managed model based 3d engineering')");
1112 writer.add(format!(
1113 "APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{application})"
1114 ));
1115 let product_context = writer.add(format!("PRODUCT_CONTEXT('',#{application},'mechanical')"));
1116 let definition_context = writer.add(format!(
1117 "PRODUCT_DEFINITION_CONTEXT('part definition',#{application},'design')"
1118 ));
1119 let length_unit = write_length_unit(writer, unit)?;
1120 let angle_unit = writer.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
1121 let solid_angle_unit = writer.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
1122 let uncertainty = writer.add(format!(
1123 "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#{length_unit},'distance_accuracy_value','')"
1124 ));
1125 let geometry_context = writer.add(format!(
1126 "(GEOMETRIC_REPRESENTATION_CONTEXT(3)\
1127 GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{uncertainty}))\
1128 GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length_unit},#{angle_unit},#{solid_angle_unit}))\
1129 REPRESENTATION_CONTEXT('',''))"
1130 ));
1131 let parametric_context = writer.add(
1136 "(GEOMETRIC_REPRESENTATION_CONTEXT(2)\
1137 PARAMETRIC_REPRESENTATION_CONTEXT()\
1138 REPRESENTATION_CONTEXT('2D SPACE',''))",
1139 );
1140 let origin = write_point(writer, Vec3::default())?;
1141 let direction_z = writer.add("DIRECTION('',(0.,0.,1.))");
1142 let direction_x = writer.add("DIRECTION('',(1.,0.,0.))");
1143 let axis = writer.add(format!(
1144 "AXIS2_PLACEMENT_3D('',#{origin},#{direction_z},#{direction_x})"
1145 ));
1146 Ok(StepFileContexts {
1147 product_context,
1148 definition_context,
1149 geometry_context,
1150 parametric_context,
1151 length_unit,
1152 angle_unit,
1153 axis,
1154 })
1155}
1156
1157pub(crate) struct ProductIds {
1161 pub definition: usize,
1162 pub product_shape: usize,
1163}
1164
1165pub(crate) fn write_product(
1171 writer: &mut StepWriter,
1172 contexts: &StepFileContexts,
1173 name: &str,
1174 id: &str,
1175 category: &str,
1176) -> ProductIds {
1177 let safe_name = step_string(name);
1178 let safe_id = step_string(if id.is_empty() { name } else { id });
1179 let product_context = contexts.product_context;
1180 let definition_context = contexts.definition_context;
1181 let product = writer.add(format!(
1182 "PRODUCT('{safe_id}','{safe_name}','',(#{product_context}))"
1183 ));
1184 writer.add(format!(
1185 "PRODUCT_RELATED_PRODUCT_CATEGORY('{}','',(#{product}))",
1186 step_string(category)
1187 ));
1188 let formation = writer.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
1189 let definition = writer.add(format!(
1190 "PRODUCT_DEFINITION('design','',#{formation},#{definition_context})"
1191 ));
1192 let product_shape = writer.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{definition})"));
1193 ProductIds {
1194 definition,
1195 product_shape,
1196 }
1197}
1198
1199pub(crate) fn write_product_geometry(
1207 writer: &mut StepWriter,
1208 contexts: &StepFileContexts,
1209 bodies: &[(String, &BrepSolid)],
1210 report: &mut StepExportReport,
1211) -> Result<ProductGeometry, String> {
1212 for (_, solid) in bodies {
1213 let policy = KernelTolerances::for_solid(solid, 1e-7);
1214 let issues = solid.validate_with_tolerances(&KernelTolerances {
1215 pcurve_consistency: policy.export_knit,
1216 ..policy
1217 });
1218 if !issues.is_empty() {
1219 return Err(format!("export_step: invalid solid: {issues:?}"));
1220 }
1221 }
1222 let parametric_context = contexts.parametric_context;
1223 let mut written = ProductGeometry::default();
1224 for (solid_name, solid) in bodies {
1225 let solid = *solid;
1226 let solid_name = solid_name.as_str();
1227 let band = KernelTolerances::for_solid(solid, 1e-7).export_knit;
1228 let mut vertex_ids = HashMap::<u64, usize>::default();
1229 let mut edge_ids = HashMap::<u64, usize>::default();
1230 let mut surfaces = HashMap::<usize, (usize, bool, EmittedSurface)>::default();
1231 let mut emitted_shells = Vec::new();
1232 for shell in &solid.shells {
1233 for face in &shell.faces {
1238 let key = surface_key(face);
1239 if surfaces.contains_key(&key) {
1240 continue;
1241 }
1242 let entry = match write_analytic_surface(writer, &face.surface)? {
1243 Some(triple) => triple,
1244 None => (
1245 write_surface(writer, &face.surface)?,
1246 false,
1247 EmittedSurface::Spline,
1248 ),
1249 };
1250 surfaces.insert(key, entry);
1251 }
1252
1253 let mut edge_uses = HashMap::<u64, Vec<CoedgeUse>>::default();
1256 let mut edge_order: Vec<u64> = Vec::new();
1257 for face in &shell.faces {
1258 for loop_record in &face.loops {
1259 for coedge in &loop_record.coedges {
1260 let edge = edge_for(solid, coedge.edge_id)?;
1261 if edge.degenerate {
1262 continue;
1263 }
1264 let uses = edge_uses.entry(edge.id).or_default();
1265 if uses.is_empty() {
1266 edge_order.push(edge.id);
1267 }
1268 uses.push(CoedgeUse {
1269 surface_key: surface_key(face),
1270 face,
1271 coedge,
1272 });
1273 }
1274 }
1275 }
1276
1277 for edge_id in &edge_order {
1279 if edge_ids.contains_key(edge_id) {
1280 continue;
1281 }
1282 let edge = edge_for(solid, *edge_id)?;
1283 let subcurve = edge_subcurve(edge)?;
1284 let (curve, emitted_curve) = match write_analytic_curve(writer, &subcurve)? {
1285 Some(pair) => pair,
1286 None => (
1287 write_curve(writer, &subcurve)?,
1288 EmittedCurve::Spline { curve: subcurve },
1289 ),
1290 };
1291 let uses = &edge_uses[edge_id];
1292 let seam = uses.len() == 2 && uses[0].surface_key == uses[1].surface_key;
1296 let mut pcurves: Vec<(usize, Pcurve2d)> = Vec::new();
1297 let mut omitted = 0usize;
1298 if uses.len() == 2 {
1299 let mut ordered: Vec<&CoedgeUse> = uses.iter().collect();
1303 if seam && !ordered[0].coedge.forward {
1304 ordered.swap(0, 1);
1305 }
1306 for coedge_use in ordered {
1307 let oriented = if coedge_use.coedge.forward {
1312 coedge_use.coedge.pcurve.clone()
1313 } else {
1314 coedge_use.coedge.pcurve.reversed()?
1315 };
1316 let (surface_id, _, emitted_surface) = &surfaces[&coedge_use.surface_key];
1317 let outcome = build_pcurve(
1318 &coedge_use.face.surface,
1319 emitted_surface,
1320 &emitted_curve,
1321 &oriented,
1322 band,
1323 )?;
1324 match outcome.curve {
1325 Some(curve_2d) => {
1326 report.max_pcurve_deviation =
1327 report.max_pcurve_deviation.max(outcome.deviation);
1328 pcurves.push((*surface_id, curve_2d));
1329 }
1330 None => {
1331 omitted += 1;
1332 if outcome.deviation.is_finite() {
1333 report.worst_omitted_deviation =
1334 report.worst_omitted_deviation.max(outcome.deviation);
1335 } else {
1336 report.worst_omitted_deviation = f64::INFINITY;
1337 }
1338 }
1339 }
1340 }
1341 }
1342 if seam && pcurves.len() != 2 {
1346 omitted += pcurves.len();
1347 pcurves.clear();
1348 }
1349 report.pcurves_omitted += omitted;
1350 report.pcurves_written += pcurves.len();
1351 let geometry = if pcurves.is_empty() {
1352 report.bare_curves += 1;
1353 curve
1354 } else {
1355 let ids = pcurves
1356 .iter()
1357 .map(|(surface_id, curve_2d)| {
1358 write_pcurve_entity(
1359 writer,
1360 *surface_id,
1361 parametric_context,
1362 curve_2d,
1363 )
1364 })
1365 .collect::<Result<Vec<_>, String>>()?;
1366 let keyword = if seam {
1367 report.seam_curves += 1;
1368 "SEAM_CURVE"
1369 } else {
1370 report.surface_curves += 1;
1371 "SURFACE_CURVE"
1372 };
1373 writer.add(format!(
1379 "{keyword}('',#{curve},{},.CURVE_3D.)",
1380 id_list(&ids)
1381 ))
1382 };
1383 let start = vertex_step_id(writer, &mut vertex_ids, solid, edge.start_vertex_id)?;
1384 let end = vertex_step_id(writer, &mut vertex_ids, solid, edge.end_vertex_id)?;
1385 let step_id =
1386 writer.add(format!("EDGE_CURVE('',#{start},#{end},#{geometry},.T.)"));
1387 edge_ids.insert(edge.id, step_id);
1388 if let Some(edge_name) = edge.name.as_deref() {
1389 written.edges.push((edge_name.to_string(), step_id));
1390 }
1391 }
1392
1393 let mut face_ids = Vec::new();
1395 for face in &shell.faces {
1396 let mut bound_ids = Vec::new();
1397 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1398 let mut oriented_edges = Vec::new();
1399 for coedge in &loop_record.coedges {
1400 let edge = edge_for(solid, coedge.edge_id)?;
1401 if edge.degenerate {
1402 continue;
1403 }
1404 let edge_id = *edge_ids
1405 .get(&edge.id)
1406 .ok_or_else(|| format!("export_step: unwritten edge {}", edge.id))?;
1407 let orientation = if coedge.forward { ".T." } else { ".F." };
1408 oriented_edges.push(
1409 writer.add(format!("ORIENTED_EDGE('',*,*,#{edge_id},{orientation})")),
1410 );
1411 }
1412 let kind = if loop_index == 0 {
1413 "FACE_OUTER_BOUND"
1414 } else {
1415 "FACE_BOUND"
1416 };
1417 if oriented_edges.is_empty() {
1418 let Some(coedge) = loop_record.coedges.first() else {
1431 continue;
1432 };
1433 let collapsed = edge_for(solid, coedge.edge_id)?;
1434 let vertex = vertex_step_id(
1435 writer,
1436 &mut vertex_ids,
1437 solid,
1438 collapsed.start_vertex_id,
1439 )?;
1440 let vertex_loop = writer.add(format!("VERTEX_LOOP('',#{vertex})"));
1441 report.vertex_loops += 1;
1442 bound_ids.push(writer.add(format!("{kind}('',#{vertex_loop},.T.)")));
1443 continue;
1444 }
1445 let edge_loop =
1446 writer.add(format!("EDGE_LOOP('',{})", id_list(&oriented_edges)));
1447 bound_ids.push(writer.add(format!("{kind}('',#{edge_loop},.T.)")));
1448 }
1449 let (surface, flipped, _) = surfaces[&surface_key(face)];
1450 let sense = if face.same_sense != flipped {
1454 ".T."
1455 } else {
1456 ".F."
1457 };
1458 let face_step_id = writer.add(format!(
1459 "ADVANCED_FACE('',{},#{surface},{sense})",
1460 id_list(&bound_ids)
1461 ));
1462 if let Some(face_name) = face.name.as_deref() {
1463 written.faces.push((face_name.to_string(), face_step_id));
1464 }
1465 face_ids.push(face_step_id);
1466 }
1467 let closed_shell = writer.add(format!("CLOSED_SHELL('',{})", id_list(&face_ids)));
1468 let signed_volume = if solid.shells.len() > 1 {
1469 crate::mass_properties::shell_signed_volume(shell)?
1470 } else {
1471 1.0
1472 };
1473 emitted_shells.push((closed_shell, signed_volume < 0.0, signed_volume.abs()));
1474 }
1475 if emitted_shells.iter().any(|&(_, inward, _)| inward) {
1476 let outer: Vec<usize> = (0..emitted_shells.len()).filter(|&i| !emitted_shells[i].1).collect();
1477 if outer.is_empty() {
1478 return Err("export_step: a solid with voids must have an outward shell".into());
1479 }
1480 let mut owned: Vec<Vec<usize>> = vec![Vec::new(); emitted_shells.len()];
1484 for void in (0..emitted_shells.len()).filter(|&i| emitted_shells[i].1) {
1485 let owner = if outer.len() == 1 {
1486 outer[0]
1487 } else {
1488 void_owner(solid, void, &outer, &emitted_shells)?
1489 };
1490 owned[owner].push(void);
1491 }
1492 for &shell in &outer {
1493 let closed_shell = emitted_shells[shell].0;
1494 let body_id = if owned[shell].is_empty() {
1495 writer.add(format!("MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)))
1496 } else {
1497 let voids = owned[shell].iter()
1498 .map(|&void| writer.add(format!("ORIENTED_CLOSED_SHELL('',*,#{},.T.)", emitted_shells[void].0)))
1499 .collect::<Vec<_>>();
1500 writer.add(format!(
1501 "BREP_WITH_VOIDS('{}',#{closed_shell},{})", step_string(solid_name), id_list(&voids)
1502 ))
1503 };
1504 written.solids.push((solid_name.to_string(), body_id));
1505 }
1506 } else {
1507 for (closed_shell, _, _) in emitted_shells {
1508 let body_id = writer.add(format!(
1509 "MANIFOLD_SOLID_BREP('{}',#{closed_shell})", step_string(solid_name)
1510 ));
1511 written.solids.push((solid_name.to_string(), body_id));
1512 }
1513 }
1514 let mut points: Vec<(Vec3, usize)> = Vec::with_capacity(vertex_ids.len());
1516 for (vertex_id, step_id) in &vertex_ids {
1517 points.push((vertex_for(solid, *vertex_id)?.point, *step_id));
1518 }
1519 written.vertices.push((solid_name.to_string(), points));
1520 }
1521 Ok(written)
1522}
1523
1524pub(crate) fn finish_step_file(
1527 writer: StepWriter,
1528 name: &str,
1529 timestamp: &str,
1530 report: &mut StepExportReport,
1531) -> Result<(), String> {
1532 let safe_name = step_string(name);
1533 let safe_timestamp = step_string(timestamp);
1534 let output = [
1535 "ISO-10303-21;".to_string(),
1536 "HEADER;".to_string(),
1537 "FILE_DESCRIPTION((''),'2;1');".to_string(),
1538 format!(
1539 "FILE_NAME('{safe_name}.step','{safe_timestamp}',(''),(''),'brep-kernel-rs','brep-kernel-rs','');"
1540 ),
1541 "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));".to_string(),
1542 "ENDSEC;".to_string(),
1543 "DATA;".to_string(),
1544 writer.data(),
1545 "ENDSEC;".to_string(),
1546 "END-ISO-10303-21;".to_string(),
1547 String::new(),
1548 ]
1549 .join("\n");
1550 let manifold_issues = audit_step_manifold(&output);
1551 if !manifold_issues.is_empty() {
1552 return Err(format!(
1553 "export_step: emitted AP242 manifold audit failed: {}",
1554 manifold_issues.join("; ")
1555 ));
1556 }
1557 let pcurve_issues = audit_step_pcurves(&output);
1558 if !pcurve_issues.is_empty() {
1559 return Err(format!(
1560 "export_step: emitted AP242 pcurve audit failed: {}",
1561 pcurve_issues.join("; ")
1562 ));
1563 }
1564 report.text = output;
1565 Ok(())
1566}
1567
1568pub fn export_step_report_named(
1577 solids: &[(String, &BrepSolid)],
1578 name: &str,
1579 unit: &str,
1580 timestamp: &str,
1581 pmi: Option<&StepPmi<'_>>,
1582 colors: Option<&StepColors>,
1583) -> Result<StepExportReport, String> {
1584 if solids.is_empty() {
1585 return Err("export_step: at least one solid is required".into());
1586 }
1587 let mut report = StepExportReport {
1588 products: 1,
1589 ..StepExportReport::default()
1590 };
1591 let mut writer = StepWriter::default();
1592 let contexts = write_file_contexts(&mut writer, unit)?;
1593 let geometry = write_product_geometry(&mut writer, &contexts, solids, &mut report)?;
1594 let mut items = vec![contexts.axis];
1595 items.extend(geometry.solids.iter().map(|(_, id)| *id));
1596 let geometry_context = contexts.geometry_context;
1597 let representation = writer.add(format!(
1598 "ADVANCED_BREP_SHAPE_REPRESENTATION('',{},#{geometry_context})",
1599 id_list(&items)
1600 ));
1601 let product = write_product(&mut writer, &contexts, name, "", "part");
1602 let product_shape = product.product_shape;
1603 writer.add(format!(
1604 "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
1605 ));
1606 if let Some(colors) = colors.filter(|colors| !colors.is_empty()) {
1611 let items = styles::styled_items(&geometry, colors, &[String::new()]);
1612 report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
1613 }
1614 if let Some(pmi) = pmi {
1615 let mut names = StepNameMaps::default();
1616 names.register(
1617 &geometry,
1618 StepItemOwner {
1619 product_shape,
1620 representation,
1621 },
1622 "",
1623 &MAT4_IDENTITY,
1624 );
1625 let context = pmi::StepContext {
1626 product_shape,
1627 representation,
1628 geometry_context,
1629 length_unit: contexts.length_unit,
1630 angle_unit: contexts.angle_unit,
1631 faces: &names.faces,
1632 edges: &names.edges,
1633 vertices: &names.vertices,
1634 };
1635 report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
1636 }
1637 finish_step_file(writer, name, timestamp, &mut report)?;
1638 Ok(report)
1639}
1640
1641fn vertex_step_id(
1643 writer: &mut StepWriter,
1644 vertex_ids: &mut HashMap<u64, usize>,
1645 solid: &BrepSolid,
1646 id: u64,
1647) -> Result<usize, String> {
1648 if let Some(step_id) = vertex_ids.get(&id) {
1649 return Ok(*step_id);
1650 }
1651 let point = write_point(writer, vertex_for(solid, id)?.point)?;
1652 let step_id = writer.add(format!("VERTEX_POINT('',#{point})"));
1653 vertex_ids.insert(id, step_id);
1654 Ok(step_id)
1655}
1656
1657fn step_entity_bodies(step: &str) -> HashMap<u64, &str> {
1660 step.lines()
1661 .filter_map(|line| {
1662 let rest = line.strip_prefix('#')?;
1663 let (digits, body) = rest.split_once('=')?;
1664 Some((
1665 digits.parse::<u64>().ok()?,
1666 body.trim_end().trim_end_matches(';'),
1667 ))
1668 })
1669 .collect()
1670}
1671
1672fn step_entity_refs(body: &str) -> Vec<u64> {
1676 let mut refs = Vec::new();
1677 let bytes = body.as_bytes();
1678 let mut index = 0;
1679 while index < bytes.len() {
1680 if bytes[index] == b'#' {
1681 let start = index + 1;
1682 let mut end = start;
1683 while end < bytes.len() && bytes[end].is_ascii_digit() {
1684 end += 1;
1685 }
1686 if end > start {
1687 if let Ok(id) = body[start..end].parse::<u64>() {
1688 refs.push(id);
1689 }
1690 }
1691 index = end;
1692 } else {
1693 index += 1;
1694 }
1695 }
1696 refs
1697}
1698
1699pub fn audit_step_pcurves(step: &str) -> Vec<String> {
1712 let bodies = step_entity_bodies(step);
1713 let mut issues = Vec::new();
1714 for (id, body) in &bodies {
1715 if !body.starts_with("EDGE_CURVE(") {
1716 continue;
1717 }
1718 let refs = step_entity_refs(body);
1719 let Some(geometry) = refs.get(2) else {
1720 issues.push(format!("EDGE_CURVE #{id} has no edge_geometry"));
1721 continue;
1722 };
1723 let Some(wrapper) = bodies.get(geometry) else {
1724 issues.push(format!("EDGE_CURVE #{id} references missing #{geometry}"));
1725 continue;
1726 };
1727 let seam = wrapper.starts_with("SEAM_CURVE(");
1728 if !seam && !wrapper.starts_with("SURFACE_CURVE(") {
1729 continue;
1730 }
1731 let wrapper_refs = step_entity_refs(wrapper);
1732 let pcurves = &wrapper_refs[wrapper_refs.len().min(1)..];
1733 if pcurves.is_empty() || pcurves.len() > 2 || (seam && pcurves.len() != 2) {
1734 issues.push(format!(
1735 "#{geometry} carries {} associated geometries",
1736 pcurves.len()
1737 ));
1738 continue;
1739 }
1740 let mut surfaces = Vec::new();
1741 for pcurve in pcurves {
1742 let Some(pcurve_body) = bodies.get(pcurve) else {
1743 issues.push(format!("#{geometry} references missing #{pcurve}"));
1744 continue;
1745 };
1746 if !pcurve_body.starts_with("PCURVE(") {
1747 issues.push(format!("#{geometry} associate #{pcurve} is not a PCURVE"));
1748 continue;
1749 }
1750 let pcurve_refs = step_entity_refs(pcurve_body);
1751 let representation = pcurve_refs.get(1).and_then(|id| bodies.get(id));
1752 if !representation.is_some_and(|body| body.starts_with("DEFINITIONAL_REPRESENTATION("))
1753 {
1754 issues.push(format!(
1755 "PCURVE #{pcurve} has no DEFINITIONAL_REPRESENTATION"
1756 ));
1757 }
1758 if let Some(surface) = pcurve_refs.first() {
1759 surfaces.push(*surface);
1760 }
1761 }
1762 if surfaces.len() == 2 && (surfaces[0] == surfaces[1]) != seam {
1763 issues.push(format!(
1764 "#{geometry} pcurves name {} surface(s) but it is a {}",
1765 if surfaces[0] == surfaces[1] { 1 } else { 2 },
1766 if seam { "SEAM_CURVE" } else { "SURFACE_CURVE" }
1767 ));
1768 }
1769 }
1770 issues.sort();
1771 issues
1772}
1773
1774pub fn audit_step_manifold(step: &str) -> Vec<String> {
1779 let marker = "ORIENTED_EDGE('',*,*,#";
1780 let mut uses = HashMap::<u64, Vec<bool>>::default();
1781 for line in step.lines() {
1782 let Some(offset) = line.find(marker) else {
1783 continue;
1784 };
1785 let rest = &line[offset + marker.len()..];
1786 let digits = rest
1787 .chars()
1788 .take_while(|character| character.is_ascii_digit())
1789 .collect::<String>();
1790 let Ok(edge_id) = digits.parse::<u64>() else {
1791 continue;
1792 };
1793 let suffix = &rest[digits.len()..];
1794 let sense = suffix.starts_with(",.T.");
1795 uses.entry(edge_id).or_default().push(sense);
1796 }
1797 let mut issues = uses
1798 .into_iter()
1799 .filter_map(|(edge, senses)| {
1800 (senses.len() != 2 || senses[0] == senses[1]).then(|| {
1801 format!(
1802 "EDGE_CURVE #{edge} has {} uses with senses {:?}",
1803 senses.len(),
1804 senses
1805 )
1806 })
1807 })
1808 .collect::<Vec<_>>();
1809 issues.sort();
1810 issues
1811}
1812