SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Fix drilled hole cuts through tapered walls (#2387) (#2401)
fkirill9ee2de9a0f3a
diff --git a/crates/engine/src/hole_face_tests.rs b/crates/engine/src/hole_face_tests.rsindex 9f026ba43f..43d6499e1a 100644--- a/crates/engine/src/hole_face_tests.rs+++ b/crates/engine/src/hole_face_tests.rs@@ -322,3 +322,55 @@ fn sketch_floating_in_the_gap_touching_neither_still_drills_down() {near(base - volume(&mut s), pi() * 25.0 * 4.0);assert!(!solid_at(&s, 20.0, 20.0, 4.0) && solid_at(&s, 20.0, 20.0, 16.0));}++/// #2387: a drill point crossing the sloping back of a wall must leave a real hole.+#[test]+fn drilled_sketch_points_break_through_a_sloping_back_face() {+ let mut s = Session::default();+ run(&mut s, "sketch.create", json!({"plane": {"origin": [0, 0, 0], "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}, "name": "Wall"}));+ run(&mut s, "sketch.line", json!({"points": [[0, 0], [15, 0], [15, 30], [7.5, 30], [0, 0]]}));+ run(&mut s, "sketch.finish", json!({}));+ run(&mut s, "solid.extrude", json!({"sketch": "Wall", "distance": 40, "direction": "negative"}));+ run(&mut s, "sketch.create", json!({"plane": {"origin": [15, 0, 0], "x_dir": [0, 1, 0], "y_dir": [0, 0, 1]}, "name": "Pts"}));+ run(&mut s, "sketch.line", json!({"points": [[5, 16], [10, 16]], "ids": ["l10"]}));+ run(&mut s, "sketch.point", json!({"point": [30, 16], "id": "p12"}));+ run(&mut s, "sketch.finish", json!({}));+ run(+ &mut s,+ "solid.hole",+ json!({"sketch": "Pts", "points": ["l10.end", "p12"], "depth": "10 mm", "diameter": "5 mm", "type": "drilled", "tip_angle": "118 deg", "name": "H"}),+ );+ let id = s.doc.find_feature("H").unwrap().id;+ let result = s.model.result(id).unwrap();+ assert!(result.error.is_none());+ assert!(result.boolean_diagnostics.unverified().is_none());+ // The cylindrical bore and cone, less the oblique conical cap outside x = z/4.+ let r = 2.5;+ let k = 59f64.to_radians().tan();+ let tip = r / k;+ let outside = 4.0 - (5.0 - tip);+ let cap = pi() * k * k * outside.powi(3) / (3.0 * (1.0 - (k / 4.0).powi(2)).powf(1.5));+ let expected = 2.0 * (pi() * r * r * (10.0 + tip / 3.0) - cap);+ let left = volume(&mut s);+ // The measured curved faces are tessellated; 0.05 mm³ is 0.013% of the removed material.+ assert!((13_500.0 - left - expected).abs() < 0.05, "removed {} vs {expected}", 13_500.0 - left);+ assert_eq!(s.model.state().bodies.len(), 1);+ for b in &s.model.state().bodies {+ assert!(b.body.validity().is_empty());+ assert_eq!(b.body.shell_count(), 1);+ }+ for y in [10.0, 30.0] {+ assert!(!solid_at(&s, 10.0, y, 16.0), "bore at y = {y}");+ assert!(!solid_at(&s, 4.2, y, 16.0), "tip breaks through at y = {y}");+ assert!(solid_at(&s, 10.0, y + 3.0, 16.0), "material beside the bore at y = {y}");+ }+ let saved = s.doc.to_json();+ run(&mut s, "edit.undo", json!({}));+ near(volume(&mut s), 13_500.0);+ run(&mut s, "edit.redo", json!({}));+ assert_eq!(s.doc.to_json(), saved);+ near(volume(&mut s), left);+ let mut reopened = Session::new(solidcraft_doc::Document::from_json(&saved).unwrap());+ assert!(reopened.model.result(id).unwrap().error.is_none());+ near(volume(&mut reopened), left);+}diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rsindex e12e407e4b..dc3e0100e0 100644--- a/crates/kernel/src/boolean_diagnostics.rs+++ b/crates/kernel/src/boolean_diagnostics.rs@@ -18,6 +18,8 @@ pub enum BooleanStrategy {GrownBoss,PlanarFallback,ToolNudge,+ /// A rotationally symmetric tool turned about its own axis; its volume is unchanged.+ ToolReseam,Piecewise,/// No retry gave a result, and the answer from sample points was kept although the bodies'/// facetings disagree with it.@@ -61,6 +63,7 @@ impl BooleanFallback {BooleanStrategy::GrownBoss => format!("boss grown {:.6e} mm into the material around the bore it fills", self.face_shift_mm),BooleanStrategy::PlanarFallback => "exact planar fallback (no displacement)".into(),BooleanStrategy::ToolNudge => format!("tool displacement {:.6e} mm, rotation {:.6e} rad", self.translation_mm, self.rotation_rad),+ BooleanStrategy::ToolReseam => format!("axisymmetric tool reseamed by {:.6e} rad (no displacement)", self.rotation_rad),BooleanStrategy::Piecewise => "piecewise retry (no displacement)".into(),BooleanStrategy::UnverifiedShortcut => format!("not verified: the bodies' facets pass through each other by more than {:.6e} mm, but they could not be intersected there; that part is ignored",diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex 08512db651..8433beb150 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -15,6 +15,9 @@ use crate::{KernelError, Result, guard, record};#[path = "bore_union_tests.rs"]mod bore_union_tests;+#[path = "tool_reseam.rs"]+mod tool_reseam;+#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum BoolOp {@@ -572,6 +575,13 @@ fn boolean_untimed(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {}}let r = boolean_via(a, b, op, &boolean_whole);+ if r.is_err()+ && op == BoolOp::Cut+ && !APART.with(|c| c.get())+ && let Some(result) = tool_reseam::cut(a, b)+ {+ return Ok(Some(result));+ }if r.is_ok() || !crate::tangent_cylinders::needed(a, b) {return r;}diff --git a/crates/kernel/src/tool_reseam.rs b/crates/kernel/src/tool_reseam.rsnew file mode 100644index 0000000000..e0c09776c8--- /dev/null+++ b/crates/kernel/src/tool_reseam.rs@@ -0,0 +1,124 @@+//! Retry a failed cut with different boundaries between a round tool's faces (#2387).+//! Every curved support must be a revolution about the same axis and every planar support+//! perpendicular to it. Turning this closed solid about that axis changes only its seams.++use solidcraft_geom::Vec3;+use truck_modeling::{self as mt, InnerSpace, Transform};++use super::{BoolOp, boolean_via, boolean_whole, nudged, transform};+use crate::body::{Body, from_p3};+use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record};+use crate::{guard, record};++thread_local! {+ static ACTIVE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };+}++/// Exact revolution axes, rather than a fit to sampled normals: splines and affine+/// distortions of round tools must never be mistaken for rotational symmetry.+fn axis(body: &Body) -> Option<(Vec3, Vec3)> {+ if body.is_mesh() || body.shell_count() != 1 || body.face_count() > 64 {+ return None;+ }+ guard("round tool axis", || {+ let mut axes = Vec::new();+ let mut normals = Vec::new();+ for face in body.solid.face_iter() {+ match face.surface() {+ mt::Surface::Plane(p) => {+ let n = p.normal();+ let Some(n) = Vec3::new(n.x, n.y, n.z).normalized() else { return Ok(None) };+ normals.push(n);+ }+ mt::Surface::RevolutedCurve(s) => {+ let m = s.transform();+ let (x, y, z) = (m.x.truncate(), m.y.truncate(), m.z.truncate());+ // Only rigid transforms: no elliptic scaling of the revolution.+ if [x, y, z].iter().any(|v| (v.magnitude2() - 1.0).abs() > 1e-9)+ || [x.dot(y), x.dot(z), y.dot(z)].iter().any(|v| v.abs() > 1e-9)+ || m.x.w != 0.0+ || m.y.w != 0.0+ || m.z.w != 0.0+ || m.w.w != 1.0+ {+ return Ok(None);+ }+ let o = from_p3(m.transform_point(s.entity().origin()));+ let a = m.transform_vector(s.entity().axis());+ let Some(a) = Vec3::new(a.x, a.y, a.z).normalized() else { return Ok(None) };+ axes.push((o, a));+ }+ _ => return Ok(None),+ }+ }+ let Some(&(o, a)) = axes.first() else { return Ok(None) };+ let tol = (body.size() * 1e-9).max(1e-10);+ let same = axes.iter().all(|(p, d)| a.cross(*d).len() < 1e-9 && (*p - o).cross(a).len() < tol);+ // Surface orientation can reverse the same axis. Choose a stable direction for retries.+ let first = [a.x, a.y, a.z].into_iter().find(|v| v.abs() > 1e-9).unwrap_or(1.0);+ let a = if first < 0.0 { -a } else { a };+ Ok((same && normals.iter().all(|n| n.cross(a).len() < 1e-9)).then_some((o, a)))+ })+ .ok()+ .flatten()+}++pub(super) fn cut(target: &Body, tool: &Body) -> Option<Body> {+ if ACTIVE.with(|a| a.get()) {+ return None;+ }+ let (origin, axis) = axis(tool)?;+ ACTIVE.with(|a| a.set(true));+ let result = guard("cut with reseamed tool", || {+ let counts = record::counts(&[target, tool]);+ // Bounded exact retries. Keep the original error if neither can be verified.+ for angle in [0.3, -0.3, 0.7, -0.7] {+ let turned = transform(tool, Vec3::ZERO, origin, axis, angle)?;+ let (result, diagnostics) = capture_boolean_diagnostics(|| boolean_via(target, &turned, BoolOp::Cut, &boolean_whole));+ if let Ok(Some(body)) = result+ && crate::boolean_guard::check_retry(target, tool, BoolOp::Cut, Some(&body)).is_ok()+ {+ let body = nudged(body, &turned, &counts);+ merge(diagnostics);+ let mut event = BooleanFallback::new(BooleanStrategy::ToolReseam);+ event.rotation_rad = angle;+ record(event);+ return Ok(Some(body));+ }+ }+ Ok(None)+ })+ .ok()+ .flatten();+ ACTIVE.with(|a| a.set(false));+ result+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::transform_matrix;+ use solidcraft_geom::{Loop2, Plane, Region2, Vec2};++ fn drill(angle: f64) -> Body {+ let profile =+ Region2 { outer: Loop2::polygon(&[Vec2::new(0., 1.), Vec2::new(2.5, 1.), Vec2::new(2.5, -10.), Vec2::new(0., -11.5)]), holes: vec![] };+ crate::revolve(&Plane::XZ, &[profile], Vec2::ZERO, Vec2::Y, angle).unwrap().pop().unwrap()+ }++ #[test]+ fn only_complete_coaxial_revolutions_can_be_reseamed() {+ let tool = drill(std::f64::consts::TAU);+ assert!(axis(&tool).is_some());+ let placed = transform(&tool, Vec3::new(11., -7., 5.), Vec3::ZERO, Vec3::new(1., 2., 3.), 0.8).unwrap();+ let (o, a) = axis(&placed).unwrap();+ let turned = transform(&placed, Vec3::ZERO, o, a, 0.3).unwrap();+ assert!((crate::measure(&placed).unwrap().volume - crate::measure(&turned).unwrap().volume).abs() < 1e-6);+ // A partial turn's radial caps would move; an affine scale can make the bore elliptic.+ assert!(axis(&drill(std::f64::consts::PI)).is_none());+ let scaled = transform_matrix(&tool, [[2., 0., 0., 0.], [0., 1., 0., 0.], [0., 0., 1., 0.], [0., 0., 0., 1.]]).unwrap();+ assert!(axis(&scaled).is_none());+ let block = crate::box_solid(Vec3::ZERO, Vec3::new(10., 20., 30.)).unwrap();+ assert!(axis(&block).is_none());+ }+}diff --git a/tests/robustness/goldens.json b/tests/robustness/goldens.jsonindex d1fe22461d..56d799e330 100644--- a/tests/robustness/goldens.json+++ b/tests/robustness/goldens.json@@ -87,7 +87,7 @@"83": {"area":8632.834978,"bodies":1,"edges":95,"error":null,"faces":35,"outcome":"ok","rejected":0,"shells":2,"steps":["box","join box","rectangular pattern","shell","cut sphere","join box","fillet"],"unsupported":2,"volume":6339.218896},"84": {"area":4906.192237,"bodies":1,"edges":67,"error":null,"faces":25,"outcome":"ok","rejected":2,"shells":1,"steps":["extruded profile","fillet","hole","hole","cut cylinder","cut box","fillet"],"unsupported":0,"volume":14219.865875},"85": {"area":3309.210936,"bodies":1,"edges":57,"error":null,"faces":24,"outcome":"ok","rejected":1,"shells":2,"steps":["revolved section","fillet","cut sphere","circular pattern","join cylinder","hole","join box"],"unsupported":0,"volume":6904.455565},- "86": {"area":7885.256491,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":28,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","rectangular pattern","shell"],"unsupported":2,"volume":21498.10695},+ "86": {"area":7570.844423,"bodies":1,"edges":66,"error":"offset: a corner whose faces don't meet the same way after t","faces":30,"outcome":"failed","rejected":0,"shells":3,"steps":["extruded profile","join cylinder","join cylinder","circular pattern","hole","rectangular pattern","shell"],"unsupported":1,"volume":20478.868768},"87": {"area":4853.708989,"bodies":1,"edges":24,"error":null,"faces":10,"outcome":"ok","rejected":0,"shells":1,"steps":["extruded profile","cut box","rectangular pattern"],"unsupported":0,"volume":18568.611108},"88": {"area":3947.799648,"bodies":1,"edges":18,"error":null,"faces":8,"outcome":"ok","rejected":0,"shells":1,"steps":["box","hole"],"unsupported":0,"volume":12788.04706},"89": {"area":2512.5,"bodies":1,"edges":12,"error":null,"faces":6,"outcome":"ok","rejected":0,"shells":1,"steps":["box","cut box"],"unsupported":0,"volume":5906.25},@@ -140,6 +140,8 @@{"platform":"windows","reason":"Independently reproduced on unmodified main 1e984c8e on Windows; the extrusion branch produces the same values. Shared references and tolerances remain unchanged.","seeds":[1,23,34,67]},{"platform":"windows","reason":"Seed 94 independently reproduced on unmodified main c5992386 on Windows after the extrusion rebase: the same steps, outcome and geometry values as the rebased branch. Shared references and tolerances remain unchanged.","seeds":[94]},{"reason":"#2064 (multi-profile extrusion) merges coplanar faces the boolean used to leave split. Seed 67 has one face/two edges fewer from its first cut on, at the same volume at every step; seed 94's last box cut leaves one face/two edges more, same volume and area. Seed 13's second cylinder cut leaves 35 faces/84 edges instead of 37/88 at the same volume, so its random fillet (edges picked by index) rounds different edges: 2688.99 instead of 2675.18 mm3 after the fillet; the hole after it removes the same 278.2 mm3. Every step passes the validity and volume-direction checks. Pull request CI ran only every 8th seed, so main was the first run to see these.","seeds":[13,67,94]},- {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]}+ {"reason":"#2247: a cut no longer splits the separate pieces of a body into bodies of their own, so these seeds keep one body (bodies N -> 1). The generator looks at the model, so after the first such cut some seeds build different steps: seed 33 joins and patterns a box instead of chamfering (volume 13858 -> 24911 mm3), seed 18 now builds (its hole pattern failed with no result), and seed 54 picks a shell that fails the same way on main before #2247 (offset corner). Every step passes the validity and volume-direction checks.","seeds":[7,9,12,16,18,22,27,31,33,45,50,54,67,72,81,93]},+ {"reason":"Reseam rotationally symmetric drill cutters after failed cuts (#2387): seed 86 now drills its hole, so its following pattern, shell and sphere cut complete with the fuzz validity and material checks.","seeds":[86]},+ {"reason":"Rebase #2387 onto #2247: patterned pieces stay in one body. Seed 86 drills its hole, then reaches the same offset-corner shell refusal as main instead of shelling separate bodies. Completed steps still pass validity and volume-direction checks.","seeds":[86]}]}