SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Wave 116/509: doc: a sweep round a closed path starts where the profile is (#3345) (and 3 more)
jyvikoec7077e3261f
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 3f04d342c9..36d5ca947a 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -5698,7 +5698,7 @@ fn feature_tools_with_constructor(let points = path_points(ps, path, start)?;let segs = match points {Some(_) => Vec::new(),- None => path_segments(ps, path, start)?,+ None => path_segments_at(ps, path, start, Some(&ss.plane))?,};let path_start =points.as_ref().and_then(|p| p.points().first().copied()).or_else(|| segs.first().map(kernel::PathSeg::start)).unwrap_or(start);@@ -5973,6 +5973,14 @@ fn path_points(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Option<}fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Vec<kernel::PathSeg>> {+ path_segments_at(ps, ids, start, None)+}++/// [`path_segments`] for a profile in `profile`: a closed path is followed from where the+/// profile's plane crosses it nearest `start`, the curve there split in two, when that is not+/// already where the chain starts (#3345). Swept from anywhere else, the profile would stand+/// off the path by the distance between the two.+pub(crate) fn path_segments_at(ps: &SolvedSketch, ids: &[String], start: Vec3, profile: Option<&Plane>) -> Result<Vec<kernel::PathSeg>> {if ids.is_empty() || ids.len() > 1000 {return Err(DocError::Invalid("the path needs 1…1000 curves".into()));}@@ -6011,6 +6019,9 @@ fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Vec<kreturn Err(DocError::Invalid("the path curves are not connected end to end".into()));}}+ if let Some(profile) = profile {+ segs = from_profile_on_closed_path(segs, &ps.plane, profile, start);+ }let n = ps.plane.normal();Ok(segs.iter()@@ -6026,6 +6037,50 @@ fn path_segments(ps: &SolvedSketch, ids: &[String], start: Vec3) -> Result<Vec<k.collect())}+/// A closed chain `segs` (in the plane `path`) begun where `profile`'s plane crosses it nearest+/// `start`: the curve there split in two, its second part first and its first part last (or the+/// chain begun at the joint there). Unchanged when the chain is open, already starts on the+/// profile's plane, or its point nearest `start` is off that plane.+fn from_profile_on_closed_path(segs: Vec<solidcraft_geom::Seg2>, path: &Plane, profile: &Plane, start: Vec3) -> Vec<solidcraft_geom::Seg2> {+ let (Some(first), Some(last)) = (segs.first(), segs.last()) else { return segs };+ let size: f64 = segs.iter().map(solidcraft_geom::Seg2::length).sum();+ let on_plane = |p: Vec2| profile.height(path.to_world(p)).abs() <= (size * 1e-9).max(1e-9);+ if !start.is_finite() || !(size > 0.0 && size.is_finite()) || last.end().dist(first.start()) > 1e-5 || on_plane(first.start()) {+ return segs;+ }+ let local = path.to_local(start);+ let Some((k, t, q)) = segs+ .iter()+ .enumerate()+ .map(|(k, s)| {+ let t = s.closest_param(local);+ (k, t, path.to_world(s.point_at(t)))+ })+ .min_by(|a, b| a.2.dist(start).total_cmp(&b.2.dist(start)))+ else {+ return segs;+ };+ if profile.height(q).abs() > (size * 1e-6).max(1e-6) {+ return segs;+ }+ let Some(seg) = segs.get(k).copied() else { return segs };+ let n = segs.len();+ let from = |k: usize| segs.iter().cycle().skip(k % n).take(n).copied().collect::<Vec<_>>();+ let at = |p: Vec2| path.to_world(p).dist(q) <= 1e-6;+ if at(seg.start()) {+ return from(k);+ }+ if at(seg.end()) {+ return from(k + 1);+ }+ let (before, after) = seg.split_at(t);+ let mut out = Vec::with_capacity(n + 1);+ out.push(after);+ out.extend(from(k + 1).into_iter().take(n - 1));+ out.push(before);+ out+}+/// Where an extrude of distance `d` starts and ends along the sketch normal, before any start/// offset: one side, the other, both (symmetric), or a second distance on the other side.///diff --git a/crates/doc/src/eval_surface.rs b/crates/doc/src/eval_surface.rsindex dbaa5506d5..5915e52f1a 100644--- a/crates/doc/src/eval_surface.rs+++ b/crates/doc/src/eval_surface.rs@@ -378,7 +378,7 @@ pub(super) fn eval(doc: &Document, vals: &BTreeMap<String, Value>, f: &Feature,kernel::sweep_sheet_points_with(&ss.plane, &chains, &pts, &ctl)?}None => {- let segs = path_segments(ps, path, start)?;+ let segs = path_segments_at(ps, path, start, Some(&ss.plane))?;let path_start = segs.first().map_or(start, kernel::PathSeg::start);let rails = crate::eval::rail_polylines(doc, st, rails, f.component, path_start)?;let ctl = crate::eval::sweep_control(vals, orientation, twist, scale, rails, *rail_fit)?;diff --git a/crates/engine/src/cmd/features.rs b/crates/engine/src/cmd/features.rsindex 89140d9821..c99a4f294b 100644--- a/crates/engine/src/cmd/features.rs+++ b/crates/engine/src/cmd/features.rs@@ -693,6 +693,17 @@ fn add_feature_in(s: &mut Session, p: &Value, kind: FeatureKind, world: bool) ->} else {participants};+ // An extrude's Join, Cut or Intersect with no bodies picked changes the bodies of the active+ // component that are shown, never a hidden one (#2464). The shown ones are kept as its+ // participants, so showing or hiding bodies later doesn't change the model.+ let participants = match &kind {+ FeatureKind::Extrude { operation: Operation::Join | Operation::Cut | Operation::Intersect, targets, .. }+ if participants.is_empty() && targets.is_empty() =>+ {+ shown_scope(s).unwrap_or_default()+ }+ _ => participants,+ };if matches!(kind, FeatureKind::ConstructionPlane { .. })&& let Some(n) = name{@@ -828,9 +839,6 @@ fn extrude(s: &mut Session, p: &Value) -> Result<Value> {} else if let Some(parts) = cut_scope(s, &p, operation, sketch, face_body)? {p.to_mut()["participants"] = json!(parts);}- if matches!(operation, Operation::Cut | Operation::Intersect) && targets.is_empty() && string_list(&p, "participants").is_empty() {- targets = shown_scope(s);- }let kind = FeatureKind::Extrude {sketch: SketchId(sketch),profiles: match face_profile {@@ -975,17 +983,6 @@ fn face_body_reached(s: &Session, sketch: u64) -> Result<Option<String>> {Ok(Some(body.name.clone()))}-/// A cut or intersect that names no bodies leaves hidden bodies alone, as hiding a body to keep-/// it out of a cut is the usual way to (#3961): while some of the active component's bodies-/// are hidden, its shown ones, stored as the feature's targets so showing the others again-/// later changes nothing. Empty (every body, as before) when none is hidden, or all are.-fn shown_scope(s: &Session) -> Vec<String> {- let st = s.model.state();- let scope = active_scope(s, &st);- let shown: Vec<String> = scope.iter().filter(|b| s.body_visible(&b.name)).map(|b| b.name.clone()).collect();- if shown.len() == scope.len() { Vec::new() } else { shown }-}-/// The body whose face `sketch` is attached to (on the face itself, not offset from it), when/// it is one the active component works on ([`active_scope`]).fn sketch_face_body(s: &Session, sketch: u64) -> Option<String> {@@ -2961,6 +2958,15 @@ fn offset_face(s: &mut Session, p: &Value) -> Result<Value> {)}+/// The shown bodies of the active component, where some of its bodies are hidden and some shown;+/// `None` where all of them are shown (or none), and the feature's usual scope applies.+fn shown_scope(s: &Session) -> Option<Vec<String>> {+ let st = s.model.state();+ let (shown, hidden): (Vec<&solidcraft_doc::ModelBody>, Vec<_>) =+ st.bodies.iter().filter(|b| s.doc.model_body_component(b) == s.active_component).partition(|b| s.body_visible(&b.name));+ (!shown.is_empty() && !hidden.is_empty()).then(|| shown.iter().map(|b| b.name.clone()).collect())+}+#[cfg(test)]#[path = "patterns_tests.rs"]mod patterns_tests;diff --git a/crates/engine/src/cmd/sweep_options_tests.rs b/crates/engine/src/cmd/sweep_options_tests.rsindex f85e7c8544..797955a79c 100644--- a/crates/engine/src/cmd/sweep_options_tests.rs+++ b/crates/engine/src/cmd/sweep_options_tests.rs@@ -161,3 +161,34 @@ fn hostile_sweep_options_are_refused() {assert_eq!(s.doc.features.len(), before, "{bad}");}}++/// #3345: a 4 x 3 profile drawn at the middle of the bottom line of a closed rounded rectangle+/// (60 x 40, corners r8), swept round all of it, path picked from that line's start. The path is+/// followed from the profile: the tube stays on the path (Pappus: A L), within 2 mm of it+/// sideways, instead of standing off it by the half line the path's start lies away.+#[test]+fn a_sweep_round_a_closed_path_starts_where_the_profile_is() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": "XY", "name": "Path"}));+ run(&mut s, "sketch.line", json!({"points": [[-22, -20], [22, -20]], "infer": false, "ids": ["l1"]}));+ run(&mut s, "sketch.arc.center_point", json!({"center": [22, -12], "start": [22, -20], "end": [30, -12], "id": "a1"}));+ run(&mut s, "sketch.line", json!({"points": [[30, -12], [30, 12]], "infer": false, "ids": ["l2"]}));+ run(&mut s, "sketch.arc.center_point", json!({"center": [22, 12], "start": [30, 12], "end": [22, 20], "id": "a2"}));+ run(&mut s, "sketch.line", json!({"points": [[22, 20], [-22, 20]], "infer": false, "ids": ["l3"]}));+ run(&mut s, "sketch.arc.center_point", json!({"center": [-22, 12], "start": [-22, 20], "end": [-30, 12], "id": "a3"}));+ run(&mut s, "sketch.line", json!({"points": [[-30, 12], [-30, -12]], "infer": false, "ids": ["l4"]}));+ run(&mut s, "sketch.arc.center_point", json!({"center": [-22, -12], "start": [-30, -12], "end": [-22, -20], "id": "a4"}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "sketch.create", json!({"plane": {"origin": [0, -20, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Prof"}));+ run(&mut s, "sketch.rectangle.center", json!({"center": [0, 0], "corner": [2, 1.5]}));+ run(&mut s, "sketch.finish", json!({}));+ let path = json!(["l1", "a1", "l2", "a2", "l3", "a3", "l4", "a4"]);+ run(&mut s, "solid.sweep", json!({"sketch": "Prof", "path_sketch": "Path", "path": path, "operation": "new", "body_name": "Tube"}));+ let m = measure(&s, "Tube");+ let want = 12.0 * (2.0 * 44.0 + 2.0 * 24.0 + 4.0 * (PI / 2.0) * 8.0);+ assert!((m.volume - want).abs() < want * 1e-3, "{} vs {want}", m.volume);+ // Within the rig's 1e-3 of the box diagonal (the box is measured on a mesh).+ for (got, want) in [(m.bbox.min.x, -32.0), (m.bbox.min.y, -22.0), (m.bbox.max.x, 32.0), (m.bbox.max.y, 22.0)] {+ assert!((got - want).abs() < 0.08, "{:?}", m.bbox);+ }+}diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rsindex 565d6a6674..a4c2ca75aa 100644--- a/crates/engine/src/tests.rs+++ b/crates/engine/src/tests.rs@@ -4493,3 +4493,27 @@ fn a_cut_leaves_hidden_bodies_alone() {let shown = setup(false);assert!(vol(&shown, "Below") < full - 1.0 && vol(&shown, "Above") < full - 1.0, "with nothing hidden, both are cut");}++/// #2464: an extrude Join with no targets onto a plate with a hidden coincident copy changes the+/// shown plate only, and keeps the shown bodies as its participants.+#[test]+fn join_leaves_a_hidden_body_alone() {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 40, "width": 40, "height": 5, "body_name": "Plate"}));+ run(&mut s, "solid.move", json!({"bodies": ["Plate"], "copy": true}));+ run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": false}));+ run(&mut s, "sketch.create", json!({"plane": "XY", "offset": 5, "name": "Rim"}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [2, 2], "p1": [38, 38]}));+ run(&mut s, "sketch.rectangle.two_point", json!({"p0": [4, 4], "p1": [36, 36]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "Rim", "profiles": [{"point": [3, 3]}], "distance": 3, "operation": "join"}));+ let st = s.model.state();+ assert_eq!(st.bodies.len(), 2);+ let v = |n: &str| solidcraft_kernel::measure(&st.body(n).unwrap().body).unwrap().volume;+ assert!(rel(v("Plate"), 8816.0) < 1e-9 && rel(v("Plate (2)"), 8000.0) < 1e-9);+ let f = s.doc.features.last().unwrap();+ assert_eq!(f.participants, vec!["Plate".to_string()]);+ // Showing the copy again doesn't change the model.+ run(&mut s, "browser.visibility", json!({"items": ["Plate (2)"], "visible": true}));+ assert_eq!(s.model.state().bodies.len(), 2);+}diff --git a/tests/kernel-cases/ladder/05-holes-and-taps/011-crossing-holes-steinmetz/expected.json b/tests/kernel-cases/ladder/05-holes-and-taps/011-crossing-holes-steinmetz/expected.jsonindex 842f4aaf17..8f9ce79fcd 100644--- a/tests/kernel-cases/ladder/05-holes-and-taps/011-crossing-holes-steinmetz/expected.json+++ b/tests/kernel-cases/ladder/05-holes-and-taps/011-crossing-holes-steinmetz/expected.json@@ -2,8 +2,8 @@"sources": [],"what": "two d10 through holes whose axes cross: vertical and along Y at z=10","source": "analytic",- "method": "equal radii, crossing axes: the common part is the Steinmetz solid 16 r^3 / 3; removed pi r^2 (20 + 40) - 16 r^3/3",+ "method": "equal radii, crossing axes: the common part is the Steinmetz solid 16 r^3 / 3; removed pi r^2 (20 + 40) - 16 r^3/3. Faces: the stock's 6 and two per hole. With equal radii the walls cross along two ellipses that meet at the two points where the walls are tangent (x = 25 and 35, y = 20, z = 10), so each wall is left in two pieces (the vertical one above and below the other hole, the horizontal one either side of the vertical hole) that touch only at those points: no edge joins them, so they are separate faces","body_count": 1,"volume_mm3": 43954.277686282,- "faces": 8+ "faces": 10}diff --git a/tools/kernel-ladder/cases.py b/tools/kernel-ladder/cases.pyindex df546855e8..fd066b0179 100644--- a/tools/kernel-ladder/cases.py+++ b/tools/kernel-ladder/cases.py@@ -299,8 +299,12 @@ case(T5, "010-hole-tangent-to-end-face", "a d10 through hole tangent to the end{"body_count": 1, "volume_mm3": VB - PI * 25 * 20}, "the wall touches x=0 along a line: removed pi 5^2 20, one body", base=B1)case(T5, "011-crossing-holes-steinmetz", "two d10 through holes whose axes cross: vertical and along Y at z=10",[H(position=top, diameter=10), H(position=[30, 0, 10], diameter=10)],- {"body_count": 1, "volume_mm3": VB - PI * 25 * 20 - PI * 25 * 40 + 16 * 125 / 3, "faces": 8},- "equal radii, crossing axes: the common part is the Steinmetz solid 16 r^3 / 3; removed pi r^2 (20 + 40) - 16 r^3/3", base=B1)+ {"body_count": 1, "volume_mm3": VB - PI * 25 * 20 - PI * 25 * 40 + 16 * 125 / 3, "faces": 10},+ "equal radii, crossing axes: the common part is the Steinmetz solid 16 r^3 / 3; removed pi r^2 (20 + 40) - 16 r^3/3. "+ "Faces: the stock's 6 and two per hole. With equal radii the walls cross along two ellipses that meet at the two "+ "points where the walls are tangent (x = 25 and 35, y = 20, z = 10), so each wall is left in two pieces (the vertical "+ "one above and below the other hole, the horizontal one either side of the vertical hole) that touch only at those "+ "points: no edge joins them, so they are separate faces", base=B1)rr, off = 2.5, 2.0lo, hi = max(-rr, off - rr), min(rr, off + rr)vx = quad(lambda u: 4 * math.sqrt(max(rr * rr - u * u, 0)) * math.sqrt(max(rr * rr - (u - off) ** 2, 0)), lo, hi, 256)