Skip to content

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

Sheet metal: a refolded sheet's faces keep the names of the faces they were (#6268)

NOWN-DEV6f340ade6985
diff --git a/crates/doc/src/naming.rs b/crates/doc/src/naming.rs
index c058022f9b..25af341f63 100644
--- a/crates/doc/src/naming.rs
+++ b/crates/doc/src/naming.rs
@@ -163,6 +163,10 @@ const MAX_DEPTH: usize = 400;
/// Up to this many sample points per face.
const SAMPLES: usize = 9;
+/// Up to this many sample points per face where a sheet's panel kept in place names the face it is
+/// part of (see [`geometric_from`]).
+const PANEL_SAMPLES: usize = 256;
+
/// Unit normals of each face's triangles.
fn normals(m: &Mesh, nf: usize) -> Vec<Vec<Vec3>> {
let mut per: Vec<Vec<Vec3>> = vec![Vec::new(); nf];
@@ -178,6 +182,11 @@ fn normals(m: &Mesh, nf: usize) -> Vec<Vec<Vec3>> {
/// Triangle centroids spread over each face: face → points.
fn samples(m: &Mesh, nf: usize) -> Vec<Vec<Vec3>> {
+ samples_up_to(m, nf, SAMPLES)
+}
+
+/// [`samples`] with up to `most` points per face.
+fn samples_up_to(m: &Mesh, nf: usize, most: usize) -> Vec<Vec<Vec3>> {
let mut per: Vec<Vec<Vec3>> = vec![Vec::new(); nf];
for (t, f) in m.triangles.iter().zip(&m.tri_face) {
if let (Some(v), Some([a, b, c])) = (per.get_mut(*f as usize), m.tri(t)) {
@@ -186,11 +195,11 @@ fn samples(m: &Mesh, nf: usize) -> Vec<Vec<Vec3>> {
}
per.into_iter()
.map(|v| {
- if v.len() <= SAMPLES {
+ if v.len() <= most {
return v;
}
- let step = v.len() as f64 / SAMPLES as f64;
- (0..SAMPLES).filter_map(|i| v.get((i as f64 * step) as usize).copied()).collect()
+ let step = v.len() as f64 / most as f64;
+ (0..most).filter_map(|i| v.get((i as f64 * step) as usize).copied()).collect()
})
.collect()
}
@@ -442,12 +451,26 @@ fn geometric_from(b: &ModelBody, o: &NamingOrigin, nf: usize, names_of: fn(&Mode
inputs.iter().find(|(x, _, _)| x.name == b.name),
) {
let input = std::slice::from_ref(input);
- for (name, ps) in names.iter_mut().zip(&pts) {
+ let mut dense: Option<Vec<Vec<Vec3>>> = None;
+ for (fi, (name, ps)) in names.iter_mut().zip(&pts).enumerate() {
if name.is_some() {
continue;
}
- let back: Option<Vec<Vec3>> = ps.iter().map(|p| after.point_before(before, *p)).collect();
- if let Some(back) = back.filter(|b| !b.is_empty()) {
+ // The panel the feature kept in place (the base an unfold lays the flanges out beside)
+ // lies on its own face before, and that face names the whole face it is part of now:
+ // a flat face spans that panel, the panels laid out beside it and the bend strips
+ // between them, whatever share of it they take. The few sample points above may all
+ // miss it (a bend strip is many small triangles), so the face is looked at closer.
+ let dense = dense.get_or_insert_with(|| samples_up_to(&m, nf, PANEL_SAMPLES));
+ if let Some(kept) = dense.get(fi).and_then(|ps| plurality(ps, input, tol)) {
+ *name = Some(kept);
+ continue;
+ }
+ // A point on a bend lies on no panel and has no place before; the face's other points
+ // do. At least half of them must, so a face that is mostly bend is not named from a
+ // few points.
+ let back: Vec<Vec3> = ps.iter().filter_map(|p| after.point_before(before, *p)).collect();
+ if !back.is_empty() && back.len() * 2 >= ps.len() {
*name = vote(&back, input, tol, None);
}
}
@@ -554,6 +577,28 @@ fn vote(ps: &[Vec3], inputs: &[(&ModelBody, FaceIndex, Arc<Vec<String>>)], tol:
votes.first().filter(|(_, n)| *n * 2 >= ps.len().max(1) && votes.get(1).is_none_or(|(_, other)| n > other)).map(|(n, _)| n.clone())
}
+/// The input face the most of `ps` lie on (pieces counted as their face), if at least two and a
+/// sixteenth of them lie on one: the face a sheet's unmoved panel was part of.
+fn plurality(ps: &[Vec3], inputs: &[(&ModelBody, FaceIndex, Arc<Vec<String>>)], tol: f64) -> Option<String> {
+ let mut votes: Vec<(String, usize)> = Vec::new();
+ for p in ps {
+ for (_, idx, nm) in inputs {
+ if let Some(f) = idx.face_at(*p, tol)
+ && let Some(n) = nm.get(f)
+ {
+ let n = strip_piece(n);
+ match votes.iter_mut().find(|(v, _)| v == n) {
+ Some(v) => v.1 += 1,
+ None => votes.push((n.to_string(), 1)),
+ }
+ break;
+ }
+ }
+ }
+ votes.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
+ votes.first().filter(|(_, n)| *n >= 2 && *n * 16 >= ps.len()).map(|(n, _)| n.clone())
+}
+
/// A face name without its piece qualifiers: the face it is a piece of (`F2:top` for
/// `F2:top#[F4:side:l1]`, for pieces of pieces, and for the numbered pieces of older designs).
pub fn strip_piece(n: &str) -> &str {
diff --git a/crates/engine/src/cmd/sheet_tests.rs b/crates/engine/src/cmd/sheet_tests.rs
index ce496e6d4c..8e862439fe 100644
--- a/crates/engine/src/cmd/sheet_tests.rs
+++ b/crates/engine/src/cmd/sheet_tests.rs
@@ -5004,3 +5004,52 @@ fn mirroring_or_copying_a_sheet_body_leaves_the_original_sheet_as_it_was() {
assert_eq!(copy["bends"], original["bends"], "{name}");
}
}
+
+/// The top and bottom face names of every panel of the first sheet body, by sheet face.
+fn panel_face_names(s: &mut Session) -> std::collections::BTreeMap<String, String> {
+ let body = s.model.state().bodies[0].name.clone();
+ let faces = run(s, "model.faces", json!({"body": body}))["faces"].as_array().cloned().unwrap_or_default();
+ faces
+ .iter()
+ .filter_map(|f| {
+ let sheet = f["sheet_face"].as_str()?;
+ (sheet.ends_with(":top") || sheet.ends_with(":bottom")).then(|| (sheet.to_string(), f["name"].as_str().unwrap_or("").to_string()))
+ })
+ .collect()
+}
+
+/// An unfold keeps the base where it is and lays the flanges out beside it: the flat face that
+/// spans them and the bend strips between them is the base's face, and is named after it; so are
+/// the faces the refold makes of it, at every size. It was named after the unfold whenever few of
+/// its sample points fell on the base (the bend strips are many small triangles, the base two big
+/// ones), and that changed with the sizes: a refolded part's faces were renamed by a size change,
+/// and joints and sketches on them lost their faces.
+#[test]
+fn an_unfolded_sheets_flat_face_is_named_after_its_base_at_every_size() {
+ let mut s = Session::default();
+ run(&mut s, "sheet.manage_rules", json!({"name":"AL2","thickness":"2 mm","k_factor":0.5,"bend_radius":"1 mm","gap":"0.5 mm","active":true}));
+ run(&mut s, "parameters.add", json!({"name": "H", "expression": "5 mm"}));
+ base(&mut s, 200.0, 150.0);
+ run(&mut s, "sheet.flange", json!({"edges":[[100,0,2],[200,75,2],[100,150,2]],"height":"H","angle":"90 deg"}));
+ let folded = panel_face_names(&mut s);
+ let (top, bottom) = (folded["sheet:Body1:base:top"].clone(), folded["sheet:Body1:base:bottom"].clone());
+ run(&mut s, "sheet.unfold", json!({}));
+ let unfold = s.doc.features.last().map_or(0, |f| f.id);
+ run(&mut s, "sheet.refold", json!({}));
+ let stem = |n: &str| solidcraft_doc::naming::strip_piece(n).to_string();
+ for h in ["5 mm", "60 mm", "5 mm"] {
+ run(&mut s, "parameters.change", json!({"name": "H", "expression": h}));
+ let body = s.model.state().bodies[0].name.clone();
+ let flat_state = s.model.results.iter().find(|r| r.id == unfold).map(|r| r.state.clone());
+ {
+ let st = flat_state.expect("the unfold's state");
+ let flat = st.bodies.iter().find(|b| b.name == body).map(|b| solidcraft_doc::naming::face_names(b).as_ref().clone()).unwrap_or_default();
+ assert!(flat.iter().any(|n| stem(n) == stem(&top)) && flat.iter().any(|n| stem(n) == stem(&bottom)), "H {h}: the flat faces {flat:?}");
+ assert!(!flat.iter().any(|n| n.starts_with(&format!("F{unfold}:"))), "H {h}: a flat face named after the unfold: {flat:?}");
+ }
+ for (sheet, name) in panel_face_names(&mut s) {
+ let want = if sheet.ends_with(":top") { &top } else { &bottom };
+ assert_eq!(stem(&name), stem(want), "H {h}: {sheet} is {name} after the refold");
+ }
+ }
+}