1use crate::analytic_surface::{circumcenter, AnalyticSurface};
2use crate::topology::{BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, VertexRecord};
3use crate::{make_arc, KernelTolerances, NurbsCurve, NurbsSurface, Vec3};
4use rustc_hash::FxHashMap as HashMap;
5
6#[path = "step/pcurve.rs"]
7mod pcurve;
8use pcurve::{build_pcurve, EmittedCurve, EmittedFrame, EmittedSurface, Pcurve2d};
9#[path = "step/pmi.rs"]
10pub(crate) mod pmi;
11pub use pmi::StepPmi;
12#[path = "step/assembly.rs"]
13pub mod assembly;
14pub use assembly::{
15 export_step_assembly, export_step_assembly_report, StepAssemblyExport, StepExportOccurrence,
16 StepExportProduct,
17};
18#[path = "step/export_tree.rs"]
19mod export_tree;
20pub use export_tree::{assembly_export_tree, PART_ATTRIBUTES, PART_NUMBER};
21#[path = "step/styles.rs"]
22pub(crate) mod styles;
23pub use styles::StepColors;
24
25pub use crate::step_matrix::Mat4;
26pub(crate) use crate::step_matrix::{mat4_mul, MAT4_IDENTITY};
27
28pub(crate) fn transform_point(matrix: &Mat4, point: Vec3) -> Vec3 {
29 crate::AffineTransform {
30 elements: *matrix,
31 }
32 .point(point)
33}
34
35pub(crate) fn step_string(value: &str) -> String {
36 value.replace('\'', "''")
37}
38
39pub(crate) fn real(value: f64) -> Result<String, String> {
40 if !value.is_finite() {
41 return Err(format!("export_step: non-finite number {value}"));
42 }
43 if value == 0.0 {
46 return Ok("0.".into());
47 }
48 if value.fract() == 0.0 && value.abs() < 1e15 {
49 return Ok(format!("{value:.0}."));
50 }
51 let mut output = format!("{value:.15}");
52 while output.ends_with('0') {
53 output.pop();
54 }
55 if output.ends_with('.') {
56 output.push('0');
57 }
58 if output == "-0.0" {
59 output = "0.0".into();
60 }
61 Ok(output)
62}
63
64fn knot_runs(knots: &[f64]) -> (Vec<f64>, Vec<usize>) {
65 let mut values = Vec::new();
66 let mut multiplicities = Vec::new();
67 for &knot in knots {
68 if values
69 .last()
70 .is_some_and(|previous: &f64| (*previous - knot).abs() <= 1e-12)
71 {
72 *multiplicities.last_mut().unwrap() += 1;
73 } else {
74 values.push(knot);
75 multiplicities.push(1);
76 }
77 }
78 (values, multiplicities)
79}
80
81pub(crate) fn edge_subcurve(edge: &EdgeRecord) -> Result<NurbsCurve, String> {
82 let [start, end] = edge.curve.domain()?;
83 let epsilon = (1e-9 * (end - start)).max(2e-9);
84 let mut curve = edge.curve.clone();
85 if edge.t0 > start + epsilon && edge.t0 < end - epsilon {
86 curve = curve.split(edge.t0)?.1;
87 }
88 let domain = curve.domain()?;
89 if edge.t1 < domain[1] - epsilon && edge.t1 > domain[0] + epsilon {
90 curve = curve.split(edge.t1)?.0;
91 }
92 Ok(curve)
93}
94
95#[derive(Default)]
96pub(crate) struct StepWriter {
97 lines: Vec<String>,
98}
99
100impl StepWriter {
101 pub(crate) fn add(&mut self, body: impl Into<String>) -> usize {
102 let id = self.lines.len() + 1;
103 self.lines.push(format!("#{id}={};", body.into()));
104 id
105 }
106
107 fn data(&self) -> String {
108 self.lines.join("\n")
109 }
110}
111
112pub(crate) fn write_point(writer: &mut StepWriter, point: Vec3) -> Result<usize, String> {
113 Ok(writer.add(format!(
114 "CARTESIAN_POINT('',({},{},{}))",
115 real(point.x)?,
116 real(point.y)?,
117 real(point.z)?
118 )))
119}
120
121pub(crate) fn id_list(ids: &[usize]) -> String {
122 format!(
123 "({})",
124 ids.iter()
125 .map(|id| format!("#{id}"))
126 .collect::<Vec<_>>()
127 .join(",")
128 )
129}
130
131pub(crate) fn write_direction(writer: &mut StepWriter, direction: Vec3) -> Result<usize, String> {
132 Ok(writer.add(format!(
133 "DIRECTION('',({},{},{}))",
134 real(direction.x)?,
135 real(direction.y)?,
136 real(direction.z)?
137 )))
138}
139
140pub(crate) fn write_placement(
141 writer: &mut StepWriter,
142 origin: Vec3,
143 axis: Vec3,
144 ref_direction: Vec3,
145) -> Result<usize, String> {
146 let origin = write_point(writer, origin)?;
147 let axis = write_direction(writer, axis)?;
148 let ref_direction = write_direction(writer, ref_direction)?;
149 Ok(writer.add(format!(
150 "AXIS2_PLACEMENT_3D('',#{origin},#{axis},#{ref_direction})"
151 )))
152}
153
154fn write_analytic_surface(
163 writer: &mut StepWriter,
164 surface: &NurbsSurface,
165) -> Result<Option<(usize, bool, EmittedSurface)>, String> {
166 let Some(analytic) = surface.analytic() else {
167 return Ok(None);
168 };
169 match analytic {
170 AnalyticSurface::Plane {
171 origin,
172 u_dir,
173 v_dir,
174 ..
175 } => {
176 let (Ok(normal), Ok(x_axis)) = (u_dir.cross(*v_dir).normalized(), u_dir.normalized())
179 else {
180 return Ok(None);
181 };
182 let placement = write_placement(writer, *origin, normal, x_axis)?;
183 Ok(Some((
188 writer.add(format!("PLANE('',#{placement})")),
189 false,
190 EmittedSurface::Plane {
191 origin: *origin,
192 x_axis,
193 y_axis: normal.cross(x_axis),
194 },
195 )))
196 }
197 AnalyticSurface::RuledRevolution {
198 frame,
199 rho0,
200 rho1,
201 height,
202 } => {
203 let flipped = *height < 0.0;
207 let radius_scale = 1.0 + rho0.abs().max(rho1.abs());
208 if (rho1 - rho0).abs() <= 1e-9 * radius_scale {
209 if *rho0 <= 0.0 {
210 return Ok(None);
211 }
212 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
213 return Ok(Some((
214 writer.add(format!(
215 "CYLINDRICAL_SURFACE('',#{placement},{})",
216 real(*rho0)?
217 )),
218 flipped,
219 EmittedSurface::Cylinder {
220 frame: EmittedFrame {
221 origin: frame.origin,
222 x_axis: frame.x_axis,
223 y_axis: frame.y_axis,
224 axis: frame.axis,
225 azimuth_sign: 1.0,
226 },
227 radius: *rho0,
228 },
229 )));
230 }
231 let slope = (rho1 - rho0) / height;
237 let apex_margin = 2.0 * (1e-4 * height.abs().max(1.0) + 1e-9) * slope.abs();
238 if rho0.min(*rho1) <= apex_margin {
239 return Ok(None);
240 }
241 let axis = if slope >= 0.0 {
245 frame.axis
246 } else {
247 frame.axis.scale(-1.0)
248 };
249 let placement = write_placement(writer, frame.origin, axis, frame.x_axis)?;
250 Ok(Some((
251 writer.add(format!(
252 "CONICAL_SURFACE('',#{placement},{},{})",
253 real(*rho0)?,
254 real(slope.abs().atan())?
255 )),
256 flipped,
257 EmittedSurface::Cone {
258 frame: EmittedFrame {
259 origin: frame.origin,
260 x_axis: frame.x_axis,
261 y_axis: axis.cross(frame.x_axis),
265 axis,
266 azimuth_sign: if slope >= 0.0 { 1.0 } else { -1.0 },
267 },
268 radius: *rho0,
269 semi_angle: slope.abs().atan(),
270 },
271 )))
272 }
273 AnalyticSurface::Sphere { frame, radius } => {
274 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
277 Ok(Some((
278 writer.add(format!(
279 "SPHERICAL_SURFACE('',#{placement},{})",
280 real(*radius)?
281 )),
282 false,
283 EmittedSurface::Sphere {
284 frame: EmittedFrame {
285 origin: frame.origin,
286 x_axis: frame.x_axis,
287 y_axis: frame.y_axis,
288 axis: frame.axis,
289 azimuth_sign: 1.0,
290 },
291 radius: *radius,
292 },
293 )))
294 }
295 AnalyticSurface::Torus {
296 frame,
297 major_radius,
298 minor_radius,
299 } => {
300 let placement = write_placement(writer, frame.origin, frame.axis, frame.x_axis)?;
301 Ok(Some((
302 writer.add(format!(
303 "TOROIDAL_SURFACE('',#{placement},{},{})",
304 real(*major_radius)?,
305 real(*minor_radius)?
306 )),
307 false,
308 EmittedSurface::Torus {
309 frame: EmittedFrame {
310 origin: frame.origin,
311 x_axis: frame.x_axis,
312 y_axis: frame.y_axis,
313 axis: frame.axis,
314 azimuth_sign: 1.0,
315 },
316 major_radius: *major_radius,
317 minor_radius: *minor_radius,
318 },
319 )))
320 }
321 AnalyticSurface::Revolution { .. } => Ok(None),
324 }
325}
326
327struct CircularArc {
332 center: Vec3,
333 axis: Vec3,
334 x_axis: Vec3,
335 y_axis: Vec3,
338 radius: f64,
339 sweep: f64,
341 spans: usize,
345}
346
347fn curve_scale(curve: &NurbsCurve) -> f64 {
348 curve
349 .control_points
350 .iter()
351 .map(|p| (p.x.abs() / p.w).max(p.y.abs() / p.w).max(p.z.abs() / p.w))
352 .fold(0.0, f64::max)
353}
354
355fn curves_match(a: &NurbsCurve, b: &NurbsCurve, scale: f64) -> bool {
359 if a.degree != b.degree
360 || a.knots.len() != b.knots.len()
361 || a.control_points.len() != b.control_points.len()
362 {
363 return false;
364 }
365 if a.knots
366 .iter()
367 .zip(&b.knots)
368 .any(|(x, y)| (x - y).abs() > 1e-12)
369 {
370 return false;
371 }
372 let tolerance = 1e-9 * scale.max(1.0);
373 a.control_points
374 .iter()
375 .zip(&b.control_points)
376 .all(|(p, q)| {
377 (p.x - q.x).abs() <= tolerance
378 && (p.y - q.y).abs() <= tolerance
379 && (p.z - q.z).abs() <= tolerance
380 && (p.w - q.w).abs() <= 1e-9
381 })
382}
383
384fn recognize_circular_arc(curve: &NurbsCurve) -> Option<CircularArc> {
389 if curve.degree != 2
390 || curve.control_points.len() < 3
391 || curve.control_points.len() % 2 == 0
392 || (curve.control_points.len() - 1) / 2 > 4
393 {
394 return None;
395 }
396 let [t0, t1] = curve.domain().ok()?;
397 let at = |fraction: f64| curve.evaluate(t0 + (t1 - t0) * fraction);
398 let p0 = at(0.0).ok()?;
401 let pa = at(0.35).ok()?;
402 let pb = at(0.7).ok()?;
403 let center = circumcenter(p0, pa, pb)?;
404 let radial = p0.sub(center);
405 let radius = radial.length();
406 let scale = curve_scale(curve);
407 if radius <= 1e-9 * scale.max(1.0) {
408 return None;
409 }
410 let x_axis = radial.scale(1.0 / radius);
411 let axis = radial.cross(pa.sub(center)).normalized().ok()?;
412 let y_axis = axis.cross(x_axis);
413 let p_end = at(1.0).ok()?;
414 let sweep = if p_end.sub(p0).length() <= 1e-9 * (1.0 + radius) {
415 std::f64::consts::TAU
416 } else {
417 let closing = p_end.sub(center);
418 let mut angle = closing.dot(y_axis).atan2(closing.dot(x_axis));
419 if angle < 0.0 {
420 angle += std::f64::consts::TAU;
421 }
422 angle
423 };
424 let rebuilt = make_arc(center, x_axis, y_axis, radius, 0.0, sweep).ok()?;
425 curves_match(curve, &rebuilt, scale).then_some(CircularArc {
426 center,
427 axis,
428 x_axis,
429 y_axis,
430 radius,
431 sweep,
432 spans: (curve.control_points.len() - 1) / 2,
433 })
434}
435
436fn write_analytic_curve(
443 writer: &mut StepWriter,
444 curve: &NurbsCurve,
445) -> Result<Option<(usize, EmittedCurve)>, String> {
446 if curve.degree == 1
447 && curve.control_points.len() == 2
448 && curve
449 .control_points
450 .iter()
451 .all(|control| (control.w - 1.0).abs() <= 1e-12)
452 {
453 let start = curve.control_points[0].point()?;
454 let end = curve.control_points[1].point()?;
455 let Ok(direction) = end.sub(start).normalized() else {
456 return Ok(None);
457 };
458 let point = write_point(writer, start)?;
459 let step_direction = write_direction(writer, direction)?;
460 let vector = writer.add(format!(
461 "VECTOR('',#{step_direction},{})",
462 real(end.sub(start).length())?
463 ));
464 return Ok(Some((
465 writer.add(format!("LINE('',#{point},#{vector})")),
466 EmittedCurve::Line { start, end },
470 )));
471 }
472 if let Some(arc) = recognize_circular_arc(curve) {
473 let placement = write_placement(writer, arc.center, arc.axis, arc.x_axis)?;
477 return Ok(Some((
478 writer.add(format!("CIRCLE('',#{placement},{})", real(arc.radius)?)),
479 EmittedCurve::Circle {
480 center: arc.center,
481 x_axis: arc.x_axis,
482 y_axis: arc.y_axis,
483 radius: arc.radius,
484 sweep: arc.sweep,
485 spans: arc.spans,
486 },
487 )));
488 }
489 Ok(None)
490}
491
492fn write_curve(writer: &mut StepWriter, curve: &NurbsCurve) -> Result<usize, String> {
493 let points = curve
494 .control_points
495 .iter()
496 .map(|control| write_point(writer, control.point()?))
497 .collect::<Result<Vec<_>, _>>()?;
498 write_bspline_curve(writer, curve, &points)
499}
500
501fn write_bspline_curve(
506 writer: &mut StepWriter,
507 curve: &NurbsCurve,
508 points: &[usize],
509) -> Result<usize, String> {
510 let (knot_values, multiplicities) = knot_runs(&curve.knots);
511 let multiplicities = format!(
512 "({})",
513 multiplicities
514 .iter()
515 .map(usize::to_string)
516 .collect::<Vec<_>>()
517 .join(",")
518 );
519 let knots = format!(
520 "({})",
521 knot_values
522 .iter()
523 .map(|value| real(*value))
524 .collect::<Result<Vec<_>, _>>()?
525 .join(",")
526 );
527 let rational = curve
528 .control_points
529 .iter()
530 .any(|control| (control.w - 1.0).abs() > 1e-12);
531 if !rational {
532 return Ok(writer.add(format!(
533 "B_SPLINE_CURVE_WITH_KNOTS('',{},{},.UNSPECIFIED.,.F.,.F.,{multiplicities},{knots},.UNSPECIFIED.)",
534 curve.degree,
535 id_list(points),
536 )));
537 }
538 let weights = format!(
539 "({})",
540 curve
541 .control_points
542 .iter()
543 .map(|control| real(control.w))
544 .collect::<Result<Vec<_>, _>>()?
545 .join(",")
546 );
547 Ok(writer.add(format!(
548 "(BOUNDED_CURVE()B_SPLINE_CURVE({},{},.UNSPECIFIED.,.F.,.F.)\
549 B_SPLINE_CURVE_WITH_KNOTS({multiplicities},{knots},.UNSPECIFIED.)\
550 CURVE()GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_CURVE({weights})\
551 REPRESENTATION_ITEM(''))",
552 curve.degree,
553 id_list(points),
554 )))
555}
556
557fn write_point_2d(writer: &mut StepWriter, point: [f64; 2]) -> Result<usize, String> {
558 Ok(writer.add(format!(
559 "CARTESIAN_POINT('',({},{}))",
560 real(point[0])?,
561 real(point[1])?
562 )))
563}
564
565fn write_direction_2d(writer: &mut StepWriter, direction: [f64; 2]) -> Result<usize, String> {
566 Ok(writer.add(format!(
567 "DIRECTION('',({},{}))",
568 real(direction[0])?,
569 real(direction[1])?
570 )))
571}
572
573fn write_pcurve_geometry(writer: &mut StepWriter, curve: &Pcurve2d) -> Result<usize, String> {
583 match curve {
584 Pcurve2d::Line { point, vector } => {
585 let magnitude = vector[0].hypot(vector[1]);
586 if magnitude <= 0.0 {
587 return Err("export_step: degenerate 2D line pcurve".into());
588 }
589 let point_id = write_point_2d(writer, *point)?;
590 let direction =
591 write_direction_2d(writer, [vector[0] / magnitude, vector[1] / magnitude])?;
592 let vector_id = writer.add(format!(
593 "VECTOR('',#{direction},{})",
594 real(magnitude)?
595 ));
596 Ok(writer.add(format!("LINE('',#{point_id},#{vector_id})")))
597 }
598 Pcurve2d::Circle {
599 center,
600 ref_direction,
601 radius,
602 } => {
603 let center_id = write_point_2d(writer, *center)?;
604 let direction = write_direction_2d(writer, *ref_direction)?;
605 let placement = writer.add(format!(
606 "AXIS2_PLACEMENT_2D('',#{center_id},#{direction})"
607 ));
608 Ok(writer.add(format!("CIRCLE('',#{placement},{})", real(*radius)?)))
609 }
610 Pcurve2d::Spline(spline) => {
611 let points = spline
612 .control_points
613 .iter()
614 .map(|control| {
615 let point = control.point()?;
616 write_point_2d(writer, [point.x, point.y])
617 })
618 .collect::<Result<Vec<_>, String>>()?;
619 write_bspline_curve(writer, spline, &points)
620 }
621 }
622}
623
624fn write_pcurve_entity(
627 writer: &mut StepWriter,
628 surface_id: usize,
629 context_2d: usize,
630 curve: &Pcurve2d,
631) -> Result<usize, String> {
632 let geometry = write_pcurve_geometry(writer, curve)?;
633 let representation = writer.add(format!(
634 "DEFINITIONAL_REPRESENTATION('',(#{geometry}),#{context_2d})"
635 ));
636 Ok(writer.add(format!("PCURVE('',#{surface_id},#{representation})")))
637}
638
639fn write_surface(writer: &mut StepWriter, surface: &NurbsSurface) -> Result<usize, String> {
640 let rows = surface
641 .control_points
642 .iter()
643 .map(|row| {
644 row.iter()
645 .map(|control| write_point(writer, control.point()?))
646 .collect::<Result<Vec<_>, _>>()
647 .map(|ids| id_list(&ids))
648 })
649 .collect::<Result<Vec<_>, _>>()?;
650 let grid = format!("({})", rows.join(","));
651 let (u_values, u_multiplicities) = knot_runs(&surface.knots_u);
652 let (v_values, v_multiplicities) = knot_runs(&surface.knots_v);
653 let multiplicities = |values: &[usize]| {
654 format!(
655 "({})",
656 values
657 .iter()
658 .map(usize::to_string)
659 .collect::<Vec<_>>()
660 .join(",")
661 )
662 };
663 let knots = |values: &[f64]| -> Result<String, String> {
664 Ok(format!(
665 "({})",
666 values
667 .iter()
668 .map(|value| real(*value))
669 .collect::<Result<Vec<_>, _>>()?
670 .join(",")
671 ))
672 };
673 let u_mults = multiplicities(&u_multiplicities);
674 let v_mults = multiplicities(&v_multiplicities);
675 let u_knots = knots(&u_values)?;
676 let v_knots = knots(&v_values)?;
677 let rational = surface
678 .control_points
679 .iter()
680 .flatten()
681 .any(|control| (control.w - 1.0).abs() > 1e-12);
682 if !rational {
683 return Ok(writer.add(format!(
684 "B_SPLINE_SURFACE_WITH_KNOTS('',{},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.,\
685 {u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)",
686 surface.degree_u, surface.degree_v,
687 )));
688 }
689 let weights = format!(
690 "({})",
691 surface
692 .control_points
693 .iter()
694 .map(|row| {
695 row.iter()
696 .map(|control| real(control.w))
697 .collect::<Result<Vec<_>, _>>()
698 .map(|values| format!("({})", values.join(",")))
699 })
700 .collect::<Result<Vec<_>, _>>()?
701 .join(",")
702 );
703 Ok(writer.add(format!(
704 "(BOUNDED_SURFACE()B_SPLINE_SURFACE({},{},{grid},.UNSPECIFIED.,.F.,.F.,.F.)\
705 B_SPLINE_SURFACE_WITH_KNOTS({u_mults},{v_mults},{u_knots},{v_knots},.UNSPECIFIED.)\
706 GEOMETRIC_REPRESENTATION_ITEM()RATIONAL_B_SPLINE_SURFACE({weights})\
707 REPRESENTATION_ITEM('')SURFACE())",
708 surface.degree_u, surface.degree_v,
709 )))
710}
711
712fn write_length_unit(writer: &mut StepWriter, unit: &str) -> Result<usize, String> {
713 let normalized = unit.to_lowercase();
714 if normalized == "meter" || normalized == "metre" {
715 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))"));
716 }
717 if normalized == "centimeter" || normalized == "centimetre" {
718 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.CENTI.,.METRE.))"));
719 }
720 if matches!(normalized.as_str(), "micron" | "micrometer" | "micrometre") {
721 return Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MICRO.,.METRE.))"));
722 }
723 if normalized == "inch" || normalized == "foot" {
724 let metre = writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT($,.METRE.))");
725 let (factor, name) = if normalized == "inch" {
726 (0.0254, "INCH")
727 } else {
728 (0.3048, "FOOT")
729 };
730 let measure = writer.add(format!(
731 "LENGTH_MEASURE_WITH_UNIT(LENGTH_MEASURE({}),#{metre})",
732 real(factor)?
733 ));
734 return Ok(writer.add(format!(
735 "(CONVERSION_BASED_UNIT('{name}',#{measure})LENGTH_UNIT()NAMED_UNIT(*))"
736 )));
737 }
738 Ok(writer.add("(LENGTH_UNIT()NAMED_UNIT(*)SI_UNIT(.MILLI.,.METRE.))"))
739}
740
741fn vertex_for(solid: &BrepSolid, id: u64) -> Result<&VertexRecord, String> {
742 solid
743 .vertices
744 .iter()
745 .find(|vertex| vertex.id == id)
746 .ok_or_else(|| format!("export_step: missing vertex {id}"))
747}
748
749fn edge_for(solid: &BrepSolid, id: u64) -> Result<&EdgeRecord, String> {
750 solid
751 .edges
752 .iter()
753 .find(|edge| edge.id == id)
754 .ok_or_else(|| format!("export_step: missing edge {id}"))
755}
756
757fn surface_key(face: &FaceRecord) -> usize {
758 face as *const FaceRecord as usize
759}
760
761struct CoedgeUse<'a> {
765 surface_key: usize,
766 face: &'a FaceRecord,
767 coedge: &'a CoedgeRecord,
768}
769
770#[derive(Clone, Debug, Default)]
779pub struct StepExportReport {
780 pub text: String,
782 pub pcurves_written: usize,
785 pub pcurves_omitted: usize,
788 pub surface_curves: usize,
790 pub seam_curves: usize,
793 pub bare_curves: usize,
796 pub vertex_loops: usize,
799 pub max_pcurve_deviation: f64,
802 pub worst_omitted_deviation: f64,
813 pub pmi_unresolved_references: usize,
820 pub products: usize,
823 pub occurrences: usize,
826 pub styled_items: usize,
831}
832
833pub fn export_step(
835 solids: &[BrepSolid],
836 name: &str,
837 unit: &str,
838 timestamp: &str,
839) -> Result<String, String> {
840 export_step_report(solids, name, unit, timestamp).map(|report| report.text)
841}
842
843pub fn export_step_report(
846 solids: &[BrepSolid],
847 name: &str,
848 unit: &str,
849 timestamp: &str,
850) -> Result<StepExportReport, String> {
851 let named: Vec<(String, &BrepSolid)> = solids
852 .iter()
853 .map(|solid| (name.to_string(), solid))
854 .collect();
855 export_step_report_named(&named, name, unit, timestamp, None, None)
856}
857
858#[derive(Clone, Copy)]
867pub(crate) struct StepItemOwner {
868 pub product_shape: usize,
869 pub representation: usize,
870}
871
872#[derive(Default)]
876pub(crate) struct ProductGeometry {
877 pub solids: Vec<(String, usize)>,
882 pub faces: Vec<(String, usize)>,
884 pub edges: Vec<(String, usize)>,
886 pub vertices: Vec<(String, Vec<(Vec3, usize)>)>,
888}
889
890#[derive(Default)]
895pub(crate) struct StepNameMaps {
896 pub faces: HashMap<String, (usize, StepItemOwner)>,
897 pub edges: HashMap<String, (usize, StepItemOwner)>,
898 pub vertices: HashMap<String, (StepItemOwner, Vec<(Vec3, usize)>)>,
901}
902
903impl StepNameMaps {
904 pub(crate) fn register(
908 &mut self,
909 geometry: &ProductGeometry,
910 owner: StepItemOwner,
911 prefix: &str,
912 world: &Mat4,
913 ) {
914 for (name, id) in &geometry.faces {
915 self.faces
916 .entry(format!("{prefix}{name}"))
917 .or_insert((*id, owner));
918 }
919 for (name, id) in &geometry.edges {
920 self.edges
921 .entry(format!("{prefix}{name}"))
922 .or_insert((*id, owner));
923 }
924 for (name, points) in &geometry.vertices {
925 let placed = points
926 .iter()
927 .map(|(point, id)| (transform_point(world, *point), *id))
928 .collect();
929 self.vertices
930 .entry(format!("{prefix}{name}"))
931 .or_insert((owner, placed));
932 }
933 }
934}
935
936pub(crate) struct StepFileContexts {
939 pub product_context: usize,
940 pub definition_context: usize,
941 pub geometry_context: usize,
942 pub parametric_context: usize,
943 pub length_unit: usize,
944 pub angle_unit: usize,
945 pub axis: usize,
949}
950
951pub(crate) fn write_file_contexts(
953 writer: &mut StepWriter,
954 unit: &str,
955) -> Result<StepFileContexts, String> {
956 let application = writer.add("APPLICATION_CONTEXT('managed model based 3d engineering')");
957 writer.add(format!(
958 "APPLICATION_PROTOCOL_DEFINITION('international standard','ap242_managed_model_based_3d_engineering',2014,#{application})"
959 ));
960 let product_context = writer.add(format!("PRODUCT_CONTEXT('',#{application},'mechanical')"));
961 let definition_context = writer.add(format!(
962 "PRODUCT_DEFINITION_CONTEXT('part definition',#{application},'design')"
963 ));
964 let length_unit = write_length_unit(writer, unit)?;
965 let angle_unit = writer.add("(NAMED_UNIT(*)PLANE_ANGLE_UNIT()SI_UNIT($,.RADIAN.))");
966 let solid_angle_unit = writer.add("(NAMED_UNIT(*)SI_UNIT($,.STERADIAN.)SOLID_ANGLE_UNIT())");
967 let uncertainty = writer.add(format!(
968 "UNCERTAINTY_MEASURE_WITH_UNIT(LENGTH_MEASURE(1.E-6),#{length_unit},'distance_accuracy_value','')"
969 ));
970 let geometry_context = writer.add(format!(
971 "(GEOMETRIC_REPRESENTATION_CONTEXT(3)\
972 GLOBAL_UNCERTAINTY_ASSIGNED_CONTEXT((#{uncertainty}))\
973 GLOBAL_UNIT_ASSIGNED_CONTEXT((#{length_unit},#{angle_unit},#{solid_angle_unit}))\
974 REPRESENTATION_CONTEXT('',''))"
975 ));
976 let parametric_context = writer.add(
981 "(GEOMETRIC_REPRESENTATION_CONTEXT(2)\
982 PARAMETRIC_REPRESENTATION_CONTEXT()\
983 REPRESENTATION_CONTEXT('2D SPACE',''))",
984 );
985 let origin = write_point(writer, Vec3::default())?;
986 let direction_z = writer.add("DIRECTION('',(0.,0.,1.))");
987 let direction_x = writer.add("DIRECTION('',(1.,0.,0.))");
988 let axis = writer.add(format!(
989 "AXIS2_PLACEMENT_3D('',#{origin},#{direction_z},#{direction_x})"
990 ));
991 Ok(StepFileContexts {
992 product_context,
993 definition_context,
994 geometry_context,
995 parametric_context,
996 length_unit,
997 angle_unit,
998 axis,
999 })
1000}
1001
1002pub(crate) struct ProductIds {
1006 pub definition: usize,
1007 pub product_shape: usize,
1008}
1009
1010pub(crate) fn write_product(
1016 writer: &mut StepWriter,
1017 contexts: &StepFileContexts,
1018 name: &str,
1019 id: &str,
1020 category: &str,
1021) -> ProductIds {
1022 let safe_name = step_string(name);
1023 let safe_id = step_string(if id.is_empty() { name } else { id });
1024 let product_context = contexts.product_context;
1025 let definition_context = contexts.definition_context;
1026 let product = writer.add(format!(
1027 "PRODUCT('{safe_id}','{safe_name}','',(#{product_context}))"
1028 ));
1029 writer.add(format!(
1030 "PRODUCT_RELATED_PRODUCT_CATEGORY('{}','',(#{product}))",
1031 step_string(category)
1032 ));
1033 let formation = writer.add(format!("PRODUCT_DEFINITION_FORMATION('','',#{product})"));
1034 let definition = writer.add(format!(
1035 "PRODUCT_DEFINITION('design','',#{formation},#{definition_context})"
1036 ));
1037 let product_shape = writer.add(format!("PRODUCT_DEFINITION_SHAPE('','',#{definition})"));
1038 ProductIds {
1039 definition,
1040 product_shape,
1041 }
1042}
1043
1044pub(crate) fn write_product_geometry(
1052 writer: &mut StepWriter,
1053 contexts: &StepFileContexts,
1054 bodies: &[(String, &BrepSolid)],
1055 report: &mut StepExportReport,
1056) -> Result<ProductGeometry, String> {
1057 for (_, solid) in bodies {
1058 let policy = KernelTolerances::for_solid(solid, 1e-7);
1059 let issues = solid.validate_with_tolerances(&KernelTolerances {
1060 pcurve_consistency: policy.export_knit,
1061 ..policy
1062 });
1063 if !issues.is_empty() {
1064 return Err(format!("export_step: invalid solid: {issues:?}"));
1065 }
1066 }
1067 let parametric_context = contexts.parametric_context;
1068 let mut written = ProductGeometry::default();
1069 for (solid_name, solid) in bodies {
1070 let solid = *solid;
1071 let solid_name = solid_name.as_str();
1072 let band = KernelTolerances::for_solid(solid, 1e-7).export_knit;
1073 let mut vertex_ids = HashMap::<u64, usize>::default();
1074 let mut edge_ids = HashMap::<u64, usize>::default();
1075 let mut surfaces = HashMap::<usize, (usize, bool, EmittedSurface)>::default();
1076 for shell in &solid.shells {
1077 for face in &shell.faces {
1082 let key = surface_key(face);
1083 if surfaces.contains_key(&key) {
1084 continue;
1085 }
1086 let entry = match write_analytic_surface(writer, &face.surface)? {
1087 Some(triple) => triple,
1088 None => (
1089 write_surface(writer, &face.surface)?,
1090 false,
1091 EmittedSurface::Spline,
1092 ),
1093 };
1094 surfaces.insert(key, entry);
1095 }
1096
1097 let mut edge_uses = HashMap::<u64, Vec<CoedgeUse>>::default();
1100 let mut edge_order: Vec<u64> = Vec::new();
1101 for face in &shell.faces {
1102 for loop_record in &face.loops {
1103 for coedge in &loop_record.coedges {
1104 let edge = edge_for(solid, coedge.edge_id)?;
1105 if edge.degenerate {
1106 continue;
1107 }
1108 let uses = edge_uses.entry(edge.id).or_default();
1109 if uses.is_empty() {
1110 edge_order.push(edge.id);
1111 }
1112 uses.push(CoedgeUse {
1113 surface_key: surface_key(face),
1114 face,
1115 coedge,
1116 });
1117 }
1118 }
1119 }
1120
1121 for edge_id in &edge_order {
1123 if edge_ids.contains_key(edge_id) {
1124 continue;
1125 }
1126 let edge = edge_for(solid, *edge_id)?;
1127 let subcurve = edge_subcurve(edge)?;
1128 let (curve, emitted_curve) = match write_analytic_curve(writer, &subcurve)? {
1129 Some(pair) => pair,
1130 None => (
1131 write_curve(writer, &subcurve)?,
1132 EmittedCurve::Spline { curve: subcurve },
1133 ),
1134 };
1135 let uses = &edge_uses[edge_id];
1136 let seam = uses.len() == 2 && uses[0].surface_key == uses[1].surface_key;
1140 let mut pcurves: Vec<(usize, Pcurve2d)> = Vec::new();
1141 let mut omitted = 0usize;
1142 if uses.len() == 2 {
1143 let mut ordered: Vec<&CoedgeUse> = uses.iter().collect();
1147 if seam && !ordered[0].coedge.forward {
1148 ordered.swap(0, 1);
1149 }
1150 for coedge_use in ordered {
1151 let oriented = if coedge_use.coedge.forward {
1156 coedge_use.coedge.pcurve.clone()
1157 } else {
1158 coedge_use.coedge.pcurve.reversed()?
1159 };
1160 let (surface_id, _, emitted_surface) = &surfaces[&coedge_use.surface_key];
1161 let outcome = build_pcurve(
1162 &coedge_use.face.surface,
1163 emitted_surface,
1164 &emitted_curve,
1165 &oriented,
1166 band,
1167 )?;
1168 match outcome.curve {
1169 Some(curve_2d) => {
1170 report.max_pcurve_deviation =
1171 report.max_pcurve_deviation.max(outcome.deviation);
1172 pcurves.push((*surface_id, curve_2d));
1173 }
1174 None => {
1175 omitted += 1;
1176 if outcome.deviation.is_finite() {
1177 report.worst_omitted_deviation =
1178 report.worst_omitted_deviation.max(outcome.deviation);
1179 } else {
1180 report.worst_omitted_deviation = f64::INFINITY;
1181 }
1182 }
1183 }
1184 }
1185 }
1186 if seam && pcurves.len() != 2 {
1190 omitted += pcurves.len();
1191 pcurves.clear();
1192 }
1193 report.pcurves_omitted += omitted;
1194 report.pcurves_written += pcurves.len();
1195 let geometry = if pcurves.is_empty() {
1196 report.bare_curves += 1;
1197 curve
1198 } else {
1199 let ids = pcurves
1200 .iter()
1201 .map(|(surface_id, curve_2d)| {
1202 write_pcurve_entity(
1203 writer,
1204 *surface_id,
1205 parametric_context,
1206 curve_2d,
1207 )
1208 })
1209 .collect::<Result<Vec<_>, String>>()?;
1210 let keyword = if seam {
1211 report.seam_curves += 1;
1212 "SEAM_CURVE"
1213 } else {
1214 report.surface_curves += 1;
1215 "SURFACE_CURVE"
1216 };
1217 writer.add(format!(
1223 "{keyword}('',#{curve},{},.CURVE_3D.)",
1224 id_list(&ids)
1225 ))
1226 };
1227 let start = vertex_step_id(writer, &mut vertex_ids, solid, edge.start_vertex_id)?;
1228 let end = vertex_step_id(writer, &mut vertex_ids, solid, edge.end_vertex_id)?;
1229 let step_id =
1230 writer.add(format!("EDGE_CURVE('',#{start},#{end},#{geometry},.T.)"));
1231 edge_ids.insert(edge.id, step_id);
1232 if let Some(edge_name) = edge.name.as_deref() {
1233 written.edges.push((edge_name.to_string(), step_id));
1234 }
1235 }
1236
1237 let mut face_ids = Vec::new();
1239 for face in &shell.faces {
1240 let mut bound_ids = Vec::new();
1241 for (loop_index, loop_record) in face.loops.iter().enumerate() {
1242 let mut oriented_edges = Vec::new();
1243 for coedge in &loop_record.coedges {
1244 let edge = edge_for(solid, coedge.edge_id)?;
1245 if edge.degenerate {
1246 continue;
1247 }
1248 let edge_id = *edge_ids
1249 .get(&edge.id)
1250 .ok_or_else(|| format!("export_step: unwritten edge {}", edge.id))?;
1251 let orientation = if coedge.forward { ".T." } else { ".F." };
1252 oriented_edges.push(
1253 writer.add(format!("ORIENTED_EDGE('',*,*,#{edge_id},{orientation})")),
1254 );
1255 }
1256 let kind = if loop_index == 0 {
1257 "FACE_OUTER_BOUND"
1258 } else {
1259 "FACE_BOUND"
1260 };
1261 if oriented_edges.is_empty() {
1262 let Some(coedge) = loop_record.coedges.first() else {
1275 continue;
1276 };
1277 let collapsed = edge_for(solid, coedge.edge_id)?;
1278 let vertex = vertex_step_id(
1279 writer,
1280 &mut vertex_ids,
1281 solid,
1282 collapsed.start_vertex_id,
1283 )?;
1284 let vertex_loop = writer.add(format!("VERTEX_LOOP('',#{vertex})"));
1285 report.vertex_loops += 1;
1286 bound_ids.push(writer.add(format!("{kind}('',#{vertex_loop},.T.)")));
1287 continue;
1288 }
1289 let edge_loop =
1290 writer.add(format!("EDGE_LOOP('',{})", id_list(&oriented_edges)));
1291 bound_ids.push(writer.add(format!("{kind}('',#{edge_loop},.T.)")));
1292 }
1293 let (surface, flipped, _) = surfaces[&surface_key(face)];
1294 let sense = if face.same_sense != flipped {
1298 ".T."
1299 } else {
1300 ".F."
1301 };
1302 let face_step_id = writer.add(format!(
1303 "ADVANCED_FACE('',{},#{surface},{sense})",
1304 id_list(&bound_ids)
1305 ));
1306 if let Some(face_name) = face.name.as_deref() {
1307 written.faces.push((face_name.to_string(), face_step_id));
1308 }
1309 face_ids.push(face_step_id);
1310 }
1311 let closed_shell = writer.add(format!("CLOSED_SHELL('',{})", id_list(&face_ids)));
1312 let body_id = writer.add(format!(
1313 "MANIFOLD_SOLID_BREP('{}',#{closed_shell})",
1314 step_string(solid_name)
1315 ));
1316 written.solids.push((solid_name.to_string(), body_id));
1317 }
1318 let mut points: Vec<(Vec3, usize)> = Vec::with_capacity(vertex_ids.len());
1320 for (vertex_id, step_id) in &vertex_ids {
1321 points.push((vertex_for(solid, *vertex_id)?.point, *step_id));
1322 }
1323 written.vertices.push((solid_name.to_string(), points));
1324 }
1325 Ok(written)
1326}
1327
1328pub(crate) fn finish_step_file(
1331 writer: StepWriter,
1332 name: &str,
1333 timestamp: &str,
1334 report: &mut StepExportReport,
1335) -> Result<(), String> {
1336 let safe_name = step_string(name);
1337 let safe_timestamp = step_string(timestamp);
1338 let output = [
1339 "ISO-10303-21;".to_string(),
1340 "HEADER;".to_string(),
1341 "FILE_DESCRIPTION((''),'2;1');".to_string(),
1342 format!(
1343 "FILE_NAME('{safe_name}.step','{safe_timestamp}',(''),(''),'brep-kernel-rs','brep-kernel-rs','');"
1344 ),
1345 "FILE_SCHEMA(('AP242_MANAGED_MODEL_BASED_3D_ENGINEERING_MIM_LF { 1 0 10303 442 1 1 4 }'));".to_string(),
1346 "ENDSEC;".to_string(),
1347 "DATA;".to_string(),
1348 writer.data(),
1349 "ENDSEC;".to_string(),
1350 "END-ISO-10303-21;".to_string(),
1351 String::new(),
1352 ]
1353 .join("\n");
1354 let manifold_issues = audit_step_manifold(&output);
1355 if !manifold_issues.is_empty() {
1356 return Err(format!(
1357 "export_step: emitted AP242 manifold audit failed: {}",
1358 manifold_issues.join("; ")
1359 ));
1360 }
1361 let pcurve_issues = audit_step_pcurves(&output);
1362 if !pcurve_issues.is_empty() {
1363 return Err(format!(
1364 "export_step: emitted AP242 pcurve audit failed: {}",
1365 pcurve_issues.join("; ")
1366 ));
1367 }
1368 report.text = output;
1369 Ok(())
1370}
1371
1372pub fn export_step_report_named(
1381 solids: &[(String, &BrepSolid)],
1382 name: &str,
1383 unit: &str,
1384 timestamp: &str,
1385 pmi: Option<&StepPmi<'_>>,
1386 colors: Option<&StepColors>,
1387) -> Result<StepExportReport, String> {
1388 if solids.is_empty() {
1389 return Err("export_step: at least one solid is required".into());
1390 }
1391 let mut report = StepExportReport {
1392 products: 1,
1393 ..StepExportReport::default()
1394 };
1395 let mut writer = StepWriter::default();
1396 let contexts = write_file_contexts(&mut writer, unit)?;
1397 let geometry = write_product_geometry(&mut writer, &contexts, solids, &mut report)?;
1398 let mut items = vec![contexts.axis];
1399 items.extend(geometry.solids.iter().map(|(_, id)| *id));
1400 let geometry_context = contexts.geometry_context;
1401 let representation = writer.add(format!(
1402 "ADVANCED_BREP_SHAPE_REPRESENTATION('',{},#{geometry_context})",
1403 id_list(&items)
1404 ));
1405 let product = write_product(&mut writer, &contexts, name, "", "part");
1406 let product_shape = product.product_shape;
1407 writer.add(format!(
1408 "SHAPE_DEFINITION_REPRESENTATION(#{product_shape},#{representation})"
1409 ));
1410 if let Some(colors) = colors.filter(|colors| !colors.is_empty()) {
1415 let items = styles::styled_items(&geometry, colors, &[String::new()]);
1416 report.styled_items = styles::write_geometry_styles(&mut writer, geometry_context, &items)?;
1417 }
1418 if let Some(pmi) = pmi {
1419 let mut names = StepNameMaps::default();
1420 names.register(
1421 &geometry,
1422 StepItemOwner {
1423 product_shape,
1424 representation,
1425 },
1426 "",
1427 &MAT4_IDENTITY,
1428 );
1429 let context = pmi::StepContext {
1430 product_shape,
1431 representation,
1432 geometry_context,
1433 length_unit: contexts.length_unit,
1434 angle_unit: contexts.angle_unit,
1435 faces: &names.faces,
1436 edges: &names.edges,
1437 vertices: &names.vertices,
1438 };
1439 report.pmi_unresolved_references = pmi::write_pmi(&mut writer, &context, pmi)?;
1440 }
1441 finish_step_file(writer, name, timestamp, &mut report)?;
1442 Ok(report)
1443}
1444
1445fn vertex_step_id(
1447 writer: &mut StepWriter,
1448 vertex_ids: &mut HashMap<u64, usize>,
1449 solid: &BrepSolid,
1450 id: u64,
1451) -> Result<usize, String> {
1452 if let Some(step_id) = vertex_ids.get(&id) {
1453 return Ok(*step_id);
1454 }
1455 let point = write_point(writer, vertex_for(solid, id)?.point)?;
1456 let step_id = writer.add(format!("VERTEX_POINT('',#{point})"));
1457 vertex_ids.insert(id, step_id);
1458 Ok(step_id)
1459}
1460
1461fn step_entity_bodies(step: &str) -> HashMap<u64, &str> {
1464 step.lines()
1465 .filter_map(|line| {
1466 let rest = line.strip_prefix('#')?;
1467 let (digits, body) = rest.split_once('=')?;
1468 Some((
1469 digits.parse::<u64>().ok()?,
1470 body.trim_end().trim_end_matches(';'),
1471 ))
1472 })
1473 .collect()
1474}
1475
1476fn step_entity_refs(body: &str) -> Vec<u64> {
1480 let mut refs = Vec::new();
1481 let bytes = body.as_bytes();
1482 let mut index = 0;
1483 while index < bytes.len() {
1484 if bytes[index] == b'#' {
1485 let start = index + 1;
1486 let mut end = start;
1487 while end < bytes.len() && bytes[end].is_ascii_digit() {
1488 end += 1;
1489 }
1490 if end > start {
1491 if let Ok(id) = body[start..end].parse::<u64>() {
1492 refs.push(id);
1493 }
1494 }
1495 index = end;
1496 } else {
1497 index += 1;
1498 }
1499 }
1500 refs
1501}
1502
1503pub fn audit_step_pcurves(step: &str) -> Vec<String> {
1516 let bodies = step_entity_bodies(step);
1517 let mut issues = Vec::new();
1518 for (id, body) in &bodies {
1519 if !body.starts_with("EDGE_CURVE(") {
1520 continue;
1521 }
1522 let refs = step_entity_refs(body);
1523 let Some(geometry) = refs.get(2) else {
1524 issues.push(format!("EDGE_CURVE #{id} has no edge_geometry"));
1525 continue;
1526 };
1527 let Some(wrapper) = bodies.get(geometry) else {
1528 issues.push(format!("EDGE_CURVE #{id} references missing #{geometry}"));
1529 continue;
1530 };
1531 let seam = wrapper.starts_with("SEAM_CURVE(");
1532 if !seam && !wrapper.starts_with("SURFACE_CURVE(") {
1533 continue;
1534 }
1535 let wrapper_refs = step_entity_refs(wrapper);
1536 let pcurves = &wrapper_refs[wrapper_refs.len().min(1)..];
1537 if pcurves.is_empty() || pcurves.len() > 2 || (seam && pcurves.len() != 2) {
1538 issues.push(format!(
1539 "#{geometry} carries {} associated geometries",
1540 pcurves.len()
1541 ));
1542 continue;
1543 }
1544 let mut surfaces = Vec::new();
1545 for pcurve in pcurves {
1546 let Some(pcurve_body) = bodies.get(pcurve) else {
1547 issues.push(format!("#{geometry} references missing #{pcurve}"));
1548 continue;
1549 };
1550 if !pcurve_body.starts_with("PCURVE(") {
1551 issues.push(format!("#{geometry} associate #{pcurve} is not a PCURVE"));
1552 continue;
1553 }
1554 let pcurve_refs = step_entity_refs(pcurve_body);
1555 let representation = pcurve_refs.get(1).and_then(|id| bodies.get(id));
1556 if !representation.is_some_and(|body| body.starts_with("DEFINITIONAL_REPRESENTATION("))
1557 {
1558 issues.push(format!(
1559 "PCURVE #{pcurve} has no DEFINITIONAL_REPRESENTATION"
1560 ));
1561 }
1562 if let Some(surface) = pcurve_refs.first() {
1563 surfaces.push(*surface);
1564 }
1565 }
1566 if surfaces.len() == 2 && (surfaces[0] == surfaces[1]) != seam {
1567 issues.push(format!(
1568 "#{geometry} pcurves name {} surface(s) but it is a {}",
1569 if surfaces[0] == surfaces[1] { 1 } else { 2 },
1570 if seam { "SEAM_CURVE" } else { "SURFACE_CURVE" }
1571 ));
1572 }
1573 }
1574 issues.sort();
1575 issues
1576}
1577
1578pub fn audit_step_manifold(step: &str) -> Vec<String> {
1583 let marker = "ORIENTED_EDGE('',*,*,#";
1584 let mut uses = HashMap::<u64, Vec<bool>>::default();
1585 for line in step.lines() {
1586 let Some(offset) = line.find(marker) else {
1587 continue;
1588 };
1589 let rest = &line[offset + marker.len()..];
1590 let digits = rest
1591 .chars()
1592 .take_while(|character| character.is_ascii_digit())
1593 .collect::<String>();
1594 let Ok(edge_id) = digits.parse::<u64>() else {
1595 continue;
1596 };
1597 let suffix = &rest[digits.len()..];
1598 let sense = suffix.starts_with(",.T.");
1599 uses.entry(edge_id).or_default().push(sense);
1600 }
1601 let mut issues = uses
1602 .into_iter()
1603 .filter_map(|(edge, senses)| {
1604 (senses.len() != 2 || senses[0] == senses[1]).then(|| {
1605 format!(
1606 "EDGE_CURVE #{edge} has {} uses with senses {:?}",
1607 senses.len(),
1608 senses
1609 )
1610 })
1611 })
1612 .collect::<Vec<_>>();
1613 issues.sort();
1614 issues
1615}
1616