Skip to main content

brep_kernel/io/parasolid/
import.rs

1//! Parasolid part to kernel `BrepSolid`s, by way of the STEP importer.
2//!
3//! Each body is translated to Part 21 ([`super::to_step`]) and imported
4//! there, so it gets the STEP builder, closure gate and refusals. A body that
5//! cannot be read correctly is refused by name; a file never imports short.
6
7use crate::topology::BrepSolid;
8use crate::{BodyAppearance, KernelDiagnostics};
9
10use super::reader::{parse_xt, parse_xt_text, Node, XtFile};
11use super::geometry::MM_PER_METRE;
12use super::to_step::body_to_step;
13
14/// What [`import_parasolid_report`] returns.
15#[derive(Clone, Debug)]
16pub struct ParasolidImportReport {
17    /// The solids, in file order.
18    pub solids: Vec<BrepSolid>,
19    /// Each solid's name (the body's name attribute), parallel to `solids`;
20    /// empty when the file gives none.
21    pub names: Vec<String>,
22    /// Each solid's colours, parallel to `solids`.
23    pub appearances: Vec<BodyAppearance>,
24    /// The writer (`APPL` in the header) and kernel version.
25    pub application: Option<String>,
26    pub modeller_version: String,
27    /// The file's linear resolution in mm (the body's `res_linear`).
28    pub stated_resolution_mm: Option<f64>,
29    /// Edges whose 3D curve was fitted (intersection curves and SP-curves,
30    /// which STEP has no entity for).
31    pub fitted_curves: usize,
32    /// Of those, the intersection curves fitted through their chart alone
33    /// where no point between chart points could be solved (a surface with
34    /// no distance the reader computes, such as a blend boundary, or a
35    /// tangency): their fit is not checked against the true curve.
36    pub unverified_curves: usize,
37    /// Measurements and warnings from the STEP lane, merged over every body.
38    pub diagnostics: KernelDiagnostics,
39}
40
41/// Read a Parasolid text part (`.x_t`, `.xmt_txt`) into solids.
42pub fn import_parasolid(text: &str) -> Result<Vec<BrepSolid>, String> {
43    Ok(import_parasolid_report(text)?.solids)
44}
45
46/// [`import_parasolid`] with names, colours and the import's diagnostics.
47pub fn import_parasolid_report(text: &str) -> Result<ParasolidImportReport, String> {
48    let file = parse_xt_text(text).map_err(|e| format!("parasolid_import: {e}"))?;
49    import_file(&file, true)
50}
51
52/// [`import_parasolid_report`] for a caller that drops the report's
53/// diagnostics (the IMPORT3D feature): under `BREP_IMPORT_LEAN` the STEP
54/// build skips its trim readings. The bodies are the same.
55pub fn import_parasolid_bodies(text: &str) -> Result<ParasolidImportReport, String> {
56    let file = parse_xt_text(text).map_err(|e| format!("parasolid_import: {e}"))?;
57    import_file(&file, false)
58}
59
60/// [`import_parasolid_bytes_report`] for a caller that drops the report's
61/// diagnostics, as [`import_parasolid_bodies`].
62pub fn import_parasolid_bytes_bodies(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
63    let file = parse_xt(bytes).map_err(|e| format!("parasolid_import: {e}"))?;
64    import_file(&file, false)
65}
66
67/// [`import_parasolid_report`] from a file's bytes: text or binary (`.x_b`),
68/// a part or a partition (the form SolidWorks embeds its bodies in).
69pub fn import_parasolid_bytes_report(bytes: &[u8]) -> Result<ParasolidImportReport, String> {
70    let file = parse_xt(bytes).map_err(|e| format!("parasolid_import: {e}"))?;
71    import_file(&file, true)
72}
73
74/// `readings`: whether the caller reads the report's trim-reading
75/// diagnostics; when it does not, `import_step_report_dropping_readings`.
76fn import_file(file: &XtFile, readings: bool) -> Result<ParasolidImportReport, String> {
77    let bodies = bodies(file).map_err(|e| format!("parasolid_import: {e}"))?;
78    let mut report = ParasolidImportReport {
79        solids: Vec::new(),
80        names: Vec::new(),
81        appearances: Vec::new(),
82        application: file.header_value("APPL").map(str::to_string),
83        modeller_version: file.modeller_version.trim_start_matches(':').trim().to_string(),
84        stated_resolution_mm: bodies
85            .first()
86            .and_then(|b| b.body.real("res_linear"))
87            .map(|r| r * MM_PER_METRE)
88            .filter(|r| *r > 0.0),
89        fitted_curves: 0,
90        unverified_curves: 0,
91        diagnostics: KernelDiagnostics::default(),
92    };
93    // Each distinct body is translated and imported once; every placement
94    // of it, in file order, is a copy moved to its place.
95    struct Imported {
96        solids: Vec<BrepSolid>,
97        appearances: Vec<Vec<Option<crate::ImportedColor>>>,
98        name: Option<String>,
99        color: Option<crate::ImportedColor>,
100    }
101    let mut imported: rustc_hash::FxHashMap<u32, Imported> = rustc_hash::FxHashMap::default();
102    let distinct = {
103        let mut seen = rustc_hash::FxHashSet::default();
104        bodies.iter().filter(|p| seen.insert(p.body.index)).count()
105    };
106    let mut occurrences: rustc_hash::FxHashMap<u32, usize> = rustc_hash::FxHashMap::default();
107    for p in &bodies {
108        *occurrences.entry(p.body.index).or_default() += 1;
109    }
110    let mut ordinal = 0;
111    let mut seen_count: rustc_hash::FxHashMap<u32, usize> = rustc_hash::FxHashMap::default();
112    for Placed { body, at } in &bodies {
113        let body = *body;
114        if !imported.contains_key(&body.index) {
115            ordinal += 1;
116            let what = || match distinct {
117                1 => "the body".to_string(),
118                _ => format!("body {ordinal}"),
119            };
120            let translated = body_to_step(file, body, ordinal - 1).map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
121            if body.int("body_type") == Some(2) {
122                // A wire body (body type 2): its wireframe, one wire body.
123                let wires = crate::step_import::import_step_wires(&translated.step)
124                    .map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
125                if wires.is_empty() {
126                    return Err(format!("parasolid_import: {}: the wire body produced no wire", what()));
127                }
128                report.fitted_curves += translated.fitted_curves;
129                report.unverified_curves += translated.unverified_curves;
130                let appearances = vec![Vec::new(); wires.len()];
131                imported.insert(body.index, Imported { solids: wires, appearances, name: translated.name, color: translated.color });
132            } else {
133                // A sheet body (body type 3) is written as open shells, which come
134                // in as sheet bodies; a solid's must close.
135                let sheet = body.int("body_type") == Some(3);
136                let step = if !readings {
137                    crate::step_import::import_step_report_dropping_readings(&translated.step, sheet)
138                } else if sheet {
139                    crate::step_import::import_step_report_with_sheets(&translated.step)
140                } else {
141                    crate::import_step_report(&translated.step)
142                }
143                .map_err(|e| format!("parasolid_import: {}: {e}", what()))?;
144                if step.failed > 0 {
145                    return Err(format!(
146                        "parasolid_import: {}: {}",
147                        what(),
148                        step.first_error.as_deref().unwrap_or("the body did not import")
149                    ));
150                }
151                if step.sheets_skipped > 0 && !step.solids.is_empty() {
152                    // Part of the body did not come in: refuse it whole.
153                    return Err(format!(
154                        "parasolid_import: {}: {} of its shells are open sheets, which do not bound a solid",
155                        what(),
156                        step.sheets_skipped
157                    ));
158                }
159                if step.solids.is_empty() {
160                    return Err(format!("parasolid_import: {}: the body produced no solid", what()));
161                }
162                report.fitted_curves += translated.fitted_curves;
163                report.unverified_curves += translated.unverified_curves;
164                merge_diagnostics(&mut report.diagnostics, step.diagnostics);
165                let appearances = (0..step.solids.len()).map(|j| step.appearances.get(j).map(|a| a.faces.clone()).unwrap_or_default()).collect();
166                imported.insert(body.index, Imported { solids: step.solids, appearances, name: translated.name, color: translated.color });
167            }
168        }
169        let entry = &imported[&body.index];
170        let count = entry.solids.len() * occurrences[&body.index];
171        let k = seen_count.entry(body.index).or_default();
172        for (j, solid) in entry.solids.iter().enumerate() {
173            let solid = match at {
174                None => solid.clone(),
175                Some(matrix) => {
176                    let transform = crate::AffineTransform::new(*matrix)
177                        .map_err(|e| format!("parasolid_import: placing an instance: {e}"))?;
178                    crate::transform_brep(solid, transform, transform.determinant3() < 0.0)
179                        .map_err(|e| format!("parasolid_import: placing an instance: {e}"))?
180                }
181            };
182            report.appearances.push(BodyAppearance { body: entry.color, faces: entry.appearances[j].clone() });
183            *k += 1;
184            let name = match (&entry.name, count) {
185                (Some(name), 1) => name.clone(),
186                (Some(name), _) => format!("{name} ({k})"),
187                (None, _) => String::new(),
188            };
189            report.names.push(name);
190            report.solids.push(solid);
191        }
192    }
193    Ok(report)
194}
195
196/// A body to import and where it goes: untransformed (`None`), or where an
197/// assembly's instance places it (row-major 4×4, mm).
198struct Placed<'f> {
199    body: &'f Node,
200    at: Option<crate::Mat4>,
201}
202
203/// The bodies a part file holds: its root BODY, or the bodies of a
204/// PART_XMT_BLOCK / POINTER_LIS_BLOCK array of parts (§2.1); a partition's,
205/// its WORLD's chain of bodies; an assembly's, every body its instances
206/// place, through sub-assemblies (§4.3.1, §4.3.2).
207fn bodies(file: &XtFile) -> Result<Vec<Placed<'_>>, String> {
208    let root = file.root().ok_or("the file holds no nodes")?;
209    let parts: Vec<&Node> = match root.type_name() {
210        "BODY" | "ASSEMBLY" => vec![root],
211        "WORLD" => {
212            // Bodies a partition places through an assembly would come in
213            // once, unplaced: refused until a partition with an assembly is
214            // seen.
215            if root.ptr("assembly") != 0 {
216                return Err("the partition holds an assembly, which is not read yet".into());
217            }
218            let mut chain = Vec::new();
219            let mut next = file.follow(root, "body");
220            while let Some(body) = next {
221                if chain.len() >= file.nodes().len() || chain.iter().any(|b: &&Node| b.index == body.index) {
222                    return Err("the partition's chain of bodies loops".into());
223                }
224                chain.push(body);
225                next = file.follow(body, "next");
226            }
227            chain
228        }
229        "PART_XMT_BLOCK" | "POINTER_LIS_BLOCK" => root
230            .ints("entries")
231            .into_iter()
232            .filter_map(|i| u32::try_from(i).ok())
233            .filter_map(|i| file.node(i))
234            .collect(),
235        other => return Err(format!("the file's root is a {other}, not a body")),
236    };
237    let mut out: Vec<Placed> = Vec::new();
238    for part in parts {
239        match part.type_name() {
240            "BODY" => out.push(Placed { body: part, at: None }),
241            "ASSEMBLY" => {
242                let mut placed = Vec::new();
243                place_instances(file, part, crate::step_matrix::MAT4_IDENTITY, 0, &mut placed)?;
244                out.extend(placed.into_iter().map(|(body, matrix)| Placed { body, at: Some(matrix) }));
245            }
246            other => return Err(format!("the file holds a {other} where a part should be")),
247        }
248    }
249    // A body listed on its own and also placed by an assembly in the file
250    // would come in twice, once unplaced: no file seen does this.
251    let unplaced: rustc_hash::FxHashSet<u32> = out.iter().filter(|p| p.at.is_none()).map(|p| p.body.index).collect();
252    if out.iter().any(|p| p.at.is_some() && unplaced.contains(&p.body.index)) {
253        return Err("the file lists a body both on its own and in an assembly, which is not read yet".into());
254    }
255    if out.is_empty() {
256        return Err("the file holds no bodies".into());
257    }
258    Ok(out)
259}
260
261/// Every body `assembly`'s instances place, with its placement composed
262/// down from `parent`. An instance's transform acts as x' = (R x + t) s
263/// (§5.2.6), R row-major as written: a SolidWorks machining assembly's four
264/// rotated blocks sit on its stock so, and off it transposed.
265fn place_instances<'f>(
266    file: &'f XtFile,
267    assembly: &'f Node,
268    parent: crate::Mat4,
269    depth: usize,
270    out: &mut Vec<(&'f Node, crate::Mat4)>,
271) -> Result<(), String> {
272    if depth > 64 {
273        return Err("the assembly nests more than 64 deep".into());
274    }
275    let mut seen = 0usize;
276    let mut next = file.follow(assembly, "sub_instance");
277    while let Some(instance) = next {
278        seen += 1;
279        if seen > file.nodes().len() {
280            return Err("an assembly's chain of instances loops".into());
281        }
282        if instance.int("type") == Some(2) {
283            return Err("the assembly holds a negative instance, which is not read yet".into());
284        }
285        let local = match file.follow(instance, "transform") {
286            None => crate::step_matrix::MAT4_IDENTITY,
287            Some(transform) => transform_matrix(file, transform)?,
288        };
289        let matrix = crate::step_matrix::mat4_mul(&parent, &local);
290        let part = file.follow(instance, "part").ok_or("an instance has no part")?;
291        match part.type_name() {
292            "BODY" => out.push((part, matrix)),
293            "ASSEMBLY" => place_instances(file, part, matrix, depth + 1, out)?,
294            other => return Err(format!("an instance places a {other}, not a body or an assembly")),
295        }
296        next = file.follow(instance, "next_in_part");
297    }
298    Ok(())
299}
300
301/// A TRANSFORM node as a row-major 4×4 in mm: x' = (R x + t) s, with the
302/// optional precision node's corrections added (§5.2.6).
303fn transform_matrix(file: &XtFile, node: &Node) -> Result<crate::Mat4, String> {
304    let mut r = node.reals("rotation_matrix");
305    let mut t = node.vector("translation_vector").unwrap_or([0.0; 3]);
306    if r.len() != 9 || r.iter().any(|x| !x.is_finite()) {
307        return Err("a transform has no rotation matrix".into());
308    }
309    if let Some(precision) = file.follow(node, "precision") {
310        let dr = precision.reals("rotation_matrix");
311        if dr.len() == 9 && dr.iter().all(|x| x.is_finite()) {
312            for (v, d) in r.iter_mut().zip(&dr) {
313                *v += d;
314            }
315        }
316        if let Some(dt) = precision.vector("translation_vector") {
317            for (v, d) in t.iter_mut().zip(dt) {
318                *v += d;
319            }
320        }
321    }
322    if node.vector("perspective_vector").is_some_and(|p| p.iter().any(|x| *x != 0.0)) {
323        return Err("an instance's transform has a perspective part, which is not read".into());
324    }
325    let s = node.real("scale").unwrap_or(1.0);
326    if !(s.is_finite() && s != 0.0) {
327        return Err(format!("a transform has scale {s}"));
328    }
329    // The kernel places a solid by a matrix whose determinant is above 1e-14
330    // (its singularity bound, in mm³ per mm³).
331    if s.abs().powi(3) <= 1e-14 {
332        return Err(format!("an instance scales its part by {s}, below what the kernel can place (1e-14 in volume)"));
333    }
334    for v in &mut r {
335        *v *= s;
336    }
337    for v in &mut t {
338        *v *= s * MM_PER_METRE;
339    }
340    Ok([r[0], r[1], r[2], t[0], r[3], r[4], r[5], t[1], r[6], r[7], r[8], t[2], 0.0, 0.0, 0.0, 1.0])
341}
342
343fn merge_diagnostics(into: &mut KernelDiagnostics, from: KernelDiagnostics) {
344    into.events.extend(from.events);
345    for (key, count) in from.counters {
346        *into.counters.entry(key).or_insert(0) += count;
347    }
348    for (key, value) in from.measurements {
349        let slot = into.measurements.entry(key).or_insert(value);
350        if value > *slot {
351            *slot = value;
352        }
353    }
354}