diff --git a/crates/doc/src/sheet_convert.rs b/crates/doc/src/sheet_convert.rs index f818aa521..1a1c2624d 100644 --- a/crates/doc/src/sheet_convert.rs +++ b/crates/doc/src/sheet_convert.rs @@ -429,7 +429,8 @@ fn other_skin(b: &Body, mesh: &Mesh, c: &Chamfer, tol: f64) -> Option { /// Face `g`'s outline with each picked chamfer along it taken out: the edge along the chamfer /// moves to where `g`'s plane meets the plane of the face across the chamfer (its corners -/// sliding along the edges before and after it), and runs along that face. +/// sliding along the edges before and after it, or stepping down to it where the face goes on +/// past the chamfer's end), and runs along that face. fn without_chamfers(b: &Body, mut face: Face, g: usize, chamfers: &[Chamfer], tol: f64) -> Result { for c in chamfers { let other = if c.a == g { @@ -447,29 +448,57 @@ fn without_chamfers(b: &Body, mut face: Face, g: usize, chamfers: &[Chamfer], to let &[k] = along.as_slice() else { return err("not supported yet: a chamfer picked as a bend that runs along a face more than once"); }; - // Its corners slide along the edges before and after it: those must be straight. - if [k + m - 1, k + 1].iter().any(|i| face.round.get(i % m).is_some_and(Option::is_some)) { - return err("not supported yet: a round edge of a face that ends at a chamfer picked as a bend"); - } - // Each end of the edge slides along the edge on its other side, out to the other plane. - let slide = |corner: usize, before: usize| -> Option { + let (Some(&p0), Some(&q0)) = (face.pts.get(k), face.pts.get((k + 1) % m)) else { return err("a face of the sheet has no outline") }; + let Some(e) = (q0 - p0).normalized() else { return err("a face of the sheet has an edge without length") }; + // Each end of the edge slides along the straight edge on its other side, out to the + // other plane. + let slide = |corner: usize, before: usize, edge: usize| -> Option { + if face.round.get(edge % m).is_some_and(Option::is_some) { + return None; + } let (p, q) = (*face.pts.get(corner % m)?, *face.pts.get(before % m)?); let d = (p - q).normalized()?; let s = (o - p).dot(n) / d.dot(n); - (s.is_finite() && s >= -tol).then_some(p + d * s) + (d.cross(e).len() > 1e-6 && s.is_finite() && s >= -tol).then_some(p + d * s) }; - let (Some(p), Some(q)) = (slide(k, k + m - 1), slide(k + 1, k + 2)) else { - return err("a face beside a chamfer picked as a bend does not reach the face across it"); + // Where that edge is round or runs on along the chamfer's line (the face goes on past + // the chamfer's end), the end keeps its corner and steps down square to the edge onto + // the other plane: a step the bend's setback takes up again. + let w = face.n.cross(e); + let drop = |p: Vec3| -> Result { + let s = (o - p).dot(n) / w.dot(n); + if s.is_finite() { Ok(p + w * s) } else { err("a face beside a chamfer picked as a bend does not reach the face across it") } }; - if let Some(x) = face.pts.get_mut(k) { - *x = p; - } - if let Some(x) = face.pts.get_mut((k + 1) % m) { - *x = q; - } - if let Some(x) = face.across.get_mut(k) { - *x = Some(other); + let (next_across, next_round) = (face.across.get((k + 1) % m).copied().flatten(), face.round.get((k + 1) % m).copied().flatten()); + let start: Vec<(Vec3, Option)> = match slide(k, k + m - 1, k + m - 1) { + Some(p) => vec![(p, Some(other))], + None => vec![(p0, None), (drop(p0)?, Some(other))], + }; + let end: Vec<(Vec3, Option, Option<(Vec3, Vec3)>)> = match slide(k + 1, k + 2, k + 1) { + Some(q) => vec![(q, next_across, next_round)], + None => vec![(drop(q0)?, None, None), (q0, next_across, next_round)], + }; + let (mut pts, mut across, mut round) = (Vec::with_capacity(m + 2), Vec::with_capacity(m + 2), Vec::with_capacity(m + 2)); + for i in 0..m { + if i == k { + for (p, a) in &start { + pts.push(*p); + across.push(*a); + round.push(None); + } + } else if i == (k + 1) % m { + for (p, a, r) in &end { + pts.push(*p); + across.push(*a); + round.push(*r); + } + } else { + pts.push(face.pts.get(i).copied().unwrap_or_default()); + across.push(face.across.get(i).copied().flatten()); + round.push(face.round.get(i).copied().flatten()); + } } + (face.pts, face.across, face.round) = (pts, across, round); } Ok(face) } @@ -489,8 +518,10 @@ fn rip_cut(x: &Face, y: &Face, e: Vec3, t: f64, gap: f64) -> Result { /// A counter-clockwise outline with each edge moved in by its own amount. Moved edges meet /// where their lines cross; two edges in one line that move by different amounts are joined by -/// a square step. Returns the corners and, per edge, the edge it was (none for a step). -fn inset(pts: &[Vec2], by: &[f64]) -> Result<(Vec, Vec>)> { +/// a square step. An edge left shorter than `tol` (a step down to a bend's line that the bend's +/// setback takes up) is dropped, with the corner it shares with the edge that moved further. +/// Returns the corners and, per edge, the edge it was (none for a step). +fn inset(pts: &[Vec2], by: &[f64], tol: f64) -> Result<(Vec, Vec>)> { let n = pts.len(); if n < 3 { return err("a face of the sheet has no outline"); @@ -518,6 +549,15 @@ fn inset(pts: &[Vec2], by: &[f64]) -> Result<(Vec, Vec>)> { } from.push(Some(i)); } + let moved_by = |from: &[Option], j: usize| from.get(j).copied().flatten().and_then(|i| by.get(i)).map_or(0.0, |b| b.abs()); + while out.len() > 3 { + let m = out.len(); + let short = (0..m).find(|j| matches!((out.get(*j), out.get((j + 1) % m)), (Some(a), Some(b)) if a.dist(*b) <= tol)); + let Some(j) = short else { break }; + let corner = if moved_by(&from, (j + m - 1) % m) > moved_by(&from, (j + 1) % m) { j } else { (j + 1) % m }; + out.remove(corner); + from.remove(j); + } // Every edge still runs the way it did, and the outline is still one simple loop. let m = out.len(); let kept = (0..m).all(|j| match (from.get(j).copied().flatten().and_then(moved), out.get(j), out.get((j + 1) % m)) { @@ -899,7 +939,7 @@ pub fn convert_body( } let first = panel.face.pts.first().copied().unwrap_or_default(); let face_at = |e: DocError| DocError::Invalid(format!("{e} (the face at {})", at(first))); - let (trimmed, from) = inset(&pts, &by).map_err(face_at)?; + let (trimmed, from) = inset(&pts, &by, tol).map_err(face_at)?; let exact = drawn(&trimmed, &from, &pts, &round).map_err(face_at)?; match fl { None => sh.base.outer = exact.unwrap_or_else(|| Loop2::polygon(&trimmed.iter().map(|q| snap(*q)).collect::>())), @@ -1047,21 +1087,21 @@ mod tests { fn edges_move_in_by_their_own_amounts_and_step_along_one_line() { let v = Vec2::new; let square = [v(0.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]; - let (p, from) = inset(&square, &[1.0, 0.0, 2.0, 0.0]).unwrap(); + let (p, from) = inset(&square, &[1.0, 0.0, 2.0, 0.0], 1e-6).unwrap(); assert_eq!(p, vec![v(0.0, 1.0), v(10.0, 1.0), v(10.0, 8.0), v(0.0, 8.0)]); assert_eq!(from, vec![Some(0), Some(1), Some(2), Some(3)]); // Two edges in one line that move by different amounts: a square step between them, // so 5 x 2 goes from the 10 x 10. let split = [v(0.0, 0.0), v(5.0, 0.0), v(10.0, 0.0), v(10.0, 10.0), v(0.0, 10.0)]; - let (p, from) = inset(&split, &[0.0, 2.0, 0.0, 0.0, 0.0]).unwrap(); + let (p, from) = inset(&split, &[0.0, 2.0, 0.0, 0.0, 0.0], 1e-6).unwrap(); assert_eq!(p, vec![v(0.0, 0.0), v(5.0, 0.0), v(5.0, 2.0), v(10.0, 2.0), v(10.0, 10.0), v(0.0, 10.0)]); assert_eq!(from, vec![Some(0), None, Some(1), Some(2), Some(3), Some(4)]); // A slanted end keeps its line: the corner slides along it (2 up a 45° edge is 2 along). let slanted = [v(0.0, 0.0), v(10.0, 0.0), v(15.0, 5.0), v(0.0, 5.0)]; - let (p, _) = inset(&slanted, &[2.0, 0.0, 0.0, 0.0]).unwrap(); + let (p, _) = inset(&slanted, &[2.0, 0.0, 0.0, 0.0], 1e-6).unwrap(); assert!(p[1].dist(v(12.0, 2.0)) < 1e-12 && p[0].dist(v(0.0, 2.0)) < 1e-12, "{p:?}"); // Setbacks longer than the face leave nothing of it. - assert!(inset(&square, &[6.0, 0.0, 6.0, 0.0]).is_err()); - assert!(inset(&square, &[f64::NAN, 0.0, 0.0, 0.0]).is_err()); + assert!(inset(&square, &[6.0, 0.0, 6.0, 0.0], 1e-6).is_err()); + assert!(inset(&square, &[f64::NAN, 0.0, 0.0, 0.0], 1e-6).is_err()); } } diff --git a/crates/engine/src/cmd/sheet_convert_tests.rs b/crates/engine/src/cmd/sheet_convert_tests.rs index 1618b1a24..9ce377d39 100644 --- a/crates/engine/src/cmd/sheet_convert_tests.rs +++ b/crates/engine/src/cmd/sheet_convert_tests.rs @@ -1777,3 +1777,80 @@ fn a_wall_on_part_of_an_edge_meets_a_wall_at_a_relieved_corner_and_is_relieved_a run(&mut s, "sheet.refold", json!({})); assert!((volume(&mut s) - v).abs() < 1e-6 * v); } + +/// A tray of this build's own sheet metal: a 120 x 90 base, T 1, R 1, K 0.5, gap 0.6, its four +/// walls 30 high under the rule's corner relief `shape`, made in one edge flange feature or in +/// two (long walls, then short), written to a STEP and inserted into a new design as a plain +/// solid. Its bends are picked at mid-length on their outer cylinders, (R + T) out from their +/// axes 45° round from the base. Returns the new design (with the rule), the picks and the +/// design the tray was made in. +fn tray_round_trip(shape: &str, two: bool) -> (Session, Vec<[f64; 3]>, Session) { + let (t, r) = (1.0, 1.0); + let rule = json!({"name": "T", "thickness": "1 mm", "k_factor": "0.5", "bend_radius": "1 mm", "gap": "0.6 mm", "corner_relief_shape": shape, "corner_relief": "3 mm", "active": true}); + let mut a = Session::default(); + run(&mut a, "sheet.manage_rules", rule.clone()); + run(&mut a, "sketch.create", json!({"plane": "XY", "name": "Base"})); + run(&mut a, "sketch.rectangle.two_point", json!({"p0": [0, 0], "p1": [120, 90]})); + run(&mut a, "sketch.finish", json!({})); + run(&mut a, "sheet.flange", json!({"type": "base", "sketch": "Base", "rule": "T"})); + let (long, short) = (json!([[60, 0, 1], [60, 90, 1]]), json!([[120, 45, 1], [0, 45, 1]])); + if two { + run(&mut a, "sheet.flange", json!({"edges": long, "height": 30})); + run(&mut a, "sheet.flange", json!({"edges": short, "height": 30})); + } else { + let mut all = long.as_array().cloned().unwrap_or_default(); + all.extend(short.as_array().cloned().unwrap_or_default()); + run(&mut a, "sheet.flange", json!({"edges": all, "height": 30})); + } + let path = std::env::temp_dir().join(format!("solidcraft-tray-round-trip-{shape}-{two}-{}.step", std::process::id())); + run(&mut a, "file.export", json!({"path": path.to_string_lossy()})); + let mut s = Session::default(); + run(&mut s, "file.insert_step", json!({"path": path.to_string_lossy()})); + let _ = std::fs::remove_file(&path); + run(&mut s, "sheet.manage_rules", rule); + // Each bend's axis lies R + T in from the base's edge and R + T above its bottom face. + let (o, d) = (r + t, (r + t) * std::f64::consts::FRAC_1_SQRT_2); + let picks = vec![[60.0, o - d, o - d], [60.0, 90.0 - o + d, o - d], [120.0 - o + d, 45.0, o - d], [o - d, 45.0, o - d]]; + (s, picks, a) +} + +/// The flat's outline area and its bends' lengths, longest first. +fn flat_area_and_bends(s: &mut Session) -> (f64, Vec) { + let f = flat(s); + let ring = |l: &Value| { + let p: Vec<(f64, f64)> = + l.as_array().into_iter().flatten().map(|q| (q[0].as_f64().unwrap_or(f64::NAN), q[1].as_f64().unwrap_or(f64::NAN))).collect(); + (0..p.len()).map(|i| p[i].0 * p[(i + 1) % p.len()].1 - p[(i + 1) % p.len()].0 * p[i].1).sum::().abs() / 2.0 + }; + let area = f["outline"].as_array().into_iter().flatten().map(ring).sum(); + let mut bends: Vec = f["bends"].as_array().into_iter().flatten().map(|b| b["length"].as_f64().unwrap_or(f64::NAN)).collect(); + bends.sort_by(|x, y| y.total_cmp(x)); + (area, bends) +} + +/// A tray made with this build's sheet metal converts back to the same tray: the walls that run +/// on past their bends' ends (a notch, a tear) step down to the bend there, and a round relief's +/// arc stays; also with the short walls made in a second feature, where the corners are notched +/// or round (a torn butt corner is torn differently from one feature's corner). +#[test] +fn trays_of_its_own_sheet_metal_convert_back() { + for shape in ["notch", "tear", "round"] { + for two in [false, true].into_iter().filter(|two| !(*two && shape == "tear")) { + let what = format!("{shape}, {}", if two { "two features" } else { "one feature" }); + let (mut s, picks, mut source) = tray_round_trip(shape, two); + let body = s.model.state().bodies.first().map(|b| b.name.clone()).unwrap_or_default(); + let out = s.execute("sheet.convert", &json!({"body": body, "face": [60, 45, 0], "bends": picks, "rule": "T"})); + assert!(out.is_ok(), "{what}: {}", out.err().map(|e| e.to_string()).unwrap_or_default()); + // The same tray: its solid, and its flat with the same bends. + let (v, size, (area, bends)) = (volume(&mut source), flat_size(&mut source), flat_area_and_bends(&mut source)); + assert!((volume(&mut s) - v).abs() < 1e-9 * v, "{what}: {} vs {v}", volume(&mut s)); + assert!(same_size(flat_size(&mut s), size, 1e-6), "{what}: {:?} vs {size:?}", flat_size(&mut s)); + let (got_area, got_bends) = flat_area_and_bends(&mut s); + assert!((got_area - area).abs() < 1e-9 * area, "{what}: {got_area} vs {area}"); + assert!( + got_bends.len() == bends.len() && got_bends.iter().zip(&bends).all(|(x, y)| (x - y).abs() < 1e-6), + "{what}: {got_bends:?} vs {bends:?}" + ); + } + } +}