SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.
Boolean: a pin in a bore of its size is clear at every placement (#2714) (#2715)
NOWN-DEV62b49f9f89e8
diff --git a/crates/engine/src/cmd/clearance_tests.rs b/crates/engine/src/cmd/clearance_tests.rsindex 3b057094fb..901f4a74a3 100644--- a/crates/engine/src/cmd/clearance_tests.rs+++ b/crates/engine/src/cmd/clearance_tests.rs@@ -415,3 +415,53 @@ fn a_roller_pressed_into_a_large_plate_is_reported() {let want = (r * r * ((r - depth) / r).acos() - (r - depth) * (r * r - (r - depth) * (r - depth)).sqrt()) * length;assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.01 * want, "{want} {res}");}++/// A pin turned from a profile (its wall in three faces) in the bore of a tube of its own size+/// (in two faces), its end inside the bore, a hair off the axis, and a slit tube with the pin+/// through it: touching, not overlapping. Their facets cross where one body's faces end on the+/// shared cylinder, and the pairs were left unchecked ("could not be intersected there").+#[test]+fn a_turned_pin_in_a_bore_of_its_size_is_contact() {+ let mut s = Session::default();+ let pin = |s: &mut Session, name: &str, off: [f64; 3], z0: f64, z1: f64| {+ run(s, "sketch.create", json!({"plane": {"origin": off, "x_dir": [1, 0, 0], "y_dir": [0, 0, 1]}}));+ run(s, "sketch.rectangle.two_point", json!({"p0": [0, z0], "p1": [3, z1]}));+ run(s, "solid.revolve", json!({"axis": "y", "body_name": name}));+ };+ let tube = |s: &mut Session, name: &str, x: f64| {+ run(s, "solid.cylinder", json!({"radius": 5.25, "height": 19.55, "base": [x, 0, 0], "body_name": name}));+ run(s, "solid.cylinder", json!({"radius": 3, "height": 19.55, "base": [x, 0, 0], "operation": "cut", "targets": [name]}));+ };+ pin(&mut s, "Pin", [2.2e-8, 4.7e-7, 0.0], -2.35, 9.65);+ tube(&mut s, "Tube", 0.0);+ pin(&mut s, "Through", [30.0, 0.0, 0.0], -3.0, 22.0);+ tube(&mut s, "Slit", 30.0);+ run(&mut s, "solid.box", json!({"length": 8, "width": 0.1, "height": 21, "corner": [22, -0.05, -1], "operation": "cut", "targets": ["Slit"]}));+ let r = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin", "Through"], "against": ["Tube", "Slit"], "clearance": 1e-6}));+ assert_eq!(r["unchecked"].as_array().map(Vec::len), Some(0), "{r}");+ assert_eq!(r["overlaps"].as_array().map(Vec::len), Some(0), "{r}");+ let near = r["near"].as_array().cloned().unwrap_or_default();+ assert_eq!(near.iter().map(pair).collect::<Vec<_>>(), [["Pin", "Tube"], ["Slit", "Through"]], "{r}");+ assert!(near.iter().all(|n| f(&n["distance_mm"]) == 0.0 && n.get("overlap_mm3").is_none()), "{r}");+}++/// A pin of a bore's size through a D-bore whose flat is 0.022 mm inside the pin shares a+/// sliver with the tube along the whole bore (the circular segment beyond the flat, 0.21 mm³):+/// an overlap, not contact. Only the facetings of the shared cylinder may cross unseen; the flat+/// reaches into it.+#[test]+fn a_pin_through_a_d_bore_of_its_size_overlaps_the_flat() {+ let (r, flat, length) = (3.0_f64, 2.978_f64, 19.55);+ let mut s = Session::default();+ run(&mut s, "solid.cylinder", json!({"radius": 5.25, "height": length, "base": [0, 0, 0], "body_name": "Tube"}));+ run(&mut s, "solid.cylinder", json!({"radius": r, "height": length, "base": [0, 0, 0], "operation": "cut", "targets": ["Tube"]}));+ run(&mut s, "solid.box", json!({"length": 1, "width": 2, "height": length, "corner": [flat, -1, 0], "operation": "join", "targets": ["Tube"]}));+ run(&mut s, "solid.cylinder", json!({"radius": r, "height": length + 6.0, "base": [0, 0, -3], "operation": "new", "body_name": "Pin"}));+ let res = run(&mut s, "inspect.clearance", json!({"bodies": ["Pin"], "against": ["Tube"], "clearance": 1e-6}));+ let want = (r * r * (flat / r).acos() - flat * (r * r - flat * flat).sqrt()) * length;+ let overlaps = res["overlaps"].as_array().cloned().unwrap_or_default();+ assert!(res["near"].as_array().is_none_or(|n| n.is_empty()), "{res}");+ assert_eq!(res["unchecked"].as_array().map(Vec::len), Some(0), "{res}");+ assert_eq!(overlaps.len(), 1, "{res}");+ assert!((f(&overlaps[0]["volume_mm3"]) - want).abs() < 0.05 * want, "{want} {res}");+}diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rsindex 92339a0ab3..45dd94161e 100644--- a/crates/geom/src/mesh.rs+++ b/crates/geom/src/mesh.rs@@ -100,7 +100,8 @@ pub fn find_close_pair(test: impl FnMut(&BoxedTriangle, &BoxedTriangle) -> bool,) -> Option<bool> {let work = std::cell::Cell::new(*budget);- let found = find_close_pair_within(a, b, gap, &work, test);+ let mut test = test;+ let found = find_close_pair_within(a, b, gap, &work, |(_, t), (_, u)| test(t, u));*budget = work.get();found}@@ -110,7 +111,7 @@ fn find_close_pair_within(b: &[BoxedTriangle],gap: f64,work: &std::cell::Cell<usize>,- mut test: impl FnMut(&BoxedTriangle, &BoxedTriangle) -> bool,+ mut test: impl FnMut((usize, &BoxedTriangle), (usize, &BoxedTriangle)) -> bool,) -> Option<bool> {let spend = |n: usize| -> Option<()> {work.set(work.get().checked_sub(n)?);@@ -125,7 +126,7 @@ fn find_close_pair_within(&& x.min.z <= y.max.z + gap&& y.min.z <= x.max.z + gap};- let mut call = |t: &BoxedTriangle, u: &BoxedTriangle| -> Option<bool> {+ let mut call = |t: (usize, &BoxedTriangle), u: (usize, &BoxedTriangle)| -> Option<bool> {spend(1)?;Some(test(t, u))};@@ -179,7 +180,7 @@ fn find_close_pair_within(for &j in &big {if let Some(u) = b.get(j).filter(|u| close(&t.1, &u.1)) {seen[j] = i + 1;- if call(t, u)? {+ if call((i, t), (j, u))? {return Some(true);}}@@ -187,7 +188,7 @@ fn find_close_pair_within(let Some([x, y, z]) = span(&t.1, 0.0) else {// A large triangle of `a`: against all of `b`.for (j, u) in b.iter().enumerate() {- if seen[j] != i + 1 && close(&t.1, &u.1) && call(t, u)? {+ if seen[j] != i + 1 && close(&t.1, &u.1) && call((i, t), (j, u))? {return Some(true);}}@@ -203,7 +204,7 @@ fn find_close_pair_within(continue;}*mark = i + 1;- if close(&t.1, &u.1) && call(t, u)? {+ if close(&t.1, &u.1) && call((i, t), (j as usize, u))? {return Some(true);}}@@ -215,7 +216,9 @@ fn find_close_pair_within(}/// Two triangles that pass through each other (see [`Mesh::crosses`]).-fn triangles_cross(t: &[Vec3; 3], u: &[Vec3; 3], tol: f64) -> bool {+/// Where two triangles pass through each other by more than `tol` (see [`Mesh::crosses`]): the+/// middle of the stretch of the line their planes share that both span, or `None`.+fn triangles_cross(t: &[Vec3; 3], u: &[Vec3; 3], tol: f64) -> Option<Vec3> {// Signed distances of one triangle's corners from the other's plane, when they lie more// than `tol` to both sides of it.let sides = |tri: &[Vec3; 3], plane: &[Vec3; 3]| -> Option<(Vec3, [f64; 3])> {@@ -224,24 +227,31 @@ fn triangles_cross(t: &[Vec3; 3], u: &[Vec3; 3], tol: f64) -> bool {let (lo, hi) = d.iter().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(*v), hi.max(*v)));(lo < -tol && hi > tol).then_some((n, d))};- let (Some((nu, dt)), Some((nt, du))) = (sides(t, u), sides(u, t)) else { return false };- let Some(line) = nt.cross(nu).normalized() else { return false };+ let (Some((nu, dt)), Some((nt, du))) = (sides(t, u), sides(u, t)) else { return None };+ let line = nt.cross(nu).normalized()?;// Where a triangle's edges pass through the other's plane, measured along the line the// two planes share.- let reach = |tri: &[Vec3; 3], d: &[f64; 3]| -> (f64, f64) {- let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);+ // With the points there, for the middle of the stretch both span.+ let reach = |tri: &[Vec3; 3], d: &[f64; 3]| -> ((f64, Vec3), (f64, Vec3)) {+ let (mut lo, mut hi) = ((f64::INFINITY, Vec3::ZERO), (f64::NEG_INFINITY, Vec3::ZERO));for (i, j) in [(0, 1), (1, 2), (2, 0)] {let (p, q, dp, dq) = (tri[i], tri[j], d[i], d[j]);if (dp < 0.0) != (dq < 0.0) && dp != dq {- let at = line.dot(p + (q - p) * (dp / (dp - dq)));- lo = lo.min(at);- hi = hi.max(at);+ let x = p + (q - p) * (dp / (dp - dq));+ let at = line.dot(x);+ if at < lo.0 {+ lo = (at, x);+ }+ if at > hi.0 {+ hi = (at, x);+ }}}(lo, hi)};let ((t0, t1), (u0, u1)) = (reach(t, &dt), reach(u, &du));- t1.min(u1) - t0.max(u0) > tol+ let (from, to) = (if t0.0 > u0.0 { t0 } else { u0 }, if t1.0 < u1.0 { t1 } else { u1 });+ (to.0 - from.0 > tol).then(|| (from.1 + to.1) * 0.5)}/// Mass properties of a closed mesh.@@ -523,6 +533,14 @@ impl Mesh {/// can still overlap without crossing: one inside the other, or sharing a slab between/// faces that are parallel or in one plane.pub fn crosses(&self, o: &Mesh, tol: f64) -> bool {+ self.crosses_except(o, tol, |_, _, _| false)+ }++ /// [`Mesh::crosses`], leaving out the crossings for which `ignored` holds, asked with the+ /// middle of the stretch the two triangles share and the faces of this mesh's and `o`'s+ /// triangle (`u32::MAX` where a mesh has no face for it): where both meshes stand for one+ /// surface of both bodies, and their facets cross by the facetings' error alone.+ pub fn crosses_except(&self, o: &Mesh, tol: f64, ignored: impl Fn(Vec3, u32, u32) -> bool) -> bool {if !tol.is_finite() {return false;}@@ -532,23 +550,29 @@ impl Mesh {if region.is_empty() {return false;}- let near = |m: &Mesh| -> Vec<([Vec3; 3], Aabb3)> {+ // The triangles near the other mesh, with their faces.+ let near = |m: &Mesh| -> (Vec<BoxedTriangle>, Vec<u32>) {m.triangles.iter()- .filter_map(|t| {+ .enumerate()+ .filter_map(|(i, t)| {let t = m.tri(t)?;let mut bx = Aabb3::EMPTY;t.iter().for_each(|p| bx.add(*p));- (!bx.is_empty() && boxes_meet(&bx, ®ion)).then_some((t, bx))+ (!bx.is_empty() && boxes_meet(&bx, ®ion)).then(|| ((t, bx), m.tri_face.get(i).copied().unwrap_or(u32::MAX)))})- .collect()+ .unzip()};- let (ta, tb) = (near(self), near(o));+ let ((ta, fa), (tb, fb)) = (near(self), near(o));if ta.is_empty() || tb.is_empty() {return false;}- let mut unlimited = usize::MAX;- find_close_pair(&ta, &tb, 0.0, &mut unlimited, |(t, _), (u, _)| triangles_cross(t, u, tol)).unwrap_or(false)+ let work = std::cell::Cell::new(usize::MAX);+ let face = |faces: &[u32], i: usize| faces.get(i).copied().unwrap_or(u32::MAX);+ find_close_pair_within(&ta, &tb, 0.0, &work, |(i, (t, _)), (j, (u, _))| {+ triangles_cross(t, u, tol).is_some_and(|at| !ignored(at, face(&fa, i), face(&fb, j)))+ })+ .unwrap_or(false)}/// Closest intersection of a ray with the mesh: (distance along `dir`, triangle index).diff --git a/crates/geom/src/tests.rs b/crates/geom/src/tests.rsindex 39010d8729..7b8513aca7 100644--- a/crates/geom/src/tests.rs+++ b/crates/geom/src/tests.rs@@ -287,6 +287,8 @@ fn box_mesh(min: Vec3, max: Vec3, n: usize) -> Mesh {let k = m.positions.len() as u32;m.positions.extend([corner(i, j), corner(i + 1, j), corner(i + 1, j + 1), corner(i, j + 1)]);m.triangles.extend(if side > 0.0 { [[k, k + 1, k + 2], [k, k + 2, k + 3]] } else { [[k, k + 2, k + 1], [k, k + 3, k + 2]] });+ // Faces: 2 * axis, plus one on the far side.+ m.tri_face.extend([(2 * axis) as u32 + side as u32; 2]);}}}@@ -318,6 +320,16 @@ fn meshes_cross_only_where_their_surfaces_pass_through_each_other() {// Passing through by less than the tolerance doesn't count.assert!(!a.crosses(&cube(9.995, 3.0, 1), 0.01));assert!(!a.crosses(&cube(9.85, 3.0, 1), f64::NAN));+ // Crossings left out where the caller knows better: only those, by where they are.+ let corner = cube(9.85, 9.85, 2);+ assert!(!a.crosses_except(&corner, 0.01, |_, _, _| true));+ assert!(!a.crosses_except(&corner, 0.01, |p, _, _| p.x > 9.8 && p.y > 9.8));+ assert!(a.crosses_except(&corner, 0.01, |p, _, _| p.x < 9.8));+ // And by the faces that cross: `a`'s side at x = 10 through the corner's at y = 9.85, and+ // `a`'s at y = 10 through the corner's at x = 9.85.+ assert!(!a.crosses_except(&corner, 0.01, |_, f, g| matches!((f, g), (1, 2) | (3, 0))));+ assert!(a.crosses_except(&corner, 0.01, |_, f, g| (f, g) == (1, 2)));+ assert!(a.crosses_except(&corner, 0.01, |_, f, g| (f, g) == (3, 0)));}/// A closed box mesh `[x0, x0+a] x [y0, y0+b] x [z0, z0+c]`, outward-facing.diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rsindex 9e0d515782..eb6f1479e1 100644--- a/crates/kernel/src/ops.rs+++ b/crates/kernel/src/ops.rs@@ -281,6 +281,8 @@ fn overlap(/// Whether some facet of `m` has material just under it (`depth` in from its middle) that is/// inside the other body (`inside`) or outside it. With `within`, only facets in that box.+/// Points for which `ignored` holds, asked with the point and the facet's face (`u32::MAX`+/// where the mesh has none), are no evidence either.fn under_surface(m: &solidcraft_geom::Mesh,own: &solidcraft_geom::InsideIndex,@@ -288,42 +290,213 @@ fn under_surface(depth: f64,inside: bool,within: Option<&solidcraft_geom::Aabb3>,+ ignored: &dyn Fn(Vec3, u32) -> bool,) -> bool {- m.triangles.iter().filter_map(|t| m.tri(t)).any(|[p, q, r]| {+ m.triangles.iter().enumerate().filter_map(|(i, t)| Some((m.tri(t)?, m.tri_face.get(i).copied().unwrap_or(u32::MAX)))).any(|([p, q, r], face)| {let Some(n) = (q - p).cross(r - p).normalized() else { return false };let c = (p + q + r) * (1.0 / 3.0) - n * depth;let near = within.is_none_or(|b| c.x >= b.min.x && c.x <= b.max.x && c.y >= b.min.y && c.y <= b.max.y && c.z >= b.min.z && c.z <= b.max.z);// A wall thinner than `depth` puts the point outside its own body: no evidence.- near && other.contains(c) == inside && own.contains(c)+ near && other.contains(c) == inside && own.contains(c) && !ignored(c, face)})}/// Whether the bodies' facetings show that the samples' answer (see [`trivial`]) is wrong:/// their surfaces pass through each other, or a facet of one has material under it on the-/// wrong side of the other. Overlaps and gaps shallower than `tol` are not seen.+/// wrong side of the other. Overlaps and gaps shallower than `tol` are not seen, nor surfaces+/// that pass through each other only on a cylinder both bodies have faces on, there between+/// those faces or one of them and an end face across its axis, nor material under such an end+/// face's facets at the cylinder (`shared`, asked only when the facetings disagree).fn contradicted((ma, ia): (&solidcraft_geom::Mesh, &solidcraft_geom::InsideIndex),(mb, ib): (&solidcraft_geom::Mesh, &solidcraft_geom::InsideIndex),(disjoint, b_in_a, a_in_b): (bool, bool, bool),tol: f64,+ shared: &dyn Fn() -> SharedCylinders,) -> bool {if !(disjoint || b_in_a || a_in_b) {return false;}+ let cylinders = std::cell::OnceCell::new();+ let shared = || cylinders.get_or_init(shared);if ma.crosses(mb, tol) {- return true;+ let shared = shared();+ if shared.cylinders.is_empty() || ma.crosses_except(mb, tol, |p, fa, fb| shared.ignores(p, fa, fb, tol)) {+ return true;+ }}+ // The end faces of a shared cylinder end on it at their own faceting: a facet of a pin's end+ // inside the hole, or of the hole part's end face round the pin, has its middle within the+ // facetings' error of the cylinder, where the other body's facets can reach over it.+ let (under_a, under_b) = (|p: Vec3, f: u32| shared().under_cap(p, f, true, tol), |p: Vec3, f: u32| shared().under_cap(p, f, false, tol));if disjoint {let (ba, bb) = (ma.bounds(), mb.bounds());- let shared = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) };- return !shared.is_empty() && (under_surface(ma, ia, ib, tol, true, Some(&shared)) || under_surface(mb, ib, ia, tol, true, Some(&shared)));+ let meet = solidcraft_geom::Aabb3 { min: ba.min.max(bb.min), max: ba.max.min(bb.max) };+ return !meet.is_empty()+ && (under_surface(ma, ia, ib, tol, true, Some(&meet), &under_a) || under_surface(mb, ib, ia, tol, true, Some(&meet), &under_b));}- (a_in_b && under_surface(ma, ia, ib, tol, false, None)) || (b_in_a && !a_in_b && under_surface(mb, ib, ia, tol, false, None))+ (a_in_b && under_surface(ma, ia, ib, tol, false, None, &under_a)) || (b_in_a && !a_in_b && under_surface(mb, ib, ia, tol, false, None, &under_b))}/// Sampled overlap fraction below which two bodies share no material.const NONE: f64 = 0.003;+/// A cylinder both bodies have faces on (a pin in a hole of its own size, a bore drilled again),+/// and where along its axis both do. The two facetings of it are chords of one circle at+/// different angles: where one body's facets end on it (a pin's wall through the end face of the+/// hole's part, the pin's end inside the hole) they cross the other's by up to the facetings'+/// error, though the surfaces only touch.+struct SharedCylinder {+ origin: Vec3,+ axis: Vec3,+ radius: f64,+ span: (f64, f64),+ /// The faces on it: of the first body, of the second.+ faces: (usize, usize),+ /// The end faces across its axis that keep to their body's side of it (a hole part's end+ /// face round the hole, a pin's end inside it), within the facetings' error: of the first+ /// body, of the second. A D-bore's end face, which reaches into the cylinder to the flat,+ /// is not one.+ caps: (Vec<usize>, Vec<usize>),+}++impl SharedCylinder {+ /// Whether `p` lies on the cylinder, within `tol`, where both bodies have faces on it.+ fn holds(&self, p: Vec3, tol: f64) -> bool {+ let v = p - self.origin;+ let along = v.dot(self.axis);+ ((v - self.axis * along).len() - self.radius).abs() <= tol && along >= self.span.0 - tol && along <= self.span.1 + tol+ }+}++/// The cylinders both bodies have faces on (see [`shared_cylinders`]).+#[derive(Default)]+struct SharedCylinders {+ cylinders: Vec<SharedCylinder>,+}++impl SharedCylinders {+ /// Whether a crossing at `p` of the first body's face `fa` with the second's `fb` is only+ /// the facetings of a shared cylinder: on it, between the two faces on it, or between one of+ /// them and one of its end faces (a pin's wall through the hole part's end face, the pin's+ /// end inside the hole). A flat, key or rib along the axis still counts.+ fn ignores(&self, p: Vec3, fa: u32, fb: u32, tol: f64) -> bool {+ let (fa, fb) = (fa as usize, fb as usize);+ self.cylinders.iter().any(|c| {+ let (on_a, on_b) = (fa == c.faces.0, fb == c.faces.1);+ ((on_a && on_b) || (on_a && c.caps.1.contains(&fb)) || (c.caps.0.contains(&fa) && on_b)) && c.holds(p, tol)+ })+ }++ /// Whether `p`, just under a facet of the first body's face `face` (`first`) or the second's,+ /// lies within `tol` of a shared cylinder with that face one of its end faces: material the+ /// other body's facets of the cylinder can cover there, though the surfaces only touch.+ fn under_cap(&self, p: Vec3, face: u32, first: bool, tol: f64) -> bool {+ let face = face as usize;+ self.cylinders.iter().any(|c| (if first { &c.caps.0 } else { &c.caps.1 }).contains(&face) && c.holds(p, tol))+ }+}++/// The cylinders on which both `a` and `b` have faces: axes parallel and within `same` of each+/// other, radii within `same` (a pin a hair off its hole's axis shares a crescent, which this+/// tolerance leaves far below any volume worth reporting). Spans from the meshes `ma`, `mb`.+fn shared_cylinders(a: &Body, b: &Body, ma: &solidcraft_geom::Mesh, mb: &solidcraft_geom::Mesh, same: f64) -> SharedCylinders {+ let cylinders = |body: &Body| -> Vec<(usize, Vec3, Vec3, f64)> {+ (0..body.face_count())+ .filter_map(|i| match crate::face_surface(body, i)? {+ crate::FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => {+ Some((i, origin, axis.normalized()?, radius))+ }+ _ => None,+ })+ .collect()+ };+ let (ca, cb) = (cylinders(a), cylinders(b));+ if ca.is_empty() || cb.is_empty() {+ return SharedCylinders::default();+ }+ // Where a face's facets reach along an axis.+ let span = |m: &solidcraft_geom::Mesh, face: usize, origin: Vec3, axis: Vec3| -> Option<(f64, f64)> {+ let (mut lo, mut hi) = (f64::INFINITY, f64::NEG_INFINITY);+ for (t, f) in m.triangles.iter().zip(&m.tri_face) {+ if *f as usize != face {+ continue;+ }+ for p in m.tri(t)? {+ let s = (p - origin).dot(axis);+ lo = lo.min(s);+ hi = hi.max(s);+ }+ }+ (lo <= hi).then_some((lo, hi))+ };+ // A face's facets.+ fn facets(m: &solidcraft_geom::Mesh, face: usize) -> impl Iterator<Item = [Vec3; 3]> + '_ {+ m.triangles.iter().zip(&m.tri_face).filter(move |(_, f)| **f as usize == face).filter_map(|(t, _)| m.tri(t))+ }+ // How near to and far from an axis a face's facets reach (nearest on their edges), and+ // whether its material is inside the cylinder there (its normals point away from the axis).+ let reach = |m: &solidcraft_geom::Mesh, face: usize, origin: Vec3, axis: Vec3| -> (f64, f64, bool) {+ let radial = |p: Vec3| {+ let v = p - origin;+ v - axis * v.dot(axis)+ };+ let (mut near, mut far, mut out) = (f64::INFINITY, 0.0f64, 0.0);+ for t in facets(m, face) {+ for (p, q) in [(t[0], t[1]), (t[1], t[2]), (t[2], t[0])] {+ let (p, q) = (radial(p), radial(q));+ let d = q - p;+ let s = if d.dot(d) > 0.0 { (-p.dot(d) / d.dot(d)).clamp(0.0, 1.0) } else { 0.0 };+ near = near.min((p + d * s).len());+ far = far.max(p.len());+ }+ out += (t[1] - t[0]).cross(t[2] - t[0]).dot(radial((t[0] + t[1] + t[2]) * (1.0 / 3.0)));+ }+ (near, far, out > 0.0)+ };+ let planes = |body: &Body| -> Vec<(usize, Vec3)> {+ (0..body.face_count())+ .filter_map(|i| match crate::face_surface(body, i)? {+ crate::FaceSurface::Plane { normal, .. } => Some((i, normal.normalized()?)),+ _ => None,+ })+ .collect()+ };+ let (pa, pb) = (planes(a), planes(b));+ let mut out = Vec::new();+ for &(fa, oa, xa, ra) in &ca {+ for &(fb, ob, xb, rb) in &cb {+ let d = ob - oa;+ if xa.dot(xb).abs() <= 1.0 - 1e-9 || (ra - rb).abs() > same || (d - xa * d.dot(xa)).len() > same {+ continue;+ }+ let (Some(sa), Some(sb)) = (span(ma, fa, oa, xa), span(mb, fb, oa, xa)) else { continue };+ let (lo, hi) = (sa.0.max(sb.0), sa.1.min(sb.1));+ if lo > hi {+ continue;+ }+ // The facetings' error on the cylinder: how far inside it their chords pass.+ let ((na, _, boss_a), (nb, _, boss_b)) = (reach(ma, fa, oa, xa), reach(mb, fb, oa, xa));+ let error = 2.0 * (ra - na).max(ra - nb).max(0.0) + same;+ // End faces across the axis that keep to their body's side of the cylinder.+ let caps = |m: &solidcraft_geom::Mesh, planes: &[(usize, Vec3)], boss: bool| -> Vec<usize> {+ planes+ .iter()+ .filter(|(_, n)| n.dot(xa).abs() >= 1.0 - 1e-6)+ .filter(|(i, _)| {+ let (near, far, _) = reach(m, *i, oa, xa);+ near <= far && if boss { far <= ra + error } else { near >= ra - error }+ })+ .map(|(i, _)| *i)+ .collect()+ };+ let caps = (caps(ma, &pa, boss_a), caps(mb, &pb, boss_b));+ out.push(SharedCylinder { origin: oa, axis: xa, radius: ra, span: (lo, hi), faces: (fa, fb), caps });+ }+ }+ SharedCylinders { cylinders: out }+}+/// Booleans that need no intersection: one body clear of the other, or inside it. These are/// common with coincident curved faces (a hole drilled where one already is, a body joined/// with itself), which the intersection can't handle. `counts`: the operands' faces and edges.@@ -351,7 +524,10 @@ fn trivial(// The samples only say that nearly all of one body is clear of, or inside, the other. A// small part can still be on the wrong side (a peg overlapping a rib, a chamfer taken off// one edge), and then the bodies have to be intersected.- let sure = !contradicted((ma, &ia), (mb, &ib), (disjoint, b_in_a > ALL, a_in_b > ALL), tol);+ // The same surface as the kernel takes it elsewhere (see `coaxial_overlap`).+ let same = (a.size().max(b.size()) * 1e-7).max(1e-9) * 10.0;+ let shared = || shared_cylinders(a, b, ma, mb, same);+ let sure = !contradicted((ma, &ia), (mb, &ib), (disjoint, b_in_a > ALL, a_in_b > ALL), tol, &shared);let answer = match op {// Sampling only selects this candidate. Validate every shell boundary and the// complete material/void nesting before preserving a disconnected union.@@ -505,6 +681,151 @@ mod shortcut_tests {assert!(trivial(&outer, &protruding, BoolOp::Cut, &mesh, &protruding_mesh, &counts, 0.09).is_none());}+ /// A pin turned from a profile (its wall in three faces) in the bore of a tube (its wall in+ /// two): one cylinder, faceted at different angles, so the pin's facets cross the tube's end+ /// face and the bore's facets cross the pin's end by the facetings' error. The pin is still+ /// clear of the tube, exactly on its axis or a hair off it (parts placed from rounded+ /// coordinates), with the pin's end inside the bore or through it, and with a slit along+ /// the tube: answered at once, without the boolean's retries.+ #[test]+ fn a_pin_in_a_bore_of_its_size_is_clear_of_it_whatever_the_facets() {+ use solidcraft_geom::{Loop2, Plane, Region2, Vec2};+ let rect = |x1: f64, y0: f64, y1: f64| Region2 {+ outer: Loop2::polygon(&[Vec2::new(0.0, y0), Vec2::new(x1, y0), Vec2::new(x1, y1), Vec2::new(0.0, y1)]),+ holes: vec![],+ };+ let pin = |off: Vec3, z0: f64, z1: f64| {+ let plane = Plane { origin: off, x: Vec3::X, y: Vec3::Z };+ crate::revolve(&plane, &[rect(3.0, z0, z1)], Vec2::ZERO, Vec2::new(0.0, 1.0), std::f64::consts::TAU).unwrap().pop().unwrap()+ };+ let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, 19.55).unwrap();+ let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 21.55).unwrap();+ let tube = boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap();+ let slit = crate::box_solid(Vec3::new(-6.0, -0.05, -1.0), Vec3::new(0.0, 0.05, 21.0)).unwrap();+ let slit_tube = boolean(&tube, &slit, BoolOp::Cut).unwrap().unwrap();+ let tube_volume = crate::measure(&tube).unwrap().volume;+ for off in [Vec3::ZERO, Vec3::new(2.2e-8, 4.7e-7, 0.0)] {+ for (p, t) in [(pin(off, -2.35, 9.65), &tube), (pin(off, -3.0, 22.0), &tube), (pin(off, -2.35, 9.65), &slit_tube)] {+ assert_eq!(p.face_count(), 5);+ for (x, y) in [(&p, t), (t, &p)] {+ let (r, report) = crate::capture_boolean_diagnostics(|| boolean(x, y, BoolOp::Intersect));+ assert!(r.unwrap().is_none() && report.events.is_empty(), "{off:?} {report:?}");+ }+ let cut = boolean(&tube, &p, BoolOp::Cut).unwrap().unwrap();+ assert!((crate::measure(&cut).unwrap().volume - tube_volume).abs() < 1e-6 * tube_volume);+ }+ }+ // Off the axis by 0.01 mm the pin shares a crescent with the tube: not taken for apart.+ let (ma, mb) = (pin(Vec3::new(0.01, 0.0, 0.0), -2.35, 9.65), tube.clone());+ let counts = record::counts(&[&ma, &mb]);+ let (sa, sb) = (ma.tessellate_with(0.009, true).unwrap(), mb.tessellate_with(0.009, true).unwrap());+ assert!(trivial(&ma, &mb, BoolOp::Intersect, &sa, &sb, &counts, 0.027).is_none_or(|(_, sure)| !sure));+ }++ /// A pin turned from a profile (its wall in three faces) and a plate with a bore of the pin's+ /// size (its wall in two), the pin's end inside the bore: turned about the pin's axis and+ /// the pair placed and tilted.+ fn pin_in_plate_bore(radius: f64, turn: f64, (to, axis, angle): (Vec3, Vec3, f64)) -> (Body, Body) {+ use solidcraft_geom::{Loop2, Plane, Region2, Vec2};+ let profile = Region2 {+ outer: Loop2::polygon(&[Vec2::new(0.0, -2.35), Vec2::new(radius, -2.35), Vec2::new(radius, 9.65), Vec2::new(0.0, 9.65)]),+ holes: vec![],+ };+ let plane = Plane { origin: Vec3::ZERO, x: Vec3::X, y: Vec3::Z };+ let pin = crate::revolve(&plane, &[profile], Vec2::ZERO, Vec2::new(0.0, 1.0), std::f64::consts::TAU).unwrap().pop().unwrap();+ let pin = crate::transform(&pin, Vec3::ZERO, Vec3::ZERO, Vec3::Z, turn).unwrap();+ let block = crate::box_solid(Vec3::new(-8.0, -8.0, 0.0), Vec3::new(8.0, 8.0, 19.5)).unwrap();+ let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 21.5).unwrap();+ let plate = boolean(&block, &bore, BoolOp::Cut).unwrap().unwrap();+ let place = |b: &Body| crate::transform(b, to, Vec3::ZERO, axis, angle).unwrap();+ (place(&pin), place(&plate))+ }++ /// Placements of the pair: as built, far off the origin on its side, and tilted two ways.+ const PLACEMENTS: [(Vec3, Vec3, f64); 4] = [+ (Vec3::ZERO, Vec3::Z, 0.0),+ (Vec3::new(-270.0, 267.1, 546.7), Vec3::Y, -std::f64::consts::FRAC_PI_2),+ (Vec3::new(120.0, -40.0, 15.0), Vec3::new(1.0, 1.0, 0.0), 0.7),+ (Vec3::new(-35.0, 80.0, -60.0), Vec3::new(0.3, -0.5, 1.0), 2.1),+ ];++ /// The pin's end lies on the bore's rim at its own faceting, the plate's end face round the+ /// pin at the bore's: the middle of a facet there can be just under the other body's facets+ /// of the cylinder, so the material under it looked inside the other body though the two+ /// only touch (the pin turned 9 steps and the pair tilted about x = y did, the boolean then+ /// fell back on its retries and called its answer unverified). At every turn and placement+ /// the pin is clear of the plate, answered at once.+ #[test]+ fn a_pin_in_a_plate_bore_of_its_size_is_clear_of_it_at_any_placement() {+ for k in 0..12 {+ for placement in PLACEMENTS {+ let (pin, plate) = pin_in_plate_bore(3.0, k as f64 * 0.13, placement);+ for (x, y) in [(&pin, &plate), (&plate, &pin)] {+ let (r, report) = crate::capture_boolean_diagnostics(|| boolean(x, y, BoolOp::Intersect));+ assert!(matches!(r, Ok(None)) && report.events.is_empty(), "{k} {placement:?} {r:?} {report:?}");+ }+ }+ }+ }++ /// The same pin 0.02 mm larger than the bore shares a ring with the plate along the length+ /// it is in it: an overlap, at the placements above too.+ #[test]+ fn a_pin_slightly_larger_than_its_plate_bore_still_overlaps_it() {+ let want = std::f64::consts::PI * (3.02f64.powi(2) - 9.0) * 9.65;+ for k in [0, 3, 6, 9] {+ for placement in PLACEMENTS {+ let (pin, plate) = pin_in_plate_bore(3.02, k as f64 * 0.13, placement);+ let (r, report) = crate::capture_boolean_diagnostics(|| boolean(&pin, &plate, BoolOp::Intersect));+ let shared = r.unwrap().map(|b| crate::measure(&b).unwrap().volume);+ assert!(shared.is_some_and(|v| (v - want).abs() < 0.05 * want), "{k} {placement:?} {shared:?} {want} {report:?}");+ }+ }+ }++ /// A pin of the bore's size pushed 0.05 mm on past the bore, into a narrower one, shares a+ /// ring with the tube there (0.2 % of the pin, under what the samples see): the crossings on+ /// the shared cylinder are left out, those of the pin's end with the narrow bore are not.+ #[test]+ fn a_pin_pushed_into_a_narrower_bore_is_not_taken_for_clear() {+ let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, 19.55).unwrap();+ let wide = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 10.0).unwrap();+ let narrow = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 2.0, 21.55).unwrap();+ let tube = boolean(&boolean(&outer, &wide, BoolOp::Cut).unwrap().unwrap(), &narrow, BoolOp::Cut).unwrap().unwrap();+ let pin = crate::cylinder(Vec3::new(0.0, 0.0, -2.0), Vec3::Z, 3.0, 11.05).unwrap();+ let counts = record::counts(&[&pin, &tube]);+ let (ma, mb) = (pin.tessellate_with(0.009, true).unwrap(), tube.tessellate_with(0.009, true).unwrap());+ for op in [BoolOp::Intersect, BoolOp::Cut] {+ assert!(trivial(&pin, &tube, op, &ma, &mb, &counts, 0.027).is_none_or(|(_, sure)| !sure), "{op:?}");+ }+ }++ /// A pin of the bore's size through a D-bore whose flat is 0.022 mm inside the pin (a sliver+ /// of 0.21 mm³ along the bore): the pin's wall passes through the tube's end faces where the+ /// flat reaches into the cylinder, near the shared cylinder but deeper than its facetings'+ /// error. That is real overlap, and must not be taken for the facetings of the cylinder.+ #[test]+ fn a_pin_through_a_d_bore_of_its_size_still_overlaps_the_flat() {+ let (r, flat, length) = (3.0, 2.978, 19.55);+ let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.25, length).unwrap();+ let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, r, length + 2.0).unwrap();+ let keep = crate::box_solid(Vec3::new(-4.0, -4.0, -2.0), Vec3::new(flat, 4.0, length + 2.0)).unwrap();+ let d_bore = boolean(&bore, &keep, BoolOp::Intersect).unwrap().unwrap();+ let tube = boolean(&outer, &d_bore, BoolOp::Cut).unwrap().unwrap();+ let pin = crate::cylinder(Vec3::new(0.0, 0.0, -3.0), Vec3::Z, r, length + 6.0).unwrap();+ // Faceted as the boolean does for bodies of this size (0.015 mm deep crossings seen).+ let counts = record::counts(&[&pin, &tube]);+ let (ma, mb) = (pin.tessellate_with(0.005, true).unwrap(), tube.tessellate_with(0.005, true).unwrap());+ for op in [BoolOp::Intersect, BoolOp::Cut] {+ assert!(trivial(&pin, &tube, op, &ma, &mb, &counts, 0.015).is_none_or(|(_, sure)| !sure), "{op:?}");+ }+ // Nor does the boolean pass them as clear without saying so: the shortcut it falls back+ // on is reported unverified (the bodies can't be intersected along the shared walls),+ // and the caller measures the overlap another way.+ let (shared, report) = crate::capture_boolean_diagnostics(|| boolean(&pin, &tube, BoolOp::Intersect));+ assert!(shared.unwrap().is_some() || report.unverified().is_some(), "{report:?}");+ }+/// Bodies sharing less than the samples can see still meet: no shortcut, and the boolean/// gives the shared part.#[test]