Skip to main content

brep_kernel/io/iges/
import.rs

1//! IGES to kernel `BrepSolid`, by way of the STEP importer.
2//!
3//! Solids (186) and trimmed-surface sets (144, 143) are translated to Part 21
4//! ([`super::to_step`]) so they get the STEP builder, closure gate and refusals.
5//! Anything that cannot be read correctly is refused by name; a file never
6//! imports short.
7
8use crate::topology::BrepSolid;
9use crate::Vec3;
10use crate::{BodyAppearance, StepAssembly, StepOccurrence, StepProduct};
11use rustc_hash::FxHashMap as HashMap;
12
13use super::reader::{parse_iges, IgesFile};
14use super::structure::{self, Matrix, Placed};
15use super::to_step::{analyse_face_sets, free_shell_to_step, manifold_solid_to_step, trimmed_surfaces, FaceSets};
16
17/// Parse an IGES document and reconstruct one or more `BrepSolid`s.
18pub fn import_iges(text: &str) -> Result<Vec<BrepSolid>, String> {
19    Ok(import_iges_report(text)?.solids)
20}
21
22/// [`import_iges_report`] for a caller that drops the report's diagnostics
23/// (the IMPORT3D feature): under `BREP_IMPORT_LEAN` the STEP builds skip their
24/// trim readings, which only read the trims already chosen (on a 4917-face
25/// surface model they were most of the import). The bodies are the same.
26pub fn import_iges_bodies(text: &str) -> Result<IgesImportReport, String> {
27    let _lean = Lean::enter();
28    import_iges_report(text)
29}
30
31std::thread_local! {
32    /// Whether this thread's IGES import builds the trim readings: off inside
33    /// [`import_iges_bodies`] and [`read_iges_assembly`] under `BREP_IMPORT_LEAN`.
34    static TRIM_READINGS: std::cell::Cell<bool> = const { std::cell::Cell::new(true) };
35}
36
37/// Turns the trim readings off on this thread for its lifetime (when
38/// `BREP_IMPORT_LEAN` is on), restoring what was there.
39struct Lean(bool);
40
41impl Lean {
42    fn enter() -> Self {
43        let before = TRIM_READINGS.with(|readings| readings.get());
44        if crate::step_import::import_lean() {
45            TRIM_READINGS.with(|readings| readings.set(false));
46        }
47        Lean(before)
48    }
49}
50
51impl Drop for Lean {
52    fn drop(&mut self) {
53        TRIM_READINGS.with(|readings| readings.set(self.0));
54    }
55}
56
57/// One translated Part 21 document through the STEP lane, with sheets built
58/// as sheet bodies when `sheets`, and the trim readings when this thread's
59/// import wants them.
60fn step_report(step: &str, sheets: bool) -> Result<crate::StepImportReport, String> {
61    let readings = TRIM_READINGS.with(|readings| readings.get());
62    if readings {
63        if sheets {
64            crate::step_import::import_step_report_with_sheets(step)
65        } else {
66            crate::import_step_report(step)
67        }
68    } else {
69        crate::step_import::import_step_report_dropping_readings(step, sheets)
70    }
71    .map_err(|error| format!("iges_import: {error}"))
72}
73
74/// What [`import_iges_report`] returns: the solids, and the diagnostics the
75/// STEP lane measured while building them, merged over every body.
76#[derive(Clone, Debug)]
77pub struct IgesImportReport {
78    /// The solids, in file order: solids standing on their own, then each
79    /// subfigure instance's (408), placed.
80    pub solids: Vec<BrepSolid>,
81    /// Each solid's name (its 406 name property, else its directory label, else
82    /// the name of the instance that placed it), parallel to `solids`; empty
83    /// when the file gives none.
84    pub names: Vec<String>,
85    /// Each solid's colour (314, or the directory colour number), parallel to
86    /// `solids`, in the shape the STEP lane returns colours in.
87    pub appearances: Vec<BodyAppearance>,
88    /// Each solid's level (layer) number from its directory entry, parallel to
89    /// `solids`; 0 when unset, negative for a 406 list of levels.
90    pub levels: Vec<i64>,
91    /// The file's stated minimum resolution in mm (Global field 19), when it
92    /// states one.
93    pub stated_resolution_mm: Option<f64>,
94    /// Measurements and warnings, as `import_step_report` gives for STEP:
95    /// stated-precision consistency, bounded trims, closure readings.
96    pub diagnostics: crate::KernelDiagnostics,
97}
98
99/// [`import_iges`] with the import's diagnostics, the IGES counterpart of
100/// [`crate::import_step_report`].
101pub fn import_iges_report(text: &str) -> Result<IgesImportReport, String> {
102    let file = parse_iges(text)?;
103    let scale = file.global.length_scale_mm()?;
104    let stated = file.global.min_resolution * scale;
105    let mut diagnostics = crate::KernelDiagnostics::default();
106    let bodies = solids_with_diagnostics(&file, scale, &mut diagnostics)?;
107    let mut report = IgesImportReport {
108        solids: Vec::with_capacity(bodies.len()),
109        names: Vec::with_capacity(bodies.len()),
110        appearances: Vec::with_capacity(bodies.len()),
111        levels: Vec::with_capacity(bodies.len()),
112        stated_resolution_mm: (stated > 0.0 && stated.is_finite()).then_some(stated),
113        diagnostics,
114    };
115    for body in bodies {
116        report.solids.push(body.solid);
117        report.names.push(body.name.unwrap_or_default());
118        report.appearances.push(BodyAppearance { body: body.color, faces: body.faces });
119        report.levels.push(body.level);
120    }
121    Ok(report)
122}
123
124/// One imported solid and what the file said about it.
125struct Body {
126    solid: BrepSolid,
127    name: Option<String>,
128    color: Option<crate::ImportedColor>,
129    /// Each face's own colour in shell/face order, or empty when no face of
130    /// the body has one.
131    faces: FaceColors,
132    level: i64,
133}
134
135impl Body {
136    fn bare(solid: BrepSolid) -> Self {
137        Self { solid, name: None, color: None, faces: Vec::new(), level: 0 }
138    }
139}
140
141/// A body's per-face colours, as [`BodyAppearance::faces`] holds them.
142type FaceColors = Vec<Option<crate::ImportedColor>>;
143
144/// Each 186 built once, through the STEP lane, in its definition frame, with
145/// the colours its faces carry.
146type SolidCache = HashMap<i64, Vec<(BrepSolid, FaceColors)>>;
147
148/// Each subfigure's (308) trimmed-surface sets, sewn once in its own frame,
149/// keyed by the 308.
150type SetCache = HashMap<i64, Vec<BrepSolid>>;
151
152fn built_solid<'c>(
153    cache: &'c mut SolidCache,
154    file: &IgesFile,
155    pointer: i64,
156    scale: f64,
157    diagnostics: &mut crate::KernelDiagnostics,
158) -> Result<&'c [(BrepSolid, FaceColors)], String> {
159    if !cache.contains_key(&pointer) {
160        let (built, measured) = manifold_solid(file, pointer, scale)?;
161        merge_diagnostics(diagnostics, measured);
162        cache.insert(pointer, built);
163    }
164    Ok(&cache[&pointer])
165}
166
167/// A built solid moved by a placement; a mirroring placement turns it inside
168/// out unless the orientation is reversed with it.
169pub(super) fn place(solid: &BrepSolid, placement: &Matrix) -> Result<BrepSolid, String> {
170    if structure::is_identity(placement) {
171        return Ok(solid.clone());
172    }
173    let transform = crate::AffineTransform::new(*placement)?;
174    let mirrored = transform.determinant3() < 0.0;
175    crate::transform_brep(solid, transform, mirrored)
176}
177
178fn solids_with_diagnostics(
179    file: &IgesFile,
180    scale: f64,
181    diagnostics: &mut crate::KernelDiagnostics,
182) -> Result<Vec<Body>, String> {
183    // A file with explicit solids or shells goes down the STEP lane whole: same
184    // builder, same closure gate, same refusals. A solid a subfigure defines
185    // comes in once per instance, where the instance puts it; a shell no solid
186    // uses comes in as the STEP lane reads a surface model.
187    if file.entities_of_type(186).next().is_some() || file.entities_of_type(514).next().is_some() {
188        refuse_uncovered_geometry(file)?;
189        let mut cache = SolidCache::default();
190        let mut bodies = Vec::new();
191        for Placed { solid, placement, name, color, level } in structure::placed_solids(file, scale)? {
192            for (built, faces) in built_solid(&mut cache, file, solid, scale, diagnostics)? {
193                bodies.push(Body { solid: place(built, &placement)?, name: name.clone(), color, faces: faces.clone(), level });
194            }
195        }
196        bodies.extend(free_shell_bodies(file, scale, diagnostics)?);
197        if bodies.is_empty() {
198            let sheets = diagnostics.counters.get(crate::step_import::SHEETS_SKIPPED).copied().unwrap_or(0);
199            return Err(format!(
200                "iges_import: the file has no solids: its {sheets} shell(s) are sheets (open, or a single untrimmed face), not solids"
201            ));
202        }
203        return Ok(bodies);
204    }
205    // A file of trimmed surfaces whose subfigures are placed: the file's own
206    // sets, then each instance's sets where it puts them.
207    if file.entities_of_type(408).next().is_some() {
208        let bodies = placed_face_set_bodies(file, scale, diagnostics)?;
209        if bodies.is_empty() {
210            return Err(nothing_to_import(file));
211        }
212        return Ok(bodies);
213    }
214
215    if file.entities_of_type(144).next().is_none() && file.entities_of_type(143).next().is_none() {
216        return Err(nothing_to_import(file));
217    }
218    let (solids, measured) = face_set_solids(file, scale, &trimmed_surfaces(file))?;
219    for each in measured {
220        merge_diagnostics(diagnostics, each);
221    }
222    Ok(solids.into_iter().map(Body::bare).collect())
223}
224
225/// Why a file without solids or sewable surfaces imports nothing.
226fn nothing_to_import(file: &IgesFile) -> String {
227    if file.entities_of_type(144).next().is_none()
228        && file.entities_of_type(143).next().is_none()
229        && file.entities_of_type(128).next().is_some()
230    {
231        return "iges_import: file has untrimmed B-spline surfaces (entity 128) but no trimmed surfaces (entity 144) to form faces"
232            .into();
233    }
234    "iges_import: the file has no solids (186) or trimmed surfaces (144, 143) to import".into()
235}
236
237/// The trimmed surfaces no subfigure (308) lists: the file's own, in
238/// directory order.
239fn loose_surfaces(file: &IgesFile) -> Result<Vec<i64>, String> {
240    let members = structure::subfigure_member_set(file)?;
241    Ok(trimmed_surfaces(file).into_iter().filter(|pointer| !members.contains(pointer)).collect())
242}
243
244/// The file's own surface sets sewn into solids, refused as the flat import
245/// of a file without subfigures refuses them.
246fn loose_set_solids(
247    file: &IgesFile,
248    scale: f64,
249    diagnostics: &mut crate::KernelDiagnostics,
250) -> Result<Vec<BrepSolid>, String> {
251    let loose = loose_surfaces(file)?;
252    if loose.is_empty() {
253        return Ok(Vec::new());
254    }
255    let (solids, measured) = face_set_solids(file, scale, &loose)?;
256    for each in measured {
257        merge_diagnostics(diagnostics, each);
258    }
259    Ok(solids)
260}
261
262/// The solids a subfigure's (308) own trimmed surfaces sew into, in its own
263/// frame, built once however many instances place it. A set that does not
264/// sew refuses the file, naming the subfigure.
265fn subfigure_set_solids<'c>(
266    cache: &'c mut SetCache,
267    file: &IgesFile,
268    pointer: i64,
269    scale: f64,
270    diagnostics: &mut crate::KernelDiagnostics,
271) -> Result<&'c [BrepSolid], String> {
272    if !cache.contains_key(&pointer) {
273        let mut surfaces = Vec::new();
274        for member in structure::subfigure_members(file.entity(pointer)?)? {
275            if matches!(file.entity(member)?.de.entity_type, 144 | 143) {
276                surfaces.push(member);
277            }
278        }
279        surfaces.sort_unstable();
280        surfaces.dedup();
281        let mut solids = Vec::new();
282        if !surfaces.is_empty() {
283            let (built, measured) =
284                face_set_solids(file, scale, &surfaces).map_err(|error| format!("subfigure DE {pointer}: {error}"))?;
285            for each in measured {
286                merge_diagnostics(diagnostics, each);
287            }
288            solids = built;
289        }
290        cache.insert(pointer, solids);
291    }
292    Ok(&cache[&pointer])
293}
294
295/// A file of trimmed surfaces with subfigure instances, flattened: the
296/// file's own sets, then each instance's sets placed, in file order.
297fn placed_face_set_bodies(
298    file: &IgesFile,
299    scale: f64,
300    diagnostics: &mut crate::KernelDiagnostics,
301) -> Result<Vec<Body>, String> {
302    // The structure's refusals come before any sewing.
303    let placed = structure::placed_face_sets(file, scale)?;
304    let mut bodies: Vec<Body> = loose_set_solids(file, scale, diagnostics)?.into_iter().map(Body::bare).collect();
305    let mut cache = SetCache::default();
306    for Placed { solid: definition, placement, name, color, level } in placed {
307        for built in subfigure_set_solids(&mut cache, file, definition, scale, diagnostics)? {
308            bodies.push(Body { solid: place(built, &placement)?, name: name.clone(), color, faces: Vec::new(), level });
309        }
310    }
311    Ok(bodies)
312}
313
314/// The file's subfigure structure, the IGES counterpart of
315/// [`crate::read_step_assembly`]: one product for the file itself holding the
316/// solids that stand on their own, one per instanced subfigure (308) holding
317/// its own solids in its own frame, and one occurrence per instance (408) with
318/// its placement in millimetres. `Ok(None)` when the file places no
319/// subfigures, so the caller takes the flat import as for STEP.
320///
321/// A file of trimmed surfaces (144, 143) without solids reads the same way:
322/// each instanced subfigure's product holds the solids its own surfaces sew
323/// into, and the root product the file's own sets.
324///
325/// Every solid is built once, as in the flat import, and a file the flat
326/// import refuses is refused here with the same words: an assembly never
327/// comes in short.
328pub fn read_iges_assembly(text: &str) -> Result<Option<StepAssembly>, String> {
329    // The structure reads no trim readings: the build skips them as for
330    // [`import_iges_bodies`].
331    let _lean = Lean::enter();
332    let file = parse_iges(text)?;
333    let members = structure::subfigure_member_set(&file)?;
334    let top_instances: Vec<i64> = file
335        .pointers_of_type(408)
336        .into_iter()
337        .map(|(pointer, _)| pointer)
338        .filter(|pointer| !members.contains(pointer))
339        .collect();
340    if top_instances.is_empty() {
341        return Ok(None);
342    }
343    // The flat import's checks and refusals, once, before any structure.
344    let scale = file.global.length_scale_mm()?;
345    if file.entities_of_type(186).next().is_none() && file.entities_of_type(514).next().is_none() {
346        return face_set_assembly(&file, scale, top_instances).map(Some);
347    }
348    if file.entities_of_type(186).next().is_none() {
349        return Err(
350            "iges_import: the file places subfigures (408) of trimmed surfaces, which this import cannot build yet"
351                .into(),
352        );
353    }
354    refuse_uncovered_geometry(&file)?;
355    structure::placed_solids(&file, scale)?;
356
357    let mut cache = SolidCache::default();
358    let mut sets = SetCache::default();
359    let mut diagnostics = crate::KernelDiagnostics::default();
360    let mut assembly = root_only_assembly(&file);
361    for (pointer, solid) in file.pointers_of_type(186) {
362        if !members.contains(&pointer) {
363            let color = structure::entity_color(&file, solid);
364            for (built, faces) in built_solid(&mut cache, &file, pointer, scale, &mut diagnostics)? {
365                assembly.products[0].bodies.push(built.clone());
366                assembly.products[0].appearances.push(BodyAppearance { body: color, faces: faces.clone() });
367            }
368        }
369    }
370    for body in free_shell_bodies(&file, scale, &mut diagnostics)? {
371        assembly.products[0].bodies.push(body.solid);
372        assembly.products[0].appearances.push(BodyAppearance { body: body.color, faces: body.faces });
373    }
374    assembly.sheets_skipped = diagnostics.counters.get(crate::step_import::SHEETS_SKIPPED).copied().unwrap_or(0) as usize;
375    let mut products: HashMap<i64, usize> = HashMap::default();
376    for pointer in top_instances {
377        add_instance(&file, scale, pointer, 0, &mut assembly, &mut products, (&mut cache, &mut sets), &mut diagnostics, 0)?;
378    }
379    Ok(Some(assembly))
380}
381
382/// The assembly with only its root product, the file itself, and nothing in it.
383fn root_only_assembly(file: &IgesFile) -> StepAssembly {
384    let root_name = {
385        let product = file.global.product_id.trim();
386        if product.is_empty() { "IGES".to_string() } else { product.to_string() }
387    };
388    StepAssembly {
389        products: vec![StepProduct {
390            pd_ref: 0,
391            name: root_name,
392            id: String::new(),
393            bodies: Vec::new(),
394            appearances: Vec::new(),
395            failed_bodies: 0,
396            pmi: None,
397        }],
398        occurrences: Vec::new(),
399        roots: vec![0],
400        first_error: None,
401        pmi: None,
402        pmi_diagnostics: Vec::new(),
403        sheets_skipped: 0,
404    }
405}
406
407/// [`read_iges_assembly`] for a file of trimmed surfaces: every set the flat
408/// import would sew is sewn first, in the flat import's order, so a file it
409/// refuses is refused here with the same words before any structure.
410fn face_set_assembly(file: &IgesFile, scale: f64, top_instances: Vec<i64>) -> Result<StepAssembly, String> {
411    let mut diagnostics = crate::KernelDiagnostics::default();
412    let placed = structure::placed_face_sets(file, scale)?;
413    let loose = loose_set_solids(file, scale, &mut diagnostics)?;
414    let mut sets = SetCache::default();
415    let mut any = !loose.is_empty();
416    for each in &placed {
417        // Each instance placed as the flat import places it, so a placement it
418        // cannot apply (singular, or one taking the geometry out of range) is
419        // refused here with its words, not carried as an occurrence that
420        // cannot be built.
421        for solid in subfigure_set_solids(&mut sets, file, each.solid, scale, &mut diagnostics)? {
422            place(solid, &each.placement)?;
423            any = true;
424        }
425    }
426    if !any {
427        return Err(nothing_to_import(file));
428    }
429    let mut assembly = root_only_assembly(file);
430    for solid in loose {
431        assembly.products[0].bodies.push(solid);
432        assembly.products[0].appearances.push(BodyAppearance { body: None, faces: Vec::new() });
433    }
434    let mut cache = SolidCache::default();
435    let mut products: HashMap<i64, usize> = HashMap::default();
436    for pointer in top_instances {
437        add_instance(file, scale, pointer, 0, &mut assembly, &mut products, (&mut cache, &mut sets), &mut diagnostics, 0)?;
438    }
439    Ok(assembly)
440}
441
442/// One 408 as an occurrence under `parent`, its subfigure as a product (added
443/// once, however many instances place it), and the subfigure's own instances
444/// beneath it.
445#[allow(clippy::too_many_arguments)]
446fn add_instance(
447    file: &IgesFile,
448    scale: f64,
449    pointer: i64,
450    parent: usize,
451    assembly: &mut StepAssembly,
452    products: &mut HashMap<i64, usize>,
453    (cache, sets): (&mut SolidCache, &mut SetCache),
454    diagnostics: &mut crate::KernelDiagnostics,
455    depth: usize,
456) -> Result<(), String> {
457    if depth > 64 {
458        return Err(format!("iges_import: instance DE {pointer} nests deeper than 64 levels"));
459    }
460    let instance = file.entity(pointer)?;
461    let (definition_pointer, definition) = structure::instanced_subfigure(file, pointer)?;
462    let child = match products.get(&definition_pointer) {
463        Some(&index) => index,
464        None => {
465            let index = assembly.products.len();
466            products.insert(definition_pointer, index);
467            assembly.products.push(StepProduct {
468                pd_ref: definition_pointer as usize,
469                name: structure::entity_name(file, definition).unwrap_or_else(|| format!("subfigure#{definition_pointer}")),
470                id: String::new(),
471                bodies: Vec::new(),
472                appearances: Vec::new(),
473                failed_bodies: 0,
474                pmi: None,
475            });
476            // The subfigure's own trimmed surfaces, sewn in its frame.
477            let color = structure::entity_color(file, definition);
478            for solid in subfigure_set_solids(sets, file, definition_pointer, scale, diagnostics)?.to_vec() {
479                assembly.products[index].bodies.push(solid);
480                assembly.products[index].appearances.push(BodyAppearance { body: color, faces: Vec::new() });
481            }
482            for member in structure::subfigure_members(definition)? {
483                let entity = file.entity(member)?;
484                match entity.de.entity_type {
485                    186 => {
486                        let color = structure::entity_color(file, entity);
487                        let built = built_solid(cache, file, member, scale, diagnostics)?.to_vec();
488                        let product = &mut assembly.products[index];
489                        for (solid, faces) in built {
490                            product.bodies.push(solid);
491                            product.appearances.push(BodyAppearance { body: color, faces });
492                        }
493                    }
494                    408 => add_instance(
495                        file,
496                        scale,
497                        member,
498                        index,
499                        assembly,
500                        products,
501                        (&mut *cache, &mut *sets),
502                        diagnostics,
503                        depth + 1,
504                    )?,
505                    _ => {}
506                }
507            }
508            index
509        }
510    };
511    let placement = structure::instance_matrix(file, instance, scale)?;
512    let rigid = crate::AffineTransform::new(placement).is_ok_and(|transform| transform.is_rigid(1e-9));
513    // An instance's colour in IGES is INHERITED: a body's or an inner
514    // instance's own colour wins over it, as the flat import reads it. As a
515    // whole-instance colour (which colours everything the instance places) it
516    // is given only where nothing beneath is coloured on its own; otherwise it
517    // goes to the child's own uncoloured bodies alone.
518    let (color, body_colors) = match structure::entity_color(file, instance) {
519        None => (None, Vec::new()),
520        Some(own) if !coloured_below(file, definition_pointer, 0)? => (Some(own), Vec::new()),
521        Some(own) => {
522            let bodies: Vec<Option<crate::ImportedColor>> = assembly.products[child]
523                .appearances
524                .iter()
525                .map(|appearance| appearance.body.is_none().then_some(own))
526                .collect();
527            let any = bodies.iter().any(Option::is_some);
528            (None, if any { bodies } else { Vec::new() })
529        }
530    };
531    assembly.occurrences.push(StepOccurrence {
532        edge_ref: pointer as usize,
533        parent,
534        child,
535        designator: structure::entity_name(file, instance).unwrap_or_else(|| format!("instance#{pointer}")),
536        placement,
537        rigid,
538        color,
539        body_colors,
540    });
541    Ok(())
542}
543
544/// Whether anything a subfigure places carries a colour of its own: the
545/// subfigure itself (its surface sets take it), a member solid, or a member
546/// instance, at any depth.
547fn coloured_below(file: &IgesFile, definition_pointer: i64, depth: usize) -> Result<bool, String> {
548    if depth > 64 {
549        return Err(format!("iges_import: subfigure DE {definition_pointer} nests deeper than 64 levels"));
550    }
551    let definition = file.entity(definition_pointer)?;
552    if structure::entity_color(file, definition).is_some() {
553        return Ok(true);
554    }
555    for member in structure::subfigure_members(definition)? {
556        let entity = file.entity(member)?;
557        match entity.de.entity_type {
558            186 if structure::entity_color(file, entity).is_some() => return Ok(true),
559            408 => {
560                if structure::entity_color(file, entity).is_some() {
561                    return Ok(true);
562                }
563                let (inner, _) = structure::instanced_subfigure(file, member)?;
564                if coloured_below(file, inner, depth + 1)? {
565                    return Ok(true);
566                }
567            }
568            _ => {}
569        }
570    }
571    Ok(false)
572}
573
574/// Fold one body's diagnostics into the file's: events and counts add up, and
575/// each measurement keeps its worst reading, as `measure_max` does.
576fn merge_diagnostics(into: &mut crate::KernelDiagnostics, from: crate::KernelDiagnostics) {
577    into.events.extend(from.events);
578    for (key, count) in from.counters {
579        *into.counters.entry(key).or_insert(0) += count;
580    }
581    for (key, value) in from.measurements {
582        let slot = into.measurements.entry(key).or_insert(value);
583        if value > *slot {
584            *slot = value;
585        }
586    }
587}
588
589/// Build trimmed surfaces (`surfaces`, in directory order) into solids: one
590/// solid per connected, closed set of faces, and a set lying inside another
591/// becomes its cavity.
592fn face_set_solids(
593    file: &IgesFile,
594    scale: f64,
595    surfaces: &[i64],
596) -> Result<(Vec<BrepSolid>, Vec<crate::KernelDiagnostics>), String> {
597    let sets = analyse_face_sets(file, scale, surfaces)?;
598    // A set that does not close bounds no volume: it comes in as the sheet it
599    // is, every face of it, not refused and not dropped. `BREP_IGES_OPEN_SHEETS`
600    // (default on; `=0` refuses the file, naming the open set).
601    let as_sheets = crate::switch!("BREP_IGES_OPEN_SHEETS", true);
602    let mut sheets = Vec::new();
603    let mut sheet_readings = Vec::new();
604    let mut closed = Vec::with_capacity(sets.bodies.len());
605    for body in &sets.bodies {
606        match sets.open_reason(body) {
607            None => closed.push(body.as_slice()),
608            Some(reason) if !as_sheets => return Err(reason),
609            Some(reason) => {
610                let (sheet, readings) = face_set_sheet(&sets, file, scale, body).map_err(|error| format!("{reason}; as a sheet: {error}"))?;
611                sheets.push(sheet);
612                sheet_readings.push(readings);
613            }
614        }
615    }
616    let mut built = Vec::with_capacity(closed.len());
617    for body in &closed {
618        built.push(face_set_body(&sets, file, scale, body, &[])?);
619    }
620    // Every body that lies inside another, whatever their sizes: no order of
621    // boxes or volumes is sure to put a container before what it holds. A
622    // body inside an odd number of others is a cavity of the one it is
623    // directly in (inside one fewer); inside an even number (none, or an
624    // island in a cavity) it is a solid of its own.
625    let reach: Vec<_> = built.iter().map(|body| brep_topology::recentre::solid_bounds(&body.solid)).collect();
626    let corners: Vec<_> = built.iter().map(|body| vertex_box(&body.solid)).collect();
627    let mut containers: Vec<Vec<usize>> = vec![Vec::new(); built.len()];
628    for inner in 0..built.len() {
629        for outer in 0..built.len() {
630            let fits = |axis: fn(Vec3) -> f64| {
631                axis(corners[inner].0) >= axis(reach[outer].minimum) && axis(corners[inner].1) <= axis(reach[outer].maximum)
632            };
633            if inner != outer
634                && fits(|p| p.x)
635                && fits(|p| p.y)
636                && fits(|p| p.z)
637                && inside(&built[inner].solid, &built[outer].solid)?
638            {
639                containers[inner].push(outer);
640            }
641        }
642    }
643    let mut cavities: Vec<Vec<usize>> = vec![Vec::new(); built.len()];
644    let mut is_cavity = vec![false; built.len()];
645    for inner in 0..built.len() {
646        let depth = containers[inner].len();
647        if depth % 2 == 1 {
648            if let Some(&parent) = containers[inner].iter().find(|&&outer| containers[outer].len() == depth - 1) {
649                cavities[parent].push(inner);
650                is_cavity[inner] = true;
651            }
652        }
653    }
654    let mut solids = Vec::with_capacity(built.len());
655    let mut measured = Vec::with_capacity(built.len());
656    for index in 0..built.len() {
657        if is_cavity[index] {
658            continue;
659        }
660        if cavities[index].is_empty() {
661            solids.push(built[index].solid.clone());
662            measured.push(built[index].diagnostics.clone());
663            continue;
664        }
665        let voids: Vec<(&[usize], bool)> = cavities[index].iter().map(|&cavity| (closed[cavity], !built[cavity].flip)).collect();
666        let with_cavities = face_set_body(&sets, file, scale, closed[index], &voids)?;
667        solids.push(with_cavities.solid);
668        measured.push(with_cavities.diagnostics);
669    }
670    solids.extend(sheets);
671    measured.extend(sheet_readings);
672    Ok((solids, measured))
673}
674
675/// One face set that does not close, through the STEP lane as a sheet body
676/// (an open shell of a surface model); a twice-walked edge is read as written
677/// first, then as a bridge.
678fn face_set_sheet(
679    sets: &FaceSets,
680    file: &IgesFile,
681    scale: f64,
682    body: &[usize],
683) -> Result<(BrepSolid, crate::KernelDiagnostics), String> {
684    let mut first_failure = None;
685    for split in [false, true] {
686        let text = sets.to_step_sheet(file, scale, body, split)?;
687        let built = step_report(&text, true).and_then(|report| {
688                if report.failed > 0 || report.solids.len() != 1 {
689                    return Err(format!(
690                        "iges_import: {}",
691                        report.first_error.as_deref().unwrap_or("the sheet did not build as one body")
692                    ));
693                }
694                Ok(report)
695            });
696        match built {
697            Ok(mut report) => {
698                let sheet = report.solids.remove(0);
699                collapsed_face_refusal(&sheet)?;
700                return Ok((sheet, report.diagnostics));
701            }
702            Err(error) => {
703                first_failure.get_or_insert(error);
704            }
705        }
706    }
707    Err(first_failure.unwrap_or_default())
708}
709
710struct BuiltBody {
711    solid: BrepSolid,
712    flip: bool,
713    diagnostics: crate::KernelDiagnostics,
714}
715
716/// One closed face set through the STEP lane as one solid (the builder turns
717/// it outward); a twice-walked edge is read as written first, then as a
718/// bridge.
719fn face_set_body(
720    sets: &FaceSets,
721    file: &IgesFile,
722    scale: f64,
723    body: &[usize],
724    voids: &[(&[usize], bool)],
725) -> Result<BuiltBody, String> {
726    let mut first_failure = None;
727    for split in [false, true] {
728        for flip in [false, true] {
729            let text = sets.to_step(file, scale, body, voids, flip, split)?;
730            match solids_or_refusal(&text) {
731                Ok((mut solids, diagnostics)) if solids.len() == 1 => {
732                    // A set of trimmed surfaces carries no face colours here.
733                    // The STEP builder has already turned the solid outward by
734                    // its volume's sign; only that sign is read again here (the
735                    // exact integral was a fifth of a 4236-face import), so a
736                    // shell enclosing nothing is still refused.
737                    let (solid, _) = solids.remove(0);
738                    let sign = crate::solid_signed_volume_for_sign(&solid, 0.0).or_else(|_| crate::solid_signed_volume(&solid))?;
739                    if sign > 0.0 {
740                        return Ok(BuiltBody { solid, flip, diagnostics });
741                    }
742                }
743                Ok(_) => {}
744                Err(error) => {
745                    first_failure.get_or_insert(error);
746                }
747            }
748        }
749    }
750    Err(first_failure.unwrap_or_else(|| {
751        format!("iges_import: a set of {} trimmed surfaces built no solid with positive volume", body.len())
752    }))
753}
754
755/// The corners of the box round a solid's vertices. A body inside another has
756/// its vertices inside the other's surfaces' control nets, which bound it.
757fn vertex_box(solid: &BrepSolid) -> (Vec3, Vec3) {
758    let mut low = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
759    let mut high = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
760    for vertex in &solid.vertices {
761        let p = vertex.point;
762        low = Vec3::new(low.x.min(p.x), low.y.min(p.y), low.z.min(p.z));
763        high = Vec3::new(high.x.max(p.x), high.y.max(p.y), high.z.max(p.z));
764    }
765    (low, high)
766}
767
768/// Whether `inner` lies inside `outer` (a cavity of it), judged at up to 16
769/// of its vertices spread through its list: every one must be in. A body one
770/// vertex of which is in and another out crosses or touches the outer one's
771/// boundary: two bodies, not a solid and its void.
772fn inside(inner: &BrepSolid, outer: &BrepSolid) -> Result<bool, String> {
773    const READINGS: usize = 16;
774    let count = inner.vertices.len();
775    if count == 0 {
776        return Ok(false);
777    }
778    let step = count.div_ceil(READINGS).max(1);
779    for vertex in inner.vertices.iter().step_by(step) {
780        if crate::classify_point(vertex.point, outer, 1e-6)?.class != crate::PointClass::In {
781            return Ok(false);
782        }
783    }
784    Ok(true)
785}
786
787/// The 514 shells no 186 uses, in file order. An OCC-written file carries a
788/// STEP SHELL_BASED_SURFACE_MODEL this way.
789fn free_shells(file: &IgesFile) -> Result<Vec<i64>, String> {
790    let mut used_shells: rustc_hash::FxHashSet<i64> = Default::default();
791    for (_, solid) in file.pointers_of_type(186) {
792        used_shells.insert(solid.int(0)?);
793        for index in 0..solid.int(2)?.max(0) as usize {
794            used_shells.insert(solid.int(3 + index * 2)?);
795        }
796    }
797    Ok(file
798        .pointers_of_type(514)
799        .into_iter()
800        .map(|(pointer, _)| pointer)
801        .filter(|pointer| !used_shells.contains(pointer))
802        .collect())
803}
804
805/// Refuse a file holding trimmed surfaces beside its solids. Importing only
806/// the solids would drop them and look like a complete import.
807fn refuse_uncovered_geometry(file: &IgesFile) -> Result<(), String> {
808    let free_faces = [144, 143]
809        .iter()
810        .flat_map(|&kind| file.pointers_of_type(kind))
811        .filter(|(_, entity)| entity.de.subordinate == 0)
812        .count();
813    if free_faces > 0 {
814        return Err(format!(
815            "iges_import: the file holds {free_faces} trimmed surface(s) outside its solids, which this import cannot build yet; importing the solids alone would leave them out"
816        ));
817    }
818    Ok(())
819}
820
821/// Each free shell through the STEP lane: a closed shell of several faces as
822/// the solid a 186 would make of it, refused by name if it fails as one; a
823/// sheet (open, or a single untrimmed face) is not a solid and is counted in
824/// `SHEETS_SKIPPED`, never dropped silently.
825fn free_shell_bodies(
826    file: &IgesFile,
827    scale: f64,
828    diagnostics: &mut crate::KernelDiagnostics,
829) -> Result<Vec<Body>, String> {
830    let mut bodies = Vec::new();
831    for pointer in free_shells(file)? {
832        let entity = file.entity(pointer)?;
833        let whole_text = free_shell_to_step(file, pointer, scale, false)?;
834        let report = match surface_model_report(&whole_text) {
835            Ok(report) => report,
836            Err(first_failure) => {
837                let split_text = free_shell_to_step(file, pointer, scale, true)?;
838                if split_text == whole_text {
839                    return Err(format!("shell DE {pointer}: {first_failure}"));
840                }
841                surface_model_report(&split_text).map_err(|_| format!("shell DE {pointer}: {first_failure}"))?
842            }
843        };
844        if report.solids.is_empty() && report.sheets_skipped == 0 {
845            // The STEP lane skips a single-face surface model as reference
846            // geometry without counting it; here it is counted with the sheets.
847            diagnostics.count_n(crate::step_import::SHEETS_SKIPPED, 1);
848        }
849        let faces = face_colors(&report);
850        merge_diagnostics(diagnostics, report.diagnostics);
851        for (solid, faces) in report.solids.into_iter().zip(faces) {
852            bodies.push(Body {
853                solid,
854                name: structure::entity_name(file, entity),
855                color: structure::entity_color(file, entity),
856                faces,
857                level: entity.de.level,
858            });
859        }
860    }
861    Ok(bodies)
862}
863
864/// A surface model through the STEP lane: what it built, refusing a shell that
865/// reached the solid builder and failed there.
866fn surface_model_report(step: &str) -> Result<crate::StepImportReport, String> {
867    let report = step_report(step, false)?;
868    if report.failed > 0 {
869        return Err(format!(
870            "iges_import: {}",
871            report.first_error.as_deref().unwrap_or("the shell did not import")
872        ));
873    }
874    for solid in &report.solids {
875        collapsed_face_refusal(solid)?;
876    }
877    Ok(report)
878}
879
880/// One 186 through the STEP lane. A twice-walked edge on a quadric is told apart
881/// by its position; elsewhere it is read as written first, because it is usually
882/// a seam the builder handles, and as a bridge (`split_at_repeated_edges`) only
883/// when that reading is refused. The first refusal is the one reported.
884fn manifold_solid(file: &IgesFile, pointer: i64, scale: f64) -> Result<Built, String> {
885    let whole_text = manifold_solid_to_step(file, pointer, scale, false)?;
886    let first_failure = match solids_or_refusal(&whole_text) {
887        Ok(built) => return Ok(built),
888        Err(error) => error,
889    };
890    let split_text = manifold_solid_to_step(file, pointer, scale, true)?;
891    if split_text == whole_text {
892        return Err(format!("solid DE {pointer}: {first_failure}"));
893    }
894    solids_or_refusal(&split_text).map_err(|_| format!("solid DE {pointer}: {first_failure}"))
895}
896
897/// Import translated STEP, refusing when the body did not build. The STEP lane
898/// skips a body that fails with text and returns the rest, but a file that
899/// comes in short looks like a complete import.
900/// Solids that built, each with its faces' colours, and the diagnostics the
901/// STEP lane measured on them.
902type Built = (Vec<(BrepSolid, FaceColors)>, crate::KernelDiagnostics);
903
904/// Each built solid's per-face colours as the STEP lane paired them: one list
905/// per solid, as long as its faces where any face has a colour, else empty.
906/// A list of another length is not a pairing and is dropped.
907fn face_colors(report: &crate::StepImportReport) -> Vec<FaceColors> {
908    report
909        .solids
910        .iter()
911        .enumerate()
912        .map(|(index, solid)| {
913            let faces: usize = solid.shells.iter().map(|shell| shell.faces.len()).sum();
914            match report.appearances.get(index) {
915                Some(appearance) if appearance.faces.len() == faces && appearance.faces.iter().any(Option::is_some) => {
916                    appearance.faces.clone()
917                }
918                _ => Vec::new(),
919            }
920        })
921        .collect()
922}
923
924fn solids_or_refusal(step: &str) -> Result<Built, String> {
925    let report = step_report(step, false)?;
926    if report.failed > 0 {
927        return Err(format!(
928            "iges_import: {}",
929            report.first_error.as_deref().unwrap_or("the body did not import")
930        ));
931    }
932    if report.solids.is_empty() {
933        return Err("iges_import: the solid produced no body".into());
934    }
935    for solid in &report.solids {
936        collapsed_face_refusal(solid)?;
937    }
938    let faces = face_colors(&report);
939    Ok((report.solids.into_iter().zip(faces).collect(), report.diagnostics))
940}
941
942/// Area over boundary length squared below which a face has collapsed. Measured
943/// on foreign files: collapsed faces read a few times 1e-6. A 1 mm by 100 mm
944/// sliver reads 2.4e-3 and a 0.01 by 100 one 2.5e-5, so real faces clear it.
945const COLLAPSED_FACE_RATIO: f64 = 1e-5;
946
947/// A face with a real boundary that encloses almost nothing is a loop the
948/// builder read the wrong way round the carrier. It validates, and the solid
949/// then quietly lacks that face, so it is refused here.
950///
951/// `BREP_IGES_AREA_SCREEN` (default on; `=0` integrates every face): a face's
952/// area is at least the length of its vector area, which its boundary alone
953/// gives (`boundary_vector_area`). A face whose boundary clears the ratio by a
954/// wide margin is not integrated; the exact area is read only for the rest.
955fn collapsed_face_refusal(solid: &BrepSolid) -> Result<(), String> {
956    let screen = crate::switch!("BREP_IGES_AREA_SCREEN", true);
957    let mut readings = [0usize; 3]; // screened, unread by the screen, short of its margin
958    let outcome = collapsed_face_scan(solid, screen, &mut readings);
959    if crate::profile::profile_enabled() {
960        profile_line!("iges.area_screen screened={} unread={} short={}", readings[0], readings[1], readings[2]);
961    }
962    outcome
963}
964
965fn collapsed_face_scan(solid: &BrepSolid, screen: bool, readings: &mut [usize; 3]) -> Result<(), String> {
966    for face in solid.shells.iter().flat_map(|shell| &shell.faces) {
967        let Ok(length) = crate::face_boundary_length(solid, face) else {
968            continue;
969        };
970        if screen {
971            match boundary_vector_area(face) {
972                Some((vector_area, error)) if vector_area - error > AREA_SCREEN_MARGIN * COLLAPSED_FACE_RATIO * length * length => {
973                    readings[0] += 1;
974                    continue;
975                }
976                Some(_) => readings[2] += 1,
977                None => readings[1] += 1,
978            }
979        }
980        let Ok(area) = crate::face_area(face) else {
981            continue;
982        };
983        if length > 0.0 && area < COLLAPSED_FACE_RATIO * length * length {
984            return Err(format!(
985                "iges_import: a face collapsed on import, enclosing {area:.3e} mm2 inside a boundary {length:.3e} mm long"
986            ));
987        }
988    }
989    Ok(())
990}
991
992/// How far a face's vector area must clear the collapse ratio before the
993/// screen skips the exact area: a face that encloses little reads well under
994/// it, and the chord error is held separately.
995const AREA_SCREEN_MARGIN: f64 = 10.0;
996
997/// Chords per coedge of the boundary polygon, shared out over its knot spans
998/// (`pcurve_stations`).
999const AREA_SCREEN_CHORDS: usize = 16;
1000
1001/// The parameters a pcurve is read at: its start, then for each chord its
1002/// middle and its end. Chords never straddle a knot, and every knot span has
1003/// at least two, so a span holding all of a curve's travel is read as closely
1004/// as a curve's span that is its whole domain; otherwise the
1005/// `AREA_SCREEN_CHORDS` chords are shared out by span length.
1006fn pcurve_stations(pcurve: &crate::NurbsCurve) -> Option<Vec<f64>> {
1007    let [start, end] = pcurve.domain().ok()?;
1008    if !(start.is_finite() && end.is_finite() && end > start) {
1009        return None;
1010    }
1011    let mut breaks = vec![start];
1012    for &knot in &pcurve.knots {
1013        if knot > breaks[breaks.len() - 1] && knot < end {
1014            breaks.push(knot);
1015        }
1016    }
1017    breaks.push(end);
1018    let mut stations = vec![start];
1019    for span in breaks.windows(2) {
1020        let share = (AREA_SCREEN_CHORDS as f64 * (span[1] - span[0]) / (end - start)).ceil() as usize;
1021        let chords = share.max(2);
1022        for chord in 0..chords {
1023            let at = |fraction: f64| span[0] + (span[1] - span[0]) * fraction;
1024            stations.push(at((chord as f64 + 0.5) / chords as f64));
1025            stations.push(if chord + 1 == chords { span[1] } else { at((chord + 1) as f64 / chords as f64) });
1026        }
1027    }
1028    Some(stations)
1029}
1030
1031/// How closely the stations' parameter area must agree with the pcurves'
1032/// quadrature: a chord polygon of a smooth loop reads within a fraction of a
1033/// percent of it, and one that misses a pcurve's travel reads far off.
1034const AREA_SCREEN_AGREEMENT: f64 = 1e-2;
1035
1036/// Fraction of a loop's parameter extent within which two pcurve ends are one
1037/// joint, closed by a chord: fitted pcurves miss their neighbours by up to a
1038/// few times 1e-6 of it, and a step across a period reads about one.
1039const AREA_SCREEN_JOINT: f64 = 1e-3;
1040
1041/// The length of a face's vector area, `|½ ∮ r × dr|` round the images of its
1042/// loops' pcurves on its carrier, and an estimate of what the chords miss: the
1043/// sliver between each chord and its arc, read as the chord times twice the
1044/// sag at its middle (about three times a parabola's sliver; a span that turns
1045/// within one chord reads less, which the caller's tenfold margin carries).
1046///
1047/// By Stokes the vector area of any surface spanning those loops is the same,
1048/// and no surface's area is less than the length of its vector area. That
1049/// holds for the region the area integral reads only when the loops bound it
1050/// in the parameter plane, so `None` (the caller integrates) unless every
1051/// loop closes there at every joint (none steps across a period; a miss within
1052/// `AREA_SCREEN_JOINT` is closed by a chord, in the plane and on the carrier)
1053/// and the loops together wind positively there: a loop laid the
1054/// wrong way round reads a negative area, which is the collapse the caller
1055/// refuses. And `None` unless the stations read every pcurve whole: each is
1056/// polynomial (a rational one can bunch its travel between any stations by its
1057/// weights alone), and the stations' parameter area agrees with the pcurves'
1058/// quadrature. `None` too when a pcurve or the carrier cannot be read.
1059pub(super) fn boundary_vector_area(face: &crate::topology::FaceRecord) -> Option<(f64, f64)> {
1060    let image = |uv: Vec3| -> Option<Vec3> {
1061        let point = face.surface.evaluate(uv.x, uv.y).ok()?;
1062        (point.x.is_finite() && point.y.is_finite() && point.z.is_finite()).then_some(point)
1063    };
1064    // A rational pcurve can bunch its travel between any stations by its
1065    // weights alone; only polynomial ones are read.
1066    let polynomial = face.loops.iter().flat_map(|loop_record| &loop_record.coedges).all(|coedge| {
1067        let first = coedge.pcurve.control_points.first().map_or(1.0, |point| point.w);
1068        first.is_finite() && first != 0.0 && coedge.pcurve.control_points.iter().all(|point| (point.w - first).abs() <= 1e-12 * first.abs())
1069    });
1070    if !polynomial {
1071        return None;
1072    }
1073    let mut origin = None;
1074    let mut sum = Vec3::new(0.0, 0.0, 0.0);
1075    let mut error = 0.0;
1076    let mut winding = 0.0;
1077    // The stations' own parameter area, joints left open, against the
1078    // quadrature of the same pcurves (exact for polynomial spans): stations
1079    // that miss part of a pcurve's travel read a different area.
1080    let mut sampled = 0.0;
1081    for loop_record in &face.loops {
1082        // The loop's parameter polygon, coedge by coedge.
1083        let mut polygon: Vec<Vec<Vec3>> = Vec::with_capacity(loop_record.coedges.len());
1084        for coedge in &loop_record.coedges {
1085            let stations = pcurve_stations(&coedge.pcurve)?
1086                .into_iter()
1087                .map(|t| coedge.pcurve.evaluate(t).ok())
1088                .collect::<Option<Vec<_>>>()?;
1089            polygon.push(stations);
1090        }
1091        let (mut low, mut high) = (Vec3::new(f64::INFINITY, f64::INFINITY, 0.0), Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, 0.0));
1092        for uv in polygon.iter().flatten() {
1093            low = Vec3::new(low.x.min(uv.x), low.y.min(uv.y), 0.0);
1094            high = Vec3::new(high.x.max(uv.x), high.y.max(uv.y), 0.0);
1095        }
1096        let joint = AREA_SCREEN_JOINT * high.sub(low).length();
1097        for (index, stations) in polygon.iter().enumerate() {
1098            let next = &polygon[(index + 1) % polygon.len()];
1099            let end = stations[stations.len() - 1];
1100            if !(end.sub(next[0]).length() <= joint) {
1101                return None;
1102            }
1103            for pair in stations.windows(2) {
1104                sampled += 0.5 * (pair[0].x * pair[1].y - pair[0].y * pair[1].x);
1105            }
1106            winding += 0.5 * (end.x * next[0].y - end.y * next[0].x);
1107        }
1108        // The image polygon, with a chord across every joint and one closing
1109        // the loop, so its vector area does not depend on the origin.
1110        let mut last: Option<Vec3> = None;
1111        let mut first = None;
1112        for stations in &polygon {
1113            let mut previous = image(stations[0])?;
1114            let origin = *origin.get_or_insert(previous);
1115            first.get_or_insert(previous);
1116            if let Some(end) = last {
1117                sum = sum.add(end.sub(origin).cross(previous.sub(origin)));
1118            }
1119            for chord in stations[1..].chunks(2) {
1120                let (arc, next) = (image(chord[0])?, image(chord[1])?);
1121                let sag = arc.sub(previous.add(next).scale(0.5)).length();
1122                error += 2.0 * next.sub(previous).length() * sag;
1123                sum = sum.add(previous.sub(origin).cross(next.sub(origin)));
1124                previous = next;
1125            }
1126            last = Some(previous);
1127        }
1128        if let (Some(start), Some(end), Some(origin)) = (first, last, origin) {
1129            sum = sum.add(end.sub(origin).cross(start.sub(origin)));
1130        }
1131    }
1132    let exact = crate::parameter_space_area(face).ok()?;
1133    if !((sampled - exact).abs() <= AREA_SCREEN_AGREEMENT * exact.abs()) {
1134        return None;
1135    }
1136    winding += sampled;
1137    let length = 0.5 * sum.length();
1138    (winding > 0.0 && length.is_finite() && error.is_finite()).then_some((length, error))
1139}