Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

IGES import: separate lumps of one part are separate solids (#3928) (#3972)

bherbruck2fdc105d879e
diff --git a/crates/kernel/src/iges_in.rs b/crates/kernel/src/iges_in.rs
index ccdf1949bc..c59b51d3e9 100644
--- a/crates/kernel/src/iges_in.rs
+++ b/crates/kernel/src/iges_in.rs
@@ -1167,14 +1167,17 @@ fn color_of(t: &Tr, seq: i64) -> Option<[f32; 3]> {
/// Write faces sewn by `sw` as a shell; the shell's id and whether it closes.
fn write_shell(o: &mut Out, sw: &Sewer, faces: &[FaceB], styles: &mut Vec<(u64, [f32; 3])>) -> (u64, bool) {
- let vids: Vec<u64> = sw
- .verts
- .iter()
- .map(|p| {
- let c = o.point(*p);
- o.add(format!("VERTEX_POINT('',#{c})"))
- })
- .collect();
+ // Vertices are written as the shell's edges use them (a sewer may hold several shells).
+ let mut vids: HashMap<usize, u64> = HashMap::new();
+ let mut vertex = |o: &mut Out, i: usize| -> Option<u64> {
+ if let Some(id) = vids.get(&i) {
+ return Some(*id);
+ }
+ let c = o.point(*sw.verts.get(i)?);
+ let id = o.add(format!("VERTEX_POINT('',#{c})"));
+ vids.insert(i, id);
+ Some(id)
+ };
let mut eids: HashMap<usize, u64> = HashMap::new();
let mut count: HashMap<usize, (usize, usize)> = HashMap::new();
for &(e, d) in faces.iter().flat_map(|f| f.loops.iter().flatten()) {
@@ -1195,7 +1198,7 @@ fn write_shell(o: &mut Out, sw: &Sewer, faces: &[FaceB], styles: &mut Vec<(u64,
let id = match eids.get(&e) {
Some(id) => *id,
None => {
- let (Some(a), Some(b)) = (vids.get(ed.v[0]), vids.get(ed.v[1])) else { continue };
+ let (Some(a), Some(b)) = (vertex(o, ed.v[0]), vertex(o, ed.v[1])) else { continue };
let id = o.add(format!("EDGE_CURVE('',#{a},#{b},#{},{})", ed.curve, if ed.rev { ".F." } else { ".T." }));
eids.insert(e, id);
id
@@ -1335,7 +1338,7 @@ fn sew_surfaces(
styles: &mut Vec<(u64, [f32; 3])>,
faces: &mut Vec<FaceB>,
sw: &mut Sewer,
-) -> R<Option<u64>> {
+) -> R<Vec<u64>> {
faces.clear();
sw.verts.clear();
sw.grid.clear();
@@ -1358,17 +1361,60 @@ fn sew_surfaces(
faces.push(FaceB { surface: d.surface, sense: true, loops, color: d.color });
}
if faces.is_empty() {
- return Ok(None);
+ return Ok(Vec::new());
}
orient(faces);
- let (shell, closed) = write_shell(&mut t.o, sw, faces, styles);
+ // Faces that share no edge, directly or through others, are separate bodies: one shell of
+ // two lumps is closed edge by edge but not a solid.
+ let pieces = connected(faces);
let name = name.replace('\'', "''");
- Ok(Some(if closed {
- t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})"))
- } else {
- t.warn("the surfaces do not close into a solid: imported as an open body");
- t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))"))
- }))
+ let mut items = Vec::with_capacity(pieces.len());
+ for (k, piece) in pieces.into_iter().enumerate() {
+ let (shell, closed) = write_shell(&mut t.o, sw, &piece, styles);
+ let name = if k == 0 { name.clone() } else { format!("{name} {}", k + 1) };
+ items.push(if closed {
+ t.o.add(format!("MANIFOLD_SOLID_BREP('{name}',#{shell})"))
+ } else {
+ t.warn("the surfaces do not close into a solid: imported as an open body");
+ t.o.add(format!("SHELL_BASED_SURFACE_MODEL('{name}',(#{shell}))"))
+ });
+ }
+ Ok(items)
+}
+
+/// The faces in groups that share edges, taken out of `faces`.
+fn connected(faces: &mut Vec<FaceB>) -> Vec<Vec<FaceB>> {
+ let mut parent: Vec<usize> = (0..faces.len()).collect();
+ let root = |parent: &[usize], mut i: usize| {
+ while let Some(&p) = parent.get(i).filter(|p| **p != i) {
+ i = p;
+ }
+ i
+ };
+ let mut first: HashMap<usize, usize> = HashMap::new();
+ for (fi, f) in faces.iter().enumerate() {
+ for &(e, _) in f.loops.iter().flatten() {
+ let other = *first.entry(e).or_insert(fi);
+ let (a, b) = (root(&parent, fi), root(&parent, other));
+ if let Some(x) = parent.get_mut(a) {
+ *x = b;
+ }
+ }
+ }
+ // In file order: a group comes where its first face does.
+ let mut slot: HashMap<usize, usize> = HashMap::new();
+ let mut out: Vec<Vec<FaceB>> = Vec::new();
+ let roots: Vec<usize> = (0..faces.len()).map(|i| root(&parent, i)).collect();
+ for (f, r) in faces.drain(..).zip(roots) {
+ let k = *slot.entry(r).or_insert_with(|| {
+ out.push(Vec::new());
+ out.len() - 1
+ });
+ if let Some(g) = out.get_mut(k) {
+ g.push(f);
+ }
+ }
+ out
}
/// A face read from a trimmed or bounded surface, its loops not yet sewn.
diff --git a/crates/kernel/src/iges_in/assembly.rs b/crates/kernel/src/iges_in/assembly.rs
index 9c77c9bcd6..2a3894f34e 100644
--- a/crates/kernel/src/iges_in/assembly.rs
+++ b/crates/kernel/src/iges_in/assembly.rs
@@ -180,9 +180,7 @@ impl Assembly {
.copied()
.filter(|s| seq != 0 || !self.referenced.contains(s))
.filter(|s| f.des.get(s).is_some_and(|d| matches!(d.typ, 143 | 144) || (d.typ == 128 && !self.surface_references.contains(s))));
- if let Some(item) = sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)? {
- items.push(item);
- }
+ items.extend(sew_surfaces(t, surfaces, if seq == 0 { "Body1" } else { name }, styles, &mut faces, &mut sewer)?);
made += items.len();
list.clear();
let _ = write!(list, "#{origin}");
diff --git a/crates/kernel/src/iges_in/tests.rs b/crates/kernel/src/iges_in/tests.rs
index c05022c864..b7922b5de6 100644
--- a/crates/kernel/src/iges_in/tests.rs
+++ b/crates/kernel/src/iges_in/tests.rs
@@ -299,6 +299,25 @@ fn trimmed_surfaces_sew_into_a_solid() {
assert!(rel(m.volume, 6000.0) < 1e-6 && rel(m.area, 2200.0) < 1e-6, "{} {}", m.volume, m.area);
}
+/// One part whose surfaces make two separate boxes: two solids, not one shell of two lumps
+/// (closed edge by edge, but not connected, so it was read as an open body).
+#[test]
+fn separate_lumps_of_one_part_are_separate_solids() {
+ let mut ents = Vec::new();
+ let mut faces = trimmed_box(&mut ents, 0.0);
+ faces.extend(trimmed_box(&mut ents, 100.0));
+ let members = faces.iter().map(|s| s.to_string()).collect::<Vec<_>>().join(",");
+ ents.push((308, 0, format!("0,5HFrame,{},{members}", faces.len())));
+ let imp = iges_import(&iges_file(&ents)).unwrap();
+ assert!(imp.warnings.is_empty(), "{:?}", imp.warnings);
+ assert_eq!(imp.bodies.len(), 2);
+ for (body, x) in imp.bodies.iter().zip([0.0, 100.0]) {
+ let m = measure(&body.body).unwrap();
+ assert!(body.closed && rel(m.volume, 6000.0) < 1e-6, "{} {}", body.name, m.volume);
+ assert!(m.bbox.min.dist(Vec3::new(x, 0.0, 0.0)) < 1e-6, "{} at {:?}", body.name, m.bbox.min);
+ }
+}
+
/// Trim pieces whose ends miss each other by a hundredth of a millimetre, far past the file's
/// stated resolution: the loop is closed and the box sews into a solid. A gap of half a
/// millimetre is no corner written loosely, and stays open.