SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
inspect.clearance: pins on one cylinder with their hole are answered or reported in seconds (#3027)
NOWN-DEVe661e6f809a9
diff --git a/crates/engine/src/cmd/clearance.rs b/crates/engine/src/cmd/clearance.rsindex 97cf6d13a0..2ef36228f5 100644--- a/crates/engine/src/cmd/clearance.rs+++ b/crates/engine/src/cmd/clearance.rs@@ -47,6 +47,9 @@ enum SkipWithin {/// Most pairs [`PairCache`] keeps; it starts over when full.const MAX_CACHED: usize = 2 * MAX_PAIRS;+/// The kernel's tries at intersecting a pin with its hole on one cylinder (each about a second+/// on real parts; a plain pin on its axis needs one or two).+const PIN_ATTEMPTS: usize = 4;/// Pairs measured before, by the two bodies' geometry where they stood/// ([`solidcraft_doc::ModelBody::geometry_key`]) and the settings that shape the result@@ -341,40 +344,73 @@ fn measure_pair(// A pair whose shared part can't be worked out is reported, not passed as clear.let region = shared_region(a, b);let (ca, cb) = (clipped(ka, region), clipped(kb, region));- let (shared, report) = solidcraft_kernel::capture_boolean_diagnostics(|| {- solidcraft_kernel::boolean(ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body), solidcraft_kernel::BoolOp::Intersect)- });- match shared {- Err(e) => {- out.unchecked = Some(e.to_string());- return out;+ // A pin of one in a hole of the other of its own size. On its very axis the boolean takes+ // the two walls as one and answers plain ones at once, but with blends next to them it+ // tries for minutes and gives up; a hair off the axis it cannot intersect them at all+ // (and may pass the pin as clear). So a pin on its axis gets a few tries of the boolean+ // first, and what the walls share is otherwise worked out apart, with a few tries of the+ // boolean left for when that declines. The body left whole is cut down to where the+ // other's piece is first, so that both meet only the faces there.+ let candidate = solidcraft_kernel::coaxial_candidate(ca.as_ref().unwrap_or(ka), cb.as_ref().unwrap_or(kb));+ let pin = candidate.is_some();+ let (ca, cb) = match (ca, cb) {+ (Some(x), None) if pin => {+ let y = narrowed(kb, &x);+ (Some(x), y)+ }+ (None, Some(y)) if pin => (narrowed(ka, &y), Some(y)),+ other => other,+ };+ // A body left whole is the copy that keeps its meshes: meeting several others at one+ // size, it is meshed once for the booleans of all of them.+ let (pa, pb) = (ca.as_ref().unwrap_or(ka), cb.as_ref().unwrap_or(kb));+ let intersect = || {+ solidcraft_kernel::capture_boolean_diagnostics(|| {+ let run = || solidcraft_kernel::boolean(pa, pb, solidcraft_kernel::BoolOp::Intersect);+ if pin { solidcraft_kernel::with_attempt_budget(PIN_ATTEMPTS, run) } else { run() }+ })+ };+ let first = (candidate != Some(false)).then(intersect);+ let answered = first.as_ref().is_some_and(|(r, report)| r.is_ok() && report.unverified().is_none());+ let coaxial = if pin && !answered { solidcraft_kernel::coaxial_overlap(pa, pb) } else { None };+ if let Some(o) = coaxial {+ if o.volume > 0.0 {+ out.overlap = Some((o.volume, o.area, o.bbox, o.centroid));}- Ok(shared) => {- if let Some(reason) = report.unverified() {- out.unchecked = Some(reason);+ } else {+ let (shared, report) = first.unwrap_or_else(intersect);+ let failed =+ |why: String| if pin { format!("a pin on one cylinder with its hole, whose walls could not be intersected ({why})") } else { why };+ let shared = match shared {+ Err(e) => {+ out.unchecked = Some(failed(e.to_string()));return out;}- if let Some(o) = shared {- match measure_near_origin(&o, region.center()) {- Ok(m) if !plausible(m.volume, m.centroid, m.bbox) => {- out.unchecked = Some(format!(- "the shared part came out malformed ({:.4} mm³ with its centre outside its own box), so it is not measured",- m.volume- ));- return out;- }- Ok(m) => {- let (wa, wb) = (ca.as_ref().unwrap_or(&ba.body), cb.as_ref().unwrap_or(&bb.body));- if let Some(reason) = union_disagrees(wa, wb, m.volume, region.center()) {- out.unchecked = Some(reason);- return out;- }- out.overlap = Some((m.volume, m.area, m.bbox, m.centroid));- }- Err(e) => {- out.unchecked = Some(e.to_string());+ Ok(shared) => shared,+ };+ if let Some(reason) = report.unverified() {+ out.unchecked = Some(failed(reason));+ return out;+ }+ if let Some(o) = shared {+ match measure_near_origin(&o, region.center()) {+ Ok(m) if !plausible(m.volume, m.centroid, m.bbox) => {+ out.unchecked = Some(format!(+ "the shared part came out malformed ({:.4} mm³ with its centre outside its own box), so it is not measured",+ m.volume+ ));+ return out;+ }+ Ok(m) => {+ if let Some(reason) = union_disagrees(pa, pb, m.volume, region.center()) {+ out.unchecked = Some(reason);return out;}+ out.overlap = Some((m.volume, m.area, m.bbox, m.centroid));+ }+ Err(e) => {+ out.unchecked = Some(e.to_string());+ return out;}}}@@ -435,6 +471,35 @@ fn clipped(body: &solidcraft_kernel::Body, region: Aabb3) -> Option<solidcraft_k}}+/// `body` cut down to where it may meet `piece` (their boxes' common part, grown as+/// [`shared_region`] grows it), when that leaves part of it out. `None`: use the whole body.+fn narrowed(body: &solidcraft_kernel::Body, piece: &solidcraft_kernel::Body) -> Option<solidcraft_kernel::Body> {+ let bounds = |b: &solidcraft_kernel::Body| b.tessellate_with((b.size() * 1e-3).max(1e-4), false).ok().map(|m| m.bounds());+ let (x, y) = (bounds(body)?, bounds(piece)?);+ let (min, max) = (x.min.max(y.min), x.max.min(y.max));+ if x.is_empty() || y.is_empty() || !(min.x <= max.x && min.y <= max.y && min.z <= max.z) {+ return None;+ }+ let grow = 1.0 + 0.05 * min.dist(max);+ let g = solidcraft_geom::Vec3::new(grow, grow, grow);+ let region = Aabb3 { min: min - g, max: max + g };+ if region.min.x <= x.min.x+ && region.min.y <= x.min.y+ && region.min.z <= x.min.z+ && x.max.x <= region.max.x+ && x.max.y <= region.max.y+ && x.max.z <= region.max.z+ {+ return None;+ }+ let cut = solidcraft_kernel::box_solid(region.min, region.max).ok()?;+ let (r, report) = solidcraft_kernel::capture_boolean_diagnostics(|| solidcraft_kernel::boolean(body, &cut, solidcraft_kernel::BoolOp::Intersect));+ match r {+ Ok(Some(c)) if report.unverified().is_none() => Some(c),+ _ => None,+ }+}+/// [`solidcraft_kernel::measure`] of `body` moved by `-at` and back: far from the origin, the/// centre of a thin part loses its precision (its moments are large numbers that nearly cancel).fn measure_near_origin(body: &solidcraft_kernel::Body, at: solidcraft_geom::Vec3) -> solidcraft_kernel::Result<solidcraft_kernel::BodyMeasure> {diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rsindex 901f4a74a3..16bc3fda7f 100644--- a/crates/engine/src/cmd/clearance_tests.rs+++ b/crates/engine/src/cmd/clearance_tests.rs@@ -345,6 +345,64 @@ fn a_body_that_changed_shape_is_measured_again() {assert!((f(&r["near"][0]["distance_mm"]) - 0.5).abs() < 1e-6, "{r}");}+/// A flanged bushing and a headed pin seated in it line to line, on its very axis, the head on+/// the flange. Plain, they touch and share nothing; sunk 0.2 into the flange, the head shares the+/// ring under it. With a fillet under the head against the bore's sharp edge, the fillet's ring+/// is in the flange (about 0.49 mm³), next to walls that lie on one another: the boolean tried+/// for minutes there and gave up; now it is reported as such within seconds.+#[test]+fn a_pin_seated_line_to_line_in_its_bushing_is_measured() {+ let ring = std::f64::consts::PI * (7.0f64.powi(2) - 4.0f64.powi(2)) * 0.2;+ for (sunk, fillet) in [(0.0, false), (0.2, false), (0.0, true)] {+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 5, "height": 12, "base": [100, 0, 0], "operation": "new", "body_name": "Bush"}));+ run(&mut s, "solid.cylinder", json!({"radius": 7.5, "height": 1, "base": [100, 0, 12], "operation": "join", "targets": ["Bush"]}));+ run(&mut s, "solid.cylinder", json!({"radius": 4, "height": 20, "base": [100, 0, -3], "operation": "cut", "targets": ["Bush"]}));+ let z = 13.0 - sunk;+ run(&mut s, "solid.cylinder", json!({"radius": 4, "height": z + 2.0, "base": [100, 0, -2], "operation": "new", "body_name": "Pin"}));+ run(&mut s, "solid.cylinder", json!({"radius": 7, "height": 1.5, "base": [100, 0, z], "operation": "join", "targets": ["Pin"]}));+ if fillet {+ run(&mut s, "solid.fillet", json!({"edges": [[104, 0, z]], "radius": 0.3, "body": "Pin"}));+ run(&mut s, "solid.fillet", json!({"edges": [[107, 0, z + 1.5]], "radius": 0.5, "body": "Pin"}));+ }+ let started = std::time::Instant::now();+ let r = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin"], "against": ["Bush"], "min_volume": 0.01, "clearance": 1e-6}));+ assert!(started.elapsed().as_secs_f64() < 30.0, "sunk {sunk}: {:?}", started.elapsed());+ if fillet {+ assert!(r["unchecked"][0]["reason"].as_str().is_some_and(|w| w.contains("pin on one cylinder")), "{r}");+ continue;+ }+ assert_eq!(r["unchecked"], json!([]), "sunk {sunk}: {r}");+ if sunk == 0.0 {+ assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(0), "{r}");+ assert_eq!(f(&r["near"][0]["distance_mm"]), 0.0, "{r}");+ } else {+ let v = f(&r["overlaps"][0]["volume_mm3"]);+ assert!((v - ring).abs() <= 1e-3 * ring, "{v} {ring}: {r}");+ }+ }+}++/// A chamfered pin through a hole of its own radius, its axis a hair off the hole's: the boolean+/// cannot intersect walls all but tangent along two lines and once passed the pair as clear.+/// The crescent the pin shares with the plate is reported, against the lens of two circles.+#[test]+fn a_pin_a_hair_off_its_hole_shares_its_crescent() {+ let crescent = |r: f64, e: f64| std::f64::consts::PI * r * r - (2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt());+ for offset in [5.9e-4, 1e-2] {+ let mut s = Session::default();+ run(&mut s, "solid.box", json!({"length": 20, "width": 20, "height": 5, "corner": [-10, -10, 0], "body_name": "Plate"}));+ run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 9, "base": [0, 0, -2], "operation": "cut", "targets": ["Plate"]}));+ run(&mut s, "solid.cylinder", json!({"radius": 3, "height": 9, "base": [offset, 0, -2], "operation": "new", "body_name": "Pin"}));+ run(&mut s, "solid.chamfer", json!({"edges": [[offset + 3.0, 0, 7]], "distance": 0.5, "body": "Pin"}));+ let r = run(&mut s, "inspect.clearance", json!({"min_volume": 1e-9}));+ assert_eq!(r["unchecked"], json!([]), "{offset}: {r}");+ let want = 5.0 * crescent(3.0, offset);+ let got = f(&r["overlaps"][0]["volume_mm3"]);+ assert!((got - want).abs() < 1e-6 * want, "{offset}: {got} against {want}: {r}");+ }+}+/// The shared volume is checked against the bodies and their union: two 10 mm cubes sharing a/// 3 mm corner cube agree at 27 mm³, and a shared part read as three times that (as a mirrored/// pair once was) does not.diff --git a/crates/kernel/src/coaxial_overlap.rs b/crates/kernel/src/coaxial_overlap.rsindex 165f0c8398..c7331f18b5 100644--- a/crates/kernel/src/coaxial_overlap.rs+++ b/crates/kernel/src/coaxial_overlap.rs@@ -1,10 +1,11 @@//! The shared volume of a pin in a hole of (nearly) its own size whose axis is a hair off the-//! hole's (parts placed from rounded coordinates).+//! hole's (parts placed from rounded coordinates), or on it: a pin seated line to line.//!//! The pin's wall and the hole's wall then meet along two lines where they are all but tangent,-//! which the boolean cannot intersect, and the facets of the two walls pass through each other+//! or lie on one another, which the boolean cannot intersect, and the facets of the two walls pass through each other//! by less than the boolean's sampled shortcuts can see. So the overlap is worked out in two-//! parts instead. The pin's wall is moved off the hole's by a clear step (`offset_body`) and the+//! parts instead. The pin's wall is moved off the hole's by a clear step (`offset_body`; where a+//! blend running into the pin's wall keeps it from moving, the hole's wall is moved instead) and the//! bodies are intersected as they then are, which the boolean can do: narrowed, that gives the//! overlap away from the walls (the core). In the band the move swept, what the two walls//! share is a crescent in every section, whose area follows from the two circles alone. The@@ -36,6 +37,10 @@ pub struct CoaxialOverlap {const NEAR: f64 = 0.01;/// The step the pin's wall is moved by, as a share of its radius.const STEP: f64 = 0.1;+/// The tries each intersection here gets: with a wall moved clear it takes one or two, and a+/// few more where a flush face is pulled back or the tool is nudged by a hair; one that needs+/// more than that meets something this work does not cover.+const ATTEMPTS: usize = 10;/// The faces of one body on one cylinder, the side its material is on and their extent along/// the axis.@@ -66,8 +71,8 @@ struct Pair {}/// The overlap of `a` and `b` when a pin of one sits in a hole of the other on nearly the same-/// cylinder (axes parallel, offset plus radius difference within 1 % of the radius, but not on-/// the same surface), worked out as the module says. `None` when there is no such pin, or the+/// cylinder (axes parallel, offset plus radius difference within 1 % of the radius, none for a+/// pin seated line to line), worked out as the module says. `None` when there is no such pin, or the/// bodies hold more than the pin and the hole where the work assumes they don't: the caller/// then takes the general boolean.pub fn coaxial_overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {@@ -78,16 +83,51 @@ pub fn coaxial_overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {crate::guard("near-coaxial overlap", || Ok(overlap(a, b).or_else(|| overlap(b, a)))).ok().flatten()}+/// Whether a cylinder of `a` and one of `b` are on one cylinder or nearly (what+/// [`coaxial_overlap`] asks first, from the faces' surfaces alone): a cheap test for whether+/// it is worth preparing the bodies for it. `Some(true)` when every such pair is on one cylinder+/// within the kernel's same-surface tolerance, which the boolean takes as one wall; `Some(false)`+/// when one is a hair off, which it cannot intersect and may even pass as clear.+pub fn coaxial_candidate(a: &Body, b: &Body) -> Option<bool> {+ if a.is_mesh() || b.is_mesh() {+ return None;+ }+ crate::guard("near-coaxial candidate", || {+ let same = same_surface(a.size().max(b.size()));+ let (ca, cb) = (cylinders(a), cylinders(b));+ let mut found = None;+ for x in &ca {+ for y in &cb {+ if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 {+ continue;+ }+ if let Some((_, offset)) = near(x, y) {+ let one = offset + (x.radius - y.radius).abs() <= same;+ found = Some(found.unwrap_or(true) && one);+ }+ }+ }+ Ok(found)+ })+ .ok()+ .flatten()+}++/// The distance within which the kernel takes two surfaces as one, for bodies of `size`.+fn same_surface(size: f64) -> f64 {+ (size * 1e-7).max(1e-9) * 10.0+}+fn overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {let size = a.size().max(b.size());if !(size.is_finite() && size > 0.0) {return None;}// The same surface as the kernel takes it elsewhere: walls that close are one wall.- let same = (size * 1e-7).max(1e-9) * 10.0;+ let same = same_surface(size);// Meshed only when two cylinders are close enough to be asked about.let (ca, cb) = (cylinders(a), cylinders(b));- let close = |x: &Wall, y: &Wall| x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && near(x, y, same).is_some();+ let close = |x: &Wall, y: &Wall| x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && near(x, y).is_some();if !ca.iter().any(|x| cb.iter().any(|y| close(x, y))) {return None;}@@ -112,16 +152,24 @@ fn overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {// Two pins or two holes on nearly one cylinder, side by side along it: not this// case. Apart along the axis (a screw's head beside a bush of its radius), they// don't meet.- _ if near(x, y, same).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None,+ _ if near(x, y).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None,_ => continue,};- let Some((toward, offset)) = near(pin, hole, same) else { continue };+ let Some((toward, offset)) = near(pin, hole) else { continue };let shared = intersect(&union(&pin.spans), &union(&project(hole, pin)));if total(&shared) <= same {continue;}let step = (pin.radius * STEP).min(size * 0.02);- pairs.push(Pair { pin: pin.clone(), pin_in_a, hole: hole.clone(), toward, offset, shared, step });+ // Within the kernel's same-surface tolerance the two walls are one: no crescent.+ let mut hole = hole.clone();+ let offset = if offset + (pin.radius - hole.radius).abs() <= same {+ hole.radius = pin.radius;+ 0.0+ } else {+ offset+ };+ pairs.push(Pair { pin: pin.clone(), pin_in_a, hole, toward, offset, shared, step });}}if pairs.is_empty() {@@ -131,26 +179,58 @@ fn overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {// an area, which the boolean cannot always take: it is pulled back off it by a little.// Only material outside the other body goes, so the overlap is the same.let back = pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 0.05;- let (fa, fb) = (flush(a, b, same, back), flush(b, a, same, back));- // A pin's faces move together: one step for each of them (the pin's walls do not repeat- // across pairs unless one pin is near two holes, which the check below then answers).+ let flat = (flush(a, b, same, back), flush(b, a, same, back), back);+ // The pin's wall is moved where its neighbours let it; where they don't (a blend running+ // into it), the hole's wall is moved away from the pin instead.+ let stuck = std::cell::Cell::new(false);+ answer(a, b, &pairs, size, &flat, false, &stuck).or_else(|| if stuck.get() { answer(a, b, &pairs, size, &flat, true, &stuck) } else { None })+}++/// The overlap of the `pairs` worked out with each pin's wall moved by steps, or each hole's+/// (`move_hole`); `stuck` set when a body could not be moved. `flat` holds the faces of `a`+/// and of `b` that touch the other flat, and how far they are pulled back off it.+fn answer(+ a: &Body,+ b: &Body,+ pairs: &[Pair],+ size: f64,+ flat: &(Vec<usize>, Vec<usize>, f64),+ move_hole: bool,+ stuck: &std::cell::Cell<bool>,+) -> Option<CoaxialOverlap> {+ let (fa, fb, back) = (&flat.0, &flat.1, flat.2);+ // The pin's and the hole's radius with the moved wall `k` steps toward the other.+ let radii = |p: &Pair, k: f64| if move_hole { (p.pin.radius, p.hole.radius - p.step * k) } else { (p.pin.radius + p.step * k, p.hole.radius) };+ // A wall's faces move together: one step for each of them (a wall does not repeat across+ // pairs unless one pin is near two holes, which the check below then answers).let shared_at = |k: f64| -> Option<(f64, Option<Body>)> {let moved = |body: &Body, in_a: bool| -> Option<Body> {- let mine: Vec<&Pair> = pairs.iter().filter(|p| p.pin_in_a == in_a).collect();+ let mine: Vec<(&Wall, f64)> = pairs+ .iter()+ .filter_map(|p| match (move_hole, p.pin_in_a == in_a) {+ (false, true) => Some((&p.pin, p.step)),+ (true, false) => Some((&p.hole, p.step)),+ _ => None,+ })+ .collect();if mine.is_empty() {return Some(body.clone());}- let flush = if in_a { &fa } else { &fb };- let shift = |i: usize, _| match mine.iter().find(|p| p.pin.faces.contains(&i)) {- Some(p) => p.step * k,+ let flush = if in_a { fa } else { fb };+ let shift = |i: usize, _| match mine.iter().find(|(w, _)| w.faces.contains(&i)) {+ Some((_, step)) => step * k,None if flush.contains(&i) => -back,None => 0.0,};- let m = crate::offset::offset_body(body, shift).ok()?;- m.validity().is_empty().then_some(m)+ let m = crate::offset::offset_body(body, shift).ok().filter(|m| m.validity().is_empty());+ if m.is_none() {+ stuck.set(true);+ }+ m};let (ma, mb) = (moved(a, true)?, moved(b, false)?);- let (r, report) = crate::capture_boolean_diagnostics(|| crate::ops::boolean(&ma, &mb, BoolOp::Intersect));+ let (r, report) =+ crate::capture_boolean_diagnostics(|| crate::ops::with_attempt_budget(ATTEMPTS, || crate::ops::boolean(&ma, &mb, BoolOp::Intersect)));// The core is the answer and must be exact. The wider pins only check the band, to// 2 % of what it gains: a tool nudged by a hair of the step there is as good.let nudge = if k > 0.0 { pairs.iter().map(|p| p.step).fold(f64::INFINITY, f64::min) * 1e-2 } else { 0.0 };@@ -162,14 +242,17 @@ fn overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {Some(body) => Some((crate::measure(&body).ok()?.volume, Some(body))),}};- // The crescents' volume with every pin grown by `k` steps.- let crescents =- |k: f64| -> f64 { pairs.iter().map(|p| total(&p.shared) * crescent(p.pin.radius + p.step * k, p.hole.radius, p.offset).area).sum() };+ // The crescents' area along each pair with the moved walls `k` steps toward each other.+ let crescent_at = |p: &Pair, k: f64| {+ let (r, h) = radii(p, k);+ crescent(r, h, p.offset).area+ };+ let crescents = |k: f64| -> f64 { pairs.iter().map(|p| total(&p.shared) * crescent_at(p, k)).sum() };let (core, core_body) = shared_at(-1.0)?;for k in [0.5, 1.0] {let (v, _) = shared_at(k)?;let gain = crescents(k) - crescents(-1.0);- if !((v - core - gain).abs() <= 0.02 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) {+ if !((v - core - gain).abs() <= 0.002 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) {return None;}}@@ -186,11 +269,11 @@ fn overlap(a: &Body, b: &Body) -> Option<CoaxialOverlap> {bbox = m.bbox;volume = m.volume;}- for p in &pairs {+ for p in pairs {let c = crescent(p.pin.radius, p.hole.radius, p.offset);let length = total(&p.shared);- // Less what the narrowed pin already reached (nothing, unless the hole is the smaller).- let v = length * c.area - length * crescent(p.pin.radius - p.step, p.hole.radius, p.offset).area;+ // Less what the moved walls already shared (nothing, unless the hole is the smaller).+ let v = length * (c.area - crescent_at(p, -1.0));let mid = p.shared.iter().map(|(s, t)| (s + t) * 0.5 * (t - s)).sum::<f64>() / length;let side = p.toward.cross(p.pin.axis);moment += (p.pin.origin + p.pin.axis * mid + p.toward * c.centroid) * v;@@ -221,17 +304,13 @@ fn altered_by_at_most(report: &crate::BooleanDiagnostics, limit: f64, size: f64).all(|e| e.strategy == crate::BooleanStrategy::ToolNudge && limit > 0.0 && e.translation_mm + e.rotation_rad * size <= limit)}-/// The pin's offset to the hole, when the two are nearly on one cylinder but not on the same-/// surface: the unit direction from the pin's axis to the hole's (any, for one axis) and the-/// distance.-fn near(pin: &Wall, hole: &Wall, same: f64) -> Option<(Vec3, f64)> {+/// The pin's offset to the hole, when the two are on one cylinder or nearly: the unit direction+/// from the pin's axis to the hole's (any, for one axis) and the distance.+fn near(pin: &Wall, hole: &Wall) -> Option<(Vec3, f64)> {let d = hole.origin - pin.origin;let across = d - pin.axis * d.dot(pin.axis);let offset = across.len();let gap = (pin.radius - hole.radius).abs();- if offset <= same && gap <= same {- return None;- }if !(offset + gap <= NEAR * pin.radius.min(hole.radius)) {return None;}@@ -499,11 +578,29 @@ mod tests {let slot = crate::box_solid(Vec3::new(2.5, -1.0, -1.0), Vec3::new(4.0, 1.0, 6.0)).unwrap();let slotted = crate::boolean(&plate, &slot, BoolOp::Cut).unwrap().unwrap();assert!(coaxial_overlap(&slotted, &pin).is_none());- // Pins on the very axis, or far off it, aren't asked about.- assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.0).1).is_none());+ // So it is for a pin on the very axis; one far off it isn't asked about.+ assert!(coaxial_overlap(&slotted, &plate_and_pin(3.0, 0.0).1).is_none());assert!(coaxial_overlap(&plate, &plate_and_pin(3.0, 0.5).1).is_none());}+ /// A pin seated line to line, on the hole's very axis: the walls share nothing, and a head+ /// sunk 0.2 into the plate's face shares the ring under it.+ #[test]+ fn a_pin_seated_line_to_line_shares_only_what_its_head_sinks() {+ let (plate, pin) = plate_and_pin(3.0, 0.0);+ for (x, y) in [(&plate, &pin), (&pin, &plate)] {+ let o = coaxial_overlap(x, y).unwrap();+ assert!(o.volume < 1e-9 && o.offset < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}");+ }+ let head = crate::cylinder(Vec3::new(0.0, 0.0, 4.8), Vec3::Z, 5.0, 2.0).unwrap();+ let headed = crate::boolean(&pin, &head, BoolOp::Union).unwrap().unwrap();+ let want = std::f64::consts::PI * (5.0f64.powi(2) - 3.0f64.powi(2)) * 0.2;+ let o = coaxial_overlap(&plate, &headed).unwrap();+ // Measured off the core's mesh, as a boolean's result is.+ assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}");+ assert!((o.centroid.z - 4.9).abs() < 1e-6, "{o:?}");+ }+/// A bush and a headed screw whose shank ends inside the bore, both written to STEP and/// read back: their cylinders come back as one face each that runs once round along a seam/// edge, which the boolean cannot intersect where the shank's end meets the bore. Thediff --git a/crates/kernel/src/lib.rs b/crates/kernel/src/lib.rsindex f6e71389d4..ece2cdc96b 100644--- a/crates/kernel/src/lib.rs+++ b/crates/kernel/src/lib.rs@@ -163,7 +163,7 @@ pub use build::{path_polyline, revolve, revolve_whole, sphere, sweep, sweep_with, torus,};pub use clearance::{Clearance, Occupancy};-pub use coaxial_overlap::{CoaxialOverlap, coaxial_overlap};+pub use coaxial_overlap::{CoaxialOverlap, coaxial_candidate, coaxial_overlap};pub use continuity::{ContinuityReport, ContinuityTolerances, EdgePick, MAX_SAMPLES, MIN_SAMPLES, SeamReport, SeamVerdict, SeamWorst, pick_edges, seam_diagnostics,};@@ -189,7 +189,7 @@ pub use native::{decode_native_body, encode_native_body, native_preview_mesh};pub use offset::with_same_surface;pub use ops::{BoolOp, boolean, can_join_all_touching_faces, can_join_touching_faces, compound_disjoint_extrusions, half_space, is_planar, join_apart,- split_by_plane, transform, transform_matrix, union_apart,+ split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget,};pub use polybool::{faceted_boolean, planar_boolean};pub use polyhedron::{HalfSpace, convex_polyhedron, draft, offset_faces, shell};diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex eb6f1479e1..8657868678 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -874,6 +874,40 @@ thread_local! {static APART: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };/// Set while a union runs with a bore narrowed off a common cylinder (no second round).static BORES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };+ /// The intersections left to the booleans running under [`with_attempt_budget`], if any.+ static ATTEMPTS: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };+}++/// `f`, with the booleans it runs on this thread allowed `attempts` of the kernel's own+/// intersections between them (each try of a boolean takes one): past those, a boolean fails at+/// once instead of trying on. For a caller that would rather report a pair it could not answer+/// than wait on bodies the boolean cannot take, and the same on every machine. A budget inside+/// another takes the smaller and uses up the outer one's too.+pub fn with_attempt_budget<T>(attempts: usize, f: impl FnOnce() -> T) -> T {+ struct Restore(Option<usize>, usize);+ impl Drop for Restore {+ fn drop(&mut self) {+ let left = ATTEMPTS.with(|c| c.get()).unwrap_or(0);+ ATTEMPTS.with(|c| c.set(self.0.map(|outer| outer.saturating_sub(self.1.saturating_sub(left)))));+ }+ }+ let outer = ATTEMPTS.with(|c| c.get());+ let mine = outer.map_or(attempts, |o| o.min(attempts));+ ATTEMPTS.with(|c| c.set(Some(mine)));+ let _restore = Restore(outer, mine);+ f()+}++/// Takes one of the attempts left under [`with_attempt_budget`]; false when none is left.+fn take_attempt() -> bool {+ ATTEMPTS.with(|c| match c.get() {+ None => true,+ Some(0) => false,+ Some(n) => {+ c.set(Some(n - 1));+ true+ }+ })}/// Boolean of two bodies. The result may be empty (`Ok(None)`) for a cut that removes@@ -1829,6 +1863,9 @@ pub(crate) fn nudged(r: Body, nb: &Body, counts: &[(usize, usize)]) -> Body {/// copies) keep the operands' face and edge order, and so does moving the result back, so the/// history truck records holds for the operands themselves.pub(crate) fn truck_boolean(a: &Body, b: &Body, op: BoolOp, shift: Option<mt::Vector3>, tol: f64) -> Result<(Solid, Option<recorded::Shapeops>)> {+ if !take_attempt() {+ return Err(KernelError::Failed("no result in the tries it was given".into()));+ }guard("boolean", || {let (mut sa, mut sb) = (a.deep_copy(), b.deep_copy());if let Some(shift) = shift {diff --git a/crates/kernel/src/tests.rs b/crates/kernel/src/tests.rsindex d29152568e..bd668d78e5 100644--- a/crates/kernel/src/tests.rs+++ b/crates/kernel/src/tests.rs@@ -2963,3 +2963,20 @@ fn loft_pairs_the_vertices_of_matching_non_convex_sections() {assert!(rel(m.volume, want) < 5e-3, "{} vs {want}", m.volume);assert!(m.centroid.x.abs() < 0.05, "centre of mass x {}", m.centroid.x);}++/// Two cylinders crossing at right angles need the kernel's own intersection: with no tries+/// left the boolean fails at once, a budget inside another uses the outer one's up, and none+/// lingers after.+#[test]+fn an_attempt_budget_stops_the_boolean_and_is_shared_by_nesting() {+ let a = cylinder(Vec3::new(0.0, 0.0, -10.0), Vec3::Z, 3.0, 20.0).unwrap();+ let b = cylinder(Vec3::new(-10.0, 0.0, 0.0), Vec3::X, 2.0, 20.0).unwrap();+ assert!(with_attempt_budget(0, || boolean(&a, &b, BoolOp::Intersect)).is_err());+ // The inner budget asks for more than the outer has left: it gets what is left.+ let (inner, after) = with_attempt_budget(1, || {+ let inner = with_attempt_budget(10, || boolean(&a, &b, BoolOp::Intersect).is_ok());+ (inner, boolean(&a, &b, BoolOp::Intersect).is_ok())+ });+ assert!(inner && !after);+ assert!(boolean(&a, &b, BoolOp::Intersect).unwrap().is_some());+}