Skip to content

SolidCraft: an open-source parametric 3D CAD application built in pure Rust. Desktop, web, and automation through MCP.

Wave 149/509: kernel: booleans, placements and splits on SMLib only, with no retries

jyviko12dd1a17cc92
diff --git a/crates/kernel/src/boolean_diagnostics.rs b/crates/kernel/src/boolean_diagnostics.rs
deleted file mode 100644
index e2a4b79cc9..0000000000
--- a/crates/kernel/src/boolean_diagnostics.rs
+++ /dev/null
@@ -1,307 +0,0 @@
-//! Scoped reports for successful Boolean retries. Discarded attempts never enter
-//! their caller's report, and independent evaluations cannot inherit old events.
-
-use std::cell::RefCell;
-
-use serde::{Deserialize, Serialize};
-
-const MAX_EVENTS: usize = 1024;
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
-#[serde(rename_all = "snake_case")]
-pub enum BooleanStrategy {
- RefinedTolerance,
- ShiftedOperands,
- CoplanarSeparation,
- CommonBore,
- /// A boss in the other body's bore, grown into the material around it (nothing recut).
- 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.
- UnverifiedShortcut,
-}
-
-/// Numerical adjustments used by a successful retry, in millimetres/radians.
-/// Operand shifts are reversed on the result; face shifts are temporary working
-/// offsets. A tool nudge, in contrast, changes the relative operand placement.
-#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
-pub struct BooleanFallback {
- pub strategy: BooleanStrategy,
- pub translation_mm: f64,
- pub rotation_rad: f64,
- pub face_shift_mm: f64,
- pub tolerance_mm: f64,
-}
-
-impl BooleanStrategy {
- /// Whether a result made this way can differ from the exact one: the tool was moved
- /// against the other body, or part of where they meet was ignored. The other retries work
- /// on temporary geometry or tolerances only, and their results are the exact ones.
- pub fn alters_result(self) -> bool {
- matches!(self, BooleanStrategy::ToolNudge | BooleanStrategy::UnverifiedShortcut)
- }
-}
-
-impl BooleanFallback {
- pub(crate) fn new(strategy: BooleanStrategy) -> Self {
- Self { strategy, translation_mm: 0., rotation_rad: 0., face_shift_mm: 0., tolerance_mm: 0. }
- }
-
- fn description(&self) -> String {
- match self.strategy {
- BooleanStrategy::RefinedTolerance => format!("refined tolerance {:.6e} mm", self.tolerance_mm),
- BooleanStrategy::ShiftedOperands => {
- format!("shifted operands {:.6e} mm (result shifted back), tolerance {:.6e} mm", self.translation_mm, self.tolerance_mm)
- }
- BooleanStrategy::CoplanarSeparation => format!("temporary coincident-face separation up to {:.6e} mm per face", self.face_shift_mm),
- BooleanStrategy::CommonBore => format!("temporary bore offset {:.6e} mm, followed by recutting the original bore", self.face_shift_mm),
- 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",
- self.tolerance_mm
- ),
- }
- }
-}
-
-#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
-pub struct BooleanDiagnostics {
- pub events: Vec<BooleanFallback>,
- pub truncated: bool,
- /// Why candidates of the retries that led to the result were discarded before they were
- /// measured (#3020: a coarse candidate whose edges run far outside the operands, which
- /// meshing never finished). Left out of the report when there are none.
- #[serde(skip_serializing_if = "Vec::is_empty")]
- pub rejected: Vec<String>,
-}
-
-impl BooleanDiagnostics {
- pub(crate) fn push(&mut self, event: BooleanFallback) {
- if self.events.len() < MAX_EVENTS {
- self.events.push(event);
- } else {
- self.truncated = true;
- }
- }
-
- fn push_rejected(&mut self, reason: String) {
- // A candidate checked twice (picked, then taken) is noted once.
- if self.rejected.contains(&reason) {
- return;
- }
- if self.rejected.len() < MAX_EVENTS {
- self.rejected.push(reason);
- } else {
- self.truncated = true;
- }
- }
-
- /// Why the result is not verified, when it ignores a place where the bodies seem to pass
- /// through each other ([`BooleanStrategy::UnverifiedShortcut`]).
- pub fn unverified(&self) -> Option<String> {
- self.events.iter().find(|event| event.strategy == BooleanStrategy::UnverifiedShortcut).map(BooleanFallback::description)
- }
-
- /// Every retry the result took, for a message about the boolean (one that failed its
- /// checks lists what was tried).
- pub fn summary(&self) -> Option<String> {
- self.described(&self.events.iter().collect::<Vec<_>>())
- }
-
- /// The note a feature carries: the retries that can make its result differ from the exact
- /// one ([`BooleanStrategy::alters_result`]). Exact retries are in `events` all the same
- /// (`timeline.inspect`), but they leave the result as it should be: no reason to warn.
- pub fn warning(&self) -> Option<String> {
- self.described(&self.events.iter().filter(|e| e.strategy.alters_result()).collect::<Vec<_>>())
- }
-
- fn described(&self, events: &[&BooleanFallback]) -> Option<String> {
- if events.is_empty() && !self.truncated {
- return None;
- }
- let mut descriptions: Vec<String> = events.iter().take(4).map(|e| e.description()).collect();
- if events.len() > 4 {
- descriptions.push(format!("{} additional retries", events.len() - 4));
- }
- if self.truncated {
- descriptions.push(format!("report capped at {MAX_EVENTS} retries"));
- }
- Some(format!("Boolean retry: {}", descriptions.join("; ")))
- }
-}
-
-thread_local! {
- static REPORT: RefCell<Option<BooleanDiagnostics>> = const { RefCell::new(None) };
-}
-
-struct Scope {
- previous: Option<Option<BooleanDiagnostics>>,
-}
-
-impl Drop for Scope {
- fn drop(&mut self) {
- if let Some(previous) = self.previous.take() {
- REPORT.with(|cell| {
- if let Ok(mut report) = cell.try_borrow_mut() {
- *report = previous;
- }
- });
- }
- }
-}
-
-/// Capture only the events produced by this call. Nested callers explicitly merge
-/// an accepted attempt; dropping a scope restores its parent even during unwinding.
-pub fn capture_boolean_diagnostics<T>(run: impl FnOnce() -> T) -> (T, BooleanDiagnostics) {
- let previous = REPORT.with(|cell| cell.try_borrow_mut().ok().map(|mut report| report.replace(BooleanDiagnostics::default())));
- let scope = Scope { previous };
- let result = run();
- let report = REPORT.with(|cell| cell.try_borrow_mut().ok().and_then(|mut report| report.take())).unwrap_or_default();
- drop(scope);
- (result, report)
-}
-
-pub(crate) fn record(event: BooleanFallback) {
- REPORT.with(|cell| {
- if let Ok(mut report) = cell.try_borrow_mut()
- && let Some(report) = report.as_mut()
- {
- report.push(event);
- }
- });
-}
-
-/// Note a candidate discarded before it was measured, and why.
-pub(crate) fn reject(reason: String) {
- REPORT.with(|cell| {
- if let Ok(mut report) = cell.try_borrow_mut()
- && let Some(report) = report.as_mut()
- {
- report.push_rejected(reason);
- }
- });
-}
-
-pub(crate) fn merge(report: BooleanDiagnostics) {
- for event in report.events {
- record(event);
- }
- for reason in report.rejected {
- reject(reason);
- }
- if report.truncated {
- REPORT.with(|cell| {
- if let Ok(mut report) = cell.try_borrow_mut()
- && let Some(report) = report.as_mut()
- {
- report.truncated = true;
- }
- });
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn nested_attempts_are_committed_explicitly_and_do_not_leak() {
- let (_, report) = capture_boolean_diagnostics(|| {
- let (_, discarded) = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge)));
- assert_eq!(discarded.events.len(), 1);
- let (_, accepted) = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::PlanarFallback)));
- merge(accepted);
- });
- assert_eq!(report.events.len(), 1);
- assert_eq!(report.events[0].strategy, BooleanStrategy::PlanarFallback);
- assert!(capture_boolean_diagnostics(|| {}).1.events.is_empty());
- record(BooleanFallback::new(BooleanStrategy::ToolNudge));
- assert!(capture_boolean_diagnostics(|| {}).1.events.is_empty());
- }
-
- /// Candidates discarded unmeasured (#3020) are reported with the attempt that led to the
- /// result, once each, and not at all when there are none.
- #[test]
- fn rejected_candidates_follow_the_accepted_attempt() {
- let (_, report) = capture_boolean_diagnostics(|| {
- let (_, discarded) = capture_boolean_diagnostics(|| reject("from a discarded attempt".into()));
- assert_eq!(discarded.rejected.len(), 1);
- let (_, accepted) = capture_boolean_diagnostics(|| {
- reject("runaway edge".into());
- reject("runaway edge".into());
- record(BooleanFallback::new(BooleanStrategy::ToolNudge));
- });
- merge(accepted);
- });
- assert_eq!(report.rejected, vec!["runaway edge".to_string()]);
- assert!(serde_json::to_string(&report).unwrap().contains("\"rejected\":[\"runaway edge\"]"));
- let plain = capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))).1;
- assert!(!serde_json::to_string(&plain).unwrap().contains("rejected"));
- }
-
- /// Only retries whose result can differ from the exact one make a warning; the summary
- /// lists every retry.
- #[test]
- fn only_retries_that_alter_the_result_warn() {
- let report = |strategies: &[BooleanStrategy]| {
- capture_boolean_diagnostics(|| {
- for s in strategies {
- record(BooleanFallback::new(*s));
- }
- })
- .1
- };
- let exact = report(&[BooleanStrategy::ShiftedOperands, BooleanStrategy::GrownBoss, BooleanStrategy::CoplanarSeparation]);
- assert!(exact.warning().is_none(), "{exact:?}");
- assert!(exact.summary().is_some_and(|s| s.contains("shifted operands") && s.contains("boss grown")));
- let nudged = report(&[BooleanStrategy::GrownBoss, BooleanStrategy::ToolNudge]);
- let warning = nudged.warning().unwrap();
- assert!(warning.contains("tool displacement") && !warning.contains("boss grown"), "{warning}");
- }
-
- #[test]
- fn exact_operations_and_failed_calls_have_no_retry_report() {
- use solidcraft_geom::Vec3;
- let body = crate::box_solid(Vec3::ZERO, Vec3::new(10., 10., 10.)).unwrap();
- let other = crate::box_solid(Vec3::new(5., 0., 0.), Vec3::new(15., 10., 10.)).unwrap();
- let (result, diagnostics) = capture_boolean_diagnostics(|| crate::boolean(&body, &other, crate::BoolOp::Union));
- assert!(result.unwrap().is_some());
- assert!(diagnostics.warning().is_none(), "{diagnostics:?}");
- let mesh = crate::mesh_body(&[Vec3::ZERO, Vec3::X, Vec3::Y], &[[0, 1, 2]]).unwrap();
- let (result, diagnostics) = capture_boolean_diagnostics(|| crate::boolean(&body, &mesh, crate::BoolOp::Cut));
- assert!(result.is_err());
- assert!(diagnostics.warning().is_none(), "{diagnostics:?}");
- }
-
- #[test]
- fn unwinding_restores_parent_and_reports_are_thread_local_and_bounded() {
- let (_, report) = capture_boolean_diagnostics(|| {
- let failed = crate::guard("diagnostic test", || {
- capture_boolean_diagnostics(|| -> crate::Result<()> {
- record(BooleanFallback::new(BooleanStrategy::ToolNudge));
- panic!("discard this attempt");
- })
- .0
- });
- assert!(failed.is_err());
- let separate = std::thread::spawn(|| capture_boolean_diagnostics(|| record(BooleanFallback::new(BooleanStrategy::ToolNudge))).1);
- assert_eq!(separate.join().unwrap().events.len(), 1);
- for _ in 0..MAX_EVENTS + 1 {
- record(BooleanFallback::new(BooleanStrategy::PlanarFallback));
- }
- });
- assert_eq!(report.events.len(), MAX_EVENTS);
- assert!(report.truncated);
- assert!(report.events.iter().all(|event| event.strategy == BooleanStrategy::PlanarFallback));
- assert!(report.warning().unwrap().contains("capped"));
- }
-}
diff --git a/crates/kernel/src/boolean_guard.rs b/crates/kernel/src/boolean_guard.rs
deleted file mode 100644
index 43c2ed3966..0000000000
--- a/crates/kernel/src/boolean_guard.rs
+++ /dev/null
@@ -1,218 +0,0 @@
-//! The check every Boolean retry's result must pass before it is returned (issue #616).
-//!
-//! A retry moves things about (the tool nudged, faces pushed apart, pieces cut off and glued
-//! back), so its result is held to what a join or a cut can do at all:
-//! - it is closed;
-//! - a join never loses volume and a cut never gains any;
-//! - outside the tool's box nothing changes: there, the result's surface is the target's and
-//! the target's surface is the result's. A join or a cut can only change the target where the
-//! tool is, so geometry anywhere else (a slit through a wall, a face moved) is wrong.
-//!
-//! A result that fails is refused with an error: a wrong result that looks right is worse.
-
-use solidcraft_geom::{Aabb3, Mesh, Vec3};
-
-use crate::body::Body;
-use crate::{BoolOp, KernelError, Result};
-
-/// Most triangles sampled from each surface (evenly spaced through the mesh).
-const MAX_SAMPLES: usize = 20_000;
-
-/// Distance from `p` to the triangle `abc`.
-pub(crate) fn point_triangle_dist(p: Vec3, a: Vec3, b: Vec3, c: Vec3) -> f64 {
- let n = (b - a).cross(c - a);
- let Some(nn) = n.normalized() else {
- return [(a, b), (b, c), (c, a)].iter().map(|(u, v)| p.dist_to_segment(*u, *v)).fold(f64::INFINITY, f64::min);
- };
- let h = (p - a).dot(nn);
- let q = p - nn * h;
- let inside = [(a, b), (b, c), (c, a)].iter().all(|(u, v)| (*v - *u).cross(q - *u).dot(n) >= 0.0);
- if inside { h.abs() } else { [(a, b), (b, c), (c, a)].iter().map(|(u, v)| p.dist_to_segment(*u, *v)).fold(f64::INFINITY, f64::min) }
-}
-
-/// The triangles of a mesh in a uniform grid of cells, each listing the triangles within `reach`
-/// of it, to answer "is this point within `reach` of the surface?".
-struct Near<'a> {
- mesh: &'a Mesh,
- min: Vec3,
- cell: f64,
- dims: [usize; 3],
- cells: Vec<Vec<u32>>,
- reach: f64,
-}
-
-impl<'a> Near<'a> {
- fn new(mesh: &'a Mesh, reach: f64) -> Option<Self> {
- let bounds = mesh.bounds();
- if bounds.is_empty() {
- return None;
- }
- let min = bounds.min - Vec3::new(reach, reach, reach);
- let size = bounds.size() + Vec3::new(2.0 * reach, 2.0 * reach, 2.0 * reach);
- // About a few triangles a cell, at most 64^3 cells.
- let n = (mesh.triangles.len().max(1) as f64).cbrt().clamp(1.0, 64.0);
- let cell = (size.x.max(size.y).max(size.z) / n).max(reach * 2.0).max(1e-9);
- let dims = [size.x, size.y, size.z].map(|s| ((s / cell).ceil() as usize).clamp(1, 256));
- let mut cells = vec![Vec::new(); dims[0] * dims[1] * dims[2]];
- for (i, t) in mesh.triangles.iter().enumerate() {
- let Some(tri) = mesh.tri(t) else { continue };
- let mut bx = Aabb3::EMPTY;
- for p in tri {
- bx.add(p);
- }
- let lo = Self::index(min, cell, dims, bx.min - Vec3::new(reach, reach, reach));
- let hi = Self::index(min, cell, dims, bx.max + Vec3::new(reach, reach, reach));
- for x in lo[0]..=hi[0] {
- for y in lo[1]..=hi[1] {
- for z in lo[2]..=hi[2] {
- if let Some(c) = cells.get_mut((x * dims[1] + y) * dims[2] + z) {
- c.push(i as u32);
- }
- }
- }
- }
- }
- Some(Near { mesh, min, cell, dims, cells, reach })
- }
-
- fn index(min: Vec3, cell: f64, dims: [usize; 3], p: Vec3) -> [usize; 3] {
- let d = p - min;
- let f = |v: f64, n: usize| ((v / cell).floor().max(0.0) as usize).min(n - 1);
- [f(d.x, dims[0]), f(d.y, dims[1]), f(d.z, dims[2])]
- }
-
- fn close(&self, p: Vec3) -> bool {
- let d = p - self.min;
- let s = [d.x, d.y, d.z];
- if s.iter().zip(self.dims).any(|(v, n)| *v < 0.0 || *v > self.cell * n as f64) {
- return false;
- }
- let [x, y, z] = Self::index(self.min, self.cell, self.dims, p);
- let Some(list) = self.cells.get((x * self.dims[1] + y) * self.dims[2] + z) else { return false };
- list.iter().any(|&t| {
- self.mesh.triangles.get(t as usize).and_then(|t| self.mesh.tri(t)).is_some_and(|[a, b, c]| point_triangle_dist(p, a, b, c) <= self.reach)
- })
- }
-}
-
-/// A point of `from`'s surface outside `region` that is not on `onto`'s surface (within
-/// `reach`), if there is one.
-fn stray_point(from: &Mesh, onto: &Near, region: &Aabb3) -> Option<Vec3> {
- let step = from.triangles.len().div_ceil(MAX_SAMPLES).max(1);
- from.triangles.iter().step_by(step).filter_map(|t| from.tri(t)).find_map(|[a, b, c]| {
- let p = (a + b + c) / 3.0;
- let outside =
- p.x < region.min.x || p.y < region.min.y || p.z < region.min.z || p.x > region.max.x || p.y > region.max.y || p.z > region.max.z;
- (outside && !onto.close(p)).then_some(p)
- })
-}
-
-/// The smallest radius of a body's cylinders, spheres and tori (their tubes).
-fn smallest_radius(body: &Body) -> Option<f64> {
- use crate::surface_kind::{FaceSurface, face_surface};
- (0..body.face_count())
- .filter_map(|i| match face_surface(body, i)? {
- FaceSurface::Cylinder { radius, .. } | FaceSurface::Sphere { radius, .. } => Some(radius),
- FaceSurface::Torus { minor, .. } => Some(minor),
- _ => None,
- })
- .filter(|r| r.is_finite() && *r > 0.0)
- .min_by(f64::total_cmp)
-}
-
-fn bad(op: BoolOp, what: String) -> KernelError {
- let verb = match op {
- BoolOp::Union => "join",
- BoolOp::Cut => "cut",
- BoolOp::Intersect => "intersect",
- };
- KernelError::Failed(format!(
- "the {verb} could not be computed reliably: {what}. The result was refused rather than kept wrong; \
- where the bodies only touch (faces flush with each other), overlapping them slightly usually helps"
- ))
-}
-
-/// Check the result of a Boolean that needed a retry (see the module docs). `result` is `None`
-/// for an empty result.
-pub(crate) fn check_retry(a: &Body, b: &Body, op: BoolOp, result: Option<&Body>) -> Result<()> {
- if op == BoolOp::Intersect || a.is_mesh() || b.is_mesh() {
- return Ok(());
- }
- let Some(r) = result else {
- // Nothing left: only a cut whose tool covers the whole target (to within the meshes'
- // chords: a tool touching a round side of the target).
- let chord = a.size().max(b.size()) * 1e-3;
- let (Ok(ma), Ok(mb)) = (a.mesh(&crate::MeshTolerance::chord(chord)), b.mesh(&crate::MeshTolerance::chord(chord))) else { return Ok(()) };
- let (ba, bb) = (ma.bounds(), mb.bounds());
- let tol = 2.0 * chord;
- let within = ba.min.x >= bb.min.x - tol
- && ba.min.y >= bb.min.y - tol
- && ba.min.z >= bb.min.z - tol
- && ba.max.x <= bb.max.x + tol
- && ba.max.y <= bb.max.y + tol
- && ba.max.z <= bb.max.z + tol;
- return if op == BoolOp::Cut && within { Ok(()) } else { Err(bad(op, "it came out empty".into())) };
- };
- if r.solid.boundaries().iter().any(|s| s.shell_condition() != truck_modeling::ShellCondition::Closed) {
- return Err(bad(op, "the result is not closed".into()));
- }
- let size = a.size().max(b.size());
- let t = (size * 2e-4).max(1e-5);
- let (Ok(ma), Ok(mb), Ok(mr)) = (a.mesh(&crate::MeshTolerance::chord(t)), b.mesh(&crate::MeshTolerance::chord(t)), r.mesh(&crate::MeshTolerance::chord(t))) else {
- return Err(bad(op, "the result could not be checked".into()));
- };
- // A mesh as coarse as `t` on a round smaller than it has no inside to speak of (a through
- // hole 0.13 mm across in a 900 mm slab measured −30272 mm³, #1255): the volumes are measured
- // at a tenth of the bodies' smallest radius, where that is finer. All three at the same
- // tolerance, so the chords' error on the faces they share cancels. `scale` refines it all.
- let finest = [a, b, r].iter().filter_map(|x| smallest_radius(x)).fold(f64::INFINITY, f64::min);
- let fine = if finest * 0.1 < t { (finest * 0.1).max(t * 1e-2) } else { t };
- let volume = |body: &Body, mesh: &Mesh, scale: f64| -> Result<f64> {
- if fine == t && scale == 1.0 {
- return Ok(mesh.measure().volume);
- }
- body.mesh(&crate::MeshTolerance::chord(fine * scale)).map(|m| m.measure().volume).map_err(|_| bad(op, "the result could not be checked".into()))
- };
- let judge = |scale: f64| -> Result<(bool, f64, f64, f64)> {
- let (va, vb, vr) = (volume(a, &ma, scale)?, volume(b, &mb, scale)?, volume(r, &mr, scale)?);
- let slack = 2e-4 * (va.abs() + vb.abs()) + 1e-9;
- let ok = vr.is_finite()
- && match op {
- BoolOp::Union => vr >= va.max(vb) - slack && vr <= va + vb + slack,
- BoolOp::Cut => vr <= va + slack && vr >= va - vb - slack,
- BoolOp::Intersect => true,
- };
- Ok((ok, va, vb, vr))
- };
- // A volume out of bounds is measured again ten times finer before it refuses the result:
- // the coarse meshes of a part with many rounds can be off by more than the slack (a 0.8 mm
- // hole through a plastic part's wall measured 6.8 mm³ more than the part, #1255).
- let (mut volume_ok, mut va, mut vb, mut vr) = judge(1.0)?;
- if !volume_ok {
- (volume_ok, va, vb, vr) = judge(0.1)?;
- }
- if !volume_ok {
- let what = match op {
- BoolOp::Union => format!("the joined body's volume would be {vr:.4} mm³ (the target is {va:.4} mm³, the tool {vb:.4} mm³)"),
- _ => format!("the cut body's volume would be {vr:.4} mm³ (the target is {va:.4} mm³, the tool {vb:.4} mm³)"),
- };
- return Err(bad(op, what));
- }
- // Outside the tool's box (with room for the meshes' chords and a nudge) the result's
- // surface and the target's must be the same.
- let reach = 3.0 * t + size * 1e-5;
- let mut region = mb.bounds();
- region.min -= Vec3::new(reach, reach, reach) * 2.0;
- region.max += Vec3::new(reach, reach, reach) * 2.0;
- let (Some(near_a), Some(near_r)) = (Near::new(&ma, reach), Near::new(&mr, reach)) else {
- return Err(bad(op, "the result could not be checked".into()));
- };
- let at = |p: Vec3| format!("({:.3}, {:.3}, {:.3})", p.x, p.y, p.z);
- if let Some(p) = stray_point(&mr, &near_a, &region) {
- return Err(bad(op, format!("it would change the body away from the tool, at {} (outside the tool's region)", at(p))));
- }
- if let Some(p) = stray_point(&ma, &near_r, &region) {
- return Err(bad(op, format!("it would remove part of the body away from the tool, at {} (outside the tool's region)", at(p))));
- }
- Ok(())
-}
diff --git a/crates/kernel/src/bore_union_tests.rs b/crates/kernel/src/bore_union_tests.rs
deleted file mode 100644
index e92aa5b954..0000000000
--- a/crates/kernel/src/bore_union_tests.rs
+++ /dev/null
@@ -1,109 +0,0 @@
-#![allow(clippy::unwrap_used, clippy::panic)]
-use crate::*;
-use solidcraft_geom::{Loop2, Plane, Region2, Vec2, Vec3};
-
-fn fixture() -> (Body, Body, Vec3, f64) {
- let slope = 1f64.to_radians().tan();
- let hs = |normal: Vec3, point: Vec3| {
- let n = normal.normalized().unwrap();
- HalfSpace { n, d: n.dot(point) }
- };
- let stock = convex_polyhedron(&[
- hs(Vec3::X, Vec3::new(40., 0., 0.)),
- hs(-Vec3::X, Vec3::ZERO),
- hs(Vec3::Y, Vec3::new(0., 30., 0.)),
- hs(-Vec3::Y, Vec3::ZERO),
- hs(-Vec3::Z, Vec3::ZERO),
- hs(Vec3::new(-slope, 0., 1.), Vec3::new(0., 0., 20.)),
- ])
- .unwrap();
- let cutter = cylinder(Vec3::new(20., 15., -5.), Vec3::Z, 5., 40.).unwrap();
- let bored = boolean(&stock, &cutter, BoolOp::Cut).unwrap().unwrap();
- let web = box_solid(Vec3::new(14., 14., 16.05), Vec3::new(26., 16., 16.07)).unwrap();
- let target = boolean(&bored, &web, BoolOp::Union).unwrap().unwrap();
- let region = Region2 { outer: Loop2::circle(Vec2::new(20., 15.), 8.), holes: vec![Loop2::circle(Vec2::new(20., 15.), 5.).reversed()] };
- let ring = extrude(&Plane::XY, &[region], 14., 24.).unwrap().remove(0);
- let web_volume = 0.02 * 2. * (24f64.sqrt() + 25. * 0.2f64.asin());
- let fine_target = target.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap();
- let added = fine_target.measure().volume - bored.mesh(&crate::MeshTolerance::chord(1e-4)).unwrap().measure().volume;
- assert!((added - web_volume).abs() < 0.005, "actual connected web adds {added}, expected {web_volume}");
- for x in [16., 20., 24.] {
- for y in [14.2, 15., 15.8] {
- assert!(fine_target.contains(Vec3::new(x, y, 16.06)), "source web must exist at {x},{y}");
- }
- }
- assert!(!fine_target.contains(Vec3::new(20., 12., 16.06)));
- let floor_volume = (20. + slope * 20.) * (1200. - 25. * std::f64::consts::PI);
- let ring_added = std::f64::consts::PI * (64. - 25.) * (24. - (20. + slope * 20.));
- (target, ring, Vec3::new(20., 15., 16.06), floor_volume + web_volume + ring_added)
-}
-
-#[test]
-fn thin_connected_web_between_bore_stations_survives_union() {
- let (target, ring, probe, expected) = fixture();
- let target_before = step_export(&[&target], "source").unwrap();
- let ring_before = step_export(&[&ring], "ring").unwrap();
- let size = target.size().max(ring.size());
- let tol = (size * 5e-4).max(size * 1e-5);
- let ma = target.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
- let mb = ring.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
- assert!(ma.contains(probe), "fixture must contain the real connected web");
- assert!(!mb.contains(probe));
- let va = ma.measure().volume;
- let vb = mb.measure().volume;
- let slack = 2e-3 * (va + vb) + 1e-9;
- let accept = |body: &Body| {
- let mr = body.mesh(&crate::MeshTolerance::chord(tol)).unwrap();
- let v = mr.measure().volume;
- let mismatch = super::mismatch(&ma, &mb, &mr, BoolOp::Union);
- eprintln!("fallback candidate V={v}, expected={expected}, web={}, mismatch={mismatch:?}", mr.contains(probe));
- v > 0. && v >= va.max(vb) - slack && v <= va + vb + slack && mismatch.is_none_or(|f| f < 0.004)
- };
- let direct = crate::coplanar::bore_union(&target, &ring, &accept);
- eprintln!("direct fallback result={}", direct.is_some());
- let public = boolean(&target, &ring, BoolOp::Union);
- if let Ok(dir) = solidcraft_geom::env::var("BORE_AUDIT_DIR").ok_or(()) {
- let dir = std::path::Path::new(&dir);
- std::fs::create_dir_all(dir).unwrap();
- std::fs::write(dir.join("target-with-web.step"), step_export(&[&target], "target with web").unwrap()).unwrap();
- if let Some(result) = &direct {
- std::fs::write(dir.join("direct-union.step"), step_export(&[result], "direct union").unwrap()).unwrap();
- }
- if let Ok(Some(result)) = &public {
- std::fs::write(dir.join("public-union.step"), step_export(&[result], "public union").unwrap()).unwrap();
- }
- }
- let direct_keeps_web = direct.as_ref().is_none_or(|result| result.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().contains(probe));
- let public_keeps_web = match &public {
- Ok(Some(result)) => {
- let keep = result.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().contains(probe);
- eprintln!("public Union result web={keep}");
- keep
- }
- result => {
- eprintln!("public Union honestly refused: {result:?}");
- true
- }
- };
- assert!(direct_keeps_web, "accepted fallback removed real web material");
- assert!(public_keeps_web, "public Union removed real web material");
- assert_eq!(step_export(&[&target], "source").unwrap(), target_before);
- assert_eq!(step_export(&[&ring], "ring").unwrap(), ring_before);
-}
-
-/// Posts sunk into one floor have their tops in a common plane but apart: they don't
-/// coincide, so joining another post doesn't go through pushing faces apart (#261).
-#[test]
-fn coplanar_faces_apart_from_each_other_do_not_coincide() {
- let floor = box_solid(Vec3::new(0., 0., 0.), Vec3::new(80., 60., 2.)).unwrap();
- let post = |x: f64| cylinder(Vec3::new(x, 30., 1.), Vec3::Z, 3., 6.).unwrap();
- let with_one = boolean(&floor, &post(10.), BoolOp::Union).unwrap().unwrap();
- assert!(crate::coplanar::coincident_planes(&with_one, &post(60.)).is_empty());
- assert!(crate::coplanar::boolean_apart(&with_one, &post(60.), BoolOp::Union).is_none());
- // A post over the first one's top does meet it there.
- assert!(!crate::coplanar::coincident_planes(&with_one, &cylinder(Vec3::new(12., 30., 7.), Vec3::Z, 3., 6.).unwrap()).is_empty());
- let joined = boolean(&with_one, &post(60.), BoolOp::Union).unwrap().unwrap();
- let v = joined.mesh(&crate::MeshTolerance::chord(1e-3)).unwrap().measure().volume;
- let expected = 80. * 60. * 2. + 2. * std::f64::consts::PI * 9. * 5.;
- assert!((v - expected).abs() < 0.5, "volume {v}, expected {expected}");
-}
diff --git a/crates/kernel/src/coaxial_overlap.rs b/crates/kernel/src/coaxial_overlap.rs
deleted file mode 100644
index d619ee1d2f..0000000000
--- a/crates/kernel/src/coaxial_overlap.rs
+++ /dev/null
@@ -1,686 +0,0 @@
-//! 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), 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,
-//! 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`; 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
-//! band is assumed to hold nothing but the two walls; that is checked by intersecting with the
-//! pin widened by half the step and by the whole step, whose volumes must come out as the core
-//! plus the crescents those wider circles give. Where they don't (a cross hole through the
-//! band, a hole that is not round all the way, a pin end inside the hole), the overlap is not
-//! answered here and the caller takes the general boolean.
-
-use solidcraft_geom::{Aabb3, UnitVec3, Vec3};
-
-use crate::body::Body;
-use crate::{BoolOp, FaceSurface};
-
-/// The overlap of two bodies with a pin of one in a hole of the other, worked out as above.
-#[derive(Clone, Debug)]
-pub struct CoaxialOverlap {
- pub volume: f64,
- /// Approximate: the core's area plus the crescents' walls and ends.
- pub area: f64,
- pub centroid: Vec3,
- pub bbox: Aabb3,
- /// The largest offset between a pin's axis and its hole's, and the length they share.
- pub offset: f64,
- pub length: f64,
-}
-
-/// Largest axis offset plus radius difference handled, as a share of the radius.
-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.
-#[derive(Clone, Debug)]
-struct Wall {
- faces: Vec<usize>,
- origin: Vec3,
- axis: UnitVec3,
- radius: f64,
- /// Material inside the cylinder (a pin), not outside it (a hole).
- boss: bool,
- /// Intervals along `axis` from `origin`, one per face.
- spans: Vec<(f64, f64)>,
-}
-
-/// A pin of one body (`pin_in_a`) in a hole of the other, and the length they share.
-#[derive(Clone, Debug)]
-struct Pair {
- pin: Wall,
- pin_in_a: bool,
- hole: Wall,
- /// The hole's axis seen from the pin's, across it, and how far.
- toward: Vec3,
- offset: f64,
- /// Where they share length along the pin's axis.
- shared: Vec<(f64, f64)>,
- step: f64,
-}
-
-/// 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, 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> {
- if a.is_mesh() || b.is_mesh() {
- return None;
- }
- // The boolean that takes the core can fail in one order of the bodies and not the other.
- 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 = 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).is_some();
- if !ca.iter().any(|x| cb.iter().any(|y| close(x, y))) {
- return None;
- }
- // A wall that runs once round along a seam edge (as STEP files have them) is cut in two
- // first: the boolean cannot always intersect it whole.
- let (sa, sb) = (crate::step_in::split::split_seams(a), crate::step_in::split::split_seams(b));
- let (ca, cb) = match (&sa, &sb) {
- (None, None) => (ca, cb),
- _ => (sa.as_ref().map_or(ca, cylinders), sb.as_ref().map_or(cb, cylinders)),
- };
- let (a, b) = (sa.as_ref().unwrap_or(a), sb.as_ref().unwrap_or(b));
- let (wa, wb) = (walls(a, ca, same)?, walls(b, cb, same)?);
- let mut pairs = Vec::new();
- for x in &wa {
- for y in &wb {
- if x.axis.dot(y.axis).abs() <= 1.0 - 1e-9 {
- continue;
- }
- let (pin, hole, pin_in_a) = match (x.boss, y.boss) {
- (true, false) => (x, y, true),
- (false, true) => (y, x, false),
- // 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).is_some() && total(&intersect(&union(&x.spans), &union(&project(y, x)))) > same => return None,
- _ => 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);
- // 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() {
- return None;
- }
- // A pin's face flush against the other body (a rivet's head on the sheet) touches it over
- // 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 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<(&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(|(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().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::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 };
- if report.unverified().is_some() || !altered_by_at_most(&report, nudge, size) {
- return None;
- }
- match r.ok()? {
- None => Some((0.0, None)),
- Some(body) => Some((crate::measure(&body).ok()?.volume, Some(body))),
- }
- };
- // 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.002 * gain + 1e-4 * v.abs() + 1e-12 * size.powi(3)) {
- return None;
- }
- }
- // The band held the two walls only: the overlap is the core plus the crescents.
- let mut volume = core;
- let mut moment = Vec3::ZERO;
- let mut area = 0.0;
- let mut bbox = Aabb3::EMPTY;
- if let Some(body) = &core_body
- && let Ok(m) = crate::measure(body)
- {
- moment = m.centroid * m.volume;
- area = m.area;
- bbox = m.bbox;
- volume = m.volume;
- }
- for p in pairs {
- let c = crescent(p.pin.radius, p.hole.radius, p.offset);
- let length = total(&p.shared);
- // 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;
- volume += v;
- area += p.shared.len() as f64 * 2.0 * c.area + length * c.perimeter;
- for (s, t) in &p.shared {
- for q in crescent_outline(p.pin.radius, p.hole.radius, p.offset) {
- let at = p.pin.origin + p.toward * q.0 + side * q.1;
- bbox.add(at + p.pin.axis * *s);
- bbox.add(at + p.pin.axis * *t);
- }
- }
- }
- let centroid = if volume > 0.0 { moment / volume } else { bbox.center() };
- let offset = pairs.iter().map(|p| p.offset).fold(0.0, f64::max);
- let length = pairs.iter().map(|p| total(&p.shared)).sum();
- Some(CoaxialOverlap { volume: volume.max(0.0), area, centroid, bbox, offset, length })
-}
-
-/// Whether every retry of a boolean that can change its result moved the tool by at most
-/// `limit` (a rotation counted at the bodies' `size` from its pivot): none for a `limit` of 0.
-fn altered_by_at_most(report: &crate::BooleanDiagnostics, limit: f64, size: f64) -> bool {
- !report.truncated
- && report
- .events
- .iter()
- .filter(|e| e.strategy.alters_result())
- .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 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 + gap <= NEAR * pin.radius.min(hole.radius)) {
- return None;
- }
- let toward = across.normalized().unwrap_or_else(|| pin.axis.any_perp());
- Some((toward, offset))
-}
-
-/// The planar faces of `x` that lie on a face of `y`'s facing the other way, where the two touch
-/// flat: on a plane of `y`'s, with `y` just beyond the face and not just behind it (within
-/// `depth`, at every sampled facet of it). A face on such a plane elsewhere (a collar's
-/// underside inside the other body, level with a pocket's floor) is not one.
-fn flush(x: &Body, y: &Body, same: f64, depth: f64) -> Vec<usize> {
- let planes = |b: &Body| -> Vec<(usize, Vec3, Vec3)> {
- (0..b.face_count())
- .filter_map(|i| match crate::face_surface(b, i)? {
- FaceSurface::Plane { normal, point } => Some((i, normal.vec(), point)),
- _ => None,
- })
- .collect()
- };
- let theirs = planes(y);
- let level: Vec<(usize, Vec3)> = planes(x)
- .into_iter()
- .filter(|(_, n, p)| theirs.iter().any(|(_, m, q)| n.dot(*m) < -1.0 + 1e-9 && (*q - *p).dot(*n).abs() <= same))
- .map(|(i, n, _)| (i, n))
- .collect();
- if level.is_empty() || !(depth.is_finite() && depth > 0.0) {
- return Vec::new();
- }
- let tol = (x.size().max(y.size()) * 2e-3).max(1e-4);
- let (Ok(mx), Ok(my)) = (x.mesh(&crate::MeshTolerance::chord(tol)), y.mesh(&crate::MeshTolerance::chord(tol))) else { return Vec::new() };
- // At most this many facets of a face are sampled.
- const SAMPLES: usize = 64;
- level
- .into_iter()
- .filter(|&(i, n)| {
- let centres: Vec<Vec3> = mx
- .triangles
- .iter()
- .zip(&mx.tri_face)
- .filter(|(_, f)| **f as usize == i)
- .filter_map(|(t, _)| mx.tri(t))
- .filter(|[a, b, c]| (*b - *a).cross(*c - *a).len() > 0.0)
- .map(|[a, b, c]| (a + b + c) / 3.0)
- .collect();
- let stride = centres.len().div_ceil(SAMPLES).max(1);
- !centres.is_empty() && centres.iter().step_by(stride).all(|c| my.contains(*c + n * depth) && !my.contains(*c - n * depth))
- })
- .map(|(i, _)| i)
- .collect()
-}
-
-/// The body's cylindrical faces, each as a wall of its own with no side or extent yet.
-fn cylinders(b: &Body) -> Vec<Wall> {
- (0..b.face_count())
- .filter_map(|i| match crate::face_surface(b, i)? {
- FaceSurface::Cylinder { origin, axis, radius } if origin.is_finite() && radius.is_finite() && radius > 0.0 => {
- Some(Wall { faces: vec![i], origin, axis, radius, boss: false, spans: Vec::new() })
- }
- _ => None,
- })
- .collect()
-}
-
-/// The cylindrical walls of a body from its `cylinders`: its faces on each cylinder, which side
-/// its material is on and where they run along the axis. `None` when the body can't be meshed.
-fn walls(b: &Body, cylinders: Vec<Wall>, same: f64) -> Option<Vec<Wall>> {
- let mut out: Vec<Wall> = Vec::new();
- let mesh = b.mesh(&crate::MeshTolerance::chord((b.size() * 1e-3).max(1e-4))).ok()?;
- for Wall { faces, origin, axis, radius, .. } in cylinders {
- let Some(&face) = faces.first() else { continue };
- // Which way the face looks: out of the axis for a pin, toward it for a hole.
- let (mut facing, mut lo, mut hi) = (0.0, f64::INFINITY, f64::NEG_INFINITY);
- for (t, f) in mesh.triangles.iter().zip(&mesh.tri_face) {
- if *f as usize != face {
- continue;
- }
- let Some([p, q, r]) = mesh.tri(t) else { continue };
- let c = (p + q + r) / 3.0;
- let radial = (c - origin) - axis * (c - origin).dot(axis);
- facing += (q - p).cross(r - p).dot(radial);
- for x in [p, q, r] {
- let s = (x - origin).dot(axis);
- lo = lo.min(s);
- hi = hi.max(s);
- }
- }
- if !(lo < hi) || facing == 0.0 {
- continue;
- }
- let boss = facing > 0.0;
- let wall = Wall { faces: vec![face], origin, axis, radius, boss, spans: vec![(lo, hi)] };
- match out.iter_mut().find(|w| w.boss == boss && on_one_cylinder(w, &wall, same)) {
- Some(w) => {
- // Where the face's origin lies along the wall's axis; a face whose axis runs the
- // other way measures its span backwards from there.
- let s = (origin - w.origin).dot(w.axis);
- let (a, b) = if axis.dot(w.axis) < 0.0 { (-hi, -lo) } else { (lo, hi) };
- w.faces.push(face);
- w.spans.push((a + s, b + s));
- }
- None => out.push(wall),
- }
- }
- Some(out)
-}
-
-fn on_one_cylinder(x: &Wall, y: &Wall, same: f64) -> bool {
- let d = y.origin - x.origin;
- x.axis.dot(y.axis).abs() > 1.0 - 1e-9 && (x.radius - y.radius).abs() < same && (d - x.axis * d.dot(x.axis)).len() < same
-}
-
-/// `wall`'s spans along `onto`'s axis.
-fn project(wall: &Wall, onto: &Wall) -> Vec<(f64, f64)> {
- let flip = wall.axis.dot(onto.axis) < 0.0;
- let s = (wall.origin - onto.origin).dot(onto.axis);
- wall.spans.iter().map(|&(lo, hi)| if flip { (s - hi, s - lo) } else { (s + lo, s + hi) }).collect()
-}
-
-/// Sorted, disjoint intervals covering `spans`.
-fn union(spans: &[(f64, f64)]) -> Vec<(f64, f64)> {
- let mut v: Vec<(f64, f64)> = spans.iter().copied().filter(|(a, b)| a < b).collect();
- v.sort_by(|x, y| x.0.total_cmp(&y.0));
- let mut out: Vec<(f64, f64)> = Vec::with_capacity(v.len());
- for (a, b) in v {
- match out.last_mut() {
- Some(last) if a <= last.1 => last.1 = last.1.max(b),
- _ => out.push((a, b)),
- }
- }
- out
-}
-
-fn intersect(x: &[(f64, f64)], y: &[(f64, f64)]) -> Vec<(f64, f64)> {
- let mut out = Vec::new();
- for &(a, b) in x {
- for &(c, d) in y {
- let (lo, hi) = (a.max(c), b.min(d));
- if lo < hi {
- out.push((lo, hi));
- }
- }
- }
- out
-}
-
-fn total(spans: &[(f64, f64)]) -> f64 {
- spans.iter().map(|(a, b)| b - a).sum()
-}
-
-/// The part of a disc of radius `pin` outside a disc of radius `hole` whose centre is `offset`
-/// away along +x: its area, its centroid's x (y is 0) and its perimeter.
-#[derive(Clone, Copy, Debug, PartialEq)]
-pub(crate) struct Crescent {
- pub(crate) area: f64,
- pub(crate) centroid: f64,
- pub(crate) perimeter: f64,
-}
-
-pub(crate) fn crescent(pin: f64, hole: f64, offset: f64) -> Crescent {
- use std::f64::consts::PI;
- let (r, q, e) = (pin.max(0.0), hole.max(0.0), offset.abs());
- let disc = PI * r * r;
- if e >= r + q {
- return Crescent { area: disc, centroid: 0.0, perimeter: 2.0 * PI * r };
- }
- if e <= (r - q).abs() {
- return if q >= r {
- Crescent { area: 0.0, centroid: 0.0, perimeter: 0.0 }
- } else {
- let area = disc - PI * q * q;
- Crescent { area, centroid: -PI * q * q * e / area, perimeter: 2.0 * PI * (r + q) }
- };
- }
- // Half-angles of the lens's two segments, seen from each centre.
- let alpha = ((e * e + r * r - q * q) / (2.0 * e * r)).clamp(-1.0, 1.0).acos();
- let beta = ((e * e + q * q - r * r) / (2.0 * e * q)).clamp(-1.0, 1.0).acos();
- let segment = |radius: f64, half: f64| {
- let area = radius * radius * (half - half.sin() * half.cos());
- let w = 2.0 * half - (2.0 * half).sin();
- let from_centre = if w > 1e-12 { 4.0 * radius * half.sin().powi(3) / (3.0 * w) } else { radius };
- (area, from_centre)
- };
- let (sa, da) = segment(r, alpha);
- let (sb, db) = segment(q, beta);
- let lens = sa + sb;
- let area = (disc - lens).max(0.0);
- let moment = -(sa * da + sb * (e - db));
- let centroid = if area > 0.0 { moment / area } else { 0.0 };
- Crescent { area, centroid, perimeter: r * (2.0 * PI - 2.0 * alpha) + q * 2.0 * beta }
-}
-
-/// Points around the crescent's outline (x toward the hole's centre, y across), for its box.
-fn crescent_outline(pin: f64, hole: f64, offset: f64) -> Vec<(f64, f64)> {
- let (r, q, e) = (pin, hole, offset);
- let alpha = if e > 0.0 { ((e * e + r * r - q * q) / (2.0 * e * r)).clamp(-1.0, 1.0).acos() } else { 0.0 };
- let n = 32;
- (0..=n)
- .map(|i| {
- let t = alpha + (2.0 * std::f64::consts::PI - 2.0 * alpha) * f64::from(i) / f64::from(n);
- (r * t.cos(), r * t.sin())
- })
- .collect()
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- /// The crescent against the textbook lens of two equal circles, and its limits.
- #[test]
- fn crescent_matches_the_lens_formula() {
- let (r, e) = (3.0f64, 0.01f64);
- let lens = 2.0 * r * r * (e / (2.0 * r)).acos() - e / 2.0 * (4.0 * r * r - e * e).sqrt();
- let c = crescent(r, r, e);
- assert!((c.area - (std::f64::consts::PI * r * r - lens)).abs() < 1e-12, "{c:?}");
- // Thin: twice the radius times the offset, its centroid π/4 of the radius away from
- // the hole's centre, its outline nearly two half circles.
- assert!((c.area - 2.0 * r * e).abs() < 1e-6, "{c:?}");
- assert!((c.centroid + std::f64::consts::FRAC_PI_4 * r).abs() < 1e-2, "{c:?}");
- assert!((c.perimeter - 2.0 * std::f64::consts::PI * r).abs() < 1e-3, "{c:?}");
- assert_eq!(crescent(r, r, 0.0).area, 0.0);
- // A pin with clearance in its hole shares nothing; a pin wider than its hole a ring.
- assert_eq!(crescent(2.99, 3.0, 0.005).area, 0.0);
- let ring = crescent(3.01, 3.0, 0.0);
- assert!((ring.area - std::f64::consts::PI * (3.01f64.powi(2) - 9.0)).abs() < 1e-12, "{ring:?}");
- }
-
- /// A 20 x 20 x 5 plate with a hole of radius 3 through it, and a pin of radius `pin` through
- /// the hole, `offset` off its axis along X.
- fn plate_and_pin(pin: f64, offset: f64) -> (Body, Body) {
- let block = crate::box_solid(Vec3::new(-10.0, -10.0, 0.0), Vec3::new(10.0, 10.0, 5.0)).unwrap();
- let drill = crate::cylinder(Vec3::new(0.0, 0.0, -2.0), Vec3::Z, 3.0, 9.0).unwrap();
- let plate = crate::boolean(&block, &drill, BoolOp::Cut).unwrap().unwrap();
- (plate, crate::cylinder(Vec3::new(offset, 0.0, -2.0), Vec3::Z, pin, 9.0).unwrap())
- }
-
- /// The pin shares a crescent with the plate over the plate's thickness, in either order.
- #[test]
- fn a_pin_off_its_hole_shares_a_crescent() {
- let (plate, pin) = plate_and_pin(3.0, 0.01);
- let want = 5.0 * crescent(3.0, 3.0, 0.01).area;
- for (x, y) in [(&plate, &pin), (&pin, &plate)] {
- let o = coaxial_overlap(x, y).unwrap();
- assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}");
- assert!((o.offset - 0.01).abs() < 1e-9 && (o.length - 5.0).abs() < 1e-9, "{o:?}");
- // The crescent is on the pin's side away from the hole's axis (+X).
- assert!(o.centroid.x > 2.0 && o.bbox.min.z > -1e-9 && o.bbox.max.z < 5.0 + 1e-9, "{o:?}");
- }
- }
-
- /// A pin with clearance all round, though off the axis, shares nothing.
- #[test]
- fn a_pin_with_clearance_shares_nothing() {
- let (plate, pin) = plate_and_pin(2.995, 0.003);
- let o = coaxial_overlap(&plate, &pin).unwrap();
- assert!(o.volume < 1e-9, "{o:?}");
- }
-
- /// A slot through the hole's wall where the crescent would be: the band holds more than the
- /// two walls, the widened pin says so, and the pair is left to the boolean.
- #[test]
- fn a_slot_through_the_band_is_left_to_the_boolean() {
- let (plate, pin) = plate_and_pin(3.0, 0.01);
- 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());
- // 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. The
- /// walls are cut in two first and the answer is the one of the bodies as built.
- #[test]
- fn a_screw_in_a_bush_after_a_step_round_trip() {
- let e = 0.01;
- let outer = crate::cylinder(Vec3::ZERO, Vec3::Z, 5.0, 10.0).unwrap();
- let bore = crate::cylinder(Vec3::new(0.0, 0.0, -1.0), Vec3::Z, 3.0, 12.0).unwrap();
- let bush = crate::boolean(&outer, &bore, BoolOp::Cut).unwrap().unwrap();
- let shank = crate::cylinder(Vec3::new(e, 0.0, -2.0), Vec3::Z, 3.0, 8.0).unwrap();
- let head = crate::cylinder(Vec3::new(e, 0.0, -5.0), Vec3::Z, 5.25, 3.0).unwrap();
- let screw = crate::boolean(&shank, &head, BoolOp::Union).unwrap().unwrap();
- let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body;
- let (bush, screw) = (back(&bush), back(&screw));
- // The shank shares a crescent with the bush over the 6 mm it reaches into the bore.
- let want = 6.0 * crescent(3.0, 3.0, e).area;
- for (x, y) in [(&bush, &screw), (&screw, &bush)] {
- let o = coaxial_overlap(x, y).unwrap();
- assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}");
- assert!((o.length - 6.0).abs() < 1e-6, "{o:?}");
- }
- // Cut in two, each wall is a face more and the body keeps its volume.
- let split = crate::step_in::split::split_seams(&bush).unwrap();
- assert_eq!(split.face_count(), bush.face_count() + 2);
- let (v0, v1) = (crate::measure(&bush).unwrap().volume, crate::measure(&split).unwrap().volume);
- assert!((v0 - v1).abs() < 1e-6 * v0, "{v0} {v1}");
- assert!(crate::step_in::split::split_seams(&outer).is_none());
- }
-
- /// A pin with a Ø7 collar embedded in a block (the collar's underside at z = 0, inside the
- /// block's material), a hair off its hole, and a pocket elsewhere in the block whose floor
- /// is at z = 0 too, facing the collar's underside: the two are level but don't touch, so the
- /// collar is not pulled back, and all of it inside the block counts.
- #[test]
- fn a_collar_level_with_a_pocket_floor_elsewhere_is_not_pulled_back() {
- let e = 0.01;
- let mut block = crate::box_solid(Vec3::new(-10.0, -10.0, -5.0), Vec3::new(20.0, 10.0, 3.0)).unwrap();
- let hole = crate::cylinder(Vec3::new(0.0, 0.0, -6.0), Vec3::Z, 2.0, 10.0).unwrap();
- let pocket = crate::box_solid(Vec3::new(10.0, -3.0, 0.0), Vec3::new(14.0, 3.0, 4.0)).unwrap();
- for cut in [&hole, &pocket] {
- block = crate::boolean(&block, cut, BoolOp::Cut).unwrap().unwrap();
- }
- let shank = crate::cylinder(Vec3::new(e, 0.0, -7.0), Vec3::Z, 2.0, 8.0).unwrap();
- let collar = crate::cylinder(Vec3::new(e, 0.0, 0.0), Vec3::Z, 3.5, 1.0).unwrap();
- let pin = crate::boolean(&shank, &collar, BoolOp::Union).unwrap().unwrap();
- // The collar less the hole, plus the shank's crescent over the 5 mm below the collar.
- let want = std::f64::consts::PI * (3.5 * 3.5 - 2.0 * 2.0) + 5.0 * crescent(2.0, 2.0, e).area;
- for (x, y) in [(&block, &pin), (&pin, &block)] {
- let o = coaxial_overlap(x, y).unwrap();
- assert!((o.volume - want).abs() < 1e-4 * want, "{o:?} {want}");
- }
- }
-
- /// Two rivets with their heads flush on both faces of a sheet, each a hair off its hole,
- /// read back from STEP: the heads touch the sheet flat, which the boolean cannot always
- /// take, so they are pulled back off it first. Each rivet shares its own crescent.
- #[test]
- fn two_rivets_flush_on_a_sheet_after_a_step_round_trip() {
- let rivet = |x: f64| {
- let shank = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 3.5).unwrap();
- let under = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 3.5, 1.0).unwrap();
- let over = crate::cylinder(Vec3::new(x, 0.0, 1.5), Vec3::Z, 3.5, 1.0).unwrap();
- let r = crate::boolean(&shank, &under, BoolOp::Union).unwrap().unwrap();
- crate::boolean(&r, &over, BoolOp::Union).unwrap().unwrap()
- };
- let mut sheet = crate::box_solid(Vec3::new(-20.0, -10.0, 0.0), Vec3::new(20.0, 10.0, 1.5)).unwrap();
- for x in [-4.0, 4.0] {
- let drill = crate::cylinder(Vec3::new(x, 0.0, -1.0), Vec3::Z, 2.0, 4.0).unwrap();
- sheet = crate::boolean(&sheet, &drill, BoolOp::Cut).unwrap().unwrap();
- }
- let back = |b: &Body| crate::step_import(&crate::step_export(&[b], "round trip").unwrap()).unwrap().bodies.remove(0).body;
- let sheet = back(&sheet);
- for (x, e) in [(-4.0, 0.004), (4.0, 0.006)] {
- let r = back(&rivet(x + e));
- let want = 1.5 * crescent(2.0, 2.0, e).area;
- for (p, q) in [(&sheet, &r), (&r, &sheet)] {
- let o = coaxial_overlap(p, q).unwrap();
- assert!((o.volume - want).abs() < 1e-6 * want, "{o:?} {want}");
- }
- }
- }
-}
diff --git a/crates/kernel/src/empty_retry_tests.rs b/crates/kernel/src/empty_retry_tests.rs
deleted file mode 100644
index 318bbe87a8..0000000000
--- a/crates/kernel/src/empty_retry_tests.rs
+++ /dev/null
@@ -1,83 +0,0 @@
-//! 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/lib.rs b/crates/kernel/src/lib.rs
index 9b05d8fc1d..fa4e07eee5 100644
--- a/crates/kernel/src/lib.rs
+++ b/crates/kernel/src/lib.rs
@@ -22,8 +22,6 @@ mod blend_variable;
#[cfg(test)]
mod blend_wrong_way_tests;
mod body;
-mod boolean_diagnostics;
-mod boolean_guard;
mod boolean_record;
mod boundary;
mod boundary_network;
@@ -32,7 +30,6 @@ mod build;
#[cfg(test)]
mod chamfer_sides_curved_tests;
mod clearance;
-mod coaxial_overlap;
mod continuity;
mod coplanar;
mod corner_g2;
@@ -163,7 +160,6 @@ pub use blend::{ChamferSide, chamfer, chamfer_sides, fillet, fillet_each, fillet
pub use blend_corner::fillet_radii;
pub use blend_variable::{RadiusSpline, Taper, fillet_chord, fillet_tapered, fillet_variable, fillet_variable_points, fillet_variable_spline, taper};
pub use body::{Body, CapSignature, DISPLAY_ANGLE, DisplayShare, EdgeInfo, FaceInfo, FacePaint, FaceSource, MeshTolerance, Paint};
-pub use boolean_diagnostics::{BooleanDiagnostics, BooleanFallback, BooleanStrategy, capture_boolean_diagnostics};
pub use boundary::{Boundary, boundary_patch};
pub use boundary_network::{BoundaryCurve, CurveSource, MAX_CHAIN_CURVES, MAX_EDGE_PICKS, boundary_join, boundary_surface};
pub use bridge::{Continuity, Frame, blend_between, bridge, chain, chain_closes, frames, frames_across, sample_grid};
@@ -172,7 +168,6 @@ pub use build::{
loft_with_rails, path_polyline, planar_face_record, revolve, revolve_whole, sphere, sweep, sweep_with, torus,
};
pub use clearance::{Clearance, Occupancy};
-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,
};
@@ -200,7 +195,7 @@ pub use native::{brep_record, decode_native_body, encode_native_body, native_pre
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,
- place_matrix, split_by_plane, transform, transform_matrix, union_apart, with_attempt_budget,
+ place_matrix, split_by_plane, transform, transform_matrix, union_apart,
};
pub use point_path::{PathPiece, PointPath, SpaceBezier, curve_path, edge_path, sketch_record_curve, sweep_point_path_with};
pub use polybool::faceted_boolean;
diff --git a/crates/kernel/src/ops.rs b/crates/kernel/src/ops.rs
index 12d7f12c9c..8d1863a96b 100644
--- a/crates/kernel/src/ops.rs
+++ b/crates/kernel/src/ops.rs
@@ -1,23 +1,13 @@
-//! Operations on bodies: booleans and rigid transforms.
+//! Operations on bodies: booleans, placements and splits by a plane, through SMLib. Bodies apart
+//! from each other join without any intersection work, their records side by side.
use serde::{Deserialize, Serialize};
use solidcraft_geom::Vec3;
-use truck_modeling as mt;
+use solidcraft_geom::brep::{Surface, part, placement::Rigid};
-use std::collections::HashMap;
-
-use crate::body::{Body, Solid, from_p3};
-use crate::boolean_diagnostics::{BooleanFallback, BooleanStrategy, capture_boolean_diagnostics, merge, record, reject};
-use crate::boolean_record::{self as recorded, Traced};
-use crate::history::BodyHistory;
-use crate::{KernelError, Result, guard, record};
-
-#[cfg(test)]
-#[path = "bore_union_tests.rs"]
-mod bore_union_tests;
-
-#[path = "tool_reseam.rs"]
-mod tool_reseam;
+use crate::body::Body;
+use crate::history::{BodyHistory, History};
+use crate::{KernelError, Result, guard};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
@@ -27,917 +17,40 @@ pub enum BoolOp {
Intersect,
}
-/// Exact planar Booleans need no sampled enlargement of their tool footprint.
+/// Whether every face of the body is planar.
pub fn is_planar(body: &Body) -> bool {
- if body.is_mesh() || body.face_count() > 16_384 {
- return false;
- }
- guard("planar body", || Ok(body.solid.face_iter().all(|face| matches!(face.oriented_surface(), mt::Surface::Plane(_))))).unwrap_or(false)
+ !body.is_mesh() && body.record().faces.iter().all(|f| matches!(f.surface, Surface::Plane { .. } | Surface::PlaneThrough { .. }))
}
-/// Batch separated extrusion tools without repeatedly unioning an ever-growing target.
-/// Construction caps provide conservative bounds, including the full circle of each arc;
-/// unsupported or touching tools retain the caller's sequential Boolean path.
+/// Extrusion tools apart from each other as one body, so a target takes them in one boolean;
+/// `None` when fewer than two are given or any two are not apart ([`union_apart`]).
pub fn compound_disjoint_extrusions(tools: &[Body]) -> Result<Option<Body>> {
- if tools.len() < 2 || tools.len() > 1024 {
- return Ok(None);
- }
- guard("compound extrusion tools", || {
- let mut bounds = Vec::with_capacity(tools.len());
- let mut corners = Vec::with_capacity(tools.len());
- let mut axes = Vec::with_capacity(tools.len());
- let mut remaining = 16_384usize;
- for tool in tools {
- let Some(sources) = tool.face_sources() else { return Ok(None) };
- if sources.len() != tool.face_count() {
- return Ok(None);
- }
- let mut bb = solidcraft_geom::Aabb3::EMPTY;
- let mut points = Some(Vec::new());
- let mut directions = Vec::new();
- let mut caps = 0;
- for source in sources {
- let Some(left) = remaining.checked_sub(1) else { return Ok(None) };
- remaining = left;
- match source {
- Some(crate::FaceSource::ExtrudeCap { region, plane, high }) => {
- caps += 1;
- // The bottom support is outward-facing, but its region retains
- // the original sketch coordinates (see build::extrude).
- let plane = if *high { *plane } else { solidcraft_geom::Plane { y: -plane.y, ..*plane } };
- for segment in &region.outer.segs {
- let Some(left) = remaining.checked_sub(1) else { return Ok(None) };
- remaining = left;
- match *segment {
- solidcraft_geom::Seg2::Line { a, b } => {
- let (a, b) = (plane.to_world(a), plane.to_world(b));
- bb.add(a);
- bb.add(b);
- if let Some(points) = points.as_mut() {
- points.extend([a, b]);
- }
- if let Some(axis) = (b - a).cross(plane.normal()).normalized() {
- directions.push(axis);
- }
- }
- solidcraft_geom::Seg2::Arc { center, radius, .. } => {
- points = None;
- for x in [-radius, radius] {
- for y in [-radius, radius] {
- bb.add(plane.to_world(center + solidcraft_geom::Vec2::new(x, y)));
- }
- }
- }
- _ => return Ok(None),
- }
- }
- }
- Some(crate::FaceSource::ExtrudeSide { .. }) => {}
- _ => return Ok(None),
- }
- }
- if caps != 2 || bb.is_empty() || !bb.min.is_finite() || !bb.max.is_finite() {
- return Ok(None);
- }
- bounds.push(bb);
- corners.push(points);
- axes.push(directions);
- }
- let mut remaining_separation_work = 16_000_000usize;
- for (i, a) in bounds.iter().enumerate() {
- for (j, b) in bounds.iter().enumerate().skip(i + 1) {
- let gap = (a.diagonal().max(b.diagonal()) * 1e-6).max(1e-7);
- let separated = a.max.x + gap < b.min.x
- || b.max.x + gap < a.min.x
- || a.max.y + gap < b.min.y
- || b.max.y + gap < a.min.y
- || a.max.z + gap < b.min.z
- || b.max.z + gap < a.min.z;
- if separated {
- continue;
- }
- let (Some(Some(x)), Some(Some(y))) = (corners.get(i), corners.get(j)) else { return Ok(None) };
- let Some(origin) = x.first() else { return Ok(None) };
- // Every straight extrusion lies inside the hull of its cap corners.
- // A separating cap-edge axis therefore proves clearance even when
- // rotated tools' world-coordinate boxes overlap. Arcs retain the box test.
- let range = |points: &[Vec3], axis: Vec3| {
- points.iter().map(|p| (*p - *origin).dot(axis)).fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), v| (lo.min(v), hi.max(v)))
- };
- let rounding = origin.x.abs().max(origin.y.abs()).max(origin.z.abs()) * f64::EPSILON * 128.0;
- let separated = axes.get(i).into_iter().flatten().chain(axes.get(j).into_iter().flatten()).any(|axis| {
- let Some(left) = remaining_separation_work.checked_sub(x.len().saturating_add(y.len())) else { return false };
- remaining_separation_work = left;
- let (a, b) = (range(x, *axis), range(y, *axis));
- a.1 + gap + rounding < b.0 || b.1 + gap + rounding < a.0
- });
- if !separated {
- return Ok(None);
- }
- }
- }
- let sources: std::collections::HashMap<_, _> = tools
- .iter()
- .flat_map(|tool| {
- tool.solid
- .face_iter()
- .zip(tool.face_sources().unwrap_or_default())
- .map(|(face, source)| (face.id(), (face.orientation(), source.clone())))
- })
- .collect();
- let operands: Vec<_> = tools.iter().collect();
- let shells = tools.iter().flat_map(|tool| tool.solid.boundaries().clone()).collect();
- let solid = Solid::try_new(shells).map_err(|error| KernelError::Failed(format!("extrusion compound: {error}")))?;
- let faces = tools
- .iter()
- .enumerate()
- .flat_map(|(operand, tool)| (0..tool.face_count()).map(move |face| record::from_face(operand, face, crate::history::Change::Kept)))
- .collect();
- let mut edges = HashMap::new();
- for (operand, tool) in tools.iter().enumerate() {
- edges.extend(record::edge_origins(&tool.solid, operand));
- }
- record::build(solid, &record::counts(&operands), Some(faces), Some(&edges)).map(|mut body| {
- body.regularization_protected = tools.iter().any(|tool| tool.regularization_protected);
- // Only unchanged face identities carry these transient tool witnesses.
- // No whole-compound extrusion/producer certificate is created.
- let mapped = body
- .solid
- .face_iter()
- .map(|face| {
- sources.get(&face.id()).filter(|(orientation, _)| *orientation == face.orientation()).and_then(|(_, source)| source.clone())
- })
- .collect();
- Some(body.with_face_sources(Some(std::sync::Arc::new(mapped))))
- })
- })
+ union_apart(tools)
}
-/// Whether a union can sew two matching planar faces without intersecting them.
-/// Callers can retain the exact touching tool instead of extending it into material.
+/// Whether a union keeps `b` as it is where it touches `a` face to face: SMLib's boolean takes
+/// touching faces exactly, so any two solid bodies.
pub fn can_join_touching_faces(a: &Body, b: &Body) -> bool {
- a.solid.boundaries().len() == 1 && b.solid.boundaries().len() == 1 && crate::coplanar::glue(a, b).is_some_and(|r| r.is_ok())
+ !a.is_mesh() && !b.is_mesh()
}
-/// Check all separated extrusion starts in one construction, without rebuilding
-/// the unchanged target once for each face. Partial seams keep the ordinary path.
+/// [`can_join_touching_faces`] for a compound of several tools.
pub fn can_join_all_touching_faces(a: &Body, b: &Body) -> bool {
- if a.solid.boundaries().len() != 1 || !(2..=1024).contains(&b.solid.boundaries().len()) || a.face_count().max(b.face_count()) > 16_384 {
- return false;
- }
- guard("check extrusion seams", || Ok(crate::coplanar::glue_all_caps(a, b).is_some_and(|result| result.is_ok()))).unwrap_or(false)
-}
-
-/// Shifts applied to both operands on retries. The boolean classifies some faces by casting a
-/// ray whose direction is derived from point coordinates; moving both solids (and the result
-/// back) leaves the geometry unchanged but changes those rays.
-const JITTER: [[f64; 3]; 4] = [[0.0, 0.0, 0.0], [0.1373, 0.2719, 0.3911], [-0.5127, 0.0833, 0.2291], [0.6911, -0.3337, -0.6127]];
-
-fn volume(b: &Body) -> f64 {
- // Measured once per (solid, tolerance) and shared by clones, so an operand a later
- // boolean takes again is not meshed twice for the same number.
- b.volume_at(b.size() * 2e-3).unwrap_or(f64::NAN)
-}
-
-/// Halton low-discrepancy value (base `b`) for index `i`.
-fn halton(mut i: usize, b: usize) -> f64 {
- let (mut f, mut r) = (1.0, 0.0);
- while i > 0 {
- f /= b as f64;
- r += f * (i % b) as f64;
- i /= b;
- }
- r
-}
-
-/// Fraction of sample points where `result` disagrees with `op` applied to `a` and `b`
-/// (membership by ray parity). Samples cover the overlap box densely and the union box lightly.
-fn mismatch(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh, result: &solidcraft_geom::Mesh, op: BoolOp) -> Option<f64> {
- if a.triangles.len() + b.triangles.len() + result.triangles.len() > 60_000 {
- return None;
- }
- let (ba, bb) = (a.bounds(), b.bounds());
- let lo = ba.min.max(bb.min);
- let hi = ba.max.min(bb.max);
- let all = ba.union(&bb);
- let mut boxes = vec![(all, 300usize)];
- // A touching seam can overlap by round-off only. Samples there sit on the
- // operands' boundaries, where ray parity cannot classify membership reliably.
- let gap = all.diagonal().max(1.0) * 1e-9;
- if hi.x - lo.x > gap && hi.y - lo.y > gap && hi.z - lo.z > gap {
- boxes.push((solidcraft_geom::Aabb3 { min: lo, max: hi }, 900));
- }
- let (ia_idx, ib_idx, ir_idx) = (a.inside_index(), b.inside_index(), result.inside_index());
- let (mut n, mut bad) = (0usize, 0usize);
- for (bx, count) in boxes {
- let s = bx.size();
- for i in 1..=count {
- let p = bx.min + Vec3::new(s.x * halton(i, 2), s.y * halton(i, 3), s.z * halton(i, 5));
- let (ia, ib) = (ia_idx.contains(p), ib_idx.contains(p));
- let want = match op {
- BoolOp::Union => ia || ib,
- BoolOp::Cut => ia && !ib,
- BoolOp::Intersect => ia && ib,
- };
- n += 1;
- if ir_idx.contains(p) != want {
- bad += 1;
- }
- }
- }
- Some(bad as f64 / n.max(1) as f64)
-}
-
-/// How one body sits relative to another, from sample points: (fraction of `b`'s samples
-/// inside `a`, fraction of `a`'s samples inside `b`).
-fn overlap(
- a: &solidcraft_geom::Mesh,
- b: &solidcraft_geom::Mesh,
- ia: &solidcraft_geom::InsideIndex,
- ib: &solidcraft_geom::InsideIndex,
-) -> Option<(f64, f64)> {
- let frac = |inner: &solidcraft_geom::Mesh, inner_i: &solidcraft_geom::InsideIndex, outer_i: &solidcraft_geom::InsideIndex| -> Option<f64> {
- let bx = inner.bounds();
- let s = bx.size();
- let (mut n, mut hit) = (0usize, 0usize);
- // A slender body lying across its box (a long hole tool drilled at an angle) fills
- // little of it: the samples go on past the first 2000 until enough land inside.
- for i in 1..=64_000 {
- if i > 2000 && n >= 50 {
- break;
- }
- let p = bx.min + Vec3::new(s.x * halton(i, 2), s.y * halton(i, 3), s.z * halton(i, 5));
- if !inner_i.contains(p) {
- continue;
- }
- n += 1;
- if outer_i.contains(p) {
- hit += 1;
- }
- }
- (n >= 50).then(|| hit as f64 / n as f64)
- };
- Some((frac(b, ib, ia)?, frac(a, ia, ib)?))
-}
-
-/// 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,
- other: &solidcraft_geom::InsideIndex,
- depth: f64,
- inside: bool,
- within: Option<&solidcraft_geom::Aabb3>,
- ignored: &dyn Fn(Vec3, u32) -> bool,
-) -> bool {
- 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) && !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, 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) {
- 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 meet = ba.intersection(&bb);
- 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, &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.
-/// `tol`: how far the meshes' surfaces may pass through each other and still count as touching
-/// (they are facetings of the bodies, so a few times their tolerance).
-///
-/// The second value is false when the facetings contradict the samples ([`contradicted`]):
-/// the answer is then only what to fall back on if the bodies can't be intersected.
-fn trivial(
- a: &Body,
- b: &Body,
- op: BoolOp,
- ma: &solidcraft_geom::Mesh,
- mb: &solidcraft_geom::Mesh,
- counts: &[(usize, usize)],
- tol: f64,
-) -> Option<(Option<Body>, bool)> {
- if ma.triangles.len() + mb.triangles.len() > 80_000 {
- return None;
- }
- let (ia, ib) = (ma.inside_index(), mb.inside_index());
- let (b_in_a, a_in_b) = overlap(ma, mb, &ia, &ib)?;
- const ALL: f64 = 0.997;
- let disjoint = b_in_a < NONE && a_in_b < NONE;
- // 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.
- // 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.
- BoolOp::Union if disjoint => {
- let pieces = vec![(a.clone(), recorded::kept(a, 0, 2)), (b.clone(), recorded::kept(b, 1, 2))];
- let joined = recorded::join(pieces, counts).ok().flatten()?;
- joined.separated_lumps().ok()?;
- Some(Some(joined))
- }
- BoolOp::Cut if disjoint => Some(Some(recorded::operand(a, 0, counts))),
- BoolOp::Cut if a_in_b > ALL => Some(None),
- BoolOp::Intersect if disjoint => Some(None),
- BoolOp::Intersect if b_in_a > ALL => Some(Some(recorded::operand(b, 1, counts))),
- BoolOp::Intersect if a_in_b > ALL => Some(Some(recorded::operand(a, 0, counts))),
- BoolOp::Union if b_in_a > ALL => Some(Some(recorded::operand(a, 0, counts))),
- BoolOp::Union if a_in_b > ALL => Some(Some(recorded::operand(b, 1, counts))),
- // The tool wholly inside, clear of the outside: a void.
- BoolOp::Cut if b_in_a > ALL => {
- let candidate = void(a, b, counts).ok().flatten()?;
- candidate.separated_lumps().ok()?;
- Some(Some(candidate))
- }
- _ => None,
- };
- answer.map(|r| (r, sure))
-}
-
-#[cfg(test)]
-mod shortcut_tests {
- use super::*;
-
- #[test]
- fn seam_roundoff_is_not_a_thin_meeting_but_real_thin_solids_are() {
- use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
-
- // This circle's seams lie on the X axis: its cylinder's vertex box is flat in Y.
- let region = Region2 { outer: Loop2::circle(Vec2::ZERO, 8.0), holes: vec![] };
- let periodic = crate::extrude(&Plane::XY, &[region], 0.0, 20.0).unwrap().pop().unwrap();
- let block = crate::box_solid(Vec3::new(-40.0, -40.0, -10.0), Vec3::new(40.0, 40.0, 10.0)).unwrap();
- assert!(meeting_size(&periodic, &block).is_infinite());
- let thin = crate::box_solid(Vec3::ZERO, Vec3::new(80.0, 80.0, 1e-5)).unwrap();
- assert!((meeting_size(&thin, &thin) - 1e-5).abs() < 1e-12);
- }
-
- #[test]
- fn rotated_extrusion_bounds_use_exact_cap_separation_and_keep_sources() {
- use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
- let rectangle = |angle: f64, offset: f64| {
- let (c, s) = (angle.cos(), angle.sin());
- Region2 {
- outer: Loop2::polygon(
- &[(-2., -0.5), (2., -0.5), (2., 0.5), (-2., 0.5)].map(|(x, y)| Vec2::new(x * c - (y + offset) * s, x * s + (y + offset) * c)),
- ),
- holes: vec![],
- }
- };
- for offset in [1.2, 1., 0.8] {
- let tools = crate::extrude(&Plane::XY, &[rectangle(0.7, 0.), rectangle(0.7, offset)], 0., 2.).unwrap();
- let compound = compound_disjoint_extrusions(&tools).unwrap();
- assert_eq!(compound.is_some(), offset > 1.);
- if let Some(compound) = compound {
- let sources = compound.face_sources().unwrap();
- assert_eq!(sources.len(), compound.face_count());
- assert_eq!(sources.iter().filter(|source| matches!(source, Some(crate::FaceSource::ExtrudeCap { high: false, .. }))).count(), 2);
- assert!(compound.validity().is_empty());
- }
- }
- }
-
- #[test]
- fn batched_contact_test_matches_individual_tolerances() {
- let target = crate::cylinder(Vec3::ZERO, Vec3::Z, 5., 3.).unwrap();
- let tools = [
- crate::box_solid(Vec3::new(-1., -1., 3.), Vec3::new(1., 1., 5.)).unwrap(),
- crate::box_solid(Vec3::new(-1., -1., 3.002), Vec3::new(1., 1., 5.)).unwrap(),
- crate::sphere(Vec3::new(20., 0., 1.), 1.).unwrap(),
- ];
- let expected = tools.iter().map(|tool| target.meets(tool).unwrap()).collect::<Vec<_>>();
- assert_eq!(target.meets_each(&tools).unwrap(), expected);
- assert!(target.meets_each(&[]).unwrap().is_empty());
- }
-
- #[test]
- fn compound_span_does_not_relax_full_face_seam_tolerance() {
- use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
- let mut target = crate::box_solid(Vec3::new(0., 0., -3.), Vec3::new(100., 2., -2.)).unwrap();
- for x in [0., 98.] {
- let boss = crate::box_solid(Vec3::new(x, 0., -2.), Vec3::new(x + 2., 2., 0.)).unwrap();
- target = boolean(&target, &boss, BoolOp::Union).unwrap().unwrap();
- }
- let regions: Vec<_> = [0., 98.]
- .into_iter()
- .map(|x| Region2 {
- outer: Loop2::polygon(&[Vec2::new(x, 0.), Vec2::new(x + 2., 0.), Vec2::new(x + 2., 2.), Vec2::new(x, 2.)]),
- holes: vec![],
- })
- .collect();
- let tools = crate::extrude(&Plane::XY, &regions, 0.000_105, 200.).unwrap();
- assert!(tools.iter().all(|tool| !can_join_touching_faces(&target, tool)));
- let compound = compound_disjoint_extrusions(&tools).unwrap().unwrap();
- assert!(!can_join_all_touching_faces(&target, &compound));
- }
-
- #[test]
- fn extrusion_compound_requires_separated_construction_bounds() {
- use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
- let rectangle = |x: f64| Region2 {
- outer: Loop2::polygon(&[Vec2::new(x, 0.0), Vec2::new(x + 2.0, 0.0), Vec2::new(x + 2.0, 2.0), Vec2::new(x, 2.0)]),
- holes: vec![],
- };
- let plane = Plane::from_normal(Vec3::new(100.0, -20.0, 8.0), Vec3::new(1.0, 2.0, 3.0)).unwrap();
- let tools = crate::extrude(&plane, &[rectangle(0.0), rectangle(20.0)], -1.0, 5.0).unwrap();
- let compound = compound_disjoint_extrusions(&tools).unwrap().unwrap();
- assert_eq!(compound.shell_count(), 2);
- assert_eq!(compound.history().unwrap().operands, 2);
- assert!((crate::measure(&compound).unwrap().volume - 48.0).abs() < 1e-8);
- assert!(compound.validity().is_empty());
- for x in [1.0, 2.0, 2.000_000_1] {
- let touching = crate::extrude(&solidcraft_geom::Plane::XY, &[rectangle(0.0), rectangle(x)], 0.0, 5.0).unwrap();
- assert!(compound_disjoint_extrusions(&touching).unwrap().is_none());
- }
- let unsupported = [crate::sphere(Vec3::ZERO, 1.0).unwrap(), crate::sphere(Vec3::new(10.0, 0.0, 0.0), 1.0).unwrap()];
- assert!(compound_disjoint_extrusions(&unsupported).unwrap().is_none());
- }
-
- #[test]
- fn extrusion_compound_includes_arc_extrema_between_seam_vertices() {
- use solidcraft_geom::{Loop2, Plane, Region2, Vec2};
- let circle = |x| Region2 { outer: Loop2::circle(Vec2::new(x, 0.0), 2.0), holes: vec![] };
- let separated = crate::extrude(&Plane::XY, &[circle(0.0), circle(8.0)], 0.0, 5.0).unwrap();
- assert!(compound_disjoint_extrusions(&separated).unwrap().is_some());
- let overlapping = crate::extrude(&Plane::XY, &[circle(0.0), circle(3.0)], 0.0, 5.0).unwrap();
- assert!(compound_disjoint_extrusions(&overlapping).unwrap().is_none());
- }
-
- #[test]
- fn curved_near_contact_never_uses_a_shell_only_boolean_candidate() {
- let direction = Vec3::new(1.0, 2.0, 3.0).normalized().unwrap();
- let outer = crate::sphere(Vec3::ZERO, 10.0).unwrap();
- let mesh = outer.mesh(&crate::MeshTolerance::chord(0.03)).unwrap();
- for distance in [19.999, 20.001] {
- let other = crate::sphere(direction * distance, 10.0).unwrap();
- let other_mesh = other.mesh(&crate::MeshTolerance::chord(0.03)).unwrap();
- let counts = record::counts(&[&outer, &other]);
- assert!(trivial(&outer, &other, BoolOp::Union, &mesh, &other_mesh, &counts, 0.09).is_none());
- assert!(trivial(&other, &outer, BoolOp::Union, &other_mesh, &mesh, &counts, 0.09).is_none());
- }
- let protruding = crate::sphere(direction * 9.001, 1.0).unwrap();
- let protruding_mesh = protruding.mesh(&crate::MeshTolerance::chord(0.03)).unwrap();
- let counts = record::counts(&[&outer, &protruding]);
- 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.mesh(&crate::MeshTolerance::chord(0.009)).unwrap(), mb.mesh(&crate::MeshTolerance::chord(0.009)).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.mesh(&crate::MeshTolerance::chord(0.009)).unwrap(), tube.mesh(&crate::MeshTolerance::chord(0.009)).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.mesh(&crate::MeshTolerance::chord(0.005)).unwrap(), tube.mesh(&crate::MeshTolerance::chord(0.005)).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]
- fn a_small_overlap_is_not_taken_for_apart_or_inside() {
- let cube = |x: f64, y: f64| crate::box_solid(Vec3::new(x, y, 0.0), Vec3::new(x + 10.0, y + 10.0, 10.0)).unwrap();
- let a = cube(0.0, 0.0);
- // A 0.01 slab between parallel faces (0.1 % of each cube), and a 0.02 x 0.02 corner.
- for (b, want) in [(cube(9.99, 0.0), 1.0), (cube(9.98, 9.98), 0.004)] {
- let (ma, mb) = (a.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(), b.mesh(&crate::MeshTolerance::chord(0.001)).unwrap());
- let counts = record::counts(&[&a, &b]);
- for op in [BoolOp::Intersect, BoolOp::Cut, BoolOp::Union] {
- assert!(trivial(&a, &b, op, &ma, &mb, &counts, 0.003).is_none_or(|(_, sure)| !sure), "{op:?} {want}");
- }
- let shared = boolean(&a, &b, BoolOp::Intersect).unwrap().unwrap();
- assert!((crate::measure(&shared).unwrap().volume - want).abs() < 1e-9, "{want}");
- let cut = boolean(&a, &b, BoolOp::Cut).unwrap().unwrap();
- assert!((crate::measure(&cut).unwrap().volume - (1000.0 - want)).abs() < 1e-9, "{want}");
- }
- // Touching on a face, and one cube well inside the other, still take the shortcut.
- let (touching, inner) = (cube(10.0, 0.0), crate::box_solid(Vec3::new(2.0, 2.0, 2.0), Vec3::new(8.0, 8.0, 8.0)).unwrap());
- let ma = a.mesh(&crate::MeshTolerance::chord(0.001)).unwrap();
- for (b, op) in [(&touching, BoolOp::Intersect), (&inner, BoolOp::Intersect), (&inner, BoolOp::Union)] {
- let counts = record::counts(&[&a, b]);
- assert!(trivial(&a, b, op, &ma, &b.mesh(&crate::MeshTolerance::chord(0.001)).unwrap(), &counts, 0.003).is_some_and(|(_, sure)| sure), "{op:?}");
- }
- }
+ can_join_touching_faces(a, b)
}
-/// `a` with the inside of `b` (wholly within it) taken out: a second, inward-facing shell.
-fn void(a: &Body, b: &Body, counts: &[(usize, usize)]) -> Result<Option<Body>> {
- guard("void", || {
- let mut inner = b.deep_copy();
- let inner_edges = record::edge_origins(&inner, 1);
- inner.not();
- let mut shells = a.solid.boundaries().clone();
- shells.extend(inner.boundaries().iter().cloned());
- let s = crate::body::Solid::try_new(shells).map_err(|e| KernelError::Failed(format!("void: {e}")))?;
- let (faces, edges) = recorded::void(a, inner_edges, b.face_count());
- Ok(Some(record::build(s, counts, Some(faces), Some(&edges))?))
- })
-}
-
-thread_local! {
- /// Set while a boolean runs on bodies whose coincident faces were pushed apart (no
- /// second round of pushing).
- 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
-/// everything or an intersection of disjoint bodies. Results are checked against volume bounds
-/// and retried with shifted copies and other tolerances when they fail or look wrong.
-///
-/// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`,
-/// whichever way it was made, or none where a step it took does not report one.
+/// Boolean of two bodies in SMLib. The result may be empty (`Ok(None)`) for a cut that removes
+/// everything or an intersection of disjoint bodies. A result SMLib's check refuses is an error.
///
-/// Truck runs it unless [`crate::KERNEL_ENV`] picks SMLib ([`crate::backend`]).
+/// The result carries its exact history ([`Body::history`]) over the operands `[a, b]`, from
+/// SMLib's own tags, or none where a body's order cannot be matched to SMLib's.
pub fn boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
- crate::profile::timed(crate::profile::Kind::Boolean, || match crate::backend()? {
- crate::Backend::Truck => boolean_untimed(a, b, op),
- crate::Backend::Smlib => smlib_boolean(a, b, op),
+ crate::profile::timed(crate::profile::Kind::Boolean, || {
+ let r = guard("SMLib boolean", || crate::smlib_boolean::smlib_boolean(a, b, op));
+ with_operand_roles(a, b, op, r)
})
}
-/// [`boolean`] through SMLib, its result given the operands' roles as truck's is.
-#[cfg(feature = "smlib")]
-fn smlib_boolean(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
- let r = guard("SMLib boolean", || crate::smlib_boolean::smlib_boolean(a, b, op));
- with_operand_roles(a, b, op, r)
-}
-
-#[cfg(not(feature = "smlib"))]
-fn smlib_boolean(_: &Body, _: &Body, _: BoolOp) -> Result<Option<Body>> {
- Err(KernelError::Invalid("not supported yet: this build has no SMLib".into()))
-}
-
/// A boolean's result with what its operands' faces stood for carried over: regularization
/// protection and the planar construction and shell roles on supports it kept.
fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result<Option<Body>>) -> Result<Option<Body>> {
@@ -951,1422 +64,118 @@ fn with_operand_roles(a: &Body, b: &Body, op: BoolOp, r: Result<Option<Body>>) -
}
}
-fn boolean_untimed(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
- if let Some(r) = with_hollow_tool(a, b, op) {
- return finished(a, b, op, Ok(r));
- }
- // Earlier coarse bores can leave a junction a later pattern copy cannot intersect.
- // Resolve conical-cut junctions from the first copy, while the operands are unchanged.
- if op == BoolOp::Cut && !APART.with(|c| c.get()) && conical_cut_junction(a, b) {
- let refined = |a: &Body, b: &Body, op| boolean_whole_with_refinement(a, b, op, true);
- if let Ok(result) = boolean_via(a, b, op, &refined) {
- return Ok(result);
- }
- }
- 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;
- }
- // Equal cylinders crossing each other touch at two points the boolean cannot take in the
- // middle of a face (#788): once more with the faces split along them.
- let split = |a: &Body, b: &Body, op| {
- crate::tangent_cylinders::boolean(a, b, op, &boolean_whole).unwrap_or_else(|| Err(KernelError::Failed("no split of faces helps".into())))
- };
- boolean_via(a, b, op, &split).or(r)
-}
-
-/// A conical cutter meeting a body with an earlier conical cut needs finer tracing at
-/// their junctions. Guard the analytic recognition as well as the Boolean itself.
-fn conical_cut_junction(a: &Body, b: &Body) -> bool {
- guard("conical cut junction", || {
- let conical = |body: &Body| {
- let tol = (body.size() * 1e-5).max(1e-7);
- body.solid.face_iter().any(|face| matches!(crate::offset::surf_of(face, tol), Some(crate::offset::Surf::Cone { .. })))
- };
- Ok(conical(b) && conical(a))
- })
- .unwrap_or(false)
-}
-
-/// [`boolean`], the boolean of the whole bodies taken by `whole`.
-fn boolean_via(a: &Body, b: &Body, op: BoolOp, whole: &dyn Fn(&Body, &Body, BoolOp) -> Result<Option<Body>>) -> Result<Option<Body>> {
- let (mut r, mut diagnostics) = capture_boolean_diagnostics(|| whole(a, b, op));
- // Bodies in several pieces: when the whole failed (or came out empty), a piece at a time.
- let retry = match &r {
- Err(_) => true,
- Ok(None) => op != BoolOp::Intersect,
- Ok(Some(_)) => false,
- };
- if retry && (a.solid.boundaries().len() > 1 || b.solid.boundaries().len() > 1) {
- let (la, lb) = (a.lumps()?, b.lumps()?);
- if la.len() > 1 || lb.len() > 1 {
- let (pieces, report) = capture_boolean_diagnostics(|| by_lumps(a, b, la, lb, op));
- if let Ok(Some(x)) = pieces {
- r = Ok(Some(x));
- diagnostics = report;
- diagnostics.push(BooleanFallback::new(BooleanStrategy::Piecewise));
- }
- }
- }
- // A piece with sealed voids, cut clear of them: the outer shell alone, the voids put back.
- if op == BoolOp::Cut && r.is_err() {
- let (cut, report) = capture_boolean_diagnostics(|| cut_around_voids(a, b, whole));
- if let Ok(Some(x)) = cut {
- r = Ok(Some(x));
- diagnostics = report;
- diagnostics.push(BooleanFallback::new(BooleanStrategy::Piecewise));
- }
- }
- if op == BoolOp::Union
- && let Ok(Some(body)) = &r
- && !preserves_planar_surfaces(a, b, body)
- {
- // Numerical retries must not quietly alter a planar design's dimensions.
- // Prefer the exact polygon result; reject an edge-only pinch if it cannot
- // form a closed solid without displacing either operand.
- r = match crate::polybool::planar_boolean(a, b, op) {
- Ok(Some(exact)) if preserves_planar_surfaces(a, b, &exact) => {
- diagnostics = Default::default();
- diagnostics.events.push(BooleanFallback::new(BooleanStrategy::PlanarFallback));
- Ok(Some(exact))
- }
- _ => Err(KernelError::Invalid(
- "join cannot preserve the original faces; check for zero-thickness edge contact or add intentional overlap".into(),
- )),
- };
- }
- r = with_operand_roles(a, b, op, r);
- // A retry's result is held to what the operation can do at all; one that fails is refused
- // rather than returned wrong (issue #616).
- if (!diagnostics.events.is_empty() || diagnostics.truncated)
- && let Ok(result) = &r
- && let Err(e) = crate::boolean_guard::check_retry(a, b, op, result.as_ref())
- {
- let tried = diagnostics.summary().unwrap_or_default();
- r = Err(match e {
- KernelError::Failed(m) => KernelError::Failed(format!("{m} ({})", tried.trim_start_matches("Boolean retry: "))),
- other => other,
- });
- }
- if r.is_ok() {
- merge(diagnostics);
- }
- r
-}
-
-/// What a boolean's result keeps of its operands: their regularization protection, and the
-/// sources of the planar faces it keeps.
-fn finished(a: &Body, b: &Body, op: BoolOp, r: Result<Option<Body>>) -> Result<Option<Body>> {
- let r = r.map(|result| result.map(|body| body.inherit_regularization_protection(a).inherit_regularization_protection(b)));
- match op {
- BoolOp::Cut => r.and_then(|result| result.map(|body| body.with_preserved_boolean_planar_sources(a, b, true)).transpose()),
- BoolOp::Union => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()),
- // Every face of an intersection lies on one operand's face, as a union's does: the same
- // roles carry over (#565).
- BoolOp::Intersect => r.and_then(|result| result.map(|body| body.with_preserved_union_planar_sources(a, b)).transpose()),
- }
-}
-
-/// The most shells [`cut_around_voids`] takes apart.
-const MAX_VOID_SHELLS: usize = 64;
-
-/// `a` cut by `b` around `a`'s voids: when `a` is one piece with sealed voids (inner shells) and
-/// `b` stays clear of every void, the outer shell alone is cut and the voids are put back. The cut
-/// of the whole failed on such bodies where the same cut of the outer shell works: a sphere cut
-/// far from a void (robustness seed 15). `None` when `a` has no voids, `b` comes near one, or
-/// the cut of the outer shell fails too. The result carries no history.
-fn cut_around_voids(a: &Body, b: &Body, whole: &dyn Fn(&Body, &Body, BoolOp) -> Result<Option<Body>>) -> Result<Option<Body>> {
- let shells = a.solid.boundaries().clone();
- if shells.len() < 2 || shells.len() > MAX_VOID_SHELLS || b.solid.boundaries().len() != 1 || a.lumps()?.len() != 1 {
- return Ok(None);
- }
- let tol = (a.size() * 1e-3).max(1e-3);
- let mut boxes = Vec::with_capacity(shells.len());
- for sh in &shells {
- let piece =
- guard("void shell", || Body::new(Solid::try_new(vec![sh.clone()]).map_err(|e| KernelError::Failed(format!("void shell: {e}")))?))?;
- let m = piece.mesh(&crate::MeshTolerance::chord(tol))?;
- if m.positions.is_empty() {
- return Ok(None);
- }
- boxes.push(m.bounds());
- }
- let extent = |i: usize| {
- boxes.get(i).map_or(0.0, |x| {
- let d = x.max - x.min;
- d.x * d.y * d.z
- })
- };
- let Some(outer) = (0..shells.len()).max_by(|i, j| extent(*i).total_cmp(&extent(*j))) else { return Ok(None) };
- let Some(ob) = boxes.get(outer) else { return Ok(None) };
- let tm = b.mesh(&crate::MeshTolerance::chord((b.size() * 1e-3).max(1e-3)))?;
- let tb = tm.bounds();
- // Clear of the tool by more than both meshes' deflection.
- let gap = 4.0 * tol + (b.size() * 1e-3).max(1e-3);
- let inside = |x: &solidcraft_geom::Aabb3| {
- x.min.x >= ob.min.x && x.min.y >= ob.min.y && x.min.z >= ob.min.z && x.max.x <= ob.max.x && x.max.y <= ob.max.y && x.max.z <= ob.max.z
- };
- let clear = |x: &solidcraft_geom::Aabb3| {
- x.max.x + gap < tb.min.x
- || tb.max.x + gap < x.min.x
- || x.max.y + gap < tb.min.y
- || tb.max.y + gap < x.min.y
- || x.max.z + gap < tb.min.z
- || tb.max.z + gap < x.min.z
- };
- let mut voids = Vec::new();
- for (i, (sh, x)) in shells.iter().zip(&boxes).enumerate() {
- if i == outer {
- continue;
- }
- if !inside(x) || !clear(x) {
- return Ok(None);
- }
- voids.push(sh.clone());
- }
- let Some(outer_shell) = shells.get(outer) else { return Ok(None) };
- let alone =
- guard("outer shell", || Body::new(Solid::try_new(vec![outer_shell.clone()]).map_err(|e| KernelError::Failed(format!("outer shell: {e}")))?))?;
- let Some(cut) = boolean_via(&alone, b, BoolOp::Cut, whole)? else { return Ok(None) };
- let mut all = cut.solid.boundaries().clone();
- all.extend(voids);
- Ok(Some(guard("voids back", || Body::new(Solid::try_new(all).map_err(|e| KernelError::Failed(format!("voids back: {e}")))?))?))
-}
-
-/// A cut or union with `b` when `b` is one outer shell with sealed voids, from booleans with the
-/// outer shell and with the solids the voids are: `a` cut by `b` is `a` cut by the outer shell
-/// beside `a` within each void, and `a` joined with `b` is `a` joined with the outer shell, with
-/// what of each void `a` does not fill as a void. truck takes a tool's shells one at a time, each
-/// as if it were a body of its own, which is neither: such cuts came out empty, or kept only what
-/// lies in the void (a block crossing both spheres of a spherical shell, #451). Planar tools are
-/// left to the exact paths. `None` for other operations and tools, a void not inside the outer
-/// shell, and a result that fails the membership samples the general way's results are held to
-/// (a piece that failed or came out empty): the bodies then go the general way.
-fn with_hollow_tool(a: &Body, b: &Body, op: BoolOp) -> Option<Option<Body>> {
- let shells = b.solid.boundaries();
- if op == BoolOp::Intersect || b.is_mesh() || shells.len() < 2 || shells.len() > MAX_VOID_SHELLS || is_planar(b) {
- return None;
- }
- let (mut outer, mut voids) = (None, Vec::new());
- for sh in shells {
- if crate::body::faces_inward(sh).ok()? {
- voids.push(sh.clone());
- } else if outer.replace(sh.clone()).is_some() {
- return None;
- }
- }
- // Each shell a body of its own, a void turned outwards: the solid it holds.
- let parts: Vec<Body> = std::iter::once(outer?)
- .chain(voids)
- .map(|sh| guard("hollow tool", || Body::new(Solid::try_new(vec![sh]).map_err(|e| KernelError::Failed(format!("hollow tool: {e}")))?)))
- .collect::<Result<_>>()
- .ok()?;
- let t = a.size().max(b.size()) * 5e-4;
- let (shell, holes) = parts.split_first()?;
- let mesh = shell.tessellate(t).ok()?;
- let inside = mesh.inside_index();
- if !holes.iter().all(|h| h.solid.vertex_iter().all(|v| inside.contains(from_p3(v.point())))) {
- return None;
- }
- let r = by_outer_and_voids(a, b, parts, op).ok()?;
- let mr = match &r {
- Some(r) => r.tessellate_with(t, true).ok()?,
- None => solidcraft_geom::Mesh::default(),
- };
- mismatch(&a.tessellate_with(t, true).ok()?, &b.tessellate_with(t, true).ok()?, &mr, op).is_some_and(|f| f < 0.004).then_some(r)
-}
-
-/// [`with_hollow_tool`]'s booleans, with `b` as its outer shell's solid, then its voids'.
-fn by_outer_and_voids(a: &Body, b: &Body, parts: Vec<Body>, op: BoolOp) -> Result<Option<Body>> {
- let counts = record::counts(&[a, b]);
- let traced: Vec<Traced> = recorded::parts_of(&parts, b).into_iter().zip(parts).map(|(h, p)| (p, recorded::placed(h, 1, 2))).collect();
- let pair = |(x, hx): &Traced, (y, hy): &Traced, op: BoolOp| -> Result<Option<Traced>> {
- Ok(boolean(x, y, op)?.map(|r| {
- let h = recorded::of_pair(&r, hx, hy);
- (r, h)
- }))
- };
- let a = (a.clone(), recorded::kept(a, 0, 2));
- let Some((shell, voids)) = traced.split_first() else { return Ok(None) };
- if op == BoolOp::Cut {
- let mut pieces: Vec<Traced> = pair(&a, shell, BoolOp::Cut)?.into_iter().collect();
- for v in voids {
- pieces.extend(pair(&a, v, BoolOp::Intersect)?);
- }
- return recorded::join(pieces, &counts);
- }
- let Some(mut joined) = pair(&a, shell, BoolOp::Union)? else { return Ok(None) };
- // What of a void `a` leaves empty lies inside the outer shell, clear of the outside: a void again.
- for v in voids {
- if let Some((left, hl)) = pair(v, &a, BoolOp::Cut)?
- && let Some(r) = void(&joined.0, &left, &record::counts(&[&joined.0, &left]))?
- {
- let h = recorded::of_pair(&r, &joined.1, &hl);
- joined = (r, h);
- }
- }
- Ok(Some(joined.0.with_checked_history(joined.1, &counts)))
-}
-
-/// Every face of an all-planar union must remain on an operand's original plane.
-/// Curved operands keep their existing surface-specific boolean handling.
-fn preserves_planar_surfaces(a: &Body, b: &Body, result: &Body) -> bool {
- guard("validate planar union", || Ok(planar_surfaces_match(a, b, result))).unwrap_or(false)
-}
-
-fn planar_surfaces_match(a: &Body, b: &Body, result: &Body) -> bool {
- let planes: Option<Vec<(Vec3, f64)>> = a
- .solid
- .face_iter()
- .chain(b.solid.face_iter())
- .map(|f| {
- let mt::Surface::Plane(p) = f.oriented_surface() else { return None };
- let n = p.normal();
- let n = Vec3::new(n.x, n.y, n.z).normalized()?;
- Some((n, n.dot(from_p3(p.origin()))))
- })
- .collect();
- let Some(planes) = planes else { return true };
- let tol = (a.size().max(b.size()) * 1e-9).max(1e-9);
- result.solid.face_iter().all(|f| {
- matches!(f.oriented_surface(), mt::Surface::Plane(_))
- && planes.iter().any(|(n, d)| f.vertex_iter().all(|v| (n.dot(from_p3(v.point())) - d).abs() <= tol))
- })
-}
-
-/// Smallest side of the box where the bodies' vertex boxes overlap (infinite when they don't).
-fn meeting_size(a: &Body, b: &Body) -> f64 {
- let bbox = |x: &Body| {
- let mut bb = solidcraft_geom::Aabb3::EMPTY;
- for v in x.solid.vertex_iter() {
- bb.add(from_p3(v.point()));
- }
- bb
- };
- let (ba, bb) = (bbox(a), bbox(b));
- let s = ba.intersection(&bb).size();
- // A closed sweep's section seams need not span its geometry. Roundoff in a flat
- // vertex box is not a thin meeting region: refining for it
- // makes millions of triangles and skips the bounded containment shortcut (#2005).
- let roundoff = a.size().max(b.size()) * 1e-12;
- if s.x > roundoff && s.y > roundoff && s.z > roundoff { s.x.min(s.y).min(s.z) } else { f64::INFINITY }
-}
-
-/// Smallest side of the box where the bounds of two meshes overlap (infinite when they don't).
-/// Unlike [`meeting_size`], this follows curved faces: a cylinder's vertices are only the points
-/// on its seam, so its vertex box says nothing about where its side reaches.
-fn mesh_meeting_size(a: &solidcraft_geom::Mesh, b: &solidcraft_geom::Mesh) -> f64 {
- let (ba, bb) = (a.bounds(), b.bounds());
- let s = ba.intersection(&bb).size();
- if s.x > 0.0 && s.y > 0.0 && s.z > 0.0 { s.x.min(s.y).min(s.z) } else { f64::INFINITY }
-}
-
-/// Whether a result volume is plausible for `op`: within the bounds the operands' volumes
-/// leave, plus the slack the meshed volumes are measured to.
-fn plausible(v: f64, op: BoolOp, va: f64, vb: f64, slack: f64) -> bool {
- v > 0.0
- && match op {
- BoolOp::Union => v >= va.max(vb) - slack && v <= va + vb + slack,
- BoolOp::Cut => v >= va - vb - slack && v <= va + slack,
- BoolOp::Intersect => v <= va.min(vb) + slack,
- }
-}
-
-/// A boolean in 2D of prisms along one direction (see [`prism_result`]).
-type Route = fn(&Body, &Body, BoolOp) -> Option<Result<Option<Body>>>;
-
-/// A prism route's result (`route`: [`crate::prism::prism_boolean`] or
-/// [`crate::prism::prism_union_between_caps`]): `Some` when both operands are prisms along one
-/// direction, with a union's slab seams healed as the general B-rep boolean does.
-fn prism_result(a: &Body, b: &Body, op: BoolOp, size: f64, counts: &[(usize, usize)], route: Route) -> Option<Result<Option<Body>>> {
- // Slab-by-slab prism booleans sew a closed solid, but leave cap and wall pieces along slab
- // boundaries: a cut along Z through a box whose side wall already has a port in it splits
- // that wall into strips at the port's top and bottom, though the cut never touches it. Merge
- // those coplanar faces for every operation, just as the general B-rep boolean does, retaining
- // intentional Split Face lines. Authored boundaries (painted faces, regularization
- // protection) keep their pieces.
- let keep: Vec<Vec<Vec3>> = a.split_keep().iter().chain(b.split_keep()).cloned().collect();
- let authored = |x: &Body| x.regularization_protected || x.paint().is_some_and(|p| !p.faces.is_empty());
- route(a, b, op).map(|result| {
- result.map(|body| {
- body.map(|body| {
- if op == BoolOp::Union {
- guard("heal prism boolean", || recorded::heal_body(&body, (*body.solid).clone(), size, &keep, counts)).unwrap_or(body)
- } else if authored(a) || authored(b) {
- body
- } else {
- guard("heal prism boolean", || recorded::heal_prism_result(&body, size, &keep, counts)).unwrap_or(body)
- }
- })
- })
- })
-}
-/// Walls swept along splines have flat B-spline tops and bottoms. With those made planes the
-/// operands are prisms, and two of them (same height, one direction) are decided in 2D: fast, and
-/// with no intersection of spline surfaces, which is what fails on them. The outlines are fitted
-/// by arcs within a micron (`prism_boolean_free_form`). `None` when the operands have no such
-/// face, are not such prisms, or the answer is implausible: the general boolean then takes over.
-fn swept_prism(a: &Body, b: &Body, op: BoolOp) -> Option<Body> {
- let (pa, pb) = (crate::planar_faces::planarized(a), crate::planar_faces::planarized(b));
- if pa.is_none() && pb.is_none() {
- return None;
- }
- let (ra, rb) = (pa.as_ref().unwrap_or(a), pb.as_ref().unwrap_or(b));
- let Some(Ok(Some(body))) = crate::prism::prism_boolean_free_form(ra, rb, op) else { return None };
- let (va, vb) = (volume(a), volume(b));
- plausible(volume(&body), op, va, vb, 2e-3 * (va + vb) + 1e-9).then_some(body)
-}
-
-fn boolean_whole(a: &Body, b: &Body, op: BoolOp) -> Result<Option<Body>> {
- boolean_whole_with_refinement(a, b, op, false)
-}
-
-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));
- }
- a.require_brep("a boolean")?;
- b.require_brep("a boolean")?;
- let size = a.size().max(b.size());
- let counts = record::counts(&[a, b]);
- // The checks mesh both bodies; where they meet in a region much thinner than they are (a
- // thin part trimmed by a long one), a step from their size would facet the small faces
- // there coarsely enough to fail the membership test on a correct result. The meshes are
- // refined: a round side trimmed to a thin band (a short boss crossing a gently sloping
- // floor) is otherwise spanned by triangles cutting through it, which reads as missing
- // material.
- let mut tol_m = (size * 5e-4).min(meeting_size(a, b) * 2e-3).max(size * 1e-5);
- // A prism pair (a plate and the tool through it) is decided exactly in 2D, with no mesh of
- // either operand. The sampled shortcuts below need a refined mesh of both, and that mesh is
- // most of what a boolean costs: a pattern or a multi-profile sketch rebuilds the whole
- // target's mesh once per tool. Only a cut or an intersection meets its tool often enough to
- // be worth asking first - parts that stay apart are settled far more cheaply by the shell
- // join the sampled shortcut does. A pair the route cannot answer still takes the path below,
- // unchanged.
- let early_prism = matches!(op, BoolOp::Cut | BoolOp::Intersect);
- let prism = early_prism.then(|| prism_result(a, b, op, size, &counts, crate::prism::prism_boolean)).flatten();
- if let Some(Ok(Some(body))) = &prism {
- let (va0, vb0) = (volume(a), volume(b));
- let (v0, slack0) = (volume(body), 2e-3 * (va0 + vb0) + 1e-9);
- // A tool that misses its target, or covers it whole, leaves it as it is, and the
- // sampled shortcut below answers that by reusing the operand itself: the very same body.
- // The 2D route rebuilds it instead - the same shape on new faces - which would turn an
- // untouched body in a timeline into a different solid. The route declines those pairs
- // itself, from its exact sections (a volume measured off meshes could not tell an
- // engraving of thin strokes from no change), and they take the path below, which
- // decides them, and the identity they keep, exactly as it always has.
- if plausible(v0, op, va0, vb0, slack0) {
- return Ok(Some(body.clone()));
- }
- }
- let mut meshes = (a.mesh(&crate::MeshTolerance::chord(tol_m)).ok(), b.mesh(&crate::MeshTolerance::chord(tol_m)).ok());
- // The vertex boxes above miss a curved operand's reach (a cylinder has only seam vertices),
- // so a thin meeting region of curved bodies kept the coarse step: a sliver 0.5 mm thick was
- // faceted at 0.017 mm and a correct result failed the membership test. The meshes just made
- // do span the bodies, so the step is set again from where they meet and the meshes are
- // remade once, when that is a much finer step.
- let refined = match &meshes {
- // A meeting box only a few steps thick is the tessellation error of bodies that merely
- // touch or miss each other: a finer mesh there cannot help and only slows the operation.
- (Some(ma), Some(mb)) => {
- let meet = mesh_meeting_size(ma, mb);
- (meet > tol_m * 8.0).then(|| (size * 5e-4).min(meet * 2e-3).max(size * 1e-5))
- }
- _ => None,
- };
- if let Some(refined) = refined
- && refined < tol_m * 0.5
- {
- let again = (a.mesh(&crate::MeshTolerance::chord(refined)).ok(), b.mesh(&crate::MeshTolerance::chord(refined)).ok());
- if again.0.is_some() && again.1.is_some() {
- tol_m = refined;
- meshes = again;
- }
- }
- let (va, vb) = match &meshes {
- (Some(ma), Some(mb)) => (ma.measure().volume, mb.measure().volume),
- _ => (volume(a), volume(b)),
- };
- let slack = 2e-3 * (va + vb) + 1e-9;
- // Where a result's edges can run: a candidate with an edge far outside the operands is
- // discarded before it is meshed (#3020), as meshing such a face may never finish.
- let reach = crate::candidate_reach::Reach::new(a, b, (meshes.0.as_ref(), meshes.1.as_ref()), size);
- // Volume bounds, then membership against the operands (catches misclassified pieces), on
- // one mesh of the result. Returns (plausible, volume).
- // Shells that touch were never fused: coincident back-to-back faces leave the intersection
- // nothing to cut, so it returns both operands side by side (#396). Volume and point
- // sampling cannot see that; the shell grouping can. Only contact over an area counts
- // (bodies tangent along a line stay two lumps), and operands already like that, saved
- // before this was caught, stay joinable. Nor can they see a skin of no thickness left over
- // a hole by a tool ending in a face of the target ([`crate::coplanar::has_skin`]).
- let unfused = |r: &Body| {
- op == BoolOp::Union
- && r.shell_count() > 1
- && r.union_lumps().is_err()
- && a.union_lumps().is_ok()
- && b.union_lumps().is_ok()
- && crate::coplanar::faces_touch(a, b)
- };
- let check = |r: &Body| -> (bool, f64) {
- if let Some(reason) = reach.as_ref().and_then(|reach| reach.runaway(r)) {
- reject(reason);
- return (false, f64::NAN);
- }
- let Ok(mr) = r.mesh(&crate::MeshTolerance::chord(tol_m)) else { return (false, f64::NAN) };
- let v = mr.measure().volume;
- let bounds = plausible(v, op, va, vb, slack);
- if !bounds {
- return (false, v);
- }
- if unfused(r) || crate::coplanar::has_skin(r, &mr) {
- return (false, v);
- }
- let consistent = match &meshes {
- (Some(ma), Some(mb)) => mismatch(ma, mb, &mr, op).is_none_or(|f| f < 0.004),
- _ => true,
- };
- (consistent, v)
- };
- if refine {
- let keep: Vec<Vec<Vec3>> = a.split_keep().iter().chain(b.split_keep()).cloned().collect();
- // 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)) = 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
- && crate::boolean_guard::check_retry(a, b, op, Some(&body)).is_ok()
- {
- let mut event = BooleanFallback::new(BooleanStrategy::RefinedTolerance);
- event.tolerance_mm = tol;
- record(event);
- return Ok(Some(body));
- }
- }
- return Err(KernelError::Failed("no reliable result at refined tolerances".into()));
- }
- // One body clear of or inside the other: no intersection needed.
- // Kept for the end when the facetings disagree with it: bodies that touch along curved
- // faces can pass through each other slightly, and often can't be intersected.
- let mut doubted = None;
- if let (Some(ma), Some(mb)) = &meshes
- && let Some((r, sure)) = trivial(a, b, op, ma, mb, &counts, 3.0 * tol_m)
- {
- if sure {
- return Ok(r);
- }
- doubted = Some(r);
- }
- let mut last = String::new();
- // Coincident faces make the intersection fail after many retries; push them apart first.
- // Prisms along one direction (plates with holes): exact, in 2D (so only the volume bounds
- // are checked). For a cut or an intersection this already ran above; the other operations
- // ask here, after the sampled shortcut, which is where that shortcut is cheapest.
- let prism = prism.or_else(|| (!early_prism).then(|| prism_result(a, b, op, size, &counts, crate::prism::prism_boolean)).flatten());
- if let Some(result) = prism {
- match result {
- Ok(Some(body)) => {
- // Measured as the operands were: a coarser mesh of a plate with many holes
- // overstates its volume by more than the slack.
- let v = match &meshes {
- (Some(_), Some(_)) => body.mesh(&crate::MeshTolerance::chord(tol_m)).map(|m| m.measure().volume).unwrap_or(f64::NAN),
- _ => volume(&body),
- };
- if plausible(v, op, va, vb, slack) {
- return Ok(Some(body));
- }
- }
- Ok(None) => return Ok(None),
- // A failed prism attempt keeps trying the other strategies, as it did before.
- Err(_) => {}
- }
- }
- // Bodies touching along one whole face (a part joined with its mirror image).
- if op == BoolOp::Union && a.solid.boundaries().len() == 1 {
- let glued = if b.solid.boundaries().len() == 1 { crate::coplanar::glue(a, b) } else { crate::coplanar::glue_all_caps(a, b) };
- if let Some(Ok(body)) = glued {
- let (ok, _) = check(&body);
- if ok {
- return Ok(Some(body));
- }
- }
- }
- // Bores on a common cylinder (a pad's bore around the hole it is joined over, a disc filling
- // a hole). Asked before faces are pushed apart: that doesn't part walls on one cylinder, and
- // its tries at the general boolean, all failing on those walls, cost seconds.
- if op == BoolOp::Union && !BORES.with(|c| c.get()) && crate::coplanar::has_coincident_cylinders(a, b) {
- BORES.with(|c| c.set(true));
- let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::bore_union(a, b, &|body| check(body).0));
- BORES.with(|c| c.set(false));
- if let Some(body) = r {
- merge(diagnostics);
- return Ok(Some(body));
- }
- }
- // Coincident planar faces: push them apart (exactly). Tried once, before the general
- // boolean; why it failed is reported if everything else fails too.
- let mut apart_failed = String::new();
- // The exact polygon boolean's answer, when it was asked for early.
- let mut planar = None;
- if !APART.with(|c| c.get()) {
- APART.with(|c| c.set(true));
- let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::boolean_apart(a, b, op));
- APART.with(|c| c.set(false));
- match r {
- Some(Ok(Some(body))) => {
- let (ok, v) = check(&body);
- if ok {
- merge(diagnostics);
- let mut event = BooleanFallback::new(BooleanStrategy::CoplanarSeparation);
- event.face_shift_mm = size * 0.0229;
- record(event);
- return Ok(Some(body));
- }
- apart_failed = format!("; faces pushed apart gave an implausible volume {v:.4}");
- }
- Some(Err(e)) => apart_failed = format!("; {e}"),
- Some(Ok(None)) | None => {}
- }
- // A face with no room to move would take or add what it moves through. The exact
- // polygon boolean takes the bodies as they lie (bodies with only planar faces, or a
- // planar tool clear of the other body's curved faces): it is asked now, before the
- // general boolean has its tries at faces lying in each other.
- if apart_failed.contains(crate::coplanar::NO_ROOM) {
- // What its own booleans report counts only when its result is taken.
- let (exact, diagnostics) = capture_boolean_diagnostics(|| crate::polybool::planar_boolean(a, b, op));
- match exact {
- Ok(Some(body)) if check(&body).0 => {
- merge(diagnostics);
- record(BooleanFallback::new(BooleanStrategy::PlanarFallback));
- return Ok(Some(body));
- }
- other => planar = Some(other),
- }
- }
- }
- // A face standing wholly inside a coincident face of the other body, back to back, and no
- // other contact (#396): exact, by topology alone.
- if op == BoolOp::Union
- && a.solid.boundaries().len() == 1
- && b.solid.boundaries().len() == 1
- && let Some(Ok(body)) = crate::coplanar::inset(a, b)
- && let (Some(ma), Some(mb)) = &meshes
- && overlap(ma, mb, &ma.inside_index(), &mb.inside_index()).is_some_and(|(b_in_a, a_in_b)| b_in_a < NONE && a_in_b < NONE)
- && check(&body).0
- {
- return Ok(Some(body));
- }
- // Faces back to back over part of their area: imprinted on each other and glued (exact; held
- // to the retry guard's checks all the same).
- if op == BoolOp::Union && crate::coplanar::faces_touch(a, b) {
- let accept = |body: &Body| check(body).0 && !unfused(body) && crate::boolean_guard::check_retry(a, b, op, Some(body)).is_ok();
- // Imprinted along the contact's own outline (faces there bounded by lines and arcs), then
- // along the sides' surfaces.
- if let Some(body) = crate::outline::outline_union(a, b, &accept) {
- return Ok(Some(body));
- }
- if let Some(body) = crate::coplanar::imprint_union(a, b, &accept) {
- return Ok(Some(body));
- }
- }
- let mut empty_votes = 0;
- let mut empty_diagnostics = crate::BooleanDiagnostics::default();
- let keep: Vec<Vec<Vec3>> = a.split_keep().iter().chain(b.split_keep()).cloned().collect();
- // The tolerances below follow the larger body. Where the bodies meet in a region much
- // smaller than that (a hole a few millimetres across drilled through a long part, whose tool
- // is longer still), they are as coarse as the tool itself: its intersection curves are
- // traced at a step wider than the hole, and the cut comes out empty or fails. When those
- // tries fail, the same boolean is asked again at tolerances (and shifts) scaled to where the
- // bodies meet. Its result is checked as the others are, and held to the retry guard.
- // Bodies in several shells are retried a piece at a time (see [`boolean`]), where each
- // piece gets this pass of its own.
- let fine_tols: Vec<f64> = match &meshes {
- (Some(ma), Some(mb)) if a.solid.boundaries().len() == 1 && b.solid.boundaries().len() == 1 => {
- let (ba, bb) = (ma.bounds(), mb.bounds());
- let s = ba.intersection(&bb).size();
- // The thinner operand's thickness (twice its volume over its area: a plate's
- // thickness, a rod's radius) bounds what the tolerance must resolve as well.
- let thickness = |m: &solidcraft_geom::Mesh| {
- let x = m.measure();
- if x.area > 0.0 { 2.0 * x.volume.abs() / x.area } else { f64::INFINITY }
- };
- let feature = s.x.min(s.y).min(s.z).min(thickness(ma)).min(thickness(mb)).max(size * 1e-4);
- if feature > 0.0 && feature * 2e-3 < size * 2.5e-4 { vec![(feature * 2e-3).max(1e-6), (feature * 5e-4).max(1e-6)] } else { Vec::new() }
- }
- _ => Vec::new(),
- };
- let fine = |last: &mut String| -> Option<Body> {
- let feature = fine_tols.first().map(|t| t / 2e-3)?;
- // Unshifted, then once shifted: each try at these tolerances costs many coarser ones.
- 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 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) => {
- let (ok, v) = check(&body);
- if ok {
- let mut event = BooleanFallback::new(if attempt > 0 {
- BooleanStrategy::ShiftedOperands
- } else {
- BooleanStrategy::RefinedTolerance
- });
- event.translation_mm = Vec3::new(j[0], j[1], j[2]).len() * (feature * 0.01);
- event.tolerance_mm = tol;
- record(event);
- return Some(body);
- }
- *last = format!("implausible result volume {v:.4}");
- }
- Err(e) => *last = e.to_string(),
- },
- Err(e) => *last = e.to_string(),
- }
- }
- }
- None
- };
- for (attempt, j) in JITTER.iter().enumerate() {
- // The operands as they lie failed. A planar tool beside the target's curved faces (a tooth
- // or a pocket cut next to a round edge) is decided exactly in the slab it lies in, where
- // the target is planar too, before the shifted tries: that is where they end anyway, as a
- // retry, after costing several times as much (on every copy of a pattern, #1197).
- if attempt == 1 && matches!(op, BoolOp::Cut | BoolOp::Intersect) {
- let (sliced, diagnostics) = capture_boolean_diagnostics(|| crate::polybool::sliced_planar_boolean(a, b, op));
- if let Some(Ok(Some(body))) = sliced
- && check(&body).0
- {
- merge(diagnostics);
- return Ok(Some(body));
- }
- }
- // A prism tool whose walls only touch the target (a corner of its outline on a ring's bore
- // or in its end face, the wall beside it outside the ring): with those walls pushed
- // outward, clear of the target, it takes the same cut exactly, without the contact the
- // tries below fail on (and the nudge after them got through only seconds later, leaving a
- // face of no width at the corner).
- if attempt == 1
- && op == BoolOp::Cut
- && let (Some(ma), Some(_)) = &meshes
- && let Some(body) = pushed_walls_cut(a, b, ma, 2.0 * tol_m, size, &keep, &counts, &check)
- {
- return Ok(Some(body));
- }
- // A prism tool whose target is a prism along its direction only round it (a pocket made
- // deeper in a plate with a chamfered rim, a ring cut round a counterbored hole in a
- // chamfered disc): the exact 2D route in a column cut round the tool. Its walls lying on
- // the target's are what the tries below fail on.
- if attempt == 1 && matches!(op, BoolOp::Cut | BoolOp::Intersect) {
- let (local, diagnostics) = capture_boolean_diagnostics(|| crate::prism_local::local_prism_boolean(a, b, op));
- if let Some(Ok(Some(body))) = local
- && check(&body).0
- {
- merge(diagnostics);
- return Ok(Some(body));
- }
- }
- // A lens cut from a sphere's projected outline carries a redundant cylinder
- // tangent to the sphere (#2750). Remove it only after proving that it
- // encloses the entire target, keeping the other wall and both caps exact.
- if attempt == 1 && op == BoolOp::Cut {
- let (lens, diagnostics) = capture_boolean_diagnostics(|| crate::sphere_lens::cut(a, b, &boolean_whole));
- if let Some(Ok(result)) = lens
- && result.as_ref().is_none_or(|body| check(body).0)
- {
- merge(diagnostics);
- return Ok(result);
- }
- }
- // A whole turn of a cylinder or cone bounded by one wire along its seam (as STEP files
- // write them) can't be divided by a loop lying inside it, and the tries below end in a
- // nudged tool, or fail: the same boolean with such faces in two halves, which is exact.
- if attempt == 1 && crate::seam_faces::needed(a, b) {
- let (halves, diagnostics) = capture_boolean_diagnostics(|| crate::seam_faces::boolean(a, b, op, &boolean));
- if let Some(Ok(r)) = halves
- && r.as_ref().is_none_or(|body| check(body).0)
- {
- merge(diagnostics);
- 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 = 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;
- if attempt > 0 || k != 2e-3 {
- let mut event =
- BooleanFallback::new(if attempt > 0 { BooleanStrategy::ShiftedOperands } else { BooleanStrategy::RefinedTolerance });
- event.translation_mm = Vec3::new(j[0], j[1], j[2]).len() * (size * 0.01);
- event.tolerance_mm = tol;
- empty_diagnostics.push(event);
- }
- last = "empty result".into();
- }
- Ok((s, h)) => match guard("boolean result", || recorded::truck_result(s, h, size, &keep, &counts)) {
- Ok(body) => {
- let (ok, v) = check(&body);
- if ok {
- if attempt > 0 || k != 2e-3 {
- let mut event = BooleanFallback::new(if attempt > 0 {
- BooleanStrategy::ShiftedOperands
- } else {
- BooleanStrategy::RefinedTolerance
- });
- event.translation_mm = Vec3::new(j[0], j[1], j[2]).len() * (size * 0.01);
- event.tolerance_mm = tol;
- record(event);
- }
- return Ok(Some(body));
- }
- last = if unfused(&body) {
- "the bodies touch along faces that could not be fused".into()
- } else {
- format!("implausible result volume {v:.4}")
- };
- }
- Err(e) => last = e.to_string(),
- },
- Err(e) => last = e.to_string(),
- }
- }
- if empty_votes >= 2 && op != BoolOp::Union {
- 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);
- }
- }
- last.push_str(&apart_failed);
- // Coincident faces defeat the B-rep boolean; bodies with only planar faces have an exact
- // polygon fallback.
- match planar.unwrap_or_else(|| crate::polybool::planar_boolean(a, b, op)) {
- Ok(Some(body)) => {
- let (ok, v) = check(&body);
- if ok {
- record(BooleanFallback::new(BooleanStrategy::PlanarFallback));
- return Ok(Some(body));
- }
- last = format!("planar fallback gave an implausible volume {v:.4}");
- }
- Ok(None) => {
- record(BooleanFallback::new(BooleanStrategy::PlanarFallback));
+/// The union of bodies when no two of them meet or touch, as one body of several pieces (see
+/// [`join_apart`]); `None` when fewer than two are given, one is a mesh, or two of them are not
+/// apart (their exact boxes, grown by the bodies' tolerances, overlap).
+pub fn union_apart(bodies: &[Body]) -> Result<Option<Body>> {
+ crate::profile::timed(crate::profile::Kind::Boolean, || {
+ if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) {
return Ok(None);
}
- Err(e) => last = format!("{last}; {e}"),
- }
- // Prisms along one direction that end at different levels (a barrel joined between two
- // faces of a wider part, its ends flush with them) were left to the B-rep boolean, which
- // the coincident ends defeat, with no room to push them apart (the part goes on past
- // them). In 2D they join exactly: asked before the tool is moved.
- if let Some(Ok(Some(body))) = prism_result(a, b, op, size, &counts, crate::prism::prism_union_between_caps) {
- let (ok, v) = check(&body);
- if ok {
- return Ok(Some(body));
- }
- last = format!("{last}; the prisms joined in 2D gave an implausible volume {v:.4}");
- }
- // Last resort: nudge the tool by a micron-scale screw motion (turned 2e-6 rad about a
- // skew axis and moved 2e-6 of the size), which breaks tangencies and seams lying exactly on
- // the other body. The result moves by no more than that.
- if !APART.with(|c| c.get()) {
- APART.with(|c| c.set(true));
- let c = b.solid.vertex_iter().fold(Vec3::ZERO, |acc, v| acc + from_p3(v.point())) * (1.0 / b.solid.vertex_iter().count().max(1) as f64);
- let translation = |screw: usize| SCREWS.get(screw).map_or(Vec3::ZERO, |s| Vec3::new(s.0[0], s.0[1], s.0[2]) * (size * 2e-6));
- let nudge = |screw: usize, sign: f64| {
- let axis = SCREWS.get(screw).map_or(Vec3::Z, |s| Vec3::new(s.1[0], s.1[1], s.1[2]));
- capture_boolean_diagnostics(|| {
- transform(b, translation(screw) * sign, c, axis, 2e-6 * sign).and_then(|nb| Ok(boolean(a, &nb, op)?.map(|r| nudged(r, &nb, &counts))))
- })
- };
- let mut used = 0;
- let (mut r, mut diagnostics) = nudge(used, 1.0);
- // A nudge that pushes a face into a curved face it only touched (a cut whose end lies
- // tangent to a round side) leaves a sliver of that face behind, a fraction of a
- // millimetre wide, which later features (a shell, a fillet) can't work with. The
- // opposite nudge parts them instead. It is tried when this one failed or left more
- // slivers than the operands brought (a thin wall or a small round is no reason to run
- // another boolean), and taken when it works with fewer; an empty result stays as it is.
- let slivers = match &r {
- Ok(Some(body)) if check(body).0 => Some(sliver_faces(body, size)),
- _ => None,
- };
- let made = slivers.is_none_or(|n| n > 0 && n > sliver_faces(a, size).saturating_add(sliver_faces(b, size)));
- if !matches!(r, Ok(None)) && made {
- let (r2, diagnostics2) = nudge(used, -1.0);
- if let Ok(Some(body)) = &r2
- && slivers.is_none_or(|n| sliver_faces(body, size) < n)
- && check(body).0
- {
- (r, diagnostics) = (r2, diagnostics2);
- }
- }
- // Neither way worked: the screw can turn the tool along a seam it lies in (a loft
- // standing in the rim of a shelled case with its ends in the wall's inner face, #1490).
- // The other screws are tried in turn, and the first result that checks is taken.
- let works = |r: &Result<Option<Body>>| match r {
- Ok(None) => true,
- Ok(Some(body)) => check(body).0,
- Err(_) => false,
- };
- if !works(&r) {
- 'screws: for screw in 1..SCREWS.len() {
- for sign in [1.0, -1.0] {
- let (r2, diagnostics2) = nudge(screw, sign);
- if matches!(&r2, Ok(Some(body)) if check(body).0) {
- (r, diagnostics, used) = (r2, diagnostics2, screw);
- break 'screws;
- }
- }
- }
- }
- let translation = translation(used);
- APART.with(|c| c.set(false));
- match r {
- Ok(Some(body)) => {
- let (ok, v) = check(&body);
- // Measured finely too: a face the boolean left a hair wide, its loops a hair
- // apart, can mesh as its whole plane at a fine step though it meshed as a sliver
- // at the check's (#1360: an annulus cut flush with a hole's wall came out 21000
- // mm³ larger than the part it was cut from, a square plane across it).
- let fine_ok = ok && crate::measure(&body).is_ok_and(|m| plausible(m.volume, op, va, vb, slack));
- if ok && !fine_ok {
- last = format!("{last}; the nudged tool gave a solid whose faces mesh inconsistently");
- } else if ok {
- merge(diagnostics);
- let mut event = BooleanFallback::new(BooleanStrategy::ToolNudge);
- event.translation_mm = translation.len();
- event.rotation_rad = 2e-6;
- record(event);
- return Ok(Some(body));
- } else {
- last = format!("{last}; the nudged tool gave an implausible volume {v:.4}");
- }
- }
- Ok(None) => {
- merge(diagnostics);
- let mut event = BooleanFallback::new(BooleanStrategy::ToolNudge);
- event.translation_mm = translation.len();
- event.rotation_rad = 2e-6;
- record(event);
- return Ok(None);
- }
- Err(e) => last = format!("{last}; nudged: {e}"),
- }
- }
- // A join whose coincident planar faces cannot be pushed apart because the neighbours of one of them curve (a flange
- // flush with the end of a lofted tube): the faces are grown instead, and what the growth leaves beyond the plane is cut
- // off by editing the faces. After every route above, the nudge included, has failed, so that a join any of them takes
- // stays as it was.
- if op == BoolOp::Union && !APART.with(|c| c.get()) {
- APART.with(|c| c.set(true));
- let (r, diagnostics) = capture_boolean_diagnostics(|| crate::coplanar::boolean_grown(a, b, op));
- APART.with(|c| c.set(false));
- match r {
- Some(Ok(Some(body))) => {
- let (ok, v) = check(&body);
- if ok {
- merge(diagnostics);
- let mut event = BooleanFallback::new(BooleanStrategy::CoplanarSeparation);
- event.face_shift_mm = size * 0.0137;
- record(event);
- return Ok(Some(body));
+ let mut boxes = Vec::with_capacity(bodies.len());
+ for b in bodies {
+ boxes.push(b.exact_bounds()?.inflated(2.0 * b.record().tolerance));
+ }
+ // Sweep along x: only boxes whose x ranges overlap are compared.
+ let mut order: Vec<usize> = (0..boxes.len()).collect();
+ order.sort_by(|&i, &j| boxes.get(i).map(|b| b.min.x).unwrap_or(0.0).total_cmp(&boxes.get(j).map(|b| b.min.x).unwrap_or(0.0)));
+ for (k, &i) in order.iter().enumerate() {
+ let Some(a) = boxes.get(i) else { continue };
+ for &j in order.iter().skip(k + 1) {
+ let Some(b) = boxes.get(j) else { continue };
+ if b.min.x > a.max.x {
+ break;
+ }
+ if a.meets(b) {
+ return Ok(None);
}
- last = format!("{last}; faces grown apart gave an implausible volume {v:.4}");
}
- Some(Err(e)) => last = format!("{last}; {e}"),
- Some(Ok(None)) | None => {}
- }
- }
- // The tries at the meeting region's scale come last, after every strategy that answered
- // before them, so a result any of those gave is kept as it was.
- if let Some(body) = fine(&mut last) {
- return Ok(Some(body));
- }
- // An intersection keeps what lies in both bodies: when the sampled answer keeps one of them
- // whole and is contradicted by facets that cross well past their faceting error, keeping it
- // would keep exactly what the intersection was asked to trim (#3244: teeth standing 0.27 mm
- // out of a trimming cylinder came back untrimmed). It fails instead, and the model is kept.
- // An empty answer stays reported as unverified: the clearance checks measure it another way.
- let deep = 2.0 * 3.0 * tol_m;
- if op == BoolOp::Intersect
- && matches!(doubted, Some(Some(_)))
- && let (Some(ma), Some(mb)) = &meshes
- && ma.crosses(mb, deep)
- {
- return Err(KernelError::Failed(format!(
- "boolean {op:?}: the bodies pass through each other by more than {deep:.3e} mm where they could not be intersected; {last}"
- )));
- }
- match doubted {
- Some(r) => {
- let mut event = BooleanFallback::new(BooleanStrategy::UnverifiedShortcut);
- event.tolerance_mm = 3.0 * tol_m;
- record(event);
- Ok(r)
- }
- None => Err(KernelError::Failed(format!("boolean {op:?}: {last}"))),
- }
-}
-
-/// `a` cut by `b` with the walls of `b` that only touch `a` pushed outward (see
-/// [`crate::touching_walls`]), at each of the general boolean's tolerances by a little more than
-/// it (at least `by`, past the sag of `target`, the mesh of `a`): the first result that checks
-/// and whose faces lie on none of the pushed walls. The pushed tool keeps `b`'s order, so the
-/// history holds for `b`.
-#[allow(clippy::too_many_arguments)]
-fn pushed_walls_cut(
- a: &Body,
- b: &Body,
- target: &solidcraft_geom::Mesh,
- by: f64,
- size: f64,
- keep: &[Vec<Vec3>],
- counts: &[(usize, usize)],
- check: &dyn Fn(&Body) -> (bool, f64),
-) -> Option<Body> {
- let inside = target.inside_index();
- for k in [2e-3, 5e-4] {
- // Pushed past what the boolean takes for touching, and past the mesh's sag.
- let tol = (size * k).max(1e-5);
- let Some(pushed) = crate::touching_walls::pushed_tool(b, &inside, (2.5 * tol).max(by)) else { continue };
- let Ok((s, h)) = truck_boolean(a, &pushed.tool, BoolOp::Cut, None, tol) else { continue };
- if s.boundaries().is_empty() || s.face_iter().next().is_none() {
- continue;
- }
- let Ok(body) = guard("boolean result", || recorded::truck_result(s, h, size, keep, counts)) else { continue };
- if pushed.untouched(&body) && check(&body).0 {
- return Some(body);
- }
- }
- None
-}
-
-/// The screw motions a tool is nudged by as a last resort: (direction of the move, axis of the
-/// turn), each tried both ways. The first is the one every nudge used before #1490; the others
-/// are asked only when it fails both ways.
-const SCREWS: [([f64; 3], [f64; 3]); 3] =
- [([0.61, -0.37, 0.71], [0.27, 0.83, -0.49]), ([-0.42, 0.68, 0.6], [0.77, -0.18, 0.61]), ([0.31, 0.52, -0.79], [-0.58, 0.41, 0.70])];
-
-/// Faces of `b` narrower than 1/200 of `size` (twice their area over their boundary's
-/// length): the slivers a nudged tool leaves where it was pushed into a face it touched.
-fn sliver_faces(b: &Body, size: f64) -> usize {
- use std::collections::HashMap;
- let Ok(m) = b.mesh(&crate::MeshTolerance::chord((size * 1e-3).max(1e-4))) else { return usize::MAX };
- let q = (size * 1e-7).max(1e-12);
- let key = |p: Vec3| ((p.x / q).round() as i64, (p.y / q).round() as i64, (p.z / q).round() as i64);
- // Per face: its area, and how many of its triangles use each mesh edge (its boundary once).
- let mut area: HashMap<u32, f64> = HashMap::new();
- let mut sides: HashMap<(u32, (i64, i64, i64), (i64, i64, i64)), (u32, f64)> = HashMap::new();
- for (t, f) in m.triangles.iter().zip(&m.tri_face) {
- let Some([a, b, c]) = m.tri(t) else { continue };
- *area.entry(*f).or_default() += (b - a).cross(c - a).len() * 0.5;
- for (p, r) in [(a, b), (b, c), (c, a)] {
- let (kp, kr) = (key(p), key(r));
- let k = if kp <= kr { (*f, kp, kr) } else { (*f, kr, kp) };
- sides.entry(k).or_insert((0, p.dist(r))).0 += 1;
- }
- }
- let mut boundary: HashMap<u32, f64> = HashMap::new();
- for ((f, _, _), (n, len)) in &sides {
- if *n == 1 {
- *boundary.entry(*f).or_default() += len;
- }
- }
- area.iter().filter(|(f, a)| boundary.get(f).is_some_and(|l| *l > 0.0 && 2.0 * **a / l < size * 5e-3)).count()
-}
-
-/// `r`, a boolean of the target and `nb` (the tool nudged), with its history over the target and
-/// the tool itself (the nudge keeps every face and edge).
-pub(crate) fn nudged(r: Body, nb: &Body, counts: &[(usize, usize)]) -> Body {
- let h = recorded::through(&r, 1, nb.history());
- r.with_checked_history(h, counts)
-}
-
-/// What truck's boolean makes of `a` and `b`: the solid, and its history in our terms (see
-/// [`recorded::shapeops`]). On copies of the operands moved by `shift` (when given; the result
-/// is moved back), which changes the rays the boolean classifies faces by. Copies (and moved
-/// 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 {
- sa = mt::builder::translated(&sa, shift);
- sb = mt::builder::translated(&sb, shift);
}
- let tool_edges = (op == BoolOp::Cut).then(|| record::edge_origins(&sb, 1));
- // A body that keeps its meshes is meshed once for all its booleans at this tolerance.
- let meshed = shift.is_none().then(|| a.boolean_meshes(tol)).flatten();
- let and = |sa: &Solid, sb: &Solid| match &meshed {
- Some(m) => truck_shapeops::and_with_history_meshed(sa, m, sb, tol),
- None => truck_shapeops::and_with_history(sa, sb, tol),
- };
- let res = match op {
- BoolOp::Union => truck_shapeops::or_with_history(&sa, &sb, tol),
- BoolOp::Cut => {
- sb.not();
- and(&sa, &sb)
- }
- BoolOp::Intersect => and(&sa, &sb),
- };
- let (s, h) = res.ok_or_else(|| KernelError::Failed("no result".into()))?;
- let h = h.and_then(|h| recorded::shapeops(&h, &sb, tool_edges.as_ref()));
- Ok((if let Some(shift) = shift { mt::builder::translated(&s, -shift) } else { s }, h))
+ join_apart(bodies)
})
}
-/// A boolean of `a` and `b` given as their pieces (`la`, `lb`); the result's pieces in one body.
-pub(crate) fn by_lumps(a: &Body, b: &Body, la: Vec<Body>, lb: Vec<Body>, op: BoolOp) -> Result<Option<Body>> {
- let boxes_meet = |x: &Body, y: &Body| -> bool {
- let (Ok(mx), Ok(my)) = (x.mesh(&crate::MeshTolerance::chord(x.size() * 0.05 + 1e-3)), y.mesh(&crate::MeshTolerance::chord(y.size() * 0.05 + 1e-3))) else { return true };
- let (bx, by) = (mx.bounds(), my.bounds());
- let g = (x.size() + y.size()) * 0.01;
- bx.min.x <= by.max.x + g
- && by.min.x <= bx.max.x + g
- && bx.min.y <= by.max.y + g
- && by.min.y <= bx.max.y + g
- && bx.min.z <= by.max.z + g
- && by.min.z <= bx.max.z + g
- };
- // Each piece with its history over [a, b] (a piece's faces and edges are its body's own).
- let traced = |pieces: Vec<Body>, whole: &Body, operand: usize| -> Vec<Traced> {
- let histories = recorded::parts_of(&pieces, whole);
- pieces.into_iter().zip(histories).map(|(p, h)| (p, recorded::placed(h, operand, 2))).collect()
- };
- let (la, lb) = (traced(la, a, 0), traced(lb, b, 1));
- let pair = |(x, hx): &Traced, (y, hy): &Traced, op: BoolOp| -> Result<Option<Traced>> {
- Ok(boolean(x, y, op)?.map(|r| {
- let h = recorded::of_pair(&r, hx, hy);
- (r, h)
- }))
- };
- let mut out: Vec<Traced> = Vec::new();
- match op {
- BoolOp::Cut => {
- for x in la {
- let mut cur = Some(x);
- for y in &lb {
- cur = match cur {
- Some(c) if boxes_meet(&c.0, &y.0) => pair(&c, y, BoolOp::Cut)?,
- other => other,
- };
- }
- out.extend(cur);
- }
- }
- BoolOp::Intersect => {
- for x in &la {
- for y in &lb {
- if boxes_meet(&x.0, &y.0)
- && let Some(r) = pair(x, y, BoolOp::Intersect)?
- {
- out.push(r);
- }
- }
- }
- }
- BoolOp::Union => {
- out = la;
- for y in lb {
- let mut cur = y;
- let mut rest = Vec::new();
- for x in out {
- if boxes_meet(&x.0, &cur.0) {
- match pair(&x, &cur, BoolOp::Union)? {
- Some(u) if u.0.solid.boundaries().len() == 1 => cur = u,
- _ => rest.push(x),
- }
- } else {
- rest.push(x);
- }
- }
- rest.push(cur);
- out = rest;
- }
- }
- }
- recorded::join(out, &record::counts(&[a, b]))
-}
-
-/// Bodies whose bounding boxes are clearly apart, as one body of several pieces, without any
-/// intersection work (many identical pattern tools, #261). `None` when any two may meet, or a
-/// body is a mesh: the caller unions those the usual way.
-pub fn union_apart(bodies: &[Body]) -> Result<Option<Body>> {
- crate::profile::timed(crate::profile::Kind::Boolean, || union_apart_untimed(bodies))
-}
-
-fn union_apart_untimed(bodies: &[Body]) -> Result<Option<Body>> {
- if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) {
- return Ok(None);
- }
- let mut boxes = Vec::with_capacity(bodies.len());
- for b in bodies {
- // A coarse mesh is enough: the chord tolerance bounds how far the true surface lies
- // outside it, and the box grows by twice that.
- let tol = (b.size() * 0.02).max(1e-3);
- let bb = b.mesh(&crate::MeshTolerance::chord(tol))?.bounds();
- if bb.is_empty() {
- return Ok(None);
- }
- boxes.push(bb.inflated(2.0 * tol));
- }
- // Sweep along x: only boxes whose x ranges overlap are compared.
- let mut order: Vec<usize> = (0..boxes.len()).collect();
- order.sort_by(|&i, &j| boxes.get(i).map(|b| b.min.x).unwrap_or(0.0).total_cmp(&boxes.get(j).map(|b| b.min.x).unwrap_or(0.0)));
- for (k, &i) in order.iter().enumerate() {
- let Some(a) = boxes.get(i) else { continue };
- for &j in order.iter().skip(k + 1) {
- let Some(b) = boxes.get(j) else { continue };
- if b.min.x > a.max.x {
- break;
- }
- if a.min.y <= b.max.y && b.min.y <= a.max.y && a.min.z <= b.max.z && b.min.z <= a.max.z {
- return Ok(None);
- }
- }
- }
- join_apart(bodies)
-}
-
/// Bodies the caller knows are apart (no two meet or touch), as one body of several pieces,
/// without any intersection work: [`union_apart`] without its check, for tools whose making
-/// shows they are apart (profiles apart in their sketch, extruded alike). `None` for fewer than
-/// two bodies or a mesh.
+/// shows they are apart. Each face and edge of the result is its piece's own (its history over
+/// `bodies`). `None` for fewer than two bodies or a mesh.
pub fn join_apart(bodies: &[Body]) -> Result<Option<Body>> {
- crate::profile::timed(crate::profile::Kind::Boolean, || join_apart_untimed(bodies))
-}
-
-fn join_apart_untimed(bodies: &[Body]) -> Result<Option<Body>> {
if bodies.len() < 2 || bodies.len() > 10_000 || bodies.iter().any(Body::is_mesh) {
return Ok(None);
}
- // The pieces stay as they are, side by side: each face and edge of the result is its piece's
- // own (the history over `bodies`).
- let Some(joined) = join_pieces(bodies.to_vec())? else { return Ok(None) };
- let operands: Vec<&Body> = bodies.iter().collect();
- let faces = bodies
- .iter()
- .enumerate()
- .flat_map(|(operand, b)| {
- (0..b.face_count()).map(move |face| (std::collections::BTreeSet::from([crate::history::FaceOrigin::Face { operand, face }]), true))
- })
- .collect();
- let mut edges = HashMap::new();
- for (operand, b) in bodies.iter().enumerate() {
- edges.extend(record::edge_origins(&b.solid, operand));
- }
- Ok(Some(record::traced(joined, &record::counts(&operands), Some(record::regions(faces)), Some(&edges))))
+ let (joined, part) = joined(bodies)?;
+ let counts: Vec<(usize, usize)> = bodies.iter().map(|b| (b.face_count(), b.edge_count())).collect();
+ let history = crate::history::of_part(&part, &counts);
+ Ok(Some(joined.with_checked_history(Some(history), &counts)))
}
-/// Bodies (apart from each other) as one body of several pieces.
+/// Bodies (apart from each other) as one body of several pieces, their face sources carried.
pub(crate) fn join_pieces(pieces: Vec<Body>) -> Result<Option<Body>> {
match pieces.len() {
0 => Ok(None),
1 => Ok(pieces.into_iter().next()),
- _ => {
- let shells: Vec<mt::Shell> = pieces.iter().flat_map(|p| p.solid.boundaries().clone()).collect();
- let solid = guard("pieces", || Solid::try_new(shells).map_err(|e| KernelError::Failed(e.to_string())))?;
- let protected = pieces.iter().any(|piece| piece.regularization_protected);
- Body::new(solid).map(|mut body| {
- body.regularization_protected = protected;
- Some(body)
- })
- }
+ _ => joined(&pieces).map(|(body, _)| Some(body)),
}
}
-/// Determinant of the linear part of a column-major 4x4 matrix: negative means the placement
-/// mirrors, which turns a solid inside out.
-fn det3(m: &[[f64; 4]; 4]) -> f64 {
- m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0])
- + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0])
-}
-
-/// Whether the linear part is a rigid motion (rotation or reflection: no scale or shear).
-pub(crate) fn rigid_placement(m: &[[f64; 4]; 4]) -> bool {
- let r = [Vec3::new(m[0][0], m[0][1], m[0][2]), Vec3::new(m[1][0], m[1][1], m[1][2]), Vec3::new(m[2][0], m[2][1], m[2][2])];
- (0..3).all(|i| (r[i].dot(r[i]) - 1.0).abs() < 1e-9) && r[0].dot(r[1]).abs() < 1e-9 && r[0].dot(r[2]).abs() < 1e-9 && r[1].dot(r[2]).abs() < 1e-9
+/// The records of `bodies` side by side, as one body, and where its items come from.
+fn joined(bodies: &[Body]) -> Result<(Body, part::Part)> {
+ let records: Vec<&solidcraft_geom::brep::Brep> = bodies.iter().map(Body::record).collect();
+ let part = part::compound(&records).map_err(|e| KernelError::Failed(format!("pieces: {e}")))?;
+ // Each face's source, numbered as `compound` numbers the inputs: one after another.
+ let sources: Vec<Option<crate::FaceSource>> = bodies
+ .iter()
+ .flat_map(|b| (0..b.face_count()).map(move |f| b.face_sources().and_then(|s| s.get(f)).cloned().flatten()))
+ .collect();
+ let mapped = bodies
+ .iter()
+ .any(|b| b.face_sources().is_some())
+ .then(|| std::sync::Arc::new(part.faces.iter().map(|&f| sources.get(f as usize).cloned().flatten()).collect::<Vec<_>>()));
+ let mut body = Body::from_record(part.brep.clone())?.with_face_sources(mapped);
+ body.regularization_protected = bodies.iter().any(|b| b.regularization_protected);
+ Ok((body, part))
}
-/// Affine transform by a column-major 4x4 matrix (rotations, translations, reflections).
+/// Affine transform by a column-major 4x4 matrix (rotations, translations, reflections,
+/// scalings). A rigid motion moves the record itself, every parameter and index as it was; any
+/// other matrix goes through SMLib's transform. Either way the result's faces and edges are
+/// the body's, in its history.
pub fn transform_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result<Body> {
- transform_matrix_keeping(body, m, false)
-}
-
-/// [`transform_matrix`] for showing a body where an assembly places it (world placement): the
-/// revolved faces stay turned the way the body has them instead of being searched again for
-/// every placed copy (#3044). A modelling operation keeps using [`transform_matrix`]: where a
-/// face wraps all the way round, the turn it finds depends on the copy's own coordinates, and
-/// booleans on the copy depend on that.
-pub fn place_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result<Body> {
- transform_matrix_keeping(body, m, body.phased)
-}
-
-fn transform_matrix_keeping(body: &Body, m: [[f64; 4]; 4], phased: bool) -> Result<Body> {
if m.iter().flatten().any(|x| !x.is_finite()) {
return Err(KernelError::Invalid("non-finite transform".into()));
}
- // A perspective row or a flattening (from a design file or a command's parameters) leaves
- // no solid: refused rather than built into faces that mesh to nonsense.
- let scale = (0..3).map(|c| Vec3::new(m[c][0], m[c][1], m[c][2]).len()).fold(0.0, f64::max);
- if m[0][3].abs() > 1e-12 || m[1][3].abs() > 1e-12 || m[2][3].abs() > 1e-12 || (m[3][3] - 1.0).abs() > 1e-12 {
- return Err(KernelError::Invalid("the transform is not affine: its last row must be 0, 0, 0, 1".into()));
- }
- if det3(&m).abs() <= 1e-12 * scale.powi(3) {
- return Err(KernelError::Invalid("the transform flattens the body: its linear part is singular".into()));
- }
if let Some(placed) = body.mesh_transformed(&m) {
- let history = crate::history::History::identity(&placed);
+ let history = History::identity(&placed);
return placed.with_history(history, &[body]);
}
- guard("transform", || {
- let mat = mt::Matrix4::new(
- m[0][0], m[0][1], m[0][2], m[0][3], m[1][0], m[1][1], m[1][2], m[1][3], m[2][0], m[2][1], m[2][2], m[2][3], m[3][0], m[3][1], m[3][2],
- m[3][3],
- );
- // An affine placement retains face order and appearance metadata. Its edges are the
- // body's by identity: a reflection turns the solid inside out, which walks each face's
- // edges the other way and so changes the edge order.
- let sources = body.transformed_sources(m)?;
- let (solid, copies) = placed_topology_mapped(&body.solid, mat)?;
- let mut rec = record::Rebuild::default();
- rec.pieces(&copies);
- for (copy, face) in solid.face_iter().zip(body.solid.face_iter()) {
- rec.whole(copy, face);
+ let sources = body.transformed_sources(m)?;
+ let placed = match Rigid::of_matrix(&m) {
+ Some(motion) => {
+ let moved = Body::from_record(body.record().moved(&motion))?;
+ let history = History::identity(&moved);
+ moved.with_history(history, &[body])?
}
- let (faces, edges) = rec.history(&solid, &[&body.solid]).unzip();
- let counts = record::solid_counts(&[&body.solid]);
- // A rigid placement leaves every face's mesh, and so the missing-face count, as it was;
- // a mirrored one turns the solid inside out. Either way the orientation is read from the
- // matrix instead of meshing the whole copy again.
- let placed = record::build_placed(
- solid,
- &counts,
- faces,
- edges.as_ref(),
- det3(&m) < 0.0,
- rigid_placement(&m).then_some(body.coarse_missing).flatten(),
- phased,
- )?;
- Ok(placed.with_color(body.color()).with_paint(body.paint().cloned()).with_face_sources(sources).inherit_regularization_protection(body))
- })
-}
-
-/// `source` moved by `matrix`, keeping its face and edge order (transforms report an identity
-/// [`crate::history::History`] on that basis). Built here rather than by generic topology
-/// builders: a STEP periodic face may traverse a seam edge twice, and those reject that wire
-/// while cloning even though placement preserves its topology.
-pub(crate) fn placed_topology(source: &Solid, matrix: mt::Matrix4) -> Result<Solid> {
- placed_topology_mapped(source, matrix).map(|(solid, _)| solid)
+ None => transformed(body, &m)?,
+ };
+ Ok(placed.with_color(body.color()).with_paint(body.paint().cloned()).with_face_sources(sources).inherit_regularization_protection(body))
}
-/// [`placed_topology`], with each edge of `source` (by identity) and its copy.
-fn placed_topology_mapped(source: &Solid, matrix: mt::Matrix4) -> Result<(Solid, HashMap<mt::EdgeID, mt::Edge>)> {
- use mt::{Transform, Transformed};
- let mut vertices = HashMap::new();
- let mut edges = HashMap::new();
- let mut shells = Vec::new();
- let mut face_count = 0usize;
- let mut edge_visits = 0usize;
- for shell in source.boundaries() {
- let mut faces = Vec::new();
- for face in shell {
- face_count = face_count.saturating_add(1);
- if face_count > 500_000 {
- return Err(KernelError::Invalid("placement exceeds face work limit".into()));
- }
- let mut wires = Vec::new();
- for wire in face.absolute_boundaries() {
- let mut mapped = Vec::new();
- for edge in wire {
- edge_visits = edge_visits.saturating_add(1);
- if edge_visits > 4_000_000 {
- return Err(KernelError::Invalid("placement exceeds edge work limit".into()));
- }
- if let std::collections::hash_map::Entry::Vacant(entry) = edges.entry(edge.id()) {
- for vertex in [edge.absolute_front(), edge.absolute_back()] {
- if let std::collections::hash_map::Entry::Vacant(entry) = vertices.entry(vertex.id()) {
- let point = matrix.transform_point(vertex.point());
- if !from_p3(point).is_finite() {
- return Err(KernelError::Invalid("placement produced nonfinite geometry".into()));
- }
- entry.insert(mt::Vertex::new(point));
- }
- }
- let front =
- vertices.get(&edge.absolute_front().id()).ok_or_else(|| KernelError::Failed("placement vertex missing".into()))?;
- let back = vertices.get(&edge.absolute_back().id()).ok_or_else(|| KernelError::Failed("placement vertex missing".into()))?;
- entry.insert(mt::Edge::new_unchecked(front, back, edge.curve().transformed(matrix)));
- }
- let copied = edges.get(&edge.id()).ok_or_else(|| KernelError::Failed("placement edge missing".into()))?;
- mapped.push(if edge.orientation() { copied.clone() } else { copied.inverse() });
- }
- wires.push(mt::Wire::from(mapped));
- }
- // Wire connectivity, seam sharing and orientation are copied exactly;
- // no new topology is introduced by this geometry-only operation.
- let mut copied = mt::Face::new_unchecked(wires, face.surface().transformed(matrix));
- if !face.orientation() {
- copied.invert();
- }
- faces.push(copied);
- }
- shells.push(mt::Shell::from(faces));
- }
- Ok((Solid::new_unchecked(shells), edges))
+/// `body` moved by a matrix that is not a rigid motion, in SMLib, its history from SMLib's tags.
+fn transformed(body: &Body, m: &[[f64; 4]; 4]) -> Result<Body> {
+ let failed = |what: &str, e: &dyn std::fmt::Display| KernelError::Failed(format!("SMLib transform: {what}: {e}"));
+ let (handle, order) = crate::native::smlib_body_ordered(body)?;
+ let moved = handle.tagged(0).map_err(|e| failed("tag", &e))?.transformed(m).map_err(|e| failed("operation", &e))?;
+ let (result, result_order) = crate::native::body_from_smlib_ordered(&moved)?;
+ let history = match (order, result_order) {
+ (Some(o), Some(r)) => moved.history().ok().and_then(|h| h.history(&[o], &r).ok()),
+ _ => None,
+ };
+ Ok(result.with_checked_history(history, &[(body.face_count(), body.edge_count())]))
}
-#[cfg(test)]
-#[test]
-fn affine_placement_keeps_body_and_face_paint_attached() {
- let paint = crate::Paint { opacity: 0.4, faces: vec![crate::FacePaint { face: 0, color: [0.8, 0.2, 0.1], opacity: 0.3 }] };
- let body = crate::box_solid(Vec3::ZERO, Vec3::new(10.0, 20.0, 30.0)).unwrap().with_color(Some([0.2, 0.6, 0.8])).with_paint(Some(paint.clone()));
- let source_faces = body.faces(0.01).unwrap();
- let transform = [[0.0, 2.0, 0.0, 0.0], [-1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 0.5, 0.0], [30.0, 40.0, 50.0, 1.0]];
- let placed = transform_matrix(&body, transform).unwrap();
- assert_eq!(placed.color(), body.color());
- assert_eq!(placed.paint(), Some(&paint));
- let faces = placed.faces(0.01).unwrap();
- for source in source_faces {
- let target = faces.iter().find(|f| f.index == source.index).unwrap();
- let p = source.centroid;
- assert!(target.centroid.dist(Vec3::new(30.0 - p.y, 40.0 + 2.0 * p.x, 50.0 + 0.5 * p.z)) < 1e-6);
- }
+/// [`transform_matrix`] for showing a body where an assembly places it (world placement).
+pub fn place_matrix(body: &Body, m: [[f64; 4]; 4]) -> Result<Body> {
+ transform_matrix(body, m)
}
/// Rigid transform: rotate about `axis` through `origin` by `angle` radians, then translate.
@@ -2374,25 +183,23 @@ pub fn transform(body: &Body, translate: Vec3, origin: Vec3, axis: Vec3, angle:
if !(translate.is_finite() && origin.is_finite() && angle.is_finite()) {
return Err(KernelError::Invalid("non-finite transform".into()));
}
- {
- // Same motion as a matrix: rotate about the line through `origin`, then translate.
- let ax = if angle.abs() > 1e-12 { axis.normalized().ok_or_else(|| KernelError::Invalid("rotation axis".into()))? } else { Vec3::Z };
- let (c, s) = (angle.cos(), angle.sin());
- let t = 1.0 - c;
- let r = [
- [t * ax.x * ax.x + c, t * ax.x * ax.y + s * ax.z, t * ax.x * ax.z - s * ax.y],
- [t * ax.x * ax.y - s * ax.z, t * ax.y * ax.y + c, t * ax.y * ax.z + s * ax.x],
- [t * ax.x * ax.z + s * ax.y, t * ax.y * ax.z - s * ax.x, t * ax.z * ax.z + c],
- ];
- let ro = Vec3::new(
- r[0][0] * origin.x + r[1][0] * origin.y + r[2][0] * origin.z,
- r[0][1] * origin.x + r[1][1] * origin.y + r[2][1] * origin.z,
- r[0][2] * origin.x + r[1][2] * origin.y + r[2][2] * origin.z,
- );
- let tr = origin - ro + translate;
- let m = [[r[0][0], r[0][1], r[0][2], 0.0], [r[1][0], r[1][1], r[1][2], 0.0], [r[2][0], r[2][1], r[2][2], 0.0], [tr.x, tr.y, tr.z, 1.0]];
- transform_matrix(body, m)
- }
+ // Same motion as a matrix: rotate about the line through `origin`, then translate.
+ let ax = if angle.abs() > 1e-12 { axis.normalized().ok_or_else(|| KernelError::Invalid("rotation axis".into()))? } else { Vec3::Z };
+ let (c, s) = (angle.cos(), angle.sin());
+ let t = 1.0 - c;
+ let r = [
+ [t * ax.x * ax.x + c, t * ax.x * ax.y + s * ax.z, t * ax.x * ax.z - s * ax.y],
+ [t * ax.x * ax.y - s * ax.z, t * ax.y * ax.y + c, t * ax.y * ax.z + s * ax.x],
+ [t * ax.x * ax.z + s * ax.y, t * ax.y * ax.z - s * ax.x, t * ax.z * ax.z + c],
+ ];
+ let ro = Vec3::new(
+ r[0][0] * origin.x + r[1][0] * origin.y + r[2][0] * origin.z,
+ r[0][1] * origin.x + r[1][1] * origin.y + r[2][1] * origin.z,
+ r[0][2] * origin.x + r[1][2] * origin.y + r[2][2] * origin.z,
+ );
+ let tr = origin - ro + translate;
+ let m = [[r[0][0], r[0][1], r[0][2], 0.0], [r[1][0], r[1][1], r[1][2], 0.0], [r[2][0], r[2][1], r[2][2], 0.0], [tr.x, tr.y, tr.z, 1.0]];
+ transform_matrix(body, m)
}
/// Split a body with a plane: the parts on the positive and the negative side of the plane
@@ -2412,98 +219,14 @@ pub fn split_by_plane(body: &Body, plane: &solidcraft_geom::Plane) -> Result<Vec
pub fn half_space(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result<(Option<Body>, Body)> {
// The box's own construction roles describe no face of the design: the cut face has none.
let tool = half_box(body, plane, positive)?.with_face_sources(None);
- let (part, report) = capture_boolean_diagnostics(|| boolean(body, &tool, BoolOp::Intersect));
- // Faces of the body lying in the plane coincide with the box's cap, which the boolean may
- // only take by nudging the box, by a share of its own size: the cut face then moves off the
- // plane, a different way for each part, and the parts lose the slab between (#1510). Moved
- // off the plane to the side the box leaves out, those faces change nothing of the part, and
- // the cap meets no face. Asked only when the boolean failed or nudged the box: a part made
- // without, its faces' names included, stays as it is.
- let nudged = report.events.iter().any(|e| e.strategy == BooleanStrategy::ToolNudge);
- if (part.is_err() || nudged)
- && let Some(moved) = off_plane(body, plane, positive)
- {
- let (exact, moved_report) = capture_boolean_diagnostics(|| boolean(&moved, &tool, BoolOp::Intersect));
- if let Ok(exact) = exact {
- merge(moved_report);
- // The part's history over [body, box], through the moved body (its faces are the body's).
- let hb = recorded::placed(recorded::through(&moved, 0, recorded::kept(body, 0, 1).as_ref()), 0, 2);
- let ht = recorded::placed(recorded::kept(&tool, 0, 1), 1, 2);
- let counts = record::counts(&[body, &tool]);
- let exact = exact.map(|r| {
- let h = recorded::of_pair(&r, &hb, &ht);
- r.with_checked_history(h, &counts)
- });
- return Ok((exact, tool));
- }
- }
- merge(report);
- Ok((part?, tool))
-}
-
-/// `body` with its planar faces lying in `plane` moved off it, a thousandth of the body's size,
-/// to the side a split's part on the `positive` side leaves out. `None` when no face lies there
-/// or moving them doesn't give a sound body.
-pub(crate) fn off_plane(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Option<Body> {
- let m = plane.normal().normalized()?;
- let keep = if positive { m } else { -m };
- let size = body.size();
- let tol = (size * 1e-7).max(1e-9);
- // Lying in the plane means in it, not within the boolean's tolerance of it: a face that close
- // but off it bounds a real sliver, which moving the face would take or add.
- let exact = (size * 1e-9).max(1e-12);
- let delta = size * 1e-3;
- let mut out: Option<Body> = None;
- for n in [keep, -keep] {
- let d = n.dot(plane.origin);
- // The faces `push_faces` takes for this plane (by their surface), which must all lie in
- // it: one only nearly parallel, its origin in the plane, would be moved where it isn't.
- let taken: Vec<&mt::Face> = body
- .solid
- .face_iter()
- .filter(|f| match f.oriented_surface() {
- mt::Surface::Plane(p) => {
- let q = p.normal();
- Vec3::new(q.x, q.y, q.z).normalized().is_some_and(|q| q.dot(n) > 1.0 - 1e-9)
- && (n.dot(from_p3(p.origin())) - d).abs() < tol * 10.0
- }
- _ => false,
- })
- .collect();
- if taken.is_empty() {
- continue;
- }
- // Its vertices and points along its edges (a disc has one vertex).
- let lies = |f: &mt::Face| {
- use mt::{BoundedCurve, ParametricCurve};
- let on = |p: mt::Point3| (n.dot(from_p3(p)) - d).abs() < exact;
- f.vertex_iter().all(|v| on(v.point()))
- && f.edge_iter().all(|e| {
- let c = e.curve();
- let (t0, t1) = c.range_tuple();
- [0.25, 0.5, 0.75].iter().all(|k| on(c.subs(t0 + (t1 - t0) * k)))
- })
- };
- if !taken.iter().all(|f| lies(f)) {
- return None;
- }
- // Along -keep: inwards for a face facing the kept side, outwards for one facing away.
- let shift = if n.dot(keep) > 0.0 { -delta } else { delta };
- let cur = out.as_ref().unwrap_or(body);
- out = Some(crate::coplanar::push_faces(cur, n, d, shift).ok().filter(|b| b.validity().is_empty())?);
- }
- out
+ Ok((boolean(body, &tool, BoolOp::Intersect)?, tool))
}
/// A box covering everything of `body` on one side of a plane, its start cap in the plane.
pub(crate) fn half_box(body: &Body, plane: &solidcraft_geom::Plane, positive: bool) -> Result<Body> {
body.require_brep("split")?;
- let size = body.size();
- let mut bb = solidcraft_geom::Aabb3::EMPTY;
- for v in body.solid.vertex_iter() {
- bb.add(crate::body::from_p3(v.point()));
- }
- let reach = (bb.diagonal() + plane.origin.dist(bb.center())) * 2.0 + size;
+ let bb = body.exact_bounds()?;
+ let reach = (bb.diagonal() + plane.origin.dist(bb.center())) * 2.0 + body.size();
let c = plane.to_local(bb.center());
let sq = solidcraft_geom::Region2 {
outer: solidcraft_geom::Loop2::polygon(&[
@@ -2518,14 +241,6 @@ pub(crate) fn half_box(body: &Body, plane: &solidcraft_geom::Plane, positive: bo
crate::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;
-
#[cfg(test)]
#[path = "placement_tests.rs"]
mod placement_tests;
diff --git a/crates/kernel/src/prism_fast_path_tests.rs b/crates/kernel/src/prism_fast_path_tests.rs
deleted file mode 100644
index 37231e0ac0..0000000000
--- a/crates/kernel/src/prism_fast_path_tests.rs
+++ /dev/null
@@ -1,59 +0,0 @@
-//! The prism fast path: `boolean_whole` asks the exact 2D prism route before it meshes both
-//! operands, so a plate and the tool through it are decided without a mesh of either.
-use super::*;
-use crate::{BoolOp, boolean, box_solid, cylinder, measure};
-use std::f64::consts::PI;
-
-/// A cylindrical tool through a plate: the exact prism route answers the pair, and the material
-/// it removes is the tool's own.
-#[test]
-fn a_hole_through_a_plate_removes_the_tool_volume() {
- let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).expect("plate");
- let tool = cylinder(Vec3::new(20.0, 15.0, -1.0), Vec3::Z, 5.0, 12.0).expect("tool");
- let cut = boolean(&plate, &tool, BoolOp::Cut).expect("cut").expect("a hole leaves material");
- let m = measure(&cut).expect("measure");
- let want = 40.0 * 30.0 * 10.0 - PI * 25.0 * 10.0;
- assert!((m.volume - want).abs() < want * 5e-3, "{} vs {want}", m.volume);
- assert!(cut.validity().is_empty(), "{:?}", cut.validity());
-}
-
-/// Boxes that stay apart: the union keeps both, whichever route decides it.
-#[test]
-fn bodies_that_stay_apart_join_into_one_body_with_both_lumps() {
- let a = box_solid(Vec3::ZERO, Vec3::new(10.0, 10.0, 10.0)).expect("a");
- let b = box_solid(Vec3::new(20.0, 0.0, 0.0), Vec3::new(30.0, 10.0, 10.0)).expect("b");
- let joined = boolean(&a, &b, BoolOp::Union).expect("union").expect("two boxes");
- assert!((measure(&joined).expect("measure").volume - 2000.0).abs() < 1e-6);
- assert_eq!(joined.lumps().expect("lumps").len(), 2);
-}
-
-/// A tool wholly inside its target leaves a closed void, not a through cut.
-#[test]
-fn a_tool_wholly_inside_leaves_a_closed_void() {
- let block = box_solid(Vec3::ZERO, Vec3::new(40.0, 40.0, 40.0)).expect("block");
- let inner = box_solid(Vec3::new(15.0, 15.0, 15.0), Vec3::new(25.0, 25.0, 25.0)).expect("inner");
- let cut = boolean(&block, &inner, BoolOp::Cut).expect("cut").expect("a void leaves material");
- assert!((measure(&cut).expect("measure").volume - 63000.0).abs() < 1e-6);
- assert!(cut.validity().is_empty(), "{:?}", cut.validity());
-}
-
-/// A tool that misses its target, in section or along the extrusion, leaves it as it is: the
-/// sampled shortcut answers that by reusing the operand itself, and the 2D route must not
-/// rebuild it into a look-alike solid on the way past - an untouched body in a timeline has to
-/// stay the very same body.
-#[test]
-fn a_cut_that_changes_nothing_keeps_the_original_body() {
- let plate = box_solid(Vec3::ZERO, Vec3::new(40.0, 30.0, 10.0)).expect("plate");
- let past_the_end = box_solid(Vec3::new(200.0, 200.0, -5.0), Vec3::new(210.0, 210.0, 20.0)).expect("tool");
- assert!(
- boolean(&plate, &past_the_end, BoolOp::Cut).expect("cut").expect("material stays").same(&plate),
- "a tool clear of the plate must leave the very same body"
- );
- let inside_the_height = box_solid(Vec3::new(200.0, 200.0, 5.0), Vec3::new(210.0, 210.0, 20.0)).expect("tool");
- assert!(
- boolean(&plate, &inside_the_height, BoolOp::Cut).expect("cut").expect("material stays").same(&plate),
- "a tool that only overlaps the plate's height must leave the very same body"
- );
- let covers_it = box_solid(Vec3::new(-10.0, -10.0, -10.0), Vec3::new(50.0, 40.0, 20.0)).expect("tool");
- assert!(boolean(&plate, &covers_it, BoolOp::Cut).expect("cut").is_none(), "a tool over the whole plate removes it");
-}
diff --git a/crates/smlib/src/ffi.rs b/crates/smlib/src/ffi.rs
index b4da384703..17c1f66e84 100644
--- a/crates/smlib/src/ffi.rs
+++ b/crates/smlib/src/ffi.rs
@@ -35,6 +35,7 @@ unsafe extern "C" {
pub fn smlib_brep_write(brep: *const RawBrep, path: *const c_char, ascii: i32) -> i32;
pub fn smlib_brep_free(brep: *mut RawBrep);
pub fn smlib_brep_copy(brep: *const RawBrep, out: *mut *mut RawBrep) -> i32;
+ pub fn smlib_brep_transform(brep: *const RawBrep, matrix: *const [f64; 4], out: *mut *mut RawBrep) -> i32;
pub fn smlib_make_box(origin: *const f64, size: *const f64, out: *mut *mut RawBrep) -> i32;
pub fn smlib_brep_volume(brep: *const RawBrep, relative_accuracy: f64, out: *mut f64) -> i32;
pub fn smlib_brep_counts(brep: *const RawBrep, out: *mut i64) -> i32;
@@ -119,6 +120,9 @@ mod calls {
pub fn copy(b: &Handle) -> Result<Handle, i32> {
new_brep(|out| unsafe { smlib_brep_copy(b.raw(), out) })
}
+ pub fn transform(b: &Handle, matrix: &[[f64; 4]; 4]) -> Result<Handle, i32> {
+ new_brep(|out| unsafe { smlib_brep_transform(b.raw(), matrix.as_ptr(), out) })
+ }
pub fn make_box(origin: &[f64; 3], size: &[f64; 3]) -> Result<Handle, i32> {
new_brep(|out| unsafe { smlib_make_box(origin.as_ptr(), size.as_ptr(), out) })
}
@@ -166,6 +170,9 @@ mod calls {
pub fn copy(_: &Handle) -> Result<Handle, i32> {
Err(NOT_BUILT)
}
+ pub fn transform(_: &Handle, _: &[[f64; 4]; 4]) -> Result<Handle, i32> {
+ Err(NOT_BUILT)
+ }
pub fn make_box(_: &[f64; 3], _: &[f64; 3]) -> Result<Handle, i32> {
Err(NOT_BUILT)
}
diff --git a/crates/smlib/src/lib.rs b/crates/smlib/src/lib.rs
index 8f4ac1082e..b2903e2ca1 100644
--- a/crates/smlib/src/lib.rs
+++ b/crates/smlib/src/lib.rs
@@ -197,6 +197,14 @@ impl Brep {
ffi::copy(&self.0).map(Brep).map_err(error)
}
+ /// This body moved by the affine `matrix` (column-major: columns 0–2 the images of x, y and
+ /// z, column 3 the translation), as SMLib's `SmBrep::Transform` takes a matrix: reflections
+ /// mirror it, a non-uniform scale or a shear turns its geometry into NURBS, tolerances scale
+ /// with it.
+ pub fn transformed(&self, matrix: &[[f64; 4]; 4]) -> Result<Brep> {
+ ffi::transform(&self.0, matrix).map(Brep).map_err(error)
+ }
+
/// The enclosed volume (mm³) at `relative_accuracy` (SMLib clamps it to [1e-8, 1e-1]).
pub fn volume(&self, relative_accuracy: f64) -> Result<f64> {
ffi::volume(&self.0, relative_accuracy).map_err(error)