brep_kernel/io/step_import/mod.rs
1//! STEP Part 21 import for NURBS and analytic surfaces, assemblies, and PMI.
2//!
3//! The importer reconstructs and validates BREP topology. Analytic carriers are
4//! converted to NURBS sized to the face bounds. Seam edges occupy opposite
5//! parameter boundaries, and collapsed pole bounds become degenerate edges so
6//! faces close and integrate correctly.
7//!
8//! Pcurves are DERIVED, by projecting each edge onto its carrier; a
9//! `SURFACE_CURVE`/`SEAM_CURVE` bundle contributes only its 3D curve.
10//!
11//! [`supplied`] can read the bundle's `PCURVE` associations instead and seat
12//! the vendor's own stated trim, and does so correctly, but it is OFF unless
13//! `BREP_SUPPLIED_PCURVES=1`. Not caution — measurement. Preferring a supplied
14//! pcurve helps only where the edge's 3D curve has drifted off its own carrier,
15//! and nothing distinguishes that case from the ones where it hurts: our own
16//! exporter writes exact analytic 3D curves with fitted pcurves, so seating the
17//! fit cost a round trip through our writer a factor of 4800 in volume
18//! fidelity. See `supplied::supplied_pcurves_enabled` for the full derivation.
19
20use crate::topology::{
21 BrepSolid, CoedgeRecord, EdgeRecord, FaceRecord, LoopRecord, ShellRecord, VertexRecord,
22};
23use crate::{
24 build_pcurve_on_surface_range, make_arc, make_extrusion, make_hyperbola, make_line,
25 make_parabola, make_plane, make_revolution, offset_surface, transform_brep, AffineTransform,
26 KernelRefusal, NurbsCurve, NurbsSurface, Vec3, Vec4,
27};
28use rustc_hash::{FxHashMap as HashMap, FxHashSet as HashSet};
29use std::collections::VecDeque;
30
31const TAU: f64 = std::f64::consts::TAU;
32
33pub(crate) mod parse;
34mod supplied;
35mod bodies;
36mod assembly;
37mod assembly_pmi;
38mod mapped;
39mod builder;
40mod geometry;
41mod styles;
42mod pmi;
43mod precision;
44mod trim_readings;
45mod tessellated;
46pub(crate) use bodies::import_lean;
47/// The projected-foot refinement's body face cap (`0` = uncapped); the
48/// soundness fixture sweep reads it to know which trims the import refined.
49#[cfg_attr(not(test), allow(unused_imports))]
50pub(crate) use builder::loops::projected_foot_refine_body_faces;
51
52use crate::appearance::{BodyAppearance, ImportedColor};
53use parse::*;
54use supplied::*;
55use bodies::*;
56use mapped::*;
57use builder::*;
58use geometry::*;
59use styles::*;
60pub use assembly::{read_step_assembly, StepAssembly, StepOccurrence, StepProduct};
61pub use assembly_pmi::{occurrence_ref_parts, rewrite_occurrence_refs, OCCURRENCE_REF_PREFIX};
62pub use mapped::StepMappedItemError;
63pub use pmi::read_step_pmi;
64pub use precision::STATED_PRECISION_INCONSISTENCY_RATIO;
65pub use trim_readings::{
66 import_step_trim_readings, StepBodyTrimReadings, StepEdgeReading, StepFaceReading,
67 StepSuppliedTrim, StepTrimReadings,
68};
69pub(crate) use pmi::decode_step_text as decode_step_text_for_tests;
70
71
72// ---------------------------------------------------------------------------
73// Topology assembly
74// ---------------------------------------------------------------------------
75
76/// Why one body did not import: the builders' legacy text, or a TYPED refusal
77/// from the one gate that mints one today, the shell-closure gate
78/// (`builder/closure.rs`). The class rides to the feature boundary through
79/// [`import_step_bodies`]; every other producer inside the importer still
80/// returns text and is preserved verbatim (typed-refusal plan, item 1).
81#[derive(Clone, Debug, PartialEq)]
82pub enum StepBodyError {
83 Text(String),
84 Refused(crate::KernelRefusal),
85}
86
87impl StepBodyError {
88 /// The human text either way — the refusal's own message, verbatim.
89 pub fn message(&self) -> &str {
90 match self {
91 Self::Text(text) => text,
92 Self::Refused(refusal) => &refusal.message,
93 }
94 }
95
96 /// Whether this is the shell-closure gate's refusal
97 /// (`RefusalClass::UnsoundResult { defect: SoundnessDefect::VectorArea }`,
98 /// `builder/closure.rs`): the one typed class the body lanes treat as a
99 /// REFUSED body rather than a body that failed to build. Every other
100 /// producer that went typed on 2026-10-03 (the pinched-vertex split, the
101 /// `BREP_WITH_VOIDS` certifications, the post-build validation) keeps the
102 /// outcome its text had: counted in `failed`, skipped on an opportunistic
103 /// surface-model sheet, never a whole-file refusal.
104 pub fn closure_refusal(&self) -> bool {
105 matches!(
106 self,
107 Self::Refused(crate::KernelRefusal {
108 class: crate::RefusalClass::UnsoundResult {
109 defect: crate::SoundnessDefect::VectorArea,
110 ..
111 },
112 ..
113 })
114 )
115 }
116
117 /// The same error with its text rewritten by `f`, the class untouched.
118 pub fn with_context(self, f: impl FnOnce(&str) -> String) -> Self {
119 match self {
120 Self::Text(text) => Self::Text(f(&text)),
121 Self::Refused(refusal) => Self::Refused(refusal.with_message(f)),
122 }
123 }
124}
125
126impl From<String> for StepBodyError {
127 fn from(text: String) -> Self {
128 Self::Text(text)
129 }
130}
131
132impl From<&str> for StepBodyError {
133 fn from(text: &str) -> Self {
134 Self::Text(text.to_string())
135 }
136}
137
138impl From<crate::KernelRefusal> for StepBodyError {
139 fn from(refusal: crate::KernelRefusal) -> Self {
140 Self::Refused(refusal)
141 }
142}
143
144impl std::fmt::Display for StepBodyError {
145 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146 f.write_str(self.message())
147 }
148}
149
150/// Public entry: parse a STEP Part 21 document and return one `BrepSolid` per
151/// MANIFOLD_SOLID_BREP, FACETED_BREP, or certified BREP_WITH_VOIDS. Every
152/// returned solid passes `validate()` and closes its shells' vector area to
153/// the import's bar; a file with a body the closure gate refuses is refused
154/// as a whole (see [`import_step_bodies`]).
155pub fn import_step(text: &str) -> Result<Vec<BrepSolid>, String> {
156 Ok(import_step_with_appearance(text)?.0)
157}
158
159/// [`import_step_with_appearance`] with the error TYPED: the lane the IMPORT3D
160/// feature uses, so a refused body reaches the app as a class and not only as
161/// text.
162///
163/// **A refused body refuses the import.** `collect_step_solids` skips a body
164/// that failed to build and returns the rest, counting it in `failed`, and
165/// until 2026-09-30 this entry point returned those bodies as a success —
166/// the count and the first error never left `ImportedBodies`, so a file with
167/// a body the importer could not build imported SILENTLY short. A body the
168/// closure gate refuses is a body the file describes and the kernel declines
169/// to certify, and returning the others as the file's contents would be the
170/// partial result the typed-refusal plan rules out ("partial geometry is not a
171/// successful result"). The feature has no per-body typed slot to say "five
172/// of seven" (`Fulfilment::rejected` is a closed selection-resolution kind),
173/// so the whole import is refused with the first body's class and a message
174/// naming every refused body; the report lane ([`import_step_report`]) keeps
175/// returning the bodies that did build beside the refusals, for tools that
176/// want to read them. Bodies that fail with TEXT keep the pre-2026-09-30
177/// behaviour (skipped, the rest returned) — changing that is the plan's
178/// migration of the builder boundary, not this gate's.
179pub fn import_step_bodies(text: &str) -> Result<ImportedStep, StepBodyError> {
180 // The trim readings feed only the report's diagnostics, which this lane
181 // never builds.
182 let imported = bodies::collect_step_solids_dropping_readings(text)?;
183 if let Some(first) = imported.refused_bodies.first() {
184 let others = imported.refused_bodies.len() - 1;
185 let refusal = if others == 0 {
186 first.clone()
187 } else {
188 let rest: Vec<String> = imported.refused_bodies[1..]
189 .iter()
190 .map(|refusal| refusal.message.clone())
191 .collect();
192 first.clone().with_message(|message| {
193 format!("{message} And {others} more: {}", rest.join(" "))
194 })
195 };
196 return Err(StepBodyError::Refused(refusal.with_message(|message| {
197 format!(
198 "{} of {} bodies refused as open; {}",
199 imported.refused_bodies.len(),
200 imported.solids.len() + imported.failed,
201 message
202 )
203 })));
204 }
205 if imported.solids.is_empty() {
206 // A SURFACE MODEL and nothing else (`BREP_STEP_SURFACE_MODEL_SHEETS`,
207 // default on, =0 restores the refusal): a file whose only bodies are
208 // open SHELL_BASED_SURFACE_MODEL shells, which the solid lane skips,
209 // reads as those sheets (`BodyKind::Sheet`), as the Parasolid and IGES
210 // lanes already read theirs. Until 2026-11-26 such a file was refused as
211 // having no body (step-conformance's bowl_01: five faces of a revolved
212 // bowl, written by Open CASCADE). A file with any solid, or any body
213 // that failed, is unchanged; so is a sheet read that fails or refuses.
214 if imported.failed == 0
215 && imported.sheets_skipped > 0
216 && crate::switch!("BREP_STEP_SURFACE_MODEL_SHEETS", true)
217 {
218 if let Ok(sheets) = bodies::collect_step_solids_with(text, true, false) {
219 if sheets.failed == 0 && sheets.refused_bodies.is_empty() && !sheets.solids.is_empty() {
220 return Ok(ImportedStep { solids: sheets.solids, appearances: sheets.appearances, approximations: Vec::new() });
221 }
222 }
223 }
224 // A file of AP242 tessellated solids and no B-rep body at all reads as
225 // polyhedra; a B-rep body that failed keeps its own error.
226 let entities = parse_data_section(text).map_err(StepBodyError::Text)?;
227 let brep = entities.values().any(|e| e.has("MANIFOLD_SOLID_BREP") || e.has("FACETED_BREP") || e.has("BREP_WITH_VOIDS"));
228 let solids = if brep || imported.failed > 0 {
229 Vec::new()
230 } else {
231 tessellated::tessellated_solids(&entities, derive_length_scale_mm(&entities)).map_err(StepBodyError::Text)?
232 };
233 if !solids.is_empty() {
234 let appearances = solids.iter().map(|_| BodyAppearance::default()).collect();
235 return Ok(ImportedStep { solids, appearances, approximations: Vec::new() });
236 }
237 return Err(StepBodyError::Text(imported.first_error.unwrap_or_else(|| {
238 "step_import: no MANIFOLD_SOLID_BREP/FACETED_BREP/BREP_WITH_VOIDS body imported (unsupported or invalid representation)"
239 .into()
240 })));
241 }
242 let approximations = imported
243 .closure_notes
244 .iter()
245 .enumerate()
246 .filter_map(|(index, note)| note.approximation().map(|a| (index, a.clone())))
247 .collect();
248 Ok(ImportedStep {
249 solids: imported.solids,
250 appearances: imported.appearances,
251 approximations,
252 })
253}
254
255/// What [`import_step_bodies`] returns: the bodies, their colours, and the
256/// typed approximations the closure gate attached to some of them.
257#[derive(Clone, Debug)]
258pub struct ImportedStep {
259 /// One solid per body that reconstructed, in file order.
260 pub solids: Vec<BrepSolid>,
261 /// One per solid, in the same order (default when the file has none).
262 pub appearances: Vec<BodyAppearance>,
263 /// `(index into solids, approximation)` for every body the closure gate
264 /// imported over its bar (`builder/closure.rs`): a typed statement that
265 /// the body's volume is determined only to the bound the approximation
266 /// carries. Empty on a file whose every body closes.
267 pub approximations: Vec<(usize, crate::Approximation)>,
268}
269
270/// [`import_step`] plus the file's PRESENTATION colours: one
271/// [`BodyAppearance`] per returned solid, in the same order.
272///
273/// This is the lane the IMPORT3D feature uses, because colour is stamped as
274/// scene metadata on the names IT chooses — see
275/// `feature_pipeline::features::import3d` and `io/appearance.rs` for the record
276/// shape. A file with no presentation entities returns default (empty)
277/// appearances, never a short vector, so callers can `zip` unconditionally.
278pub fn import_step_with_appearance(
279 text: &str,
280) -> Result<(Vec<BrepSolid>, Vec<BodyAppearance>), String> {
281 import_step_bodies(text)
282 .map(|imported| (imported.solids, imported.appearances))
283 .map_err(|error| error.to_string())
284}
285
286/// What [`import_step_report`] returns: the bodies, how gracefully the file
287/// imported, and the import's diagnostics.
288#[derive(Clone, Debug)]
289pub struct StepImportReport {
290 /// One solid per body that reconstructed, in file order.
291 pub solids: Vec<BrepSolid>,
292 /// The file's presentation colours, one per solid in the same order
293 /// (default where the file styles nothing), as
294 /// [`import_step_with_appearance`] returns them.
295 pub appearances: Vec<BodyAppearance>,
296 /// Things that did not come in (skipped, not fatal): a body that failed to
297 /// reconstruct, an occurrence whose transform failed, or a mapping that was
298 /// refused (`mapped::StepMappedItemError`).
299 pub failed: usize,
300 /// The first such failure's text, when `failed > 0`.
301 pub first_error: Option<String>,
302 /// The bodies the shell-closure gate refused, typed
303 /// (`RefusalClass::UnsoundResult { defect: SoundnessDefect::VectorArea }`),
304 /// in file order. Each is counted in `failed`. [`import_step`] and the
305 /// feature lane refuse the whole file on any of these; this lane returns
306 /// the bodies that did import beside them.
307 pub refused: Vec<crate::KernelRefusal>,
308 /// The bodies that FAILED to build with a typed cause that is not the
309 /// closure gate's, in file order: the pinched-vertex split, a
310 /// `BREP_WITH_VOIDS` certification, the post-build validation
311 /// (2026-10-03). Each is counted in `failed`, and the first is
312 /// `first_error`'s text; none refuses the whole file on any lane, which
313 /// is the outcome their text had.
314 pub failed_refusals: Vec<crate::KernelRefusal>,
315 /// Open surface-model sheets skipped (not solids, so not in `failed`);
316 /// also the counter `SHEETS_SKIPPED` in `diagnostics`.
317 pub sheets_skipped: usize,
318 /// `(index into solids, approximation)` for every imported body whose
319 /// shell closes over its bar (`import.shell_closure`); see
320 /// [`ImportedStep::approximations`].
321 pub approximations: Vec<(usize, crate::Approximation)>,
322 /// Every precision the file states, in millimetres, ascending — see
323 /// `parse::stated_precisions_mm`. Empty when it states none.
324 pub stated_precisions_mm: Vec<f64>,
325 /// The import's diagnostics: measurements always, plus one
326 /// `import.stated_precision_inconsistent` warning when the file's stated
327 /// precision is far under the deviation its own geometry shows
328 /// (`precision::stated_precision_diagnostics`). Informational only —
329 /// acceptance never depends on it.
330 pub diagnostics: crate::KernelDiagnostics,
331}
332
333/// The event code for a body that carries a derived trim off the fit bar (the
334/// 1e-7 floor plus its stations' standoff) after the refit at the floor, which
335/// the importer accepts as it did every fit before the bar, and the counters
336/// and measure beside it. The residual
337/// is the band `EntityTolerances` measures for that edge; the event names how
338/// many are the file's residual and how many the fitter's miss, and the worst
339/// with its numbers, so what the importer accepted before the bar silently is
340/// visible (2026-09-26). Since 2026-10-03 both numbers are read BETWEEN the
341/// fit's stations too (`geometry::trim_floor_reading`) and the class is the
342/// corrected bar's: a trim within the floor of the file curve's standoff is
343/// the file's residual whatever its image does along the carrier.
344pub const TRIM_BOUNDED: &str = "import.trim_bounded";
345pub const TRIMS_BOUNDED: &str = "import.trims_bounded";
346pub const TRIMS_FITTER_MISS: &str = "import.trims_fitter_miss";
347pub const TRIM_BOUND_MM: &str = "import.trim_bound_mm";
348/// Bounded trims whose fit was CLAMPED into the carrier's chart, and the worst
349/// 3D distance that clamp corresponds to (2026-09-30; a report, not a bar).
350pub const TRIMS_CLAMPED: &str = "import.trims_clamped";
351pub const TRIM_CLAMP_MM: &str = "import.trim_clamp_mm";
352
353/// The shell-closure gate's readings on the bodies it ACCEPTED
354/// (`builder/closure.rs`): the worst residual-to-bar ratio over the accepted
355/// bodies, how many bodies the scan could not judge (span budget or an
356/// unreadable face — accepted unjudged, one Degraded event each), and how
357/// many bodies it refused (also in [`StepImportReport::refused`]).
358pub const CLOSURE_RATIO_MAX: &str = "import.closure_ratio_max";
359pub const CLOSURE_APPROXIMATE: &str = "import.closure_approximate";
360pub const CLOSURE_UNJUDGED: &str = "import.closure_unjudged";
361pub const CLOSURE_REFUSED: &str = "import.closure_refused";
362
363/// Open `SHELL_BASED_SURFACE_MODEL` sheets the importer SKIPPED, counted
364/// where it drops them (the flat lane, the occurrence lane once per part, and
365/// [`import_step_assembly`] once per product body). A sheet is not a solid,
366/// so it is neither `failed` nor `refused`; before 2026-10-12 it vanished
367/// uncounted (table 3: ten in `BIMExample-Site.step`).
368pub const SHEETS_SKIPPED: &str = "import.sheets_skipped";
369
370fn closure_diagnostics(
371 notes: &[builder::ClosureNote],
372 refused: &[crate::KernelRefusal],
373 diagnostics: &mut crate::KernelDiagnostics,
374) {
375 for (index, note) in notes.iter().enumerate() {
376 match note {
377 builder::ClosureNote::Closed { residual, bar } => {
378 diagnostics.measure_max(CLOSURE_RATIO_MAX, residual / bar);
379 }
380 builder::ClosureNote::Approximate(approximation) => {
381 diagnostics.measure_max(CLOSURE_RATIO_MAX, approximation.measured / approximation.bar);
382 diagnostics.count(CLOSURE_APPROXIMATE);
383 diagnostics.event(
384 crate::DiagnosticSeverity::Degraded,
385 crate::KernelStage::Validate,
386 CLOSURE_APPROXIMATE,
387 format!("body {index}: {}", approximation.message),
388 );
389 }
390 builder::ClosureNote::Unmeasured { reason, spans } => {
391 diagnostics.count(CLOSURE_UNJUDGED);
392 diagnostics.event(
393 crate::DiagnosticSeverity::Degraded,
394 crate::KernelStage::Validate,
395 CLOSURE_UNJUDGED,
396 format!("body {index}: shell closure not judged — {reason} ({spans} spans); the body is accepted unjudged, not certified closed."),
397 );
398 }
399 builder::ClosureNote::Unreadable { first, count } => {
400 diagnostics.count(CLOSURE_UNJUDGED);
401 diagnostics.event(
402 crate::DiagnosticSeverity::Degraded,
403 crate::KernelStage::Validate,
404 CLOSURE_UNJUDGED,
405 format!("body {index}: shell closure not judged — {count} face(s) unreadable by the scan, first: {first}; the body is accepted unjudged, not certified closed."),
406 );
407 }
408 builder::ClosureNote::Unjudged => {
409 diagnostics.count(CLOSURE_UNJUDGED);
410 }
411 builder::ClosureNote::Overridden(refusal) => {
412 diagnostics.count(CLOSURE_UNJUDGED);
413 diagnostics.event(
414 crate::DiagnosticSeverity::Degraded,
415 crate::KernelStage::Validate,
416 CLOSURE_UNJUDGED,
417 format!("body {index}: the closure guard is OFF (BREP_IMPORT_CLOSURE_GUARD=0); it would have refused: {}", refusal.message),
418 );
419 }
420 }
421 }
422 diagnostics.count_n(CLOSURE_REFUSED, refused.len() as u64);
423}
424
425fn bounded_trim_diagnostics(
426 bounded: &[Vec<builder::readings::BoundedTrim>],
427 diagnostics: &mut crate::KernelDiagnostics,
428) {
429 for (index, trims) in bounded.iter().enumerate() {
430 let Some(worst) = trims
431 .iter()
432 .max_by(|a, b| a.residual.partial_cmp(&b.residual).unwrap_or(std::cmp::Ordering::Equal))
433 else {
434 continue;
435 };
436 let fitters = trims.iter().filter(|trim| trim.fitter).count();
437 let clamped = trims.iter().filter(|trim| trim.clamped_excursion > 0.0).count();
438 let worst_clamp = trims.iter().map(|trim| trim.clamped_distance).fold(0.0f64, f64::max);
439 diagnostics.count_n(TRIMS_BOUNDED, trims.len() as u64);
440 diagnostics.count_n(TRIMS_FITTER_MISS, fitters as u64);
441 diagnostics.measure_max(TRIM_BOUND_MM, worst.residual);
442 diagnostics.count_n(TRIMS_CLAMPED, clamped as u64);
443 diagnostics.measure_max(TRIM_CLAMP_MM, worst_clamp);
444 diagnostics.event(
445 crate::DiagnosticSeverity::Degraded,
446 crate::KernelStage::Collect,
447 TRIM_BOUNDED,
448 format!(
449 "body {index}: {} trim(s) sit off the {:.0e} mm fit bar and carry their measured residual as their band ({} of them the file's residual, within the floor of the curve's standoff read between the stations; {} the fitter's miss); worst ADVANCED_FACE #{} (surface #{}) edge {}: {:.3e} mm, its curve {:.3e} mm off the carrier, the image {:.3e} mm off its feet ({}; {} at {} samples).{}",
450 trims.len(),
451 crate::PCURVE_REFINEMENT_TOLERANCE,
452 trims.len() - fitters,
453 fitters,
454 worst.face_ref,
455 worst.surface_ref,
456 worst.edge_id,
457 worst.residual,
458 worst.standoff,
459 worst.image_to_foot,
460 if worst.fitter { "the fitter's miss" } else { "the file's residual" },
461 worst.exit,
462 worst.samples,
463 if clamped > 0 {
464 format!(" {clamped} of them were clamped into their chart, by up to {worst_clamp:.3e} mm.")
465 } else {
466 String::new()
467 }
468 ),
469 );
470 }
471}
472
473/// Like [`import_step`] but reports how many bodies failed and the first error,
474/// so callers can distinguish a fully- from a partially-imported assembly —
475/// and runs the stated-precision consistency check over the imported bodies,
476/// whose result rides in [`StepImportReport::diagnostics`].
477///
478/// The check measures every edge and vertex of every body (the same
479/// `EntityTolerances` reading the per-entity-tolerance census took), which is
480/// why it lives on this lane and not on [`import_step_with_appearance`]: the
481/// feature pipeline has no diagnostics channel to carry the answer, and a
482/// measurement nobody reads is not worth its cost on every IMPORT3D.
483pub fn import_step_report(text: &str) -> Result<StepImportReport, String> {
484 import_step_report_with(text, false, true)
485}
486
487/// [`import_step_report`] building every OPEN_SHELL as a sheet body
488/// (`BodyKind::Sheet`) among its solids, not skipping it: the Parasolid
489/// lane's, whose translation writes a sheet body as an open shell.
490pub(crate) fn import_step_report_with_sheets(text: &str) -> Result<StepImportReport, String> {
491 import_step_report_with(text, true, true)
492}
493
494/// The faces of a STEP file sewn into one solid where their edges lie within
495/// `tolerance` (mm) of each other: every body the file holds, an open shell or a
496/// face set read as a sheet, joined and sewn by [`crate::solid_from_sheets`].
497/// Refuses a file with nothing to sew, a body that did not reconstruct, and
498/// sheets that leave an edge open (saying how many) or do not close a valid
499/// solid.
500pub fn sew_step(text: &str, tolerance: f64) -> Result<crate::BrepSolid, crate::KernelRefusal> {
501 use crate::{KernelRefusal, KernelStage};
502 if !(tolerance.is_finite() && tolerance > 0.0) {
503 return Err(KernelRefusal::input(KernelStage::Collect, "sew_step_tolerance", format!("sew_step: tolerance {tolerance} must be positive")));
504 }
505 let report = import_step_report_with_sheets(text).map_err(|e| KernelRefusal::input(KernelStage::Collect, "sew_step_read", format!("sew_step: {e}")))?;
506 if report.failed > 0 {
507 return Err(KernelRefusal::input(
508 KernelStage::Collect,
509 "sew_step_body",
510 format!("sew_step: {} bodies did not reconstruct: {}", report.failed, report.first_error.unwrap_or_default()),
511 ));
512 }
513 if report.solids.is_empty() {
514 return Err(KernelRefusal::input(KernelStage::Collect, "sew_step_empty", "sew_step: the file holds no faces".to_string()));
515 }
516 crate::solid_from_sheets(&report.solids, tolerance)
517}
518
519/// [`import_step_report`] (with `sheets` as [`import_step_report_with_sheets`])
520/// for a caller that drops the report's trim-reading diagnostics: under
521/// `BREP_IMPORT_LEAN` the build skips them.
522pub(crate) fn import_step_report_dropping_readings(text: &str, sheets: bool) -> Result<StepImportReport, String> {
523 import_step_report_with(text, sheets, !bodies::import_lean())
524}
525
526/// Every `EDGE_BASED_WIREFRAME_MODEL` of a Part 21 document, in file order,
527/// as wire bodies (`BodyKind::Wire`, plan 3.3): the Parasolid lane's, whose
528/// translation writes a wire body as one. Ordinary STEP import does not read
529/// wireframes yet.
530pub(crate) fn import_step_wires(text: &str) -> Result<Vec<BrepSolid>, String> {
531 let entities = parse_data_section(text)?;
532 let resolver = Resolver::new(&entities, derive_length_scale_mm(&entities));
533 let mut models: Vec<usize> =
534 entities.iter().filter(|(_, e)| e.has("EDGE_BASED_WIREFRAME_MODEL")).map(|(&id, _)| id).collect();
535 models.sort_unstable();
536 models.into_iter().map(|id| build_wire(&resolver, id)).collect()
537}
538
539fn import_step_report_with(text: &str, sheets: bool, readings: bool) -> Result<StepImportReport, String> {
540 let imported = bodies::collect_step_solids_with(text, sheets, readings)?;
541 let mut diagnostics =
542 precision::stated_precision_diagnostics(&imported.stated_precisions_mm, &imported.solids);
543 bounded_trim_diagnostics(&imported.bounded_trims, &mut diagnostics);
544 closure_diagnostics(&imported.closure_notes, &imported.refused_bodies, &mut diagnostics);
545 diagnostics.count_n(SHEETS_SKIPPED, imported.sheets_skipped as u64);
546 if let Some(band) = imported.unstated_identity_band_mm {
547 diagnostics.measure_max(precision::UNSTATED_IDENTITY_BAND_MM, band);
548 }
549 Ok(StepImportReport {
550 solids: imported.solids,
551 appearances: imported.appearances,
552 failed: imported.failed,
553 first_error: imported.first_error,
554 refused: imported.refused_bodies,
555 failed_refusals: imported.failed_refusals,
556 sheets_skipped: imported.sheets_skipped,
557 approximations: imported
558 .closure_notes
559 .iter()
560 .enumerate()
561 .filter_map(|(index, note)| note.approximation().map(|a| (index, a.clone())))
562 .collect(),
563 stated_precisions_mm: imported.stated_precisions_mm,
564 diagnostics,
565 })
566}