SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Try exact local cuts after invalid empty numerical results (#1765) (#1858)
Karl Von Richter759e22b58249
diff --git a/crates/engine/src/boolean_regression_tests.rs b/crates/engine/src/boolean_regression_tests.rsindex 1b751b81f0..59a28da749 100644--- a/crates/engine/src/boolean_regression_tests.rs+++ b/crates/engine/src/boolean_regression_tests.rs@@ -88,6 +88,30 @@ fn read_back(s: &Session, body: &solidcraft_kernel::Body) -> (String, usize) {(text, back.file_faces)}+/// The timeline insertion from #1765 on a small part with analytic material. The kernel test+/// separately forces the empty numerical attempts, without needing the reporter's design.+#[test]+fn shallow_cuts_rebuild_after_inserting_an_earlier_pocket() {+ let s = replay(include_str!("../../../examples/regressions/shallow_cuts_after_earlier_pocket.json"));+ let rounded_plate = 40.0 * 30.0 * 10.0 - (4.0 - std::f64::consts::PI) * 40.0;+ // Half of each circle overlaps the existing 0.75 mm pocket.+ let expected = rounded_plate - 30.0 * 10.0 * 0.75 - 2.0 * std::f64::consts::PI * 25.0 * (1.5 - 0.75 / 2.0);+ let reopened = Session::new(solidcraft_doc::Document::from_json(&s.doc.to_json()).unwrap());+ for session in [s, reopened] {+ assert!(session.model.results.iter().all(|r| r.error.is_none()));+ assert_eq!(session.model.state().bodies.len(), 1);+ let body = &session.model.state().bodies[0].body;+ assert!(body.validity().is_empty(), "{:?}", body.validity());+ let actual = volume(&session, "Plate");+ assert!((actual - expected).abs() < 0.02, "{actual} vs {expected}");+ let mesh = body.tessellate(0.001).unwrap();+ assert!(!mesh.contains(solidcraft_geom::Vec3::new(12.0, 14.0, 9.0)));+ assert!(mesh.contains(solidcraft_geom::Vec3::new(12.0, 14.0, 8.0)));+ assert!(!mesh.contains(solidcraft_geom::Vec3::new(20.0, 20.0, 9.5)));+ assert!(mesh.contains(solidcraft_geom::Vec3::new(20.0, 20.0, 9.0)));+ }+}+/// #2059: tabs exactly as wide as their supporting ribs share the ribs' side/// planes. The base's remote conical chamfer must not prevent their join.#[test]diff --git a/crates/kernel/src/empty_retry_tests.rs b/crates/kernel/src/empty_retry_tests.rsnew file mode 100644index 0000000000..318bbe87a8--- /dev/null+++ b/crates/kernel/src/empty_retry_tests.rs@@ -0,0 +1,83 @@+//! A shallow circular cut after a pocket (#1765): repeated empty numerical answers must not+//! stop the later geometric strategies. Inject the numerical failure on a real small part;+//! the exact rounding and ray classification of the original design are not available.++use super::*;+use crate::{box_solid, cylinder, fillet, measure, sphere, step_export, step_import};+use std::cell::Cell;+use std::f64::consts::PI;++#[test]+fn shallow_cut_after_a_pocket_recovers_from_empty_numerical_attempts() {+ let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).unwrap();+ let plate = fillet(&plate, &[Vec3::new(20.0, 0.0, 10.0)], 2.0).unwrap();+ let pocket = box_solid(Vec3::new(5.0, 15.0, 9.25), Vec3::new(35.0, 25.0, 10.25)).unwrap();+ let target = boolean(&plate, &pocket, BoolOp::Cut).unwrap().unwrap();+ let tool = cylinder(Vec3::new(12.0, 15.0, 8.5), Vec3::Z, 5.0, 1.75).unwrap();+ let attempts = Cell::new(0);+ let empty = |_: &Body, _: &Body, _: BoolOp, _: Option<mt::Vector3>, _: f64| {+ attempts.set(attempts.get() + 1);+ Ok((Solid::new_unchecked(Vec::new()), None))+ };+ let (result, diagnostics) =+ capture_boolean_diagnostics(|| boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty)));+ assert!(attempts.get() >= 2, "the first two numerical tries must really have failed");+ let cut = result.unwrap().expect("a shallow cut leaves the plate");+ assert!(cut.validity().is_empty(), "{:?}", cut.validity());+ assert_eq!(cut.lumps().unwrap().len(), 1);+ // Half of the circle overlaps the existing 0.75 mm pocket.+ let expected = 40.0 * 30.0 * 10.0 - (4.0 - PI) * 40.0 - 30.0 * 10.0 * 0.75 - PI * 25.0 * (1.5 - 0.75 / 2.0);+ let actual = measure(&cut).unwrap().volume;+ assert!((actual - expected).abs() < 0.02, "{actual} vs {expected}");+ assert!(diagnostics.events.iter().all(|e| e.strategy != BooleanStrategy::RefinedTolerance));+}++#[test]+fn step_seam_cut_recovers_from_empty_numerical_attempts() {+ let pin = cylinder(Vec3::new(-5.0, 0.0, 0.0), Vec3::X, 4.5, 10.0).unwrap();+ let target = step_import(&step_export(&[&pin], "seam regression").unwrap()).unwrap().bodies.remove(0).body;+ let tool = sphere(Vec3::new(-5.0, 0.0, 0.0), 6.0).unwrap();+ assert!(crate::seam_faces::needed(&target, &tool));+ let attempts = Cell::new(0);+ let shifted_attempts = Cell::new(0);+ let empty = |_: &Body, _: &Body, _: BoolOp, shift: Option<mt::Vector3>, _: f64| {+ attempts.set(attempts.get() + 1);+ if shift.is_some() {+ shifted_attempts.set(shifted_attempts.get() + 1);+ }+ Ok((Solid::new_unchecked(Vec::new()), None))+ };+ let (result, diagnostics) =+ capture_boolean_diagnostics(|| boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty)));+ assert!(attempts.get() >= 2, "the initial numerical tries must really have failed");+ assert_eq!(shifted_attempts.get(), 0, "seam recovery must precede displaced retries");+ let cut = result.unwrap().expect("the spherical cut leaves the end of the pin");+ assert!(cut.validity().is_empty(), "{:?}", cut.validity());+ assert_eq!(cut.lumps().unwrap().len(), 1);+ assert!(cut.history().is_some());+ // Along the common axis, integrate min(pi*4.5^2, pi*(6^2-x^2)) from 0 to 6.+ let full_radius_end = (6.0_f64.powi(2) - 4.5_f64.powi(2)).sqrt();+ let removed = PI * (4.5_f64.powi(2) * full_radius_end + 36.0 * (6.0 - full_radius_end) - (216.0 - full_radius_end.powi(3)) / 3.0);+ let expected = PI * 4.5_f64.powi(2) * 10.0 - removed;+ let actual = measure(&cut).unwrap().volume;+ assert!((actual - expected).abs() < expected * 1e-3, "{actual} vs {expected}");+ assert!(diagnostics.warning().is_none(), "{:?}", diagnostics.warning());+}++#[test]+fn unrecovered_empty_attempts_keep_refusal_without_displacing_tool() {+ // These spheres keep fine_tols empty, isolating retries after the exact local strategies.+ let target = sphere(Vec3::ZERO, 10.0).unwrap();+ let tool = sphere(Vec3::new(8.0, 0.0, 0.0), 5.0).unwrap();+ let shifted_attempts = Cell::new(0);+ let empty = |_: &Body, _: &Body, _: BoolOp, shift: Option<mt::Vector3>, _: f64| {+ if shift.is_some() {+ shifted_attempts.set(shifted_attempts.get() + 1);+ }+ Ok((Solid::new_unchecked(Vec::new()), None))+ };+ let result = boolean_via(&target, &tool, BoolOp::Cut, &|a, b, op| boolean_whole_with(a, b, op, false, &empty));+ assert_eq!(shifted_attempts.get(), 0, "unrecovered empty attempts must not enable displaced retries");+ let error = result.unwrap_err();+ assert!(error.to_string().contains("it came out empty"), "{error}");+}diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex 8657868678..a69977cbbf 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -1214,6 +1214,15 @@ fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {}fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -> Result<Option<Body>> {+ boolean_whole_with(a, b, op, refine, &truck_boolean)+}++/// The whole-body strategies with the numerical intersection supplied separately, so tests+/// can reproduce an empty numerical attempt without depending on a particular ray seed.+fn boolean_whole_with<F>(a: &Body, b: &Body, op: BoolOp, refine: bool, intersect: &F) -> Result<Option<Body>>+where+ F: Fn(&Body, &Body, BoolOp, Option<mt::Vector3>, f64) -> Result<(Solid, Option<recorded::Shapeops>)>,+{if let Some(body) = swept_prism(a, b, op) {return Ok(Some(body));}@@ -1316,7 +1325,7 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -// Bounded to two finer meshes; no tool displacement or relaxed acceptance tests.for k in [1e-5, 1e-6] {let tol = (size * k).max(1e-6);- if let Ok((solid, history)) = truck_boolean(a, b, op, None, tol)+ if let Ok((solid, history)) = intersect(a, b, op, None, tol)&& !solid.boundaries().is_empty()&& let Ok(body) = guard("refined boolean result", || recorded::truck_result(solid, history, size, &keep, &counts))&& check(&body).0@@ -1486,7 +1495,7 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -for (attempt, j) in JITTER.iter().enumerate().take(2) {let shift = mt::Vector3::new(j[0], j[1], j[2]) * (feature * 0.01);for &tol in &fine_tols {- match truck_boolean(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol) {+ match intersect(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol) {Ok((s, _)) if s.boundaries().is_empty() || s.face_iter().next().is_none() => *last = "empty result".into(),Ok((s, h)) => match guard("boolean result", || recorded::truck_result(s, h, size, &keep, &counts)) {Ok(body) => {@@ -1575,10 +1584,17 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -return Ok(r);}}+ // An implausible empty result from the unshifted numerical tries must still give+ // the exact strategies above a chance (#1765), including seam-face recovery. If none+ // recovers it, keep the original candidate for the outer guard, before displaced retries.+ if empty_votes >= 2 && op != BoolOp::Union {+ merge(empty_diagnostics);+ return Ok(None);+ }let shift = mt::Vector3::new(j[0], j[1], j[2]) * (size * 0.01);for k in [2e-3, 5e-4] {let tol = (size * k).max(1e-5);- let r = truck_boolean(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol);+ let r = intersect(a, b, op, if attempt > 0 { Some(shift) } else { None }, tol);match r {Ok((s, _)) if s.boundaries().is_empty() || s.face_iter().next().is_none() => {empty_votes += 1;@@ -1622,6 +1638,9 @@ fn boolean_whole_with_refinement(a: &Body, b: &Body, op: BoolOp, refine: bool) -if let Some(body) = fine(&mut last) {return Ok(Some(body));}+ if attempt == 0 && crate::boolean_guard::check_retry(a, b, op, None).is_err() {+ continue;+ }merge(empty_diagnostics);return Ok(None);}@@ -2339,6 +2358,10 @@ pub(crate) fn half_box(body: &Body, plane: &solidcraft_geom::Plane, positive: bocrate::build::extrude(plane, std::slice::from_ref(&sq), lo, hi)?.pop().ok_or_else(|| KernelError::Failed("half space".into()))}+#[cfg(test)]+#[path = "empty_retry_tests.rs"]+mod empty_retry_tests;+#[cfg(test)]#[path = "prism_fast_path_tests.rs"]mod prism_fast_path_tests;diff --git a/examples/regressions/shallow_cuts_after_earlier_pocket.json b/examples/regressions/shallow_cuts_after_earlier_pocket.jsonnew file mode 100644index 0000000000..1ba14c351d--- /dev/null+++ b/examples/regressions/shallow_cuts_after_earlier_pocket.json@@ -0,0 +1,19 @@+{+ "description": "Public-safe companion for #1765: a 40 x 30 x 10 plate with a 2 mm round on its top-front edge and two radius-5 circular cuts 1.5 mm deep. Roll back before the circles, insert a 30 x 10 pocket 0.75 mm deep across their upper halves, restore the timeline and redefine the circular cut. This part checks the rebuild and analytic material; empty numerical attempts are injected separately in the kernel regression, since the original design is unavailable.",+ "commands": [+ {"command": "solid.box", "params": {"length": 40, "width": 30, "height": 10, "body_name": "Plate", "name": "Plate"}},+ {"command": "solid.fillet", "params": {"edges": [[20, 0, 10]], "radius": 2, "name": "Rim"}},+ {"command": "sketch.create", "params": {"plane": "XY", "offset": 10, "name": "Circles"}},+ {"command": "sketch.circle.center", "params": {"center": [12, 15], "radius": 5}},+ {"command": "sketch.circle.center", "params": {"center": [28, 15], "radius": 5}},+ {"command": "sketch.finish", "params": {}},+ {"command": "solid.extrude", "params": {"sketch": "Circles", "distance": -1.5, "operation": "cut", "name": "ShallowCuts"}},+ {"command": "timeline.rollback", "params": {"position": 2}},+ {"command": "sketch.create", "params": {"plane": "XY", "offset": 10, "name": "PocketOutline"}},+ {"command": "sketch.rectangle.two_point", "params": {"p0": [5, 15], "p1": [35, 25]}},+ {"command": "sketch.finish", "params": {}},+ {"command": "solid.extrude", "params": {"sketch": "PocketOutline", "distance": -0.75, "operation": "cut", "name": "EarlierPocket"}},+ {"command": "timeline.rollback", "params": {}},+ {"command": "timeline.redefine", "params": {"feature": "ShallowCuts", "command": "solid.extrude", "params": {"sketch": "Circles", "profiles": [0, 1], "distance": "-1.5", "direction": "positive", "convention": "total_distance", "operation": "cut"}}}+ ]+}