SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Cosmetic tap markings: look for their cylinder only in nearby bodies (#10303)
kaltenbrunnermarkus12ebc80e1592
diff --git a/crates/doc/src/eval.rs b/crates/doc/src/eval.rsindex 8533da1e7b..ca2c701047 100644--- a/crates/doc/src/eval.rs+++ b/crates/doc/src/eval.rs@@ -465,7 +465,12 @@ fn thread_on_impl(let (body, cyl) = st.bodies.iter()- .filter_map(|b| kernel::cylinder_face_at(&b.body, p).map(|c| (b.name.clone(), c)))+ .filter(|b| !more::beyond_cylinder_reach(b, p))+ .filter_map(|b| {+ #[cfg(test)]+ cost_tests::count(|c| c.cylinder_search += 1);+ kernel::cylinder_face_at(&b.body, p).map(|c| (b.name.clone(), c))+ }).min_by(|a, b| {let dist = |c: &kernel::CylinderFace| ((p - c.axis_point - c.axis * (p - c.axis_point).dot(c.axis)).len() - c.radius).abs();dist(&a.1).total_cmp(&dist(&b.1))@@ -3308,10 +3313,29 @@ fn apply_traced_with(let affected: std::collections::BTreeMap<String, usize> =target_idx.iter().filter_map(|i| state.bodies.get(*i)).map(|b| (b.name.clone(), b.body.lumps().map_or(1, |l| l.len()))).collect();let mut remove = Vec::new();+ // A cut hands a body its tools cannot reach back as it was, but only after a whole+ // boolean: in a design of many bodies that was most of a hole's time (#10225). Such a+ // body is left as it is. Its box and the tools' are their meshes' grown past how far+ // the exact faces can curve out from them (a dome rises above the outline of its+ // edges), so a tool that touches a body, or only comes near it, still meets it in the+ // boolean. A body shown in another frame, and a mesh body, are cut as before; an+ // intersect removes the bodies it misses, and is left as it was.+ let reach: Option<Vec<Option<solidcraft_geom::Aabb3>>> =+ (op == Operation::Cut && !tools.iter().any(|t| t.body.is_mesh())).then(|| tools.iter().map(|t| more::body_box(&t.body)).collect());for &ti in &target_idx {let Some(mut acc) = state.bodies.get(ti).map(|b| Some(b.traced())) else { continue };// The tools meet the target where it is shown: in its frame (#3383).let into = state.bodies.get(ti).and_then(|b| tool_frame(&b.name));+ if let (Some(reach), None, Some(mb)) = (&reach, into, state.bodies.get(ti))+ && !reach.is_empty()+ && !mb.body.is_mesh()+ && let Some(target) = more::mesh_box(mb)+ && reach.iter().all(|tool| more::boxes_apart(&Some(target), tool))+ {+ continue;+ }+ #[cfg(test)]+ cost_tests::count(|c| c.cut += 1);for t in &tools {let t = &tool_in(t, into)?;acc = match acc {diff --git a/crates/doc/src/eval_cost_tests.rs b/crates/doc/src/eval_cost_tests.rsindex a851e33b9d..7cbaa0025d 100644--- a/crates/doc/src/eval_cost_tests.rs+++ b/crates/doc/src/eval_cost_tests.rs@@ -16,7 +16,8 @@ use crate::eval::{PlacementReads, body_world, hash_placement, placement_digest};use crate::*;/// Work counted on this thread: bodies moved, STEP texts digested, joint faces and bodies-/// measured, bodies searched for by name, features searched for by id.+/// measured, bodies searched for by name, features searched for by id, bodies a cut (or+/// intersect) ran its booleans on, and bodies searched for the cylinder a tap marking lies on.#[derive(Clone, Copy, Debug, Default, PartialEq)]pub(super) struct Counts {pub moved: usize,@@ -25,11 +26,23 @@ pub(super) struct Counts {pub measures: usize,pub body_searches: usize,pub feature_searches: usize,+ pub cut: usize,+ pub cylinder_search: usize,}thread_local! {- static COUNTS: Cell<Counts> =- const { Cell::new(Counts { moved: 0, digested: 0, joint_faces: 0, measures: 0, body_searches: 0, feature_searches: 0 }) };+ static COUNTS: Cell<Counts> = const {+ Cell::new(Counts {+ moved: 0,+ digested: 0,+ joint_faces: 0,+ measures: 0,+ body_searches: 0,+ feature_searches: 0,+ cut: 0,+ cylinder_search: 0,+ })+ };}pub(super) fn count(f: impl FnOnce(&mut Counts)) {@@ -1083,3 +1096,251 @@ fn a_placed_tap_follows_its_body_offset() {apply_point(&mat_mul(&doc.component_transform(comp), &rigid(Vec3::new(0.0, 0.0, 7.0), Vec3::ZERO, Vec3::Z, 0.0)), Vec3::new(1.0, 1.0, 0.0));assert!(tap.axis_point.dist(expected) < 1e-9, "{:?} {expected:?}", tap.axis_point);}++/// What adding a feature of `kind` at the end of `doc` did to the bodies already there: how many+/// its cut ran booleans on, and which it left exactly as they were (the same geometry, its name,+/// key and face names carried over). A cut that cannot reach a body hands it back as it was, and+/// must not pay a whole boolean to find that out (#10225); the sheet metal hole (#10226) and the+/// cosmetic thread (#10227) check their own shortcuts with it too.+pub(super) struct CutWork {+ pub cut: usize,+ pub kept: Vec<String>,+ pub model: Model,+}++pub(super) fn cut_work(doc: &mut Document, kind: FeatureKind) -> CutWork {+ let mut model = Model::new();+ model.evaluate(doc);+ let id = doc.add_feature(kind, None).unwrap();+ let work = counted(|| model.evaluate(doc));+ let result = model.result(id).unwrap();+ assert_eq!(result.error, None, "the feature builds");+ let before = model.state_before(id);+ let kept = result+ .state+ .bodies+ .iter()+ .filter(|b| {+ before+ .body(&b.name)+ .is_some_and(|old| old.body.same(&b.body) && old.key == b.key && crate::naming::face_names(old) == crate::naming::face_names(b))+ })+ .map(|b| b.name.clone())+ .collect();+ CutWork { cut: work.cut, kept, model }+}++/// A box body named `name`, `size` long on each side from `corner`.+fn block(doc: &mut Document, name: &str, corner: Vec3, size: [f64; 3]) {+ let id = doc+ .add_feature(+ FeatureKind::Box {+ corner: point_expr(corner),+ length: size[0].to_string().into(),+ width: size[1].to_string().into(),+ height: size[2].to_string().into(),+ operation: Operation::NewBody,+ },+ None,+ )+ .unwrap();+ doc.feature_mut(id).unwrap().body_names = vec![name.into()];+}++/// A cylinder that cuts, standing on `base` along Z.+fn cutter(base: Vec3, radius: f64, height: f64) -> FeatureKind {+ FeatureKind::Cylinder {+ base: point_expr(base),+ axis: Dir(Vec3::Z),+ radius: radius.to_string().into(),+ height: height.to_string().into(),+ operation: Operation::Cut,+ references: Vec::new(),+ }+}++/// A cut leaves the bodies its tool cannot reach as they were, without a boolean on each: in a+/// design of many bodies those booleans were most of a hole's time (#10225).+#[test]+fn a_cut_leaves_bodies_it_cannot_reach_as_they_were() {+ let mut doc = Document::new("far");+ block(&mut doc, "Near", Vec3::ZERO, [50.0, 40.0, 30.0]);+ // 0.5 mm clear of the tool, and far off.+ block(&mut doc, "Beside", Vec3::new(13.5, 0.0, 0.0), [20.0, 40.0, 30.0]);+ for i in 0..5 {+ block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]);+ }+ // Near and Beside overlap; the hole goes through Near only, beside Beside.+ let work = cut_work(&mut doc, cutter(Vec3::new(10.0, 20.0, -5.0), 3.0, 40.0));+ assert_eq!(work.cut, 1, "only the body the tool reaches goes through the boolean");+ assert_eq!(work.kept, ["Beside", "Far0", "Far1", "Far2", "Far3", "Far4"]);+ assert!(volume(&work.model, "Near") < 60_000.0 - 800.0, "and it is cut");+}++/// A cut still goes through the boolean wherever its tool reaches a body or comes close: on a+/// face, along a line, a hair beside it, into a dome above its edge circle. (Bodies its tool+/// cannot reach are left out of it: `a_cut_leaves_bodies_it_cannot_reach_as_they_were`.)+#[test]+fn a_cut_still_runs_where_its_tool_touches_grazes_or_meets_a_curved_face() {+ // A cylinder whose side is tangent to the face x = 50, one a hair clear of it, one 0.1 mm in.+ for (x, cuts) in [(53.0, false), (53.0005, false), (52.9, true)] {+ let mut doc = Document::new("graze");+ block(&mut doc, "A", Vec3::ZERO, [50.0, 40.0, 30.0]);+ let work = cut_work(&mut doc, cutter(Vec3::new(x, 20.0, 0.0), 3.0, 30.0));+ assert_eq!(work.cut, 1, "the tool at x = {x} goes through the boolean");+ let v = volume(&work.model, "A");+ assert_eq!(v < 60_000.0 - 1.0, cuts, "the tool at x = {x} cuts material: {v}");+ assert!(!cuts || work.kept.is_empty(), "a body cut is a new body");+ }+ // A box meeting the block only along its top edge.+ let mut doc = Document::new("edge");+ block(&mut doc, "A", Vec3::ZERO, [50.0, 40.0, 30.0]);+ let along = FeatureKind::Box {+ corner: point_expr(Vec3::new(50.0, 0.0, 30.0)),+ length: "10".into(),+ width: "40".into(),+ height: "10".into(),+ operation: Operation::Cut,+ };+ assert_eq!(cut_work(&mut doc, along).cut, 1);+ // A dome: a sphere's cap rising 10 mm above the circle it stands on. A thin tool drilled into+ // its top near the apex, well above that circle, cuts it.+ let mut doc = Document::new("dome");+ doc.add_feature(FeatureKind::Sphere { center: point_expr(Vec3::new(0.0, 0.0, -10.0)), radius: "20".into(), operation: Operation::NewBody }, None)+ .unwrap();+ let below = FeatureKind::Box {+ corner: point_expr(Vec3::new(-30.0, -30.0, -40.0)),+ length: "60".into(),+ width: "60".into(),+ height: "40".into(),+ operation: Operation::Cut,+ };+ doc.add_feature(below, None).unwrap();+ let mut model = Model::new();+ model.evaluate(&doc);+ let dome = model.state().bodies[0].name.clone();+ let whole = volume(&model, &dome);+ let work = cut_work(&mut doc, cutter(Vec3::new(2.0, 1.0, 8.0), 1.0, 5.0));+ assert_eq!(work.cut, 1);+ assert!(volume(&work.model, &dome) < whole - 1.0, "the drill cuts into the dome");+ assert!(work.kept.is_empty());+}++/// A cylinder body named `name` standing on `base` along Z.+fn shaft(doc: &mut Document, name: &str, base: Vec3, radius: f64, height: f64) {+ let id = doc+ .add_feature(+ FeatureKind::Cylinder {+ base: point_expr(base),+ axis: Dir(Vec3::Z),+ radius: radius.to_string().into(),+ height: height.to_string().into(),+ operation: Operation::NewBody,+ references: Vec::new(),+ },+ None,+ )+ .unwrap();+ doc.feature_mut(id).unwrap().body_names = vec![name.into()];+}++/// The work of adding `kind` at the end of `doc`, and the tap markings the design then has.+fn marking_work(doc: &mut Document, kind: FeatureKind) -> (Counts, Vec<ThreadInfo>) {+ let mut model = Model::new();+ model.evaluate(doc);+ let id = doc.add_feature(kind, None).unwrap();+ let work = counted(|| model.evaluate(doc));+ assert_eq!(model.result(id).unwrap().error, None, "the feature builds");+ (work, model.state().threads.clone())+}++/// A cosmetic tap marking at `p`.+fn marking(p: Vec3) -> FeatureKind {+ FeatureKind::Thread { face: FacePick(p), designation: Some("M6".into()), length: None, modeled: false, handedness: ThreadHandedness::Right }+}++/// A tap marking looks for its cylinder in the bodies near it only: each body searched was+/// tessellated again, so many markings in a design of many bodies took quadratic time (#10227).+#[test]+fn a_tap_marking_searches_only_the_bodies_near_it() {+ let mut doc = Document::new("far");+ shaft(&mut doc, "Shaft", Vec3::ZERO, 3.0, 6.0);+ for i in 0..5 {+ block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]);+ }+ let (work, threads) = marking_work(&mut doc, marking(Vec3::new(3.0, 0.0, 3.0)));+ assert_eq!(work.cylinder_search, 1, "only the shaft is searched");+ assert_eq!(threads.len(), 1);+ assert_eq!(threads[0].body, "Shaft");+ assert_eq!(threads[0].designation, "M6");+ assert!((threads[0].radius - 3.0).abs() < 1e-6 && !threads[0].internal);++ // A tapped hole in a plate among far bodies: only the plate is searched for its wall.+ let mut doc = Document::new("tapped");+ block(&mut doc, "Plate", Vec3::ZERO, [60.0, 60.0, 12.0]);+ for i in 0..5 {+ block(&mut doc, &format!("Far{i}"), Vec3::new(200.0 * (i + 1) as f64, 0.0, 0.0), [50.0, 40.0, 30.0]);+ }+ let hole = FeatureKind::Hole {+ position: FacePick(Vec3::new(30.0, 30.0, 12.0)),+ at: None,+ direction: Dir(-Vec3::Z),+ diameter: "5".into(),+ depth: Some("10".into()),+ hole: HoleKind::default(),+ points: None,+ thread: Some("M6".into()),+ thread_depth: None,+ handedness: ThreadHandedness::Right,+ to: None,+ references: Vec::new(),+ };+ let (work, threads) = marking_work(&mut doc, hole);+ assert_eq!(work.cylinder_search, 1, "only the plate is searched");+ assert_eq!(threads.len(), 1);+ assert_eq!(threads[0].body, "Plate");+ assert!(threads[0].internal && (threads[0].radius - 2.5).abs() < 1e-6);+}++/// Bodies within reach of a tap marking are still searched: the shaft it lies on, a block 3 mm+/// off (within a twentieth of the block's size, where the cylinder search itself looks), and one+/// 3.6 mm off (just past it, but within the margin the boxes keep); a block 4.5 mm off is not.+/// The marking stays on the shaft.+#[test]+fn a_tap_marking_still_searches_the_bodies_within_its_reach() {+ let mut doc = Document::new("near");+ shaft(&mut doc, "Shaft", Vec3::ZERO, 3.0, 6.0);+ // Each block is 50 x 40 x 30 (a twentieth of its size is 3.54 mm), its face x = 3 + gap.+ for (name, gap) in [("Close", 3.0), ("Edge", 3.6), ("Clear", 4.5)] {+ block(&mut doc, name, Vec3::new(3.0 + gap, -20.0, 0.0), [50.0, 40.0, 30.0]);+ }+ let (work, threads) = marking_work(&mut doc, marking(Vec3::new(3.0, 0.0, 3.0)));+ assert_eq!(work.cylinder_search, 3, "the shaft, Close and Edge are searched");+ assert_eq!(threads.len(), 1);+ assert_eq!(threads[0].body, "Shaft");++ // A pin in a hole a hair wider: a marking on the pin, and one on the hole's wall.+ for (p, body, internal) in [(Vec3::new(2.0, 0.0, 5.0), "Pin", false), (Vec3::new(2.5, 0.0, 5.0), "Plate", true)] {+ let mut doc = Document::new("pin");+ block(&mut doc, "Plate", Vec3::new(-20.0, -20.0, 0.0), [40.0, 40.0, 10.0]);+ let bore = FeatureKind::Cylinder {+ base: point_expr(Vec3::new(0.0, 0.0, -1.0)),+ axis: Dir(Vec3::Z),+ radius: "2.5".into(),+ height: "12".into(),+ operation: Operation::Cut,+ references: Vec::new(),+ };+ doc.add_feature(bore, None).unwrap();+ shaft(&mut doc, "Pin", Vec3::ZERO, 2.0, 10.0);+ let mut kind = marking(p);+ if let FeatureKind::Thread { designation, .. } = &mut kind {+ *designation = None;+ }+ let (work, threads) = marking_work(&mut doc, kind);+ assert_eq!(work.cylinder_search, 2, "both bodies are searched for {body}");+ assert_eq!(threads.len(), 1);+ assert_eq!(threads[0].body, body);+ assert_eq!(threads[0].internal, internal);+ }+}diff --git a/crates/doc/src/eval_more.rs b/crates/doc/src/eval_more.rsindex 1b0f2e17d2..8a81b4f2bd 100644--- a/crates/doc/src/eval_more.rs+++ b/crates/doc/src/eval_more.rs@@ -1569,13 +1569,13 @@ fn sheet_prism_cut(/// A box around `body`, grown past its mesh's deflection from the exact faces (and a hair/// more): bodies whose boxes are apart do not meet. None when it can't be worked out.-fn body_box(body: &Body) -> Option<Aabb3> {+pub(super) fn body_box(body: &Body) -> Option<Aabb3> {let tol = (body.size() * 1e-3).max(1e-4);padded_box(&body.tessellate(tol).ok()?, tol)}/// [`body_box`] of a model body, from the mesh it keeps.-fn mesh_box(mb: &ModelBody) -> Option<Aabb3> {+pub(super) fn mesh_box(mb: &ModelBody) -> Option<Aabb3> {padded_box(&mb.mesh(), mb.display_tol())}@@ -1584,8 +1584,25 @@ fn padded_box(mesh: &solidcraft_geom::Mesh, tol: f64) -> Option<Aabb3> {(!b.is_empty() && b.min.is_finite() && b.max.is_finite()).then(|| b.inflated(2.0 * tol + 1e-6))}+/// Whether [`kernel::cylinder_face_at`] is known to find no face of `mb` at `p`. It takes a+/// face only when its own mesh of the body comes within a twentieth of the body's size of the+/// point. That mesh lies in the body's box ([`mesh_box`]) give or take its own deflection, which+/// the reach allows for, so a box farther away than that holds no face for it. Working that out from the mesh the body keeps+/// spares a tessellation of every body in the design for each tap marking (#10227). A mesh+/// body, and a body whose box is unknown, are searched as before.+pub(super) fn beyond_cylinder_reach(mb: &ModelBody, p: Vec3) -> bool {+ if mb.body.is_mesh() {+ return false;+ }+ let Some(b) = mesh_box(mb) else { return false };+ let size = mb.body.size();+ let reach = size * 0.05 + 2.0 * (size * 1e-3).max(1e-3);+ let off = (b.min - p).max(p - b.max).max(Vec3::ZERO);+ off.len() > reach+}+/// Whether two boxes are known to be apart (an unknown box is never apart).-fn boxes_apart(a: &Option<Aabb3>, b: &Option<Aabb3>) -> bool {+pub(super) fn boxes_apart(a: &Option<Aabb3>, b: &Option<Aabb3>) -> bool {let (Some(a), Some(b)) = (a, b) else { return false };a.max.x < b.min.x || b.max.x < a.min.x || a.max.y < b.min.y || b.max.y < a.min.y || a.max.z < b.min.z || b.max.z < a.min.z}