A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server
//! Ultra-fast, zero-HashMap, tolerance-guided BVH-localized CSG boolean engine
//! with deterministic repair pipeline and perturbation retry.
//!
//! Algorithm (inspired by Zhou et al. 2016 "Mesh Arrangements for Solid Geometry"):
//! 1. Normalize operands into a shared unit cube around their combined AABB center so all
//! floating-point tolerances stay scale-invariant across arbitrary part dimensions.
//! 2. Build lightweight flat binary AABB-BVHs over triangles of A and B (~20-50 us).
//! 3. Partition A into A_hit (triangles whose AABB overlaps at least one triangle of B)
//! and A_far (guaranteed non-intersecting!). Do the same for B -> B_hit, B_far.
//! 4. Classify A_far against solid B (and B_far against solid A) in O(log N) per triangle
//! using BVH-accelerated ray-parity / Generalized Winding Number (no splitting ever!).
//! 5. Subdivide ONLY each triangle `ta` in A_hit against ONLY the ~2-8 triangles `tb` of B
//! that actually overlap `ta`'s AABB (and vice versa for B_hit) using stack-inline
//! `SmallVec<[Vec3; 8]>` polygons — zero global BSP fragmentation, zero String clones!
//! 6. Classify each tiny subdivided fragment via BVH winding number (with coplanar
//! normal tie-breaking when a fragment lies on a face of the opposing mesh).
//! 7. Sort-based spatial vertex welding + deterministic opposing-tri cancellation +
//! spatial-grid T-junction elimination + seam snapping + folded-flap pruning.
//! 8. Deterministic perturbation retry (2 nudged `(shift, scale)` attempts) on grazing curved seams,
//! un-normalizing the final mesh back to world coordinates.
use crate::math::{Aabb, Vec3};
use crate::mesh::{Face, LineageId, PolyMesh};
use smallvec::SmallVec;
use std::collections::HashSet;
use std::f64::consts::PI;
const PLANE_EPS: f64 = 1e-7;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BoolOp {
Union,
Difference,
Intersect,
}
#[derive(Debug, Clone, Copy)]
struct Tri {
v: [Vec3; 3],
normal: Vec3,
w: f64,
aabb: Aabb,
centroid: Vec3,
tag_idx: u32,
lineage: LineageId,
mat_id: u16,
}
impl Tri {
#[inline]
fn from_verts(v0: Vec3, v1: Vec3, v2: Vec3, tag_idx: u32, lineage: LineageId, mat_id: u16) -> Option<Self> {
let n = (v1 - v0).cross(v2 - v0);
let l = n.len();
if l < 1e-13 {
return None;
}
let normal = n / l;
let w = normal.dot(v0);
let aabb = Aabb {
min: v0.min(v1).min(v2),
max: v0.max(v1).max(v2),
};
let centroid = (v0 + v1 + v2) * (1.0 / 3.0);
Some(Self {
v: [v0, v1, v2],
normal,
w,
aabb,
centroid,
tag_idx,
lineage,
mat_id,
})
}
/// Scale-invariant triangle builder: normalizes edge lengths before cross product so valid
/// micro-scale or macro-scale triangles are never dropped by an absolute area threshold.
#[inline]
fn from_verts_rel(v0: Vec3, v1: Vec3, v2: Vec3, tag_idx: u32, lineage: LineageId, mat_id: u16) -> Option<Self> {
let e1 = v1 - v0;
let e2 = v2 - v0;
let max_c = e1.x.abs().max(e1.y.abs()).max(e1.z.abs())
.max(e2.x.abs()).max(e2.y.abs()).max(e2.z.abs());
if !max_c.is_finite() || max_c <= 0.0 {
return None;
}
let inv = 1.0 / max_c;
let n = (e1 * inv).cross(e2 * inv);
let l = n.len();
if !l.is_finite() || l < 1e-13 {
return None;
}
let normal = n / l;
let w = normal.dot(v0);
let aabb = Aabb {
min: v0.min(v1).min(v2),
max: v0.max(v1).max(v2),
};
let centroid = (v0 + v1 + v2) * (1.0 / 3.0);
Some(Self {
v: [v0, v1, v2],
normal,
w,
aabb,
centroid,
tag_idx,
lineage,
mat_id,
})
}
}
/// Flat array-backed binary AABB-BVH (64B node = 1 cache line) for O(log N) overlap & ray queries.
struct BvhNode {
aabb: Aabb,
left: u32, // if count > 0, start index into `indices`; else left child node index
right: u32, // right child node index (unused for leaf)
count: u32, // > 0 => leaf
}
struct TriBvh {
nodes: Vec<BvhNode>,
indices: Vec<u32>,
root_aabb: Aabb,
uniform_ray_pad: bool,
}
impl TriBvh {
fn build(tris: &[Tri]) -> Self {
let n = tris.len();
if n == 0 {
return Self {
nodes: Vec::new(),
indices: Vec::new(),
root_aabb: Aabb::empty(),
uniform_ray_pad: true,
};
}
let mut indices: Vec<u32> = (0..n as u32).collect();
let mut nodes = Vec::with_capacity(n / 2 + 2);
Self::build_rec(tris, &mut indices, &mut nodes, 0, n);
let root_aabb = nodes[0].aabb;
let uniform_ray_pad = root_aabb.size().len_sq() <= 100.0;
Self {
nodes,
indices,
root_aabb,
uniform_ray_pad,
}
}
fn build_rec(tris: &[Tri], indices: &mut [u32], nodes: &mut Vec<BvhNode>, start: usize, end: usize) -> u32 {
let mut aabb = Aabb::empty();
let mut cmin = Vec3::new(f64::INFINITY, f64::INFINITY, f64::INFINITY);
let mut cmax = Vec3::new(f64::NEG_INFINITY, f64::NEG_INFINITY, f64::NEG_INFINITY);
for &idx in &indices[start..end] {
let t = &tris[idx as usize];
aabb.min = aabb.min.min(t.aabb.min);
aabb.max = aabb.max.max(t.aabb.max);
cmin = cmin.min(t.centroid);
cmax = cmax.max(t.centroid);
}
let count = end - start;
let node_idx = nodes.len() as u32;
nodes.push(BvhNode {
aabb,
left: start as u32,
right: 0,
count: count as u32,
});
if count <= 8 {
return node_idx;
}
let ext = cmax - cmin;
let axis = if ext.x >= ext.y && ext.x >= ext.z {
0
} else if ext.y >= ext.z {
1
} else {
2
};
let mid = start + count / 2;
indices[start..end].select_nth_unstable_by(mid - start, |&a, &b| {
let ca = tris[a as usize].centroid;
let cb = tris[b as usize].centroid;
let (va, vb) = match axis {
0 => (ca.x, cb.x),
1 => (ca.y, cb.y),
_ => (ca.z, cb.z),
};
va.total_cmp(&vb).then_with(|| a.cmp(&b))
});
let left = Self::build_rec(tris, indices, nodes, start, mid);
let right = Self::build_rec(tris, indices, nodes, mid, end);
nodes[node_idx as usize].left = left;
nodes[node_idx as usize].right = right;
nodes[node_idx as usize].count = 0;
node_idx
}
/// Collect all triangle indices whose AABB overlaps `query` (within `eps`).
fn query_aabb(&self, query: &Aabb, eps: f64, out: &mut Vec<u32>) {
out.clear();
if self.nodes.is_empty() {
return;
}
let qmin = query.min - Vec3::splat(eps);
let qmax = query.max + Vec3::splat(eps);
let rb = &self.root_aabb;
if rb.max.x < qmin.x || rb.min.x > qmax.x
|| rb.max.y < qmin.y || rb.min.y > qmax.y
|| rb.max.z < qmin.z || rb.min.z > qmax.z
{
return;
}
let mut stack: SmallVec<[u32; 64]> = SmallVec::new();
stack.push(0);
while let Some(ni) = stack.pop() {
let node = &self.nodes[ni as usize];
let nb = &node.aabb;
if nb.max.x < qmin.x || nb.min.x > qmax.x
|| nb.max.y < qmin.y || nb.min.y > qmax.y
|| nb.max.z < qmin.z || nb.min.z > qmax.z
{
continue;
}
if node.count > 0 {
let s = node.left as usize;
let e = s + node.count as usize;
out.extend_from_slice(&self.indices[s..e]);
} else {
stack.push(node.left);
stack.push(node.right);
}
}
}
/// Fast O(log N) exact ray-parity inside test along a non-axis-aligned golden-ratio ray.
/// If ray 1 grazes an edge/vertex, tries a second independent irrational ray in O(log N)
/// before falling back to exact Generalized Winding Number.
fn point_inside(&self, tris: &[Tri], p: Vec3) -> bool {
if self.nodes.is_empty() || !self.root_aabb.overlaps(&Aabb { min: p, max: p }, 1e-6) {
return false;
}
const RAYS: [(Vec3, Vec3); 2] = [
(
Vec3 { x: 0.7310552815, y: 0.5178911243, z: 0.4442371891 },
Vec3 { x: 1.0 / 0.7310552815, y: 1.0 / 0.5178911243, z: 1.0 / 0.4442371891 },
),
(
Vec3 { x: 0.3917284512, y: 0.8129471638, z: 0.4309184726 },
Vec3 { x: 1.0 / 0.3917284512, y: 1.0 / 0.8129471638, z: 1.0 / 0.4309184726 },
),
];
let mut stack: SmallVec<[u32; 64]> = SmallVec::new();
if self.uniform_ray_pad {
// Fast branchless uniform-pad path (99.9% of normalized CSG calls): pre-shift `p` once!
let p_lo = p + Vec3::splat(1e-4);
let p_hi = p - Vec3::splat(1e-4);
for &(ray_dir, inv_dir) in &RAYS {
let mut hits = 0u32;
let mut grazing = false;
stack.clear();
stack.push(0);
while let Some(ni) = stack.pop() {
let node = &self.nodes[ni as usize];
if !ray_hits_aabb_preshifted(p_lo, p_hi, inv_dir, &node.aabb) {
continue;
}
if node.count > 0 {
let s = node.left as usize;
let e = s + node.count as usize;
for &ti in &self.indices[s..e] {
let lt = &tris[ti as usize];
if !ray_hits_aabb_preshifted(p_lo, p_hi, inv_dir, <.aabb) {
continue;
}
match ray_tri_intersect(p, ray_dir, lt.v[0], lt.v[1], lt.v[2]) {
RayHit::Hit => hits += 1,
RayHit::Graze => {
grazing = true;
break;
}
RayHit::Miss => {}
}
}
if grazing {
break;
}
} else {
stack.push(node.left);
stack.push(node.right);
}
}
if !grazing {
return (hits & 1) == 1;
}
}
} else {
for &(ray_dir, inv_dir) in &RAYS {
let mut hits = 0u32;
let mut grazing = false;
stack.clear();
stack.push(0);
while let Some(ni) = stack.pop() {
let node = &self.nodes[ni as usize];
if !ray_hits_aabb_padded(p, inv_dir, &node.aabb, aabb_ray_pad(&node.aabb)) {
continue;
}
if node.count > 0 {
let s = node.left as usize;
let e = s + node.count as usize;
for &ti in &self.indices[s..e] {
let lt = &tris[ti as usize];
if !ray_hits_aabb_padded(p, inv_dir, <.aabb, aabb_ray_pad(<.aabb)) {
continue;
}
match ray_tri_intersect(p, ray_dir, lt.v[0], lt.v[1], lt.v[2]) {
RayHit::Hit => hits += 1,
RayHit::Graze => {
grazing = true;
break;
}
RayHit::Miss => {}
}
}
if grazing {
break;
}
} else {
stack.push(node.left);
stack.push(node.right);
}
}
if !grazing {
return (hits & 1) == 1;
}
}
}
// Exact Generalized Winding Number fallback (Jacobson et al. 2013)
winding_number(tris, p).abs() > 0.5
}
}
#[inline(always)]
fn ray_hits_aabb_preshifted(p_lo: Vec3, p_hi: Vec3, inv_d: Vec3, bb: &Aabb) -> bool {
let tx0 = (bb.min.x - p_lo.x) * inv_d.x;
let tx1 = (bb.max.x - p_hi.x) * inv_d.x;
let ty0 = (bb.min.y - p_lo.y) * inv_d.y;
let ty1 = (bb.max.y - p_hi.y) * inv_d.y;
let tz0 = (bb.min.z - p_lo.z) * inv_d.z;
let tz1 = (bb.max.z - p_hi.z) * inv_d.z;
let tmin = tx0.max(ty0).max(tz0).max(0.0);
let tmax = tx1.min(ty1).min(tz1);
tmax >= tmin
}
#[expect(
dead_code,
reason = "kept as branchless reference helper alongside ray_hits_aabb_dist"
)]
#[inline]
fn ray_hits_aabb(p: Vec3, inv_d: Vec3, bb: &Aabb) -> bool {
// Since inv_d > 0 on all 3 axes, tmin/tmax are branchless!
let tx0 = (bb.min.x - p.x) * inv_d.x;
let tx1 = (bb.max.x - p.x) * inv_d.x;
let ty0 = (bb.min.y - p.y) * inv_d.y;
let ty1 = (bb.max.y - p.y) * inv_d.y;
let tz0 = (bb.min.z - p.z) * inv_d.z;
let tz1 = (bb.max.z - p.z) * inv_d.z;
let tmin = tx0.max(ty0).max(tz0);
let tmax = tx1.min(ty1).min(tz1);
tmax >= tmin.max(0.0) - 1e-9
}
/// Exact equivalent of `1e-4_f64.max(1e-5 * bb.size().len())` without calling `sqrt()`
/// when `len_sq <= 100.0` (the 99.9% case in normalized CSG space).
#[inline]
fn aabb_ray_pad(bb: &Aabb) -> f64 {
let len_sq = bb.size().len_sq();
if len_sq > 100.0 {
1e-5 * len_sq.sqrt()
} else {
1e-4
}
}
/// Conservative padded slab test (pad >> all ray_tri_intersect tolerances) used as a
/// pure Miss-prefilter: never rejects a triangle that could report Hit or Graze.
#[inline]
fn ray_hits_aabb_padded(p: Vec3, inv_d: Vec3, bb: &Aabb, pad: f64) -> bool {
let tx0 = (bb.min.x - p.x - pad) * inv_d.x;
let tx1 = (bb.max.x - p.x + pad) * inv_d.x;
let ty0 = (bb.min.y - p.y - pad) * inv_d.y;
let ty1 = (bb.max.y - p.y + pad) * inv_d.y;
let tz0 = (bb.min.z - p.z - pad) * inv_d.z;
let tz1 = (bb.max.z - p.z + pad) * inv_d.z;
let tmin = tx0.max(ty0).max(tz0).max(0.0);
let tmax = tx1.min(ty1).min(tz1);
tmax >= tmin
}
enum RayHit {
Miss,
Hit,
Graze,
}
#[inline]
fn ray_tri_intersect(orig: Vec3, dir: Vec3, v0: Vec3, v1: Vec3, v2: Vec3) -> RayHit {
let e1 = v1 - v0;
let e2 = v2 - v0;
let h = dir.cross(e2);
let a = e1.dot(h);
if a.abs() < 1e-11 {
// Ray parallel to triangle plane
let dist = (orig - v0).dot(e1.cross(e2).normalized()).abs();
return if dist < 1e-7 { RayHit::Graze } else { RayHit::Miss };
}
let f = 1.0 / a;
let s = orig - v0;
let u = f * s.dot(h);
if !(-1e-6..=1.0 + 1e-6).contains(&u) {
return RayHit::Miss;
}
let q = s.cross(e1);
let v = f * dir.dot(q);
if v < -1e-6 || u + v > 1.0 + 1e-6 {
return RayHit::Miss;
}
let t = f * e2.dot(q);
if t < -1e-6 {
return RayHit::Miss;
}
if t < 1e-6 || u < 1e-6 || v < 1e-6 || u + v > 1.0 - 1e-6 {
return RayHit::Graze;
}
RayHit::Hit
}
/// Half solid angle `atan2(det, denom)` subtended by triangle `t` at `p`
/// (Van Oosterom & Strackee; sum over a closed mesh equals `2*PI * winding_number`).
#[inline]
fn tri_half_solid_angle(t: &Tri, p: Vec3) -> f64 {
let a = t.v[0] - p;
let b = t.v[1] - p;
let c = t.v[2] - p;
let la = a.len();
let lb = b.len();
let lc = c.len();
let det = a.dot(b.cross(c));
let denom = la * lb * lc + a.dot(b) * lc + b.dot(c) * la + c.dot(a) * lb;
det.atan2(denom)
}
fn winding_number(tris: &[Tri], p: Vec3) -> f64 {
let mut sum = 0.0;
for t in tris {
sum += tri_half_solid_angle(t, p);
}
sum / (2.0 * PI)
}
/// Compute the 1D interval `[min, max]` along `dir` where triangle `v` intersects a plane
/// given vertex signed distances `d` to that plane. Returns `None` if all vertices are
/// strictly on one side of the plane.
#[inline]
fn tri_plane_interval(v: &[Vec3; 3], d: [f64; 3], dir: Vec3) -> Option<(f64, f64)> {
let mut lo = f64::INFINITY;
let mut hi = f64::NEG_INFINITY;
let mut any = false;
for i in 0..3 {
let di = d[i];
if di.abs() <= PLANE_EPS {
let t = dir.dot(v[i]);
lo = lo.min(t);
hi = hi.max(t);
any = true;
}
let j = (i + 1) % 3;
let dj = d[j];
if (di > PLANE_EPS && dj < -PLANE_EPS) || (di < -PLANE_EPS && dj > PLANE_EPS) {
let s = (di / (di - dj)).clamp(0.0, 1.0);
let p = v[i].lerp(v[j], s);
let t = dir.dot(p);
lo = lo.min(t);
hi = hi.max(t);
any = true;
}
}
if any { Some((lo, hi)) } else { None }
}
/// Fast 2D Separating Axis Test for two coplanar triangles sharing normal `n`.
#[inline]
fn coplanar_tris_overlap(ta: &Tri, tb: &Tri) -> bool {
let n = ta.normal;
for (p, q) in [(ta, tb), (tb, ta)] {
for i in 0..3 {
let a = p.v[i];
let b = p.v[(i + 1) % 3];
let c = p.v[(i + 2) % 3];
// Outward normal in plane
let mut en = (b - a).cross(n);
if en.dot(c - a) > 0.0 {
en = -en;
}
let l = en.len();
if l < 1e-12 {
continue;
}
let en = en / l;
let w = en.dot(a);
if en.dot(q.v[0]) - w > PLANE_EPS
&& en.dot(q.v[1]) - w > PLANE_EPS
&& en.dot(q.v[2]) - w > PLANE_EPS
{
return false;
}
}
}
true
}
type PolyVerts = SmallVec<[Vec3; 8]>;
/// Split a convex polygon (moved by value with cached AABB — zero clones when unsplit!) by plane
/// `(n, w)` ONLY IF its AABB overlaps `cut_aabb` AND its cut segment along `line_dir` overlaps
/// `[seg_lo, seg_hi]` (within `1e-5`). Prevents O(k^2) distant shattering!
#[inline]
#[expect(
clippy::too_many_arguments,
reason = "hot inner-loop plane clipper taking precomputed plane, segment, and AABB bounds"
)]
fn split_poly_by_plane_guarded(
poly: PolyVerts,
p_bb: Aabb,
n: Vec3,
w: f64,
line_dir: Vec3,
seg_lo: f64,
seg_hi: f64,
cut_aabb: &Aabb,
out: &mut Vec<(PolyVerts, Aabb)>,
) {
if !p_bb.overlaps(cut_aabb, 1e-5) {
out.push((poly, p_bb));
return;
}
let len = poly.len();
let mut has_pos = false;
let mut has_neg = false;
let mut dists: SmallVec<[f64; 8]> = SmallVec::with_capacity(len);
for &v in &poly {
let d = n.dot(v) - w;
dists.push(d);
if d > PLANE_EPS {
has_pos = true;
} else if d < -PLANE_EPS {
has_neg = true;
}
}
if !(has_pos && has_neg) {
out.push((poly, p_bb));
return;
}
// Fast pre-check: compute the cut interval [p_lo, p_hi] AND cache crossing points so we never divide/lerp twice!
let mut p_lo = f64::INFINITY;
let mut p_hi = f64::NEG_INFINITY;
let mut crossings: SmallVec<[(usize, Vec3); 2]> = SmallVec::new();
for i in 0..len {
let di = dists[i];
if di.abs() <= PLANE_EPS {
let t = line_dir.dot(poly[i]);
p_lo = p_lo.min(t);
p_hi = p_hi.max(t);
}
let j = (i + 1) % len;
let dj = dists[j];
if (di > PLANE_EPS && dj < -PLANE_EPS) || (di < -PLANE_EPS && dj > PLANE_EPS) {
let s = (di / (di - dj)).clamp(0.0, 1.0);
let p = poly[i].lerp(poly[j], s);
crossings.push((i, p));
let t = line_dir.dot(p);
p_lo = p_lo.min(t);
p_hi = p_hi.max(t);
}
}
if p_hi < seg_lo - 1e-5 || p_lo > seg_hi + 1e-5 {
out.push((poly, p_bb));
return;
}
let mut front: PolyVerts = SmallVec::with_capacity(len + 1);
let mut back: PolyVerts = SmallVec::with_capacity(len + 1);
let mut f_bb = Aabb::empty();
let mut b_bb = Aabb::empty();
let mut c_cursor = 0usize;
for i in 0..len {
let di = dists[i];
let vi = poly[i];
if di >= -PLANE_EPS {
front.push(vi);
f_bb.include(vi);
}
if di <= PLANE_EPS {
back.push(vi);
b_bb.include(vi);
}
if c_cursor < crossings.len() && crossings[c_cursor].0 == i {
let p = crossings[c_cursor].1;
c_cursor += 1;
front.push(p);
f_bb.include(p);
back.push(p);
b_bb.include(p);
}
}
if front.len() >= 3 {
out.push((front, f_bb));
}
if back.len() >= 3 {
out.push((back, b_bb));
}
}
struct CutPlane {
n: Vec3,
w: f64,
line_dir: Vec3,
seg_lo: f64,
seg_hi: f64,
aabb: Aabb,
}
/// Clip a single triangle `ta` against ONLY the deduplicated local planes of opposing triangles
/// `other_tris[cand]` that ACTUALLY intersect `ta` in 3D (Möller 1997 interval test + plane merge).
fn subdivide_tri_local(
ta: &Tri,
cands: &[u32],
other_tris: &[Tri],
scratch_a: &mut Vec<(PolyVerts, Aabb)>,
scratch_b: &mut Vec<(PolyVerts, Aabb)>,
cuts: &mut Vec<CutPlane>,
coplanar_cands: &mut Vec<u32>,
) -> bool {
scratch_a.clear();
cuts.clear();
coplanar_cands.clear();
for &ci in cands {
let tb = &other_tris[ci as usize];
let d0 = ta.normal.dot(tb.v[0]) - ta.w;
let d1 = ta.normal.dot(tb.v[1]) - ta.w;
let d2 = ta.normal.dot(tb.v[2]) - ta.w;
if (d0 > PLANE_EPS && d1 > PLANE_EPS && d2 > PLANE_EPS)
|| (d0 < -PLANE_EPS && d1 < -PLANE_EPS && d2 < -PLANE_EPS)
{
continue;
}
let dot_n = ta.normal.dot(tb.normal).abs();
if dot_n > 1.0 - 1e-6 {
if !coplanar_tris_overlap(ta, tb) {
continue;
}
coplanar_cands.push(ci);
for ei in 0..3 {
let va = tb.v[ei];
let vb = tb.v[(ei + 1) % 3];
let edge = vb - va;
let elen = edge.len();
if elen < 1e-12 {
continue;
}
let edge_dir = edge / elen;
let en = edge.cross(tb.normal).normalized();
if en.len_sq() < 1e-12 {
continue;
}
let ew = en.dot(va);
let s0 = edge_dir.dot(va);
let s1 = edge_dir.dot(vb);
let (seg_lo, seg_hi) = if s0 <= s1 { (s0, s1) } else { (s1, s0) };
let ebb = Aabb { min: va.min(vb), max: va.max(vb) };
push_or_merge_cut(cuts, en, ew, edge_dir, seg_lo, seg_hi, ebb);
}
} else {
let e0 = tb.normal.dot(ta.v[0]) - tb.w;
let e1 = tb.normal.dot(ta.v[1]) - tb.w;
let e2 = tb.normal.dot(ta.v[2]) - tb.w;
if (e0 > PLANE_EPS && e1 > PLANE_EPS && e2 > PLANE_EPS)
|| (e0 < -PLANE_EPS && e1 < -PLANE_EPS && e2 < -PLANE_EPS)
{
continue;
}
let line_dir = ta.normal.cross(tb.normal);
let llen = line_dir.len();
if llen < 1e-12 {
continue;
}
let line_dir = line_dir / llen;
let Some((tb_lo, tb_hi)) = tri_plane_interval(&tb.v, [d0, d1, d2], line_dir) else {
continue;
};
let Some((ta_lo, ta_hi)) = tri_plane_interval(&ta.v, [e0, e1, e2], line_dir) else {
continue;
};
if ta_hi < tb_lo - 1e-5 || tb_hi < ta_lo - 1e-5 {
continue;
}
push_or_merge_cut(cuts, tb.normal, tb.w, line_dir, tb_lo, tb_hi, tb.aabb);
}
}
if cuts.is_empty() {
return false;
}
let mut init: PolyVerts = SmallVec::new();
init.extend_from_slice(&ta.v);
scratch_a.push((init, ta.aabb));
let mut did_split = false;
for cut in cuts.iter() {
// Hard OOM guard on pathological/self-intersecting fuzzed meshes
if scratch_a.len() >= 4096 {
break;
}
let prev_len = scratch_a.len();
scratch_b.clear();
for (p, p_bb) in scratch_a.drain(..) {
split_poly_by_plane_guarded(p, p_bb, cut.n, cut.w, cut.line_dir, cut.seg_lo, cut.seg_hi, &cut.aabb, scratch_b);
}
if scratch_b.len() > prev_len {
did_split = true;
}
std::mem::swap(scratch_a, scratch_b);
}
did_split
}
#[inline]
fn push_or_merge_cut(
cuts: &mut Vec<CutPlane>,
mut n: Vec3,
mut w: f64,
mut line_dir: Vec3,
mut seg_lo: f64,
mut seg_hi: f64,
aabb: Aabb,
) {
// Canonicalize normal sign so coplanar opposing tris merge cleanly
let flip = if n.x.abs() > 1e-7 {
n.x < 0.0
} else if n.y.abs() > 1e-7 {
n.y < 0.0
} else {
n.z < 0.0
};
if flip {
n = -n;
w = -w;
}
for c in cuts.iter_mut() {
if c.n.dot(n) > 1.0 - 1e-8 && (c.w - w).abs() < 1e-6 {
// Same plane! Align line_dir sign and merge interval if overlapping/adjacent
let d = c.line_dir.dot(line_dir);
if d.abs() > 1.0 - 1e-6 {
if d < 0.0 {
let (lo, hi) = (-seg_hi, -seg_lo);
seg_lo = lo;
seg_hi = hi;
line_dir = -line_dir;
}
if seg_hi >= c.seg_lo - 1e-4 && seg_lo <= c.seg_hi + 1e-4 {
c.seg_lo = c.seg_lo.min(seg_lo);
c.seg_hi = c.seg_hi.max(seg_hi);
c.aabb.min = c.aabb.min.min(aabb.min);
c.aabb.max = c.aabb.max.max(aabb.max);
return;
}
}
}
}
cuts.push(CutPlane { n, w, line_dir, seg_lo, seg_hi, aabb });
}
#[inline]
fn point_in_tri_3d(p: Vec3, t: &Tri) -> bool {
let e0 = t.v[1] - t.v[0];
let e1 = t.v[2] - t.v[1];
let e2 = t.v[0] - t.v[2];
let c0 = e0.cross(p - t.v[0]).dot(t.normal);
let c1 = e1.cross(p - t.v[1]).dot(t.normal);
let c2 = e2.cross(p - t.v[2]).dot(t.normal);
if c0 >= 0.0 && c1 >= 0.0 && c2 >= 0.0 {
return true;
}
// Outside, `p` is in when within 1e-7 of an edge, the edge itself and not its line: past a
// needle's sharp corner both long edges' lines stay that close for far longer than the needle.
let q = p - t.normal * (t.normal.dot(p) - t.w);
[(t.v[0], e0), (t.v[1], e1), (t.v[2], e2)].into_iter().any(|(a, e)| {
let s = (q - a).dot(e) / e.len_sq().max(1e-300);
(q - (a + e * s.clamp(0.0, 1.0))).len_sq() <= 1e-14
})
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Loc {
Outside,
Inside,
CoplanarSame,
CoplanarOpp,
}
fn classify_point_vs_mesh(
p: Vec3,
n_p: Vec3,
other_tris: &[Tri],
other_bvh: &TriBvh,
local_cands: &[u32],
) -> Loc {
// Check if `p` lies on a coplanar triangle of `other`, by the normal test `subdivide_tri_local`
// splits with: a nearly parallel pair it cut along their crossing line is classified by winding
// on both sides of it, never as coplanar on the fragments that happen to lie within 1e-5 of it.
for &ci in local_cands {
let tb = &other_tris[ci as usize];
let dn = n_p.dot(tb.normal);
if dn.abs() > 1.0 - 1e-6
&& (tb.normal.dot(p) - tb.w).abs() < 1e-5
&& point_in_tri_3d(p, tb)
{
return if dn > 0.0 {
Loc::CoplanarSame
} else {
Loc::CoplanarOpp
};
}
}
if other_bvh.point_inside(other_tris, p) {
Loc::Inside
} else {
Loc::Outside
}
}
/// Decide whether a fragment from side A (is_a=true) or side B (is_a=false) is kept,
/// and whether its winding should be flipped.
#[inline]
fn keep_decision(op: BoolOp, is_a: bool, loc: Loc) -> Option<bool> {
match (op, is_a, loc) {
// Union: keep A outside B (plus coplanar-same on A); keep B strictly outside A
(BoolOp::Union, true, Loc::Outside | Loc::CoplanarSame) => Some(false),
(BoolOp::Union, false, Loc::Outside) => Some(false),
// Difference (A - B): keep A outside B (plus coplanar-opp on A); keep B inside A (flipped!)
(BoolOp::Difference, true, Loc::Outside | Loc::CoplanarOpp) => Some(false),
(BoolOp::Difference, false, Loc::Inside) => Some(true),
// Intersect (A ∩ B): keep A inside B (plus coplanar-same on A); keep B strictly inside A
(BoolOp::Intersect, true, Loc::Inside | Loc::CoplanarSame) => Some(false),
(BoolOp::Intersect, false, Loc::Inside) => Some(false),
_ => None,
}
}
struct OutTri {
v: [Vec3; 3],
tag_idx: u32,
lineage: LineageId,
mat_id: u16,
}
fn emit_poly_tris(poly: &PolyVerts, normal: Vec3, flip: bool, tag_idx: u32, lineage: LineageId, mat_id: u16, out: &mut Vec<OutTri>) {
// Deduplicate & drop strictly collinear boundary points
let mut pts: PolyVerts = SmallVec::with_capacity(poly.len());
for &v in poly {
if pts.last().is_none_or(|&prev| (v - prev).len_sq() > 1e-14) {
pts.push(v);
}
}
while pts.len() > 1
&& pts
.first()
.zip(pts.last())
.is_some_and(|(&first, &last)| (first - last).len_sq() <= 1e-14)
{
pts.pop();
}
let mut changed = true;
while changed && pts.len() >= 3 {
changed = false;
let n = pts.len();
for i in 0..n {
let prev = pts[(i + n - 1) % n];
let curr = pts[i];
let next = pts[(i + 1) % n];
let seg = next - prev;
let sl = seg.len();
let h = if sl > 1e-12 {
(curr - prev).cross(seg).len() / sl
} else {
0.0
};
if h < 1e-7 {
pts.remove(i);
changed = true;
break;
}
}
}
if pts.len() < 3 {
return;
}
if pts.len() == 3 {
let (a, b, c) = if flip { (pts[0], pts[2], pts[1]) } else { (pts[0], pts[1], pts[2]) };
let area2 = (b - a).cross(c - a).len();
let max_e = (b - a).len().max((c - b).len()).max((a - c).len()).max(1e-12);
if area2 / max_e > 1e-8 {
out.push(OutTri { v: [a, b, c], tag_idx, lineage, mat_id });
}
return;
}
// Max-min-height ear triangulation of convex polygon
while pts.len() > 3 {
let k = pts.len();
let mut best_i = 0;
let mut best_h = -1.0f64;
for i in 0..k {
let a = pts[(i + k - 1) % k];
let b = pts[i];
let c = pts[(i + 1) % k];
let cross = (b - a).cross(c - a);
if cross.dot(normal) <= 0.0 {
continue;
}
let area2 = cross.len();
let max_e = (b - a).len().max((c - b).len()).max((a - c).len()).max(1e-12);
let h = area2 / max_e;
if h > best_h {
best_h = h;
best_i = i;
}
}
let a = pts[(best_i + k - 1) % k];
let b = pts[best_i];
let c = pts[(best_i + 1) % k];
if best_h > 1e-8 {
let v = if flip { [a, c, b] } else { [a, b, c] };
out.push(OutTri { v, tag_idx, lineage, mat_id });
}
pts.remove(best_i);
}
let (a, b, c) = if flip { (pts[0], pts[2], pts[1]) } else { (pts[0], pts[1], pts[2]) };
let area2 = (b - a).cross(c - a).len();
let max_e = (b - a).len().max((c - b).len()).max((a - c).len()).max(1e-12);
if area2 / max_e > 1e-8 {
out.push(OutTri { v: [a, b, c], tag_idx, lineage, mat_id });
}
}
fn intern_tags(
tags: &SmallVec<[String; 2]>,
extra_tag: Option<&str>,
tag_table: &mut Vec<SmallVec<[String; 2]>>,
) -> u32 {
// Fast-path lookup against existing unique tag sets (typically only 4-10 per mesh!)
let Some(et) = extra_tag else {
if let Some(pos) = tag_table.iter().position(|existing| existing.as_slice() == tags.as_slice()) {
return pos as u32;
}
let id = tag_table.len() as u32;
tag_table.push(tags.clone());
return id;
};
let has_et = tags.iter().any(|x| x == et);
if has_et {
if let Some(pos) = tag_table.iter().position(|existing| existing.as_slice() == tags.as_slice()) {
return pos as u32;
}
let id = tag_table.len() as u32;
tag_table.push(tags.clone());
return id;
}
let mut full = tags.clone();
full.push(et.to_string());
if let Some(pos) = tag_table.iter().position(|existing| existing.as_slice() == full.as_slice()) {
return pos as u32;
}
let id = tag_table.len() as u32;
tag_table.push(full);
id
}
fn extract_tris(
mesh: &PolyMesh,
extra_tag: Option<&str>,
mat_remap: &[u16],
tag_table: &mut Vec<SmallVec<[String; 2]>>,
) -> Vec<Tri> {
let mut out = Vec::with_capacity(mesh.faces.len() * 2);
for (fi, f) in mesh.faces.iter().enumerate() {
let tid = intern_tags(&f.tags, extra_tag, tag_table);
let mid = if mat_remap.is_empty() {
f.mat_id
} else {
mat_remap.get(f.mat_id as usize).copied().unwrap_or(0)
};
for [a, b, c] in mesh.triangulate_face(fi) {
if let Some(tri) = Tri::from_verts(mesh.verts[a], mesh.verts[b], mesh.verts[c], tid, f.lineage, mid) {
out.push(tri);
}
}
}
out
}
fn process_csg_side(
src_tris: &[Tri],
other_tris: &[Tri],
other_bvh: &TriBvh,
op: BoolOp,
is_a: bool,
) -> Vec<OutTri> {
let mut out_tris: Vec<OutTri> = Vec::with_capacity(src_tris.len());
let mut cands: Vec<u32> = Vec::with_capacity(32);
let mut scratch_a: Vec<(PolyVerts, Aabb)> = Vec::with_capacity(16);
let mut scratch_b: Vec<(PolyVerts, Aabb)> = Vec::with_capacity(16);
let mut cuts: Vec<CutPlane> = Vec::with_capacity(16);
let mut coplanar_cands: Vec<u32> = Vec::with_capacity(8);
let root_bb = other_bvh.root_aabb;
for t in src_tris {
// Ultra-fast root-AABB rejection: guaranteed strictly outside opposing solid -> zero BVH/ray work!
if !t.aabb.overlaps(&root_bb, 1e-5) {
if let Some(flip) = keep_decision(op, is_a, Loc::Outside) {
let v = if flip { [t.v[0], t.v[2], t.v[1]] } else { t.v };
out_tris.push(OutTri { v, tag_idx: t.tag_idx, lineage: t.lineage, mat_id: t.mat_id });
}
continue;
}
other_bvh.query_aabb(&t.aabb, 1e-5, &mut cands);
if cands.is_empty() {
let loc = if other_bvh.point_inside(other_tris, t.centroid) {
Loc::Inside
} else {
Loc::Outside
};
if let Some(flip) = keep_decision(op, is_a, loc) {
let v = if flip { [t.v[0], t.v[2], t.v[1]] } else { t.v };
out_tris.push(OutTri { v, tag_idx: t.tag_idx, lineage: t.lineage, mat_id: t.mat_id });
}
continue;
}
subdivide_tri_local(t, &cands, other_tris, &mut scratch_a, &mut scratch_b, &mut cuts, &mut coplanar_cands);
if scratch_a.is_empty() {
// No cutting plane intersected `t` — classify `t.centroid` directly without polygon emission
let loc = classify_point_vs_mesh(t.centroid, t.normal, other_tris, other_bvh, &coplanar_cands);
if let Some(flip) = keep_decision(op, is_a, loc) {
let v = if flip { [t.v[0], t.v[2], t.v[1]] } else { t.v };
out_tris.push(OutTri { v, tag_idx: t.tag_idx, lineage: t.lineage, mat_id: t.mat_id });
}
continue;
}
for (poly, _) in &scratch_a {
let mut c = Vec3::ZERO;
for &v in poly {
c += v;
}
c = c / (poly.len() as f64);
let loc = classify_point_vs_mesh(c, t.normal, other_tris, other_bvh, &coplanar_cands);
if let Some(flip) = keep_decision(op, is_a, loc) {
emit_poly_tris(poly, t.normal, flip, t.tag_idx, t.lineage, t.mat_id, &mut out_tris);
}
}
}
out_tris
}
/// Precomputed operand-A state (`tris_a`, `bvh_a`, material remap, tag table prefix) so
/// perturbation retries only re-triangulate and re-index perturbed operand B.
struct PreparedCsgA<'a> {
a: &'a PolyMesh,
tris_a: Vec<Tri>,
bvh_a: TriBvh,
tag_table: Vec<SmallVec<[String; 2]>>,
tag_table_a_len: usize,
merged_mats: Vec<crate::mesh::Material>,
b_mat_remap: Vec<u16>,
}
impl<'a> PreparedCsgA<'a> {
fn new(a: &'a PolyMesh, b: &PolyMesh) -> Self {
// Merge material palettes from A and B (invariant across vertex perturbations of B)
let mut merged_mats = a.materials.clone();
let mut b_mat_remap: Vec<u16> = Vec::new();
if !b.materials.is_empty() {
if merged_mats.is_empty() && !a.faces.is_empty() {
merged_mats.push(crate::mesh::Material::default());
}
for bm in &b.materials {
if let Some(pos) = merged_mats.iter().position(|m| m == bm) {
b_mat_remap.push(pos as u16);
} else {
let idx = merged_mats.len() as u16;
merged_mats.push(bm.clone());
b_mat_remap.push(idx);
}
}
}
let mut tag_table: Vec<SmallVec<[String; 2]>> = Vec::with_capacity(16);
let tris_a = extract_tris(a, None, &[], &mut tag_table);
let tag_table_a_len = tag_table.len();
let bvh_a = TriBvh::build(&tris_a);
Self {
a,
tris_a,
bvh_a,
tag_table,
tag_table_a_len,
merged_mats,
b_mat_remap,
}
}
fn run(&mut self, b: &PolyMesh, op: BoolOp, b_tag: Option<&str>, op_id: u32) -> (PolyMesh, usize) {
if self.tris_a.is_empty() {
let m = match op {
BoolOp::Union => b.clone(),
BoolOp::Difference | BoolOp::Intersect => PolyMesh::new(),
};
let bad = count_bad_edges(&m);
return (m, bad);
}
self.tag_table.truncate(self.tag_table_a_len);
let tris_b = extract_tris(b, b_tag, &self.b_mat_remap, &mut self.tag_table);
if tris_b.is_empty() {
let m = match op {
BoolOp::Union | BoolOp::Difference => self.a.clone(),
BoolOp::Intersect => PolyMesh::new(),
};
let bad = count_bad_edges(&m);
return (m, bad);
}
let bvh_b = TriBvh::build(&tris_b);
let tris_a = &self.tris_a;
let bvh_a = &self.bvh_a;
// Only spawn an OS thread for very large meshes (>=8,000 tris) on native targets (never wasm32).
#[cfg(not(target_arch = "wasm32"))]
let out_tris = if tris_a.len() + tris_b.len() >= 8_000 {
std::thread::scope(|s| {
let h_b = s.spawn(|| process_csg_side(&tris_b, tris_a, bvh_a, op, false));
let mut out_a = process_csg_side(tris_a, &tris_b, &bvh_b, op, true);
// A panic on the worker side must not turn into a silently missing half of the result.
let out_b = h_b.join().unwrap_or_else(|p| std::panic::resume_unwind(p));
out_a.extend(out_b);
out_a
})
} else {
let mut out_a = process_csg_side(tris_a, &tris_b, &bvh_b, op, true);
let out_b = process_csg_side(&tris_b, tris_a, bvh_a, op, false);
out_a.extend(out_b);
out_a
};
#[cfg(target_arch = "wasm32")]
let out_tris = {
let mut out_a = process_csg_side(tris_a, &tris_b, &bvh_b, op, true);
let out_b = process_csg_side(&tris_b, tris_a, bvh_a, op, false);
out_a.extend(out_b);
out_a
};
let (mut m, bad) = assemble_clean_mesh(out_tris, &self.tag_table, op_id);
m.materials = self.merged_mats.clone();
m.smooth_angle_deg = self.a.smooth_angle_deg;
m.weighted_normals = self.a.weighted_normals;
(m, bad)
}
}
fn assemble_clean_mesh(out_tris: Vec<OutTri>, tag_table: &[SmallVec<[String; 2]>], op_id: u32) -> (PolyMesh, usize) {
let mut m = PolyMesh::new();
m.verts.reserve(out_tris.len() * 3);
m.faces.reserve(out_tris.len());
// Stash `ot.tag_idx` in `f.op_id` while running weld/cancel/T-junction/simplify so zero heap
// `String` tag clones occur for intermediate or collapsed faces; materialize tags once at end.
for ot in out_tris {
let base = m.verts.len();
m.verts.push(ot.v[0]);
m.verts.push(ot.v[1]);
m.verts.push(ot.v[2]);
let mut f = Face::new(SmallVec::from_slice(&[base, base + 1, base + 2]), ot.lineage, ot.tag_idx);
f.mat_id = ot.mat_id;
m.faces.push(f);
}
m.weld_and_clean(1e-6);
cancel_opposing_and_dup_tris(&mut m);
let mut bad = count_bad_or_unoriented_edges(&m);
if bad > 0 {
eliminate_t_junctions(&mut m, 1e-5);
cancel_opposing_and_dup_tris(&mut m);
bad = count_bad_or_unoriented_edges(&m);
if bad > 0 {
repair_seam_micro_edges(&mut m);
prune_folded_flaps(&mut m);
m.compact_unused_verts();
bad = count_bad_or_unoriented_edges(&m);
if bad > 0 && bad <= 24 && seal_micro_tri_holes(&mut m) {
bad = count_bad_or_unoriented_edges(&m);
}
if bad > 0 && count_bad_edges(&m) == 0 {
fix_isolated_flipped_faces(&mut m);
bad = count_bad_or_unoriented_edges(&m);
}
}
}
if bad == 0 && m.faces.len() > 12 {
unfold_coplanar_slivers(&mut m);
}
if bad == 0 && m.faces.len() > 24 {
simplify_coplanar_mesh(&mut m);
unfold_coplanar_slivers(&mut m);
}
for f in &mut m.faces {
let tid = f.op_id as usize;
f.op_id = op_id;
if let Some(tags) = tag_table.get(tid) {
f.tags = tags.clone();
}
}
(m, bad)
}
/// Seal isolated 3-edge micro-sliver boundary holes `(a -> b -> c -> a)` left when `emit_poly_tris`
/// drops a near-collinear seam triangle (height < 1e-4). Adds the matching closing triangle `[a, c, b]`
/// (inheriting material/tag from the longest adjacent edge), which `unfold_coplanar_slivers` then
/// immediately edge-flips into two healthy triangles.
fn seal_micro_tri_holes(mesh: &mut PolyMesh) -> bool {
let nf = mesh.faces.len();
if nf < 4 {
return false;
}
let mut half_edges: Vec<(u64, usize, usize, u32)> = Vec::with_capacity(nf * 3);
for (fi, f) in mesh.faces.iter().enumerate() {
if f.verts.len() != 3 {
continue;
}
for ei in 0..3 {
let u = f.verts[ei];
let v = f.verts[(ei + 1) % 3];
if u == v {
continue;
}
let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
half_edges.push(((lo << 32) | hi, u, v, fi as u32));
}
}
half_edges.sort_unstable_by_key(|&(ek, _, _, fi)| (ek, fi));
// Collect strictly naked boundary half-edges `(u -> v)` (undirected count == 1)
let mut b_edges: Vec<(usize, usize, u32)> = Vec::new();
let mut i = 0;
while i < half_edges.len() {
let ek = half_edges[i].0;
let mut j = i + 1;
while j < half_edges.len() && half_edges[j].0 == ek {
j += 1;
}
if j - i == 1 {
b_edges.push((half_edges[i].1, half_edges[i].2, half_edges[i].3));
}
i = j;
}
if b_edges.len() < 3 || b_edges.len() > 48 {
return false;
}
// Match 3-cycles `(a -> b), (b -> c), (c -> a)` where each vertex has unique outgoing edge
let mut used = vec![false; b_edges.len()];
let mut added = false;
for i0 in 0..b_edges.len() {
if used[i0] {
continue;
}
let (a, b, f0) = b_edges[i0];
let Some(i1) = (0..b_edges.len()).find(|&k| !used[k] && b_edges[k].0 == b) else {
continue;
};
let (_, c, f1) = b_edges[i1];
if c == a || c == b {
continue;
}
let Some(i2) = (0..b_edges.len()).find(|&k| !used[k] && b_edges[k].0 == c && b_edges[k].1 == a) else {
continue;
};
let f2 = b_edges[i2].2;
let pa = mesh.verts[a];
let pb = mesh.verts[b];
let pc = mesh.verts[c];
let e0 = (pb - pa).len();
let e1 = (pc - pb).len();
let e2 = (pa - pc).len();
let max_e = e0.max(e1).max(e2).max(1e-12);
let h = (pb - pa).cross(pc - pa).len() / max_e;
// Only seal genuine micro-sliver seam holes (height < 1e-4)
if h < 1e-4 {
let src_fi = if e0 >= e1 && e0 >= e2 {
f0 as usize
} else if e1 >= e2 {
f1 as usize
} else {
f2 as usize
};
let src = &mesh.faces[src_fi];
let mut nf_face = Face::new(SmallVec::from_slice(&[a, c, b]), src.lineage, src.op_id);
nf_face.mat_id = src.mat_id;
mesh.faces.push(nf_face);
used[i0] = true;
used[i1] = true;
used[i2] = true;
added = true;
}
}
added
}
/// On a closed undirected 2-manifold (`NM == 0 && B == 0`), flip any isolated triangle whose 3
/// edges ALL share the same half-edge direction as their manifold neighbors (e.g., a micro-sliver
/// whose vertices were snapped past collinearity). Subsequent `unfold_coplanar_slivers` then
/// replaces any resulting 180°-folded coplanar pair with two properly oriented triangles.
fn fix_isolated_flipped_faces(mesh: &mut PolyMesh) {
let nf = mesh.faces.len();
if nf < 4 {
return;
}
let mut half_edges: Vec<(u64, u32, u8)> = Vec::with_capacity(nf * 3);
for (fi, f) in mesh.faces.iter().enumerate() {
if f.verts.len() != 3 {
continue;
}
for ei in 0..3 {
let u = f.verts[ei];
let v = f.verts[(ei + 1) % 3];
if u == v {
continue;
}
if u < v {
half_edges.push((((u as u64) << 32) | (v as u64), fi as u32, 0));
} else {
half_edges.push((((v as u64) << 32) | (u as u64), fi as u32, 1));
}
}
}
half_edges.sort_unstable_by_key(|&(ek, fi, _)| (ek, fi));
let mut bad_edge_cnt = vec![0u8; nf];
let mut i = 0;
while i < half_edges.len() {
let ek = half_edges[i].0;
let mut j = i + 1;
while j < half_edges.len() && half_edges[j].0 == ek {
j += 1;
}
if j - i == 2 && half_edges[i].2 == half_edges[i + 1].2 {
bad_edge_cnt[half_edges[i].1 as usize] += 1;
bad_edge_cnt[half_edges[i + 1].1 as usize] += 1;
}
i = j;
}
for (fi, &cnt) in bad_edge_cnt.iter().enumerate() {
if cnt == 3 && mesh.faces[fi].verts.len() == 3 {
mesh.faces[fi].verts.swap(1, 2);
}
}
}
/// Unfold 180°-folded coplanar sliver triangles across shared interior manifold edges via exact
/// zero-geometry-change edge flips `(a, b) -> (c, d)`. Preserves manifoldness, winding, and volume
/// while eliminating self-intersections caused by seam snapping across ultra-thin coplanar wedges.
fn unfold_coplanar_slivers(mesh: &mut PolyMesh) {
let nf = mesh.faces.len();
if nf < 4 {
return;
}
for _pass in 0..4 {
// Build sorted undirected edge -> incident face list (zero HashMap)
let mut edge_inc: Vec<(u64, u32, u8)> = Vec::with_capacity(nf * 3);
for (fi, f) in mesh.faces.iter().enumerate() {
if f.verts.len() != 3 {
continue;
}
for ei in 0..3 {
let u = f.verts[ei];
let v = f.verts[(ei + 1) % 3];
if u == v {
continue;
}
let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
edge_inc.push(((lo << 32) | hi, fi as u32, ei as u8));
}
}
edge_inc.sort_unstable();
let has_edge = |u: usize, v: usize| -> bool {
let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
let ek = (lo << 32) | hi;
edge_inc.binary_search_by_key(&ek, |&(k, _, _)| k).is_ok()
};
let mut flipped_face = vec![false; nf];
let mut added_edges: Vec<u64> = Vec::new();
let mut flipped_any = false;
let mut i = 0;
while i < edge_inc.len() {
let ek = edge_inc[i].0;
let mut j = i + 1;
while j < edge_inc.len() && edge_inc[j].0 == ek {
j += 1;
}
if j - i == 2 {
let f1 = edge_inc[i].1 as usize;
let e1 = edge_inc[i].2 as usize;
let f2 = edge_inc[i + 1].1 as usize;
let e2 = edge_inc[i + 1].2 as usize;
if !flipped_face[f1]
&& !flipped_face[f2]
&& mesh.faces[f1].mat_id == mesh.faces[f2].mat_id
&& mesh.faces[f1].op_id == mesh.faces[f2].op_id
{
let a = mesh.faces[f1].verts[e1];
let b = mesh.faces[f1].verts[(e1 + 1) % 3];
let c = mesh.faces[f1].verts[(e1 + 2) % 3];
let a2 = mesh.faces[f2].verts[e2];
let b2 = mesh.faces[f2].verts[(e2 + 1) % 3];
let d = mesh.faces[f2].verts[(e2 + 2) % 3];
// Must be consistently opposed half-edges: f1 has (a -> b), f2 has (b -> a)
if a2 == b && b2 == a && c != d {
let pa = mesh.verts[a];
let pb = mesh.verts[b];
let pc = mesh.verts[c];
let pd = mesh.verts[d];
let n1 = (pb - pa).cross(pc - pa);
let n2 = (pa - pb).cross(pd - pb);
let l1 = n1.len();
let l2 = n2.len();
// Detect either:
// (1) 180°-folded coplanar pair (opposite normals on the same plane), OR
// (2) Zero-area / collinear bridge sliver lying on the shared edge of a larger
// coplanar triangle (which blocks direct vertex sharing across a rim!).
let is_folded = l1 > 1e-18 && l2 > 1e-18 && n1.dot(n2) < -(1.0 - 1e-4) * l1 * l2;
let is_collinear_cap =
(l1 > 1e-14 && l2 <= 1e-10 * l1) || (l2 > 1e-14 && l1 <= 1e-10 * l2);
if is_folded || is_collinear_cap {
let n_true = if l2 >= l1 { n2 / l2 } else { n1 / l1 };
let plane_ok = (pc - pa).dot(n_true).abs() < 1e-6
&& (pd - pa).dot(n_true).abs() < 1e-6;
if plane_ok {
let nt1 = (pd - pa).cross(pc - pa);
let nt2 = (pb - pd).cross(pc - pd);
let lt1 = nt1.len();
let lt2 = nt2.len();
let min_a = if is_folded {
1e-12 * l1.max(l2)
} else {
(1e-10 * l1.max(l2)).max(l1.min(l2) * 10.0)
};
if lt1 > min_a
&& lt2 > min_a
&& nt1.dot(n_true) > lt1 * (1.0 - 1e-4)
&& nt2.dot(n_true) > lt2 * (1.0 - 1e-4)
&& !has_edge(c, d)
{
let (lo, hi) = if c < d { (c as u64, d as u64) } else { (d as u64, c as u64) };
let new_ek = (lo << 32) | hi;
if !added_edges.contains(&new_ek) {
mesh.faces[f1].verts = SmallVec::from_slice(&[a, d, c]);
mesh.faces[f2].verts = SmallVec::from_slice(&[d, b, c]);
flipped_face[f1] = true;
flipped_face[f2] = true;
added_edges.push(new_ek);
flipped_any = true;
}
}
}
}
}
}
}
i = j;
}
if !flipped_any {
break;
}
}
}
/// Strictly manifold-preserving, zero-error coplanar & collinear-ridge half-edge collapse.
/// Enforces the exact Edelsbrunner Link Condition (`|N(u) ∩ N(v)| == 2`, `shared_faces == 2`)
/// plus positive oriented area preservation so `WT=true, NM=0` and exact volume are invariant.
fn simplify_coplanar_mesh(mesh: &mut PolyMesh) {
let nv = mesh.verts.len();
let nf = mesh.faces.len();
if nf < 12 || nv < 8 {
return;
}
let mut alive = vec![true; nf];
let mut f_norm: Vec<Vec3> = Vec::with_capacity(nf);
let mut v_faces: Vec<SmallVec<[u32; 8]>> = vec![SmallVec::new(); nv];
for (fi, f) in mesh.faces.iter().enumerate() {
if f.verts.len() != 3 {
alive[fi] = false;
f_norm.push(Vec3::ZERO);
continue;
}
let a = mesh.verts[f.verts[0]];
let b = mesh.verts[f.verts[1]];
let c = mesh.verts[f.verts[2]];
let n = (b - a).cross(c - a).normalized();
f_norm.push(n);
for &vi in &f.verts {
v_faces[vi].push(fi as u32);
}
}
let mut total_collapsed = 0usize;
let mut nbrs_u: SmallVec<[usize; 16]> = SmallVec::new();
let mut nbrs_v: SmallVec<[usize; 16]> = SmallVec::new();
// Track which vertices are dirty (need re-checking) and which have dead faces to prune.
let mut dirty_v = vec![true; nv];
let mut needs_prune = vec![false; nv];
for _pass in 0..3 {
let mut pass_collapsed = 0usize;
for u in 0..nv {
if !dirty_v[u] {
continue;
}
dirty_v[u] = false;
if needs_prune[u] {
v_faces[u].retain(|fi| alive[*fi as usize]);
needs_prune[u] = false;
}
if v_faces[u].len() < 3 {
continue;
}
// Check distinct plane normals & consistent material across incident faces of `u`
let mut planes: SmallVec<[Vec3; 3]> = SmallVec::new();
let mat0 = mesh.faces[v_faces[u][0] as usize].mat_id;
let mut skip = false;
for &fi32 in &v_faces[u] {
let fi = fi32 as usize;
if mesh.faces[fi].mat_id != mat0 {
skip = true;
break;
}
let n = f_norm[fi];
if n.len_sq() < 0.5 {
skip = true;
break;
}
if !planes.iter().any(|p| p.dot(n) > 1.0 - 1e-6) {
if planes.len() >= 2 {
// Corner with >=3 distinct planes: preserve exact geometry!
skip = true;
break;
}
planes.push(n);
}
}
if skip || planes.is_empty() {
continue;
}
// Collect deterministic sorted neighbor vertices of `u`
nbrs_u.clear();
for &fi32 in &v_faces[u] {
for &vi in &mesh.faces[fi32 as usize].verts {
if vi != u && !nbrs_u.contains(&vi) {
nbrs_u.push(vi);
}
}
}
nbrs_u.sort_unstable();
let pu = mesh.verts[u];
let mut target_v = None;
let mut shared_pair = [0usize; 2];
'try_nbr: for &v in &nbrs_u {
let dir = mesh.verts[v] - pu;
let dlen = dir.len();
if dlen < 1e-10 {
continue;
}
let udir = dir / dlen;
// Exact zero-error plane/ridge constraint
if planes.iter().any(|p| p.dot(udir).abs() > 1e-5) {
continue;
}
// Count shared alive faces between u and v (must be exactly 2)
let mut scnt = 0usize;
for &fi32 in &v_faces[u] {
let fv = &mesh.faces[fi32 as usize].verts;
if fv[0] == v || fv[1] == v || fv[2] == v {
if scnt < 2 {
shared_pair[scnt] = fi32 as usize;
}
scnt += 1;
}
}
if scnt != 2 {
continue;
}
// Only prune `v_faces[v]` when one of `v`'s faces was actually killed
if needs_prune[v] {
v_faces[v].retain(|fi| alive[*fi as usize]);
needs_prune[v] = false;
}
nbrs_v.clear();
for &fi32 in &v_faces[v] {
for &vi in &mesh.faces[fi32 as usize].verts {
if vi != v && !nbrs_v.contains(&vi) {
nbrs_v.push(vi);
}
}
}
let common = nbrs_u.iter().filter(|x| nbrs_v.contains(x)).count();
if common != 2 {
continue;
}
// Ensure every remaining triangle incident to `u` stays valid & unflipped after `u -> v`
let pv = mesh.verts[v];
for &fi32 in &v_faces[u] {
let fi = fi32 as usize;
if fi == shared_pair[0] || fi == shared_pair[1] {
continue;
}
let fv = &mesh.faces[fi].verts;
let a = if fv[0] == u { pv } else { mesh.verts[fv[0]] };
let b = if fv[1] == u { pv } else { mesh.verts[fv[1]] };
let c = if fv[2] == u { pv } else { mesh.verts[fv[2]] };
let cross = (b - a).cross(c - a);
let cl = cross.len();
if cl < 1e-10 || cross.dot(f_norm[fi]) < cl * (1.0 - 1e-4) {
continue 'try_nbr;
}
}
target_v = Some(v);
break;
}
if let Some(v) = target_v {
alive[shared_pair[0]] = false;
alive[shared_pair[1]] = false;
for &dead_fi in &shared_pair {
for &vi in &mesh.faces[dead_fi].verts {
needs_prune[vi] = true;
dirty_v[vi] = true;
}
}
let moved: SmallVec<[u32; 8]> = std::mem::take(&mut v_faces[u]);
for fi32 in moved {
let fi = fi32 as usize;
if !alive[fi] {
continue;
}
for vi in &mut mesh.faces[fi].verts {
if *vi == u {
*vi = v;
} else {
dirty_v[*vi] = true;
}
}
v_faces[v].push(fi32);
}
dirty_v[v] = true;
pass_collapsed += 1;
total_collapsed += 1;
}
}
if pass_collapsed == 0 {
break;
}
}
if total_collapsed > 0 {
let mut idx = 0usize;
mesh.faces.retain(|_| {
let keep = alive[idx];
idx += 1;
keep
});
mesh.compact_unused_verts();
}
}
/// Fast sort-based count of boundary + non-manifold edges (zero HashMaps).
fn count_bad_edges(mesh: &PolyMesh) -> usize {
if mesh.faces.is_empty() {
return 1;
}
let mut edges: Vec<u64> = Vec::with_capacity(mesh.faces.len() * 3);
for f in &mesh.faces {
let n = f.verts.len();
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u != v {
let (a, b) = if u < v { (u, v) } else { (v, u) };
edges.push(((a as u64) << 32) | (b as u64));
}
}
}
edges.sort_unstable();
let mut bad = 0usize;
let mut i = 0;
let m = edges.len();
while i < m {
let e = edges[i];
let mut j = i + 1;
while j < m && edges[j] == e {
j += 1;
}
if j - i != 2 {
bad += 1;
}
i = j;
}
bad
}
/// Sort-based deterministic opposing/duplicate triangle cancellation (16B packed entries, zero String clones).
fn cancel_opposing_and_dup_tris(mesh: &mut PolyMesh) {
let mut old_faces: Vec<Option<Face>> = mesh.faces.drain(..).map(Some).collect();
// Pack ([a, b, c]: [u32; 3], idx_sign: u32) = 16 bytes (half the size of ([usize; 3], u32, i32))
let mut entries: Vec<([u32; 3], u32)> = Vec::with_capacity(old_faces.len());
for (idx, opt_f) in old_faces.iter().enumerate() {
let Some(f) = opt_f.as_ref() else {
continue;
};
if f.verts.len() != 3 {
continue;
}
let [a, b, c] = [f.verts[0], f.verts[1], f.verts[2]];
if a == b || b == c || c == a {
continue;
}
let (key, sign) = canonical_tri(a, b, c);
let idx_sign = ((idx as u32) << 1) | if sign > 0 { 1 } else { 0 };
entries.push(([key[0] as u32, key[1] as u32, key[2] as u32], idx_sign));
}
entries.sort_unstable_by(|x, y| x.0.cmp(&y.0).then_with(|| (x.1 >> 1).cmp(&(y.1 >> 1))));
mesh.faces.reserve(entries.len());
let mut i = 0;
while i < entries.len() {
let key = entries[i].0;
let rep_idx = (entries[i].1 >> 1) as usize;
let mut cnt: i32 = if (entries[i].1 & 1) != 0 { 1 } else { -1 };
let mut j = i + 1;
while j < entries.len() && entries[j].0 == key {
cnt += if (entries[j].1 & 1) != 0 { 1 } else { -1 };
j += 1;
}
if cnt != 0 {
if let Some(mut f) = old_faces[rep_idx].take() {
let [a, b, c] = [key[0] as usize, key[1] as usize, key[2] as usize];
f.verts = if cnt > 0 {
SmallVec::from_slice(&[a, b, c])
} else {
SmallVec::from_slice(&[a, c, b])
};
mesh.faces.push(f);
}
}
i = j;
}
}
#[inline]
fn canonical_tri(a: usize, b: usize, c: usize) -> ([usize; 3], i32) {
let rot = if a <= b && a <= c {
[a, b, c]
} else if b <= a && b <= c {
[b, c, a]
} else {
[c, a, b]
};
if rot[1] < rot[2] {
(rot, 1)
} else {
([rot[0], rot[2], rot[1]], -1)
}
}
/// Fast single-pass packed-u64 boundary edge & vertex extraction (zero HashMaps).
fn collect_bad_edges_and_verts(mesh: &PolyMesh) -> (Vec<u64>, Vec<usize>, Vec<bool>) {
let mut edges: Vec<u64> = Vec::with_capacity(mesh.faces.len() * 3);
for f in &mesh.faces {
let n = f.verts.len();
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u != v {
let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
edges.push((lo << 32) | hi);
}
}
}
edges.sort_unstable();
let mut bad_edges: Vec<u64> = Vec::new();
let mut bad_verts: Vec<usize> = Vec::new();
let mut bad_mask = vec![false; mesh.verts.len()];
let mut i = 0;
while i < edges.len() {
let e = edges[i];
let mut j = i + 1;
while j < edges.len() && edges[j] == e {
j += 1;
}
if j - i != 2 {
bad_edges.push(e);
let u = (e >> 32) as usize;
let v = (e & 0xFFFF_FFFF) as usize;
if !bad_mask[u] {
bad_mask[u] = true;
bad_verts.push(u);
}
if !bad_mask[v] {
bad_mask[v] = true;
bad_verts.push(v);
}
}
i = j;
}
bad_verts.sort_unstable();
(bad_edges, bad_verts, bad_mask)
}
struct PtBvhNode {
aabb: Aabb,
left: u32,
right: u32,
count: u32,
}
/// Compact 3D point-BVH over boundary vertex indices for O(log B + k) T-junction queries.
struct PointBvh {
nodes: Vec<PtBvhNode>,
verts: Vec<usize>,
}
impl PointBvh {
fn build(positions: &[Vec3], indices: &[usize]) -> Self {
let mut verts = indices.to_vec();
let mut nodes = Vec::with_capacity(verts.len() / 4 + 1);
if !verts.is_empty() {
let len = verts.len();
Self::build_node(positions, &mut verts, 0, len, &mut nodes);
}
Self { nodes, verts }
}
fn build_node(
positions: &[Vec3],
verts: &mut [usize],
start: usize,
end: usize,
nodes: &mut Vec<PtBvhNode>,
) -> u32 {
let mut aabb = Aabb::empty();
for &vi in &verts[start..end] {
aabb.include(positions[vi]);
}
let node_idx = nodes.len() as u32;
let count = end - start;
if count <= 8 {
nodes.push(PtBvhNode {
aabb,
left: start as u32,
right: 0,
count: count as u32,
});
return node_idx;
}
let ext = aabb.size();
let axis = if ext.x >= ext.y && ext.x >= ext.z {
0
} else if ext.y >= ext.z {
1
} else {
2
};
let mid = start + count / 2;
verts[start..end].select_nth_unstable_by(mid - start, |&a, &b| {
let pa = positions[a];
let pb = positions[b];
let (ca, cb) = match axis {
0 => (pa.x, pb.x),
1 => (pa.y, pb.y),
_ => (pa.z, pb.z),
};
ca.total_cmp(&cb).then_with(|| a.cmp(&b))
});
nodes.push(PtBvhNode {
aabb,
left: 0,
right: 0,
count: 0,
});
let left = Self::build_node(positions, verts, start, mid, nodes);
let right = Self::build_node(positions, verts, mid, end, nodes);
nodes[node_idx as usize].left = left;
nodes[node_idx as usize].right = right;
node_idx
}
fn query_aabb(&self, q: &Aabb, pad: f64, out: &mut Vec<usize>) {
out.clear();
if self.nodes.is_empty() {
return;
}
let mut stack: SmallVec<[u32; 64]> = SmallVec::new();
stack.push(0);
while let Some(ni) = stack.pop() {
let node = &self.nodes[ni as usize];
if !node.aabb.overlaps(q, pad) {
continue;
}
if node.count > 0 {
let s = node.left as usize;
let e = s + node.count as usize;
out.extend_from_slice(&self.verts[s..e]);
} else {
stack.push(node.left);
stack.push(node.right);
}
}
}
}
/// 3D point-BVH incremental T-junction resolver: splits boundary/unmatched triangle edges passing
/// through seam vertices, with an automatic full-edge fallback if a pinch sits on an interior edge.
fn eliminate_t_junctions(mesh: &mut PolyMesh, seg_tol: f64) {
let seg_tol_sq = seg_tol * seg_tol;
let end_tol_sq = (seg_tol * 0.25).max(1e-6).powi(2);
let pad = seg_tol.max(1e-4);
let max_faces = (mesh.faces.len() * 4 + 2048).min(250_000);
let mut prev_bverts: Vec<usize> = Vec::new();
let mut face_is_new: Vec<bool> = vec![true; mesh.faces.len()];
let mut cand_verts: Vec<usize> = Vec::with_capacity(32);
let mut bad_edges_only = true;
for pass in 0..8 {
if mesh.faces.len() >= max_faces {
return;
}
let (bad_edges, bverts, bad_mask) = collect_bad_edges_and_verts(mesh);
if bverts.is_empty() {
return;
}
let bvh_all = if bverts.len() > 16 {
Some(PointBvh::build(&mesh.verts, &bverts))
} else {
None
};
let bvh_new = if pass > 0 && !bad_edges_only {
let new_bv: Vec<usize> = bverts
.iter()
.copied()
.filter(|vi| prev_bverts.binary_search(vi).is_err())
.collect();
if new_bv.is_empty() {
None
} else {
Some(PointBvh::build(&mesh.verts, &new_bv))
}
} else {
None
};
let mut new_faces: Vec<Face> = Vec::with_capacity(mesh.faces.len() + 64);
let mut next_is_new: Vec<bool> = Vec::with_capacity(mesh.faces.len() + 64);
let mut did_split = false;
// When scanning interior (`count == 2`) edges in the `!bad_edges_only` fallback, collect
// proposals first and only split a non-bad edge if BOTH incident triangles split it at the
// exact same vertex list. Half-splitting a manifold edge always breaks topology.
type DeferredSplit = (usize, SmallVec<[usize; 4]>, bool);
let mut deferred_splits: Vec<Option<DeferredSplit>> = if !bad_edges_only {
vec![None; mesh.faces.len()]
} else {
Vec::new()
};
let nf_cur = mesh.faces.len();
let mut old_faces = if bad_edges_only {
std::mem::take(&mut mesh.faces)
} else {
Vec::new()
};
for fi_old in 0..nf_cur {
let f_ref: &Face = if bad_edges_only { &old_faces[fi_old] } else { &mesh.faces[fi_old] };
let is_new = face_is_new.get(fi_old).copied().unwrap_or(true);
if f_ref.verts.len() != 3 || (bad_edges_only && new_faces.len() >= max_faces) {
if bad_edges_only {
new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
}
continue;
}
let tri = [f_ref.verts[0], f_ref.verts[1], f_ref.verts[2]];
let mut edge_bad_flags = [true; 3];
let mut bad_edge_cnt = 3usize;
if bad_edges_only {
// O(1) reject: ~95% of faces have zero boundary vertices and cannot own a T-junction edge!
if !bad_mask[tri[0]] && !bad_mask[tri[1]] && !bad_mask[tri[2]] {
new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
continue;
}
bad_edge_cnt = 0;
for ei in 0..3 {
let u = tri[ei];
let v = tri[(ei + 1) % 3];
let is_bad = bad_mask[u] && bad_mask[v] && {
let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
bad_edges.binary_search(&((lo << 32) | hi)).is_ok()
};
edge_bad_flags[ei] = is_bad;
if is_bad {
bad_edge_cnt += 1;
}
}
if bad_edge_cnt == 0 {
new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
continue;
}
}
if !bad_edges_only && !is_new && bvh_new.is_none() {
continue;
}
let p0 = mesh.verts[tri[0]];
let p1 = mesh.verts[tri[1]];
let p2 = mesh.verts[tri[2]];
// Use tight edge AABB when only 1 edge is bad (avoids pulling unrelated verts on long slivers!)
let query_bb = if bad_edge_cnt == 1 {
let ei = if edge_bad_flags[0] { 0 } else if edge_bad_flags[1] { 1 } else { 2 };
let a = mesh.verts[tri[ei]];
let b = mesh.verts[tri[(ei + 1) % 3]];
Aabb { min: a.min(b), max: a.max(b) }
} else {
Aabb {
min: p0.min(p1).min(p2),
max: p0.max(p1).max(p2),
}
};
let verts_slice: &[usize] = if !bad_edges_only && !is_new {
bvh_new
.as_ref()
.expect("bvh_new is built whenever !bad_edges_only")
.query_aabb(&query_bb, pad, &mut cand_verts);
&cand_verts
} else if let Some(ref bvh) = bvh_all {
bvh.query_aabb(&query_bb, pad, &mut cand_verts);
&cand_verts
} else {
&bverts
};
if verts_slice.is_empty() {
if bad_edges_only {
new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
}
continue;
}
let n_orig = (p1 - p0).cross(p2 - p0);
let orig_area2_sq = n_orig.len_sq();
if orig_area2_sq < 1e-24 {
if bad_edges_only {
new_faces.push(std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0)));
next_is_new.push(false);
}
continue;
}
let min_dot = 1e-10 * orig_area2_sq;
type EdgeSplitProposal = (usize, SmallVec<[(f64, usize); 4]>);
let mut best_edge: Option<EdgeSplitProposal> = None;
for ei in 0..3 {
if !edge_bad_flags[ei] {
continue;
}
let a = mesh.verts[tri[ei]];
let b = mesh.verts[tri[(ei + 1) % 3]];
let c_pt = mesh.verts[tri[(ei + 2) % 3]];
let ab = b - a;
let ab_len_sq = ab.len_sq();
if ab_len_sq < end_tol_sq * 4.0 {
continue;
}
let e_min = a.min(b) - Vec3::splat(pad);
let e_max = a.max(b) + Vec3::splat(pad);
// Endpoint exclusion as a fraction of the edge, capped to an absolute length so a
// very long edge (large part, small cutter) still accepts seam vertices near its ends.
let t_eps = (1e-5_f64).min(1e-5 / ab_len_sq.sqrt());
let mut hits: SmallVec<[(f64, usize); 4]> = SmallVec::new();
for &bv in verts_slice {
if bv == tri[0] || bv == tri[1] || bv == tri[2] {
continue;
}
let q = mesh.verts[bv];
if q.x < e_min.x || q.x > e_max.x || q.y < e_min.y || q.y > e_max.y || q.z < e_min.z || q.z > e_max.z {
continue;
}
// Reject vertices already within snap distance of edge endpoints (prevents sliver cascades!)
if (q - a).len_sq() <= end_tol_sq || (q - b).len_sq() <= end_tol_sq {
continue;
}
let t = (q - a).dot(ab) / ab_len_sq;
if t > t_eps && t < 1.0 - t_eps {
let proj = a + ab * t;
if (q - proj).len_sq() < seg_tol_sq {
hits.push((t, bv));
}
}
}
if !hits.is_empty() {
hits.sort_by(|x, y| x.0.total_cmp(&y.0).then_with(|| x.1.cmp(&y.1)));
// Deduplicate hits that are too close together along the edge
let mut filtered: SmallVec<[(f64, usize); 4]> = SmallVec::new();
for &(t, bv) in &hits {
if filtered.last().is_none_or(|&(_, prev_bv)| {
(mesh.verts[bv] - mesh.verts[prev_bv]).len_sq() > end_tol_sq
}) {
filtered.push((t, bv));
}
}
// Orientation guard: reject any split that would invert or collapse a sub-triangle!
if !filtered.is_empty() {
let mut valid_orient = true;
let mut prev_pt = a;
for &(_, bv) in &filtered {
let cur_pt = mesh.verts[bv];
if (cur_pt - prev_pt).cross(c_pt - prev_pt).dot(n_orig) <= min_dot {
valid_orient = false;
break;
}
prev_pt = cur_pt;
}
if valid_orient && (b - prev_pt).cross(c_pt - prev_pt).dot(n_orig) <= min_dot {
valid_orient = false;
}
if valid_orient {
best_edge = Some((ei, filtered));
break;
}
}
}
}
if bad_edges_only {
let f = std::mem::replace(&mut old_faces[fi_old], Face::new(SmallVec::new(), 0, 0));
if let Some((ei, hits)) = best_edge {
did_split = true;
let a = tri[ei];
let b = tri[(ei + 1) % 3];
let c = tri[(ei + 2) % 3];
let mut prev = a;
for &(_, bv) in &hits {
let mut nf = f.clone();
nf.verts = SmallVec::from_slice(&[prev, bv, c]);
new_faces.push(nf);
next_is_new.push(true);
prev = bv;
}
let mut last_f = f;
last_f.verts = SmallVec::from_slice(&[prev, b, c]);
new_faces.push(last_f);
next_is_new.push(true);
} else {
new_faces.push(f);
next_is_new.push(false);
}
} else if let Some((ei, hits)) = best_edge {
let u = tri[ei];
let v = tri[(ei + 1) % 3];
let is_bad = bad_mask[u] && bad_mask[v] && {
let (lo, hi) = if u < v { (u as u64, v as u64) } else { (v as u64, u as u64) };
bad_edges.binary_search(&((lo << 32) | hi)).is_ok()
};
let hit_ids: SmallVec<[usize; 4]> = hits.iter().map(|&(_, bv)| bv).collect();
deferred_splits[fi_old] = Some((ei, hit_ids, is_bad));
}
}
if !bad_edges_only {
// Pair-match proposed splits on interior (`!is_bad`) edges: only commit if BOTH
// incident faces propose splitting the same edge at the exact same vertices.
let mut interior_props: Vec<(u64, usize, SmallVec<[usize; 4]>)> = Vec::new();
for (fi, prop) in deferred_splits.iter().enumerate() {
if let Some((ei, hit_ids, false)) = prop {
let fv = &mesh.faces[fi].verts;
let u = fv[*ei];
let v = fv[(*ei + 1) % 3];
let (ek, canon_hits) = if u < v {
(((u as u64) << 32) | (v as u64), hit_ids.clone())
} else {
let mut rev = hit_ids.clone();
rev.reverse();
(((v as u64) << 32) | (u as u64), rev)
};
interior_props.push((ek, fi, canon_hits));
}
}
interior_props.sort_unstable_by_key(|&(ek, fi, _)| (ek, fi));
let mut k = 0;
while k < interior_props.len() {
let ek = interior_props[k].0;
let mut m = k + 1;
while m < interior_props.len() && interior_props[m].0 == ek {
m += 1;
}
let matched_pair = (m - k) == 2 && interior_props[k].2 == interior_props[k + 1].2;
if !matched_pair {
for item in &interior_props[k..m] {
deferred_splits[item.1] = None;
}
}
k = m;
}
for (fi_old, f) in mesh.faces.drain(..).enumerate() {
if new_faces.len() < max_faces {
if let Some((ei, hit_ids, _)) = &deferred_splits[fi_old] {
did_split = true;
let tri = [f.verts[0], f.verts[1], f.verts[2]];
let a = tri[*ei];
let b = tri[(*ei + 1) % 3];
let c = tri[(*ei + 2) % 3];
let mut prev = a;
for &bv in hit_ids {
let mut nf = f.clone();
nf.verts = SmallVec::from_slice(&[prev, bv, c]);
new_faces.push(nf);
next_is_new.push(true);
prev = bv;
}
let mut last_f = f;
last_f.verts = SmallVec::from_slice(&[prev, b, c]);
new_faces.push(last_f);
next_is_new.push(true);
continue;
}
}
new_faces.push(f);
next_is_new.push(false);
}
}
mesh.faces = new_faces;
face_is_new = next_is_new;
prev_bverts = bverts;
if !did_split {
if bad_edges_only {
// Rare fallback: check interior edges in case a seam vertex sits on a count==2 edge.
bad_edges_only = false;
face_is_new.fill(true);
continue;
}
break;
}
}
}
fn repair_seam_micro_edges(mesh: &mut PolyMesh) {
for &snap_tol in &[5e-6_f64, 2e-5_f64, 8e-5_f64, 2e-4_f64] {
let mut blist = collect_bad_edges_and_verts(mesh).1;
if blist.is_empty() {
return;
}
// Sort by X for O(B log B) spatial sweep instead of O(B^2) pairwise checks
blist.sort_unstable_by(|&a, &b| {
mesh.verts[a]
.x
.total_cmp(&mesh.verts[b].x)
.then_with(|| a.cmp(&b))
});
let mut remap: Vec<usize> = (0..mesh.verts.len()).collect();
let tol_sq = snap_tol * snap_tol;
let mut merged_any = false;
for i in 0..blist.len() {
let vi = blist[i];
if remap[vi] != vi {
continue;
}
let pi = mesh.verts[vi];
let max_x = pi.x + snap_tol;
for &vj in &blist[(i + 1)..] {
if mesh.verts[vj].x > max_x {
break;
}
if remap[vj] != vj {
continue;
}
if (mesh.verts[vj] - pi).len_sq() <= tol_sq {
remap[vj] = vi;
merged_any = true;
}
}
}
if merged_any {
for f in &mut mesh.faces {
for vi in &mut f.verts {
*vi = remap[*vi];
}
}
mesh.faces.retain(|f| {
f.verts.len() == 3
&& f.verts[0] != f.verts[1]
&& f.verts[1] != f.verts[2]
&& f.verts[2] != f.verts[0]
});
cancel_opposing_and_dup_tris(mesh);
unfold_coplanar_slivers(mesh);
eliminate_t_junctions(mesh, snap_tol.clamp(1e-5, 2e-5));
cancel_opposing_and_dup_tris(mesh);
} else if snap_tol > 1e-5 && snap_tol <= 2e-5 {
eliminate_t_junctions(mesh, snap_tol);
cancel_opposing_and_dup_tris(mesh);
}
}
}
fn prune_folded_flaps(mesh: &mut PolyMesh) {
for _ in 0..8 {
if count_bad_edges(mesh) == 0 {
return;
}
// Build edge -> incident faces lookup (zero HashMap via sort)
let nf = mesh.faces.len();
let mut edge_inc: Vec<(u64, usize)> = Vec::with_capacity(nf * 3);
for (fi, f) in mesh.faces.iter().enumerate() {
let n = f.verts.len();
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u != v {
let (a, b) = if u < v { (u, v) } else { (v, u) };
edge_inc.push((((a as u64) << 32) | (b as u64), fi));
}
}
}
edge_inc.sort_unstable();
let mut counts: Vec<(u64, u32, usize, usize)> = Vec::with_capacity(edge_inc.len() / 2 + 1);
let mut i = 0;
while i < edge_inc.len() {
let k = edge_inc[i].0;
let mut j = i + 1;
while j < edge_inc.len() && edge_inc[j].0 == k {
j += 1;
}
counts.push((k, (j - i) as u32, i, j));
i = j;
}
let edge_key_u64 = |u: usize, v: usize| -> u64 {
let (a, b) = if u < v { (u, v) } else { (v, u) };
((a as u64) << 32) | (b as u64)
};
let lookup = |k: u64| -> (u32, usize, usize) {
counts
.binary_search_by_key(&k, |&(ek, _, _, _)| ek)
.map_or((0, 0, 0), |idx| (counts[idx].1, counts[idx].2, counts[idx].3))
};
let is_sliver = |fi: usize| -> bool {
let f = &mesh.faces[fi];
if f.verts.len() != 3 {
return false;
}
let pa = mesh.verts[f.verts[0]];
let pb = mesh.verts[f.verts[1]];
let pc = mesh.verts[f.verts[2]];
let area2 = (pb - pa).cross(pc - pa).len();
let max_e = (pb - pa).len().max((pc - pb).len()).max((pa - pc).len()).max(1e-12);
area2 / max_e < 2e-3
};
let mut to_remove: HashSet<usize> = HashSet::new();
let mut visited = vec![false; nf];
for seed in 0..nf {
if visited[seed] || !is_sliver(seed) {
continue;
}
let f = &mesh.faces[seed];
let es = [
edge_key_u64(f.verts[0], f.verts[1]),
edge_key_u64(f.verts[1], f.verts[2]),
edge_key_u64(f.verts[2], f.verts[0]),
];
let cs = [lookup(es[0]).0, lookup(es[1]).0, lookup(es[2]).0];
// Seed must touch at least one boundary (1) edge
if !cs.contains(&1) {
continue;
}
// Fast path: classic single-triangle [1, >=3, >=3] flap
let mut cs_sorted = cs;
cs_sorted.sort_unstable();
if cs_sorted[0] == 1 && cs_sorted[1] >= 3 && cs_sorted[2] >= 3 {
visited[seed] = true;
to_remove.insert(seed);
continue;
}
// Generalized path: flood-fill small connected sliver-flap component (up to 16 tris)
// across internal count==2 edges. Valid to remove iff EVERY outer perimeter edge of
// the component has mesh count == 1 or >= 3 (leaves zero new host boundary edges!).
let mut comp: SmallVec<[usize; 16]> = SmallVec::new();
let mut queue: SmallVec<[usize; 16]> = SmallVec::new();
visited[seed] = true;
queue.push(seed);
let mut valid_comp = true;
while let Some(cur) = queue.pop() {
comp.push(cur);
if comp.len() > 16 {
valid_comp = false;
break;
}
let cf = &mesh.faces[cur];
for e_idx in 0..3 {
let ek = edge_key_u64(cf.verts[e_idx], cf.verts[(e_idx + 1) % 3]);
let (cnt, s, e) = lookup(ek);
if cnt == 2 {
let mut found_sliver_nbr = false;
for &(_, nbr) in &edge_inc[s..e] {
if nbr == cur {
continue;
}
if is_sliver(nbr) {
found_sliver_nbr = true;
if !visited[nbr] {
visited[nbr] = true;
queue.push(nbr);
}
}
}
if !found_sliver_nbr {
// Would expose a non-sliver host manifold edge!
valid_comp = false;
break;
}
}
}
if !valid_comp {
break;
}
}
if !valid_comp || comp.is_empty() {
continue;
}
// Verify external boundary of `comp`: must touch at least one count==1 and one count>=3 edge,
// and ZERO count==2 edges leaving `comp`.
let mut comp_edges: SmallVec<[u64; 32]> = SmallVec::new();
for &fi in &comp {
let cf = &mesh.faces[fi];
for e_idx in 0..3 {
comp_edges.push(edge_key_u64(cf.verts[e_idx], cf.verts[(e_idx + 1) % 3]));
}
}
comp_edges.sort_unstable();
let mut has_b = false;
let mut has_nm = false;
let mut touches_host_2 = false;
let mut ei = 0;
while ei < comp_edges.len() {
let ek = comp_edges[ei];
let mut ej = ei + 1;
while ej < comp_edges.len() && comp_edges[ej] == ek {
ej += 1;
}
if ej - ei == 1 {
let cnt = lookup(ek).0;
if cnt == 1 {
has_b = true;
} else if cnt >= 3 {
has_nm = true;
} else {
touches_host_2 = true;
break;
}
}
ei = ej;
}
if has_b && has_nm && !touches_host_2 {
for &fi in &comp {
to_remove.insert(fi);
}
}
}
if to_remove.is_empty() {
break;
}
let mut idx = 0usize;
mesh.faces.retain(|_| {
let keep = !to_remove.contains(&idx);
idx += 1;
keep
});
}
}
/// Fast manifold + consistent-winding check (returns number of bad undirected/unoriented edges).
fn count_bad_or_unoriented_edges(mesh: &PolyMesh) -> usize {
if mesh.faces.is_empty() {
return 1;
}
// Pack (lo: 31 bits, hi: 32 bits, dir: 1 bit) into a single u64 for 2x faster cache-dense sort.
let mut half_edges: Vec<u64> = Vec::with_capacity(mesh.faces.len() * 3);
for f in &mesh.faces {
let n = f.verts.len();
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u == v {
continue;
}
if u < v {
half_edges.push(((u as u64) << 33) | ((v as u64) << 1));
} else {
half_edges.push(((v as u64) << 33) | ((u as u64) << 1) | 1);
}
}
}
half_edges.sort_unstable();
let mut bad = 0usize;
let mut i = 0;
let m = half_edges.len();
while i < m {
let ek = half_edges[i] >> 1;
let mut j = i + 1;
while j < m && (half_edges[j] >> 1) == ek {
j += 1;
}
if (j - i) != 2 || (half_edges[i] ^ half_edges[i + 1]) != 1 {
bad += 1;
}
i = j;
}
bad
}
/// Execute a scale-invariant, tolerance-guided BVH-localized CSG boolean operation
/// between two closed solids, with post-assembly manifold repair and perturbation retries.
/// Largest combined-extent / thinnest-operand-dimension ratio handled by normalizing to the
/// combined extent. Past it the operands are normalized to the thin feature instead.
const BOOL_FEATURE_RATIO: f64 = 32.0;
/// Upper bound on normalized coordinates (keeps absolute tolerances far above f64 round-off).
const BOOL_MAX_NORM_EXTENT: f64 = 1.0e6;
pub fn boolean_op(
a: &PolyMesh,
b: &PolyMesh,
op: BoolOp,
b_name: Option<&str>,
op_id: u32,
) -> Result<PolyMesh, String> {
let res = boolean_op_unchecked(a, b, op, b_name, op_id)?;
if let Some(msg) = silent_noop_reason(a, b, op, &res) {
return Err(msg);
}
Ok(res)
}
/// Safety net against a boolean that silently returns operand A untouched (or nothing) although
/// the geometry contradicts it. Only runs when the result looks unchanged or empty, so it is
/// free otherwise.
fn silent_noop_reason(a: &PolyMesh, b: &PolyMesh, op: BoolOp, res: &PolyMesh) -> Option<String> {
if a.faces.is_empty() || b.faces.is_empty() {
return None;
}
if res.faces.is_empty() {
return match op {
// Everything removed: wrong if some of A lies measurably outside B.
BoolOp::Difference => surface_sample_decisive(b, a, false).map(|_| {
"cut: removed the whole part although it extends outside the cutter (boolean failed; rescale or split the operation)".to_string()
}),
BoolOp::Intersect => surface_sample_decisive(a, b, true).map(|ratio| {
format!("intersect: returned nothing although the operands overlap (size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation)")
}),
BoolOp::Union => None,
};
}
let unchanged = !matches!(op, BoolOp::Intersect)
&& res.verts.len() == a.verts.len()
&& res.faces.len() <= a.faces.len().max(1) * 2
&& {
let (va, vr) = (a.signed_volume(), res.signed_volume());
(va - vr).abs() <= 1e-12 * va.abs()
};
if !unchanged {
return None;
}
// For cut the evidence is a point of B well inside A; for union, well outside A.
let want_inside = matches!(op, BoolOp::Difference);
let ratio = surface_sample_decisive(a, b, want_inside)?;
let (name, what) = if want_inside {
("cut", "removed no material although the cutter penetrates the part")
} else {
("add", "added nothing although the tool extends outside the part")
};
let pair_hint = diagnose_boolean_pair(a, b, op)
.map(|h| format!("; {h}"))
.unwrap_or_default();
Some(format!(
"{name}: {what} (part/tool size ratio {ratio:.1e} is beyond what the boolean tolerance resolves; rescale or split the operation){pair_hint}"
))
}
/// Detect coplanar/grazing axis-aligned bounding planes between two boolean operands and return a concrete edit hint.
pub fn diagnose_boolean_pair(a: &PolyMesh, b: &PolyMesh, op: BoolOp) -> Option<String> {
let (bb_a, bb_b) = (a.aabb(), b.aabb());
if !bb_a.is_valid() || !bb_b.is_valid() {
return None;
}
let ext = bb_a.max.max(bb_b.max) - bb_a.min.min(bb_b.min);
let scale = ext.x.max(ext.y).max(ext.z).max(1e-9);
let tol = 1e-4 * scale;
let delta = (0.02 * scale).clamp(1e-3, 1.0);
let axes = ['x', 'y', 'z'];
let a_min = [bb_a.min.x, bb_a.min.y, bb_a.min.z];
let a_max = [bb_a.max.x, bb_a.max.y, bb_a.max.z];
let b_min = [bb_b.min.x, bb_b.min.y, bb_b.min.z];
let b_max = [bb_b.max.x, bb_b.max.y, bb_b.max.z];
let mut hits: Vec<String> = Vec::new();
for k in 0..3 {
let ax = axes[k];
if (a_min[k] - b_min[k]).abs() <= tol {
hits.push(format!("{ax}={:.3} (min)", a_min[k]));
}
if (a_max[k] - b_max[k]).abs() <= tol {
hits.push(format!("{ax}={:.3} (max)", a_max[k]));
}
if (a_max[k] - b_min[k]).abs() <= tol {
hits.push(format!("{ax}={:.3} (tangent)", a_max[k]));
}
if (a_min[k] - b_max[k]).abs() <= tol {
hits.push(format!("{ax}={:.3} (tangent)", a_min[k]));
}
}
if hits.is_empty() {
return None;
}
let action = match op {
BoolOp::Difference => format!("extend cutter past coplanar face by +{delta:.3}"),
BoolOp::Union => format!("increase overlap past tangent/coplanar face by +{delta:.3}"),
BoolOp::Intersect => format!("widen overlap past coplanar face by +{delta:.3}"),
};
Some(format!("coplanar/grazing face at {}; {action}", hits.join(", ")))
}
/// Pinpoint offending boundary, non-manifold, or flipped-winding edges on a failed mesh with a centroid and fix hint.
/// Only called on error paths (zero overhead on valid builds).
pub fn diagnose_bad_edges(mesh: &PolyMesh) -> Option<String> {
if mesh.faces.is_empty() || mesh.verts.is_empty() {
return None;
}
let mut half_edges: Vec<(u32, u32, i8)> = Vec::with_capacity(mesh.faces.len() * 3);
for f in &mesh.faces {
let n = f.verts.len();
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u == v || u >= mesh.verts.len() || v >= mesh.verts.len() {
continue;
}
if u < v {
half_edges.push((u as u32, v as u32, 1));
} else {
half_edges.push((v as u32, u as u32, -1));
}
}
}
if half_edges.is_empty() {
return None;
}
half_edges.sort_unstable_by_key(|&(u, v, _)| (u, v));
let mut sum = Vec3::ZERO;
let mut bad_bb = Aabb::empty();
let mut bad_count = 0usize;
let mut i = 0;
let m = half_edges.len();
while i < m {
let (u, v, _) = half_edges[i];
let mut j = i + 1;
let mut dir_sum: i32 = half_edges[i].2 as i32;
while j < m && half_edges[j].0 == u && half_edges[j].1 == v {
dir_sum += half_edges[j].2 as i32;
j += 1;
}
let count = j - i;
if count != 2 || dir_sum != 0 {
let pu = mesh.verts[u as usize];
let pv = mesh.verts[v as usize];
if pu.is_finite() && pv.is_finite() {
sum += (pu + pv) * 0.5;
bad_bb.include(pu);
bad_bb.include(pv);
bad_count += 1;
}
}
i = j;
}
if bad_count == 0 || !bad_bb.is_valid() {
return None;
}
let centroid = sum * (1.0 / bad_count as f64);
let span = bad_bb.size();
let mesh_ext = mesh.aabb().size();
let scale = mesh_ext.x.max(mesh_ext.y).max(mesh_ext.z).max(1e-9);
let plane_tol = 1e-4 * scale;
let delta = (0.02 * scale).clamp(1e-3, 1.0);
let plane_hint = if span.z <= plane_tol && (span.x > plane_tol || span.y > plane_tol) {
Some(format!(
"coplanar at z={:.3}; extend cutter/overlap past z={:.3} by +{delta:.3}",
centroid.z, centroid.z
))
} else if span.x <= plane_tol && (span.y > plane_tol || span.z > plane_tol) {
Some(format!(
"coplanar at x={:.3}; extend cutter/overlap past x={:.3} by +{delta:.3}",
centroid.x, centroid.x
))
} else if span.y <= plane_tol && (span.x > plane_tol || span.z > plane_tol) {
Some(format!(
"coplanar at y={:.3}; extend cutter/overlap past y={:.3} by +{delta:.3}",
centroid.y, centroid.y
))
} else {
None
};
match plane_hint {
Some(ph) => Some(format!(
"at ({:.3}, {:.3}, {:.3}) [{bad_count} bad edges, {ph}]",
centroid.x, centroid.y, centroid.z
)),
None => Some(format!(
"at ({:.3}, {:.3}, {:.3}) [{bad_count} bad edges, span=[{:.3},{:.3},{:.3}]]; extend cutter/overlap by +{delta:.3} or nudge seam slightly",
centroid.x, centroid.y, centroid.z, span.x, span.y, span.z
)),
}
}
/// Looks for a surface sample of `probe` (vertices and face centroids) that is decisively inside
/// (`want_inside`) or outside `container`: on the wanted side and at least 0.1% of the probe's
/// thinnest dimension away from the container's surface, so touching or coincident surfaces
/// never count. Returns the container/probe size ratio when such a sample exists.
fn surface_sample_decisive(container: &PolyMesh, probe: &PolyMesh, want_inside: bool) -> Option<f64> {
let (bb_c, bb_p) = (container.aabb(), probe.aabb());
if !bb_c.is_valid() || !bb_p.is_valid() || probe.signed_volume().abs() <= 0.0 || container.signed_volume().abs() <= 0.0 {
return None;
}
let sp = bb_p.size();
let p_max = sp.x.max(sp.y).max(sp.z);
if !p_max.is_finite() || p_max <= 0.0 {
return None;
}
let mut p_min = p_max;
for d in [sp.x, sp.y, sp.z] {
if d > p_max * 1e-12 && d < p_min {
p_min = d;
}
}
// Work in probe-sized coordinates so the ray tolerances are small against the probe.
let c = bb_p.center();
let inv = 1.0 / p_min;
let to_local = |p: Vec3| (p - c) * inv;
let mut tris: Vec<Tri> = Vec::with_capacity(container.faces.len() * 2);
for fi in 0..container.faces.len() {
for [i, j, k] in container.triangulate_face(fi) {
if let Some(t) = Tri::from_verts(
to_local(container.verts[i]),
to_local(container.verts[j]),
to_local(container.verts[k]),
0,
0,
0,
) {
tris.push(t);
}
}
}
let bvh = TriBvh::build(&tris);
let delta = 1e-3;
let mut near: Vec<u32> = Vec::new();
let v_stride = (probe.verts.len() / 48).max(1);
let f_stride = (probe.faces.len() / 48).max(1);
let samples = probe
.verts
.iter()
.step_by(v_stride)
.copied()
.chain((0..probe.faces.len()).step_by(f_stride).map(|fi| probe.face_centroid(fi)));
for p in samples {
if !p.is_finite() {
continue;
}
let q = to_local(p);
if bvh.point_inside(&tris, q) != want_inside {
continue;
}
bvh.query_aabb(&Aabb { min: q, max: q }, delta, &mut near);
let clear = near.iter().all(|&ti| {
let t = &tris[ti as usize];
(crate::spatial::closest_pt_on_tri(q, t.v[0], t.v[1], t.v[2]) - q).len_sq() > delta * delta
});
if clear {
let sc = bb_c.size();
return Some(sc.x.max(sc.y).max(sc.z) / p_min);
}
}
None
}
fn boolean_op_unchecked(
a: &PolyMesh,
b: &PolyMesh,
op: BoolOp,
b_name: Option<&str>,
op_id: u32,
) -> Result<PolyMesh, String> {
let bb_a = a.aabb();
let bb_b = b.aabb();
if !bb_a.is_valid() || !bb_b.is_valid() {
return Ok(match op {
BoolOp::Union => {
if bb_a.is_valid() {
a.clone()
} else {
b.clone()
}
}
BoolOp::Difference => a.clone(),
BoolOp::Intersect => PolyMesh::new(),
});
}
let cmin = bb_a.min.min(bb_b.min);
let cmax = bb_a.max.max(bb_b.max);
let center = (cmin + cmax) * 0.5;
let ext = cmax - cmin;
let scale = ext.x.max(ext.y).max(ext.z).max(1e-9);
let rel_eps = 1e-5 * scale;
if !bb_a.overlaps(&bb_b, rel_eps) {
return Ok(match op {
BoolOp::Union => {
let mut out = a.clone();
out.append_mesh(b);
out
}
BoolOp::Difference => a.clone(),
BoolOp::Intersect => PolyMesh::new(),
});
}
// The kernel's weld/coplanarity tolerances are absolute in normalized space, so they must
// be small against the smallest operand feature, not against the combined extent: a 2 mm
// cutter in a 10 m part normalized to the part would fall below them and be dropped whole.
// When the extents are far apart, normalize to the thinnest operand dimension instead.
let feature = {
let floor = scale * 1e-12;
let mut f = scale;
for bb in [&bb_a, &bb_b] {
let s = bb.size();
for d in [s.x, s.y, s.z] {
if d > floor && d < f {
f = d;
}
}
}
f
};
let extreme_ratio = scale > BOOL_FEATURE_RATIO * feature;
let scale = if extreme_ratio {
(feature * BOOL_FEATURE_RATIO).max(scale / BOOL_MAX_NORM_EXTENT)
} else {
scale
};
// Normalize both operands around their combined AABB center whenever the geometry is far
// from unit scale, far from the origin, or has an extreme part/tool feature ratio.
let needs_norm = !(0.25..=8.0).contains(&scale) || center.len() > 1e3 || extreme_ratio;
let (an_buf, bn_buf);
let (a_ref, b_ref): (&PolyMesh, &PolyMesh) = if needs_norm {
let inv_scale = 1.0 / scale;
let mut an = a.clone();
for v in &mut an.verts {
*v = (*v - center) * inv_scale;
}
let mut bn = b.clone();
for v in &mut bn.verts {
*v = (*v - center) * inv_scale;
}
an_buf = an;
bn_buf = bn;
(&an_buf, &bn_buf)
} else {
(a, b)
};
let unnormalize = |mut m: PolyMesh| -> PolyMesh {
if needs_norm {
for v in &mut m.verts {
*v = *v * scale + center;
}
}
m
};
let tag_str = b_name.map(|n| format!("bool:{n}"));
let mut prep_a = PreparedCsgA::new(a_ref, b_ref);
let (res, bad0) = prep_a.run(b_ref, op, tag_str.as_deref(), op_id);
if bad0 == 0 && !res.faces.is_empty() {
return Ok(unnormalize(res));
}
// A clean empty result is a real answer for cut/intersect (the tool swallows the part, or the
// operands only touch). Perturbing the tool here would leave a zero-thickness skin behind.
// `silent_noop_reason` separately rejects an empty result that the geometry contradicts.
if bad0 == 0 && res.faces.is_empty() && !matches!(op, BoolOp::Union) {
return Ok(res);
}
// Deterministic perturbation retry on grazing curved seams (only reached when exact pass has bad/unoriented edges)
let perturbations = [
(Vec3::new(1.37e-5, -2.11e-5, 1.73e-5), 1.0 + 1.9e-5, (0.0, 0.0, 0.0)),
(Vec3::new(-2.91e-5, 1.63e-5, -1.49e-5), 1.0 - 2.3e-5, (0.0, 0.0, 0.0)),
(Vec3::new(3.13e-5, 2.71e-5, -2.29e-5), 1.0 + 3.7e-5, (0.013, -0.017, 0.011)),
(Vec3::new(-4.19e-5, -3.53e-5, 2.81e-5), 1.0 - 4.1e-5, (-0.019, 0.014, -0.016)),
];
let mut best = res;
let mut best_bad = bad0;
let c = b_ref.aabb().center();
let mut bp = b_ref.clone();
for (shift, sc, (rx, ry, rz)) in perturbations {
let rot = if rx != 0.0 || ry != 0.0 || rz != 0.0 {
Some(Vec3::euler_xyz_deg_matrix(rx, ry, rz))
} else {
None
};
for (dst, &src) in bp.verts.iter_mut().zip(&b_ref.verts) {
let mut rel = (src - c) * sc;
if let Some(ref m) = rot {
rel = rel.mul_mat3(m);
}
*dst = c + rel + shift;
}
let (cand, bad) = prep_a.run(&bp, op, tag_str.as_deref(), op_id);
if bad == 0 && !cand.faces.is_empty() {
// The tool was nudged by up to ~1e-4 of its size. A cut/intersect result no thicker
// than that nudge is the nudge itself (coincident or merely touching operands), not
// geometry: the true result is empty.
if !matches!(op, BoolOp::Union) {
let area: f64 = (0..cand.faces.len()).map(|fi| cand.face_area(fi)).sum();
let bs = bp.aabb().size();
let b_ext = bs.x.max(bs.y).max(bs.z);
let thickness = 2.0 * cand.signed_volume().abs() / area.max(1e-300);
if thickness < 5e-4 * b_ext + 1e-4 {
return Ok(PolyMesh::new());
}
}
return Ok(unnormalize(cand));
}
if bad < best_bad {
best_bad = bad;
best = cand;
}
}
Ok(unnormalize(best))
}
/// Apply a pairwise-disjoint group of tools in one batch, automatically falling back to
/// binary-split sub-batches (down to sequential cuts) if the combined batch yields any bad edges.
fn apply_disjoint_group(
a: &PolyMesh,
group: &[&PolyMesh],
op: BoolOp,
b_name: Option<&str>,
op_id: u32,
) -> Result<PolyMesh, String> {
if group.is_empty() {
return Ok(a.clone());
}
if group.len() == 1 {
return boolean_op(a, group[0], op, b_name, op_id);
}
let mut merged = group[0].clone();
for t in &group[1..] {
merged.append_mesh(t);
}
if let Ok(cand) = boolean_op(a, &merged, op, b_name, op_id) {
if count_bad_or_unoriented_edges(&cand) == 0 && !cand.faces.is_empty() {
return Ok(cand);
}
}
// Automatic binary-split fallback so multi-hole batches never fail when sequential cuts pass!
let mid = group.len() / 2;
let left = apply_disjoint_group(a, &group[..mid], op, b_name, op_id)?;
apply_disjoint_group(&left, &group[mid..], op, b_name, op_id)
}
/// Batch boolean of `a` with multiple tool meshes.
/// Pairwise-disjoint tools are chunked (up to 4 tools / 256 faces per pass) into fast BVH boolean
/// passes with automatic binary-split fallback on any grazing seam, while overlapping tools run sequentially.
pub fn boolean_batch(
a: &PolyMesh,
tools: &[PolyMesh],
op: BoolOp,
b_name: Option<&str>,
op_id: u32,
) -> Result<PolyMesh, String> {
if tools.is_empty() {
return Ok(a.clone());
}
if tools.len() == 1 {
return boolean_op(a, &tools[0], op, b_name, op_id);
}
if op == BoolOp::Intersect {
let mut acc = a.clone();
for t in tools {
acc = boolean_op(&acc, t, op, b_name, op_id)?;
}
return Ok(acc);
}
// Partition tools into bounded pairwise-disjoint batches (keeps 4-hole flanges in 1 pass
// while preventing 8-20+ hole rows from shattering 2 giant plate triangles with 500+ planes).
const MAX_BATCH_TOOLS: usize = 4;
const MAX_BATCH_FACES: usize = 256;
let target_scale = a.aabb().size().len().max(1e-6);
let disj_eps = (1e-4_f64).min(1e-4 * target_scale);
let bbs: Vec<Aabb> = tools.iter().map(|t| t.aabb()).collect();
let mut used = vec![false; tools.len()];
let mut acc = a.clone();
for i in 0..tools.len() {
if used[i] {
continue;
}
used[i] = true;
let mut group: Vec<&PolyMesh> = vec![&tools[i]];
let mut group_faces = tools[i].faces.len();
let mut batch_bbs = vec![bbs[i]];
let mut group_bb = bbs[i];
let mut min_tool_dim = bbs[i].size().len();
for j in (i + 1)..tools.len() {
if used[j] || group.len() >= MAX_BATCH_TOOLS {
continue;
}
if group_faces + tools[j].faces.len() > MAX_BATCH_FACES {
continue;
}
if !batch_bbs.iter().any(|bb| bb.overlaps(&bbs[j], disj_eps)) {
let mut next_bb = group_bb;
next_bb.include(bbs[j].min);
next_bb.include(bbs[j].max);
let next_min = min_tool_dim.min(bbs[j].size().len());
// Avoid merging tiny tools across a huge span that would defeat extreme_ratio normalization.
if next_min < 0.04 * next_bb.size().len() {
continue;
}
group.push(&tools[j]);
group_faces += tools[j].faces.len();
batch_bbs.push(bbs[j]);
group_bb = next_bb;
min_tool_dim = next_min;
used[j] = true;
}
}
acc = apply_disjoint_group(&acc, &group, op, b_name, op_id)?;
}
Ok(acc)
}
#[inline]
fn clip_poly_2d_halfplane(
poly: &[(f64, f64)],
a: (f64, f64),
b: (f64, f64),
) -> SmallVec<[(f64, f64); 8]> {
let mut out: SmallVec<[(f64, f64); 8]> = SmallVec::new();
let n = poly.len();
if n == 0 {
return out;
}
let dx = b.0 - a.0;
let dy = b.1 - a.1;
let side = |p: (f64, f64)| -> f64 { dx * (p.1 - a.1) - dy * (p.0 - a.0) };
let mut prev = poly[n - 1];
let mut prev_s = side(prev);
for &curr in poly {
let curr_s = side(curr);
let prev_in = prev_s >= 0.0;
let curr_in = curr_s >= 0.0;
if curr_in {
if !prev_in {
let denom = prev_s - curr_s;
if denom.abs() > 1e-18 {
let t = prev_s / denom;
out.push((prev.0 + (curr.0 - prev.0) * t, prev.1 + (curr.1 - prev.1) * t));
}
}
out.push(curr);
} else if prev_in {
let denom = prev_s - curr_s;
if denom.abs() > 1e-18 {
let t = prev_s / denom;
out.push((prev.0 + (curr.0 - prev.0) * t, prev.1 + (curr.1 - prev.1) * t));
}
}
prev = curr;
prev_s = curr_s;
}
out
}
fn coplanar_tris_overlap_area(a: &[Vec3; 3], b: &[Vec3; 3], n: Vec3) -> f64 {
let drop_axis = if n.x.abs() >= n.y.abs() && n.x.abs() >= n.z.abs() {
0
} else if n.y.abs() >= n.z.abs() {
1
} else {
2
};
let proj = |p: Vec3| -> (f64, f64) {
match drop_axis {
0 => (p.y, p.z),
1 => (p.z, p.x),
_ => (p.x, p.y),
}
};
let mut pa = [proj(a[0]), proj(a[1]), proj(a[2])];
let mut pb = [proj(b[0]), proj(b[1]), proj(b[2])];
let cross2 = |p0: (f64, f64), p1: (f64, f64), p2: (f64, f64)| -> f64 {
(p1.0 - p0.0) * (p2.1 - p0.1) - (p1.1 - p0.1) * (p2.0 - p0.0)
};
if cross2(pa[0], pa[1], pa[2]) < 0.0 {
pa.swap(1, 2);
}
if cross2(pb[0], pb[1], pb[2]) < 0.0 {
pb.swap(1, 2);
}
let mut poly: SmallVec<[(f64, f64); 8]> = SmallVec::from_slice(&pa);
for i in 0..3 {
poly = clip_poly_2d_halfplane(&poly, pb[i], pb[(i + 1) % 3]);
if poly.len() < 3 {
return 0.0;
}
}
let mut area2 = 0.0;
for i in 0..poly.len() {
let p0 = poly[i];
let p1 = poly[(i + 1) % poly.len()];
area2 += p0.0 * p1.1 - p1.0 * p0.1;
}
0.5 * area2.abs()
}
fn tri_plane_overlap_interval(tri: &[Vec3; 3], dists: [f64; 3], line_dir: Vec3, eps: f64) -> Option<(f64, f64)> {
let mut tmin = f64::INFINITY;
let mut tmax = f64::NEG_INFINITY;
let mut count = 0usize;
for k in 0..3 {
if dists[k].abs() <= eps {
let t = tri[k].dot(line_dir);
tmin = tmin.min(t);
tmax = tmax.max(t);
count += 1;
}
let kn = (k + 1) % 3;
if (dists[k] > eps && dists[kn] < -eps) || (dists[k] < -eps && dists[kn] > eps) {
let frac = dists[k] / (dists[k] - dists[kn]);
let p = tri[k] + (tri[kn] - tri[k]) * frac;
let t = p.dot(line_dir);
tmin = tmin.min(t);
tmax = tmax.max(t);
count += 1;
}
}
if count > 0 {
Some((tmin, tmax))
} else {
None
}
}
fn tris_overlap_3d(a: &Tri, b: &Tri, scale: f64) -> bool {
let s = scale.max(1e-9);
let plane_eps = 1e-7 * s;
let da = [
b.normal.dot(a.v[0]) - b.w,
b.normal.dot(a.v[1]) - b.w,
b.normal.dot(a.v[2]) - b.w,
];
if (da[0] > plane_eps && da[1] > plane_eps && da[2] > plane_eps)
|| (da[0] < -plane_eps && da[1] < -plane_eps && da[2] < -plane_eps)
{
return false;
}
let db = [
a.normal.dot(b.v[0]) - a.w,
a.normal.dot(b.v[1]) - a.w,
a.normal.dot(b.v[2]) - a.w,
];
if (db[0] > plane_eps && db[1] > plane_eps && db[2] > plane_eps)
|| (db[0] < -plane_eps && db[1] < -plane_eps && db[2] < -plane_eps)
{
return false;
}
let line_dir = a.normal.cross(b.normal);
if line_dir.len_sq() < 1e-6 {
// Parallel or nearly parallel planes: only count as overlapping if genuinely coplanar
// and their 2D projections share positive area.
if da.iter().any(|d| d.abs() > plane_eps) || db.iter().any(|d| d.abs() > plane_eps) {
return false;
}
let area = coplanar_tris_overlap_area(&a.v, &b.v, a.normal);
let area_eps = 1e-10 * s * s;
return area > area_eps;
}
// Non-parallel planes: a triangle strictly on one side of the other's plane cannot intersect it.
if (da[0] > 0.0 && da[1] > 0.0 && da[2] > 0.0)
|| (da[0] < 0.0 && da[1] < 0.0 && da[2] < 0.0)
|| (db[0] > 0.0 && db[1] > 0.0 && db[2] > 0.0)
|| (db[0] < 0.0 && db[1] < 0.0 && db[2] < 0.0)
{
return false;
}
let d = line_dir.normalized();
let exact_eps = 1e-12 * s;
let Some((ta0, ta1)) = tri_plane_overlap_interval(&a.v, da, d, exact_eps) else {
return false;
};
let Some((tb0, tb1)) = tri_plane_overlap_interval(&b.v, db, d, exact_eps) else {
return false;
};
ta0.max(tb0) < ta1.min(tb1) - plane_eps
}
/// Fast per-component AABB + BVH inter-shell overlap check for multi-component meshes.
/// Zero cost for single-component meshes; cleanly permits valid negative-volume inner cavities
/// (e.g. closed `shell(..., open_top=false)`) whose triangles do not intersect the outer shell.
pub fn has_overlapping_components(mesh: &PolyMesh) -> bool {
check_overlapping_components(mesh) == OverlapCheck::Overlap
}
/// Multi-shell overlap check in near-linear time: shells are labelled by union-find, then a
/// single triangle BVH finds candidate pairs across shells. A work budget bounds pathological
/// layouts; when it runs out the result is `Unverified` instead of a multi-minute stall.
pub fn check_overlapping_components(mesh: &PolyMesh) -> OverlapCheck {
let n_faces = mesh.faces.len();
if n_faces < 2 {
return OverlapCheck::Clear;
}
// 1. Sort-based face-edge Union-Find to partition connected shell components
let mut edges: Vec<(u32, u32, u32)> = Vec::with_capacity(n_faces * 4);
for (fi, f) in mesh.faces.iter().enumerate() {
let n = f.verts.len();
let fi32 = fi as u32;
for i in 0..n {
let u = f.verts[i];
let v = f.verts[(i + 1) % n];
if u != v {
let (a, b) = if u < v { (u as u32, v as u32) } else { (v as u32, u as u32) };
edges.push((a, b, fi32));
}
}
}
edges.sort_unstable_by_key(|&(a, b, _)| ((a as u64) << 32) | (b as u64));
let mut parent: Vec<u32> = (0..n_faces as u32).collect();
let find = |parent: &mut [u32], mut x: u32| -> u32 {
while parent[x as usize] != x {
let gp = parent[parent[x as usize] as usize];
parent[x as usize] = gp;
x = gp;
}
x
};
let mut i = 0;
let m = edges.len();
while i < m {
let (u, v, f0) = edges[i];
let mut j = i + 1;
while j < m && edges[j].0 == u && edges[j].1 == v {
let ra = find(&mut parent, f0);
let rb = find(&mut parent, edges[j].2);
if ra != rb {
parent[rb as usize] = ra;
}
j += 1;
}
i = j;
}
let mut root_to_cid = vec![u32::MAX; n_faces];
let mut comp_faces: Vec<Vec<usize>> = Vec::new();
for fi in 0..n_faces {
let r = find(&mut parent, fi as u32) as usize;
if root_to_cid[r] == u32::MAX {
root_to_cid[r] = comp_faces.len() as u32;
comp_faces.push(Vec::new());
}
comp_faces[root_to_cid[r] as usize].push(fi);
}
let nc = comp_faces.len();
if nc <= 1 {
return OverlapCheck::Clear;
}
// 2. Per-component scale-invariant signed compactness (vol / area^1.5) and global bounds.
// Computing per component in local normalized coordinates prevents micro-scale underflow,
// macro-scale overflow, and distant-origin precision loss.
let mut comp_vols: Vec<f64> = Vec::with_capacity(nc);
let mut global_bb = Aabb::empty();
for c_faces in &comp_faces {
let mut comp_bb = Aabb::empty();
for &fi in c_faces {
for &vi in &mesh.faces[fi].verts {
let p = mesh.verts[vi];
comp_bb.include(p);
global_bb.include(p);
}
}
if !comp_bb.is_valid() {
comp_vols.push(0.0);
continue;
}
let c_ext = comp_bb.size().x.max(comp_bb.size().y).max(comp_bb.size().z);
if !c_ext.is_finite() || c_ext <= 0.0 {
comp_vols.push(0.0);
continue;
}
let c_orig = comp_bb.min;
let c_inv = 1.0 / c_ext;
let mut vol6 = 0.0;
let mut area2 = 0.0;
for &fi in c_faces {
for [a, b, c] in mesh.triangulate_face(fi) {
let va = (mesh.verts[a] - c_orig) * c_inv;
let vb = (mesh.verts[b] - c_orig) * c_inv;
let vc = (mesh.verts[c] - c_orig) * c_inv;
vol6 += va.dot(vb.cross(vc));
area2 += (vb - va).cross(vc - va).len();
}
}
let area = 0.5 * area2;
let compactness = if area > 0.0 && area.is_finite() && vol6.is_finite() {
(vol6 / 6.0) / area.powf(1.5)
} else {
0.0
};
comp_vols.push(compactness);
}
if !global_bb.is_valid() {
return OverlapCheck::Clear;
}
// 3. One BVH over every triangle (tagged with its shell id) instead of a shell-pair loop:
// O(T log T + candidate pairs). A first pass runs in world axes; if thin diagonal shells
// make the axis-aligned boxes useless, retry in the dominant edge frame, then deterministic
// 45-degree / golden-angle orthonormal fallback frames (handling isotropic +/-45 deg fins).
if let Some(r) = overlap_pass(mesh, &comp_faces, &comp_vols, &global_bb, None, OVERLAP_WORLD_BUDGET) {
return r;
}
let frame = dominant_edge_frame(mesh);
if let Some(r) = overlap_pass(mesh, &comp_faces, &comp_vols, &global_bb, Some(frame), OVERLAP_WORLD_BUDGET) {
return r;
}
for fb in fallback_overlap_frames() {
if let Some(r) = overlap_pass(mesh, &comp_faces, &comp_vols, &global_bb, Some(fb), OVERLAP_WORLD_BUDGET) {
return r;
}
}
match overlap_pass(mesh, &comp_faces, &comp_vols, &global_bb, Some(frame), OVERLAP_FRAME_BUDGET) {
Some(r) => r,
None => OverlapCheck::Unverified,
}
}
/// Outcome of the multi-shell overlap check.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OverlapCheck {
/// No two shells cross, overlap or contain each other.
Clear,
/// At least two shells cross, overlap coplanar, or one solid sits inside another.
Overlap,
/// The work budget ran out before the mesh could be cleared (pathological shell layout).
Unverified,
}
/// Candidate triangle-pair / BVH-node visits allowed for the world-axis pass.
const OVERLAP_WORLD_BUDGET: u64 = 6_000_000;
/// Candidate visits allowed for the retry in the dominant-direction frame.
const OVERLAP_FRAME_BUDGET: u64 = 40_000_000;
/// Orthonormal frame whose first axis is the dominant direction of the mesh's longest
/// triangle edges (power iteration on their length-weighted covariance). Deterministic.
fn dominant_edge_frame(mesh: &PolyMesh) -> [Vec3; 3] {
let mut c = [[0.0f64; 3]; 3];
for fi in 0..mesh.faces.len() {
for [a, b, cc] in mesh.triangulate_face(fi) {
let p = [mesh.verts[a], mesh.verts[b], mesh.verts[cc]];
let mut best = Vec3::ZERO;
for k in 0..3 {
let e = p[(k + 1) % 3] - p[k];
if e.len_sq() > best.len_sq() {
best = e;
}
}
let l = best.len();
if !l.is_finite() || l < 1e-300 {
continue;
}
let d = [best.x, best.y, best.z];
for (r, row) in c.iter_mut().enumerate() {
let dr = d[r] / l;
for (s, cell) in row.iter_mut().enumerate() {
*cell += dr * d[s];
}
}
}
}
let mut v = Vec3::new(0.6123, 0.5231, 0.5929).normalized();
for _ in 0..64 {
let w = Vec3::new(
c[0][0] * v.x + c[0][1] * v.y + c[0][2] * v.z,
c[1][0] * v.x + c[1][1] * v.y + c[1][2] * v.z,
c[2][0] * v.x + c[2][1] * v.y + c[2][2] * v.z,
);
let l = w.len();
if !l.is_finite() || l < 1e-300 {
break;
}
v = w / l;
}
let helper = if v.x.abs() < 0.9 { Vec3::new(1.0, 0.0, 0.0) } else { Vec3::new(0.0, 1.0, 0.0) };
let u = v.cross(helper).normalized();
let w = v.cross(u).normalized();
[v, u, w]
}
/// Deterministic fallback orthonormal frames for layouts whose edge covariance is isotropic
/// (e.g. balanced +/-45 deg fins in XY, XZ, or YZ, or skewed 3D diagonals).
fn fallback_overlap_frames() -> [[Vec3; 3]; 4] {
let s = std::f64::consts::FRAC_1_SQRT_2;
let phi = 0.5 * (1.0 + 5.0_f64.sqrt());
let g0 = Vec3::new(1.0, phi, 1.0 / phi).normalized();
let g1 = g0.cross(Vec3::new(-phi, 1.0, 0.0)).normalized();
let g2 = g0.cross(g1).normalized();
[
[Vec3::new(s, s, 0.0), Vec3::new(-s, s, 0.0), Vec3::new(0.0, 0.0, 1.0)],
[Vec3::new(s, 0.0, s), Vec3::new(0.0, 1.0, 0.0), Vec3::new(-s, 0.0, s)],
[Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, s, s), Vec3::new(0.0, -s, s)],
[g0, g1, g2],
]
}
/// One pass of the multi-shell overlap check. `None` means the work budget ran out.
fn overlap_pass(
mesh: &PolyMesh,
comp_faces: &[Vec<usize>],
comp_vols: &[f64],
global_bb: &Aabb,
frame: Option<[Vec3; 3]>,
budget: u64,
) -> Option<OverlapCheck> {
let nc = comp_faces.len();
let extent = global_bb.size().x.max(global_bb.size().y).max(global_bb.size().z);
if !extent.is_finite() || extent <= 0.0 {
return Some(OverlapCheck::Clear);
}
let center = (global_bb.min + global_bb.max) * 0.5;
let shift = if center.x.abs().max(center.y.abs()).max(center.z.abs()) > 2.0 * extent {
center
} else {
Vec3::ZERO
};
let inv_scale = 1.0 / extent;
let aabb_eps = 1e-6;
let xf = |p: Vec3| -> Vec3 {
let q = (p - shift) * inv_scale;
match &frame {
Some(f) => Vec3::new(q.dot(f[0]), q.dot(f[1]), q.dot(f[2])),
None => q,
}
};
// Shell id rides in `tag_idx`; `first_tri[c]` is the first triangle of shell c.
let mut tris: Vec<Tri> = Vec::with_capacity(mesh.faces.len() * 2);
let mut first_tri: Vec<u32> = vec![u32::MAX; nc];
for (cid, c_faces) in comp_faces.iter().enumerate() {
for &fi in c_faces {
for [a, b, c] in mesh.triangulate_face(fi) {
if let Some(t) = Tri::from_verts_rel(xf(mesh.verts[a]), xf(mesh.verts[b]), xf(mesh.verts[c]), cid as u32, 0, 0) {
if first_tri[cid] == u32::MAX {
first_tri[cid] = tris.len() as u32;
}
tris.push(t);
}
}
}
}
let bvh = TriBvh::build(&tris);
let mut work: u64 = 0;
// Triangle-triangle crossing or coplanar face overlap between different shells
let mut hits: Vec<u32> = Vec::with_capacity(32);
for (i, ta) in tris.iter().enumerate() {
bvh.query_aabb(&ta.aabb, aabb_eps, &mut hits);
work += hits.len() as u64 + 1;
for &j in &hits {
let j = j as usize;
if j <= i {
continue;
}
let tb = &tris[j];
if tb.tag_idx != ta.tag_idx && tris_overlap_3d(ta, tb, 1.0) {
return Some(OverlapCheck::Overlap);
}
}
if work > budget {
return None;
}
}
// Solid-inside-solid full containment (valid negative-volume inner cavities are skipped):
// one ray per positive shell through the shared BVH, crossing parity counted per other shell.
const RAYS: [Vec3; 3] = [
Vec3 { x: 0.7310552815, y: 0.5178911243, z: 0.4442371891 },
Vec3 { x: 0.3917284512, y: 0.8129471638, z: 0.4309184726 },
Vec3 { x: 0.5521938476, y: 0.2917463851, z: 0.7809815432 },
];
let n_pos = comp_vols.iter().filter(|v| **v > 1e-12).count();
if n_pos < 2 {
return Some(OverlapCheck::Clear);
}
let mut crossings: Vec<u32> = vec![0; nc];
let mut touched: Vec<u32> = Vec::new();
let mut stack: SmallVec<[u32; 64]> = SmallVec::new();
for ci in 0..nc {
if comp_vols[ci] <= 1e-12 || first_tri[ci] == u32::MAX {
continue;
}
let p = tris[first_tri[ci] as usize].centroid;
let mut resolved = false;
for ray_dir in &RAYS {
let inv_dir = Vec3::new(1.0 / ray_dir.x, 1.0 / ray_dir.y, 1.0 / ray_dir.z);
for &t in &touched {
crossings[t as usize] = 0;
}
touched.clear();
let mut grazing = false;
stack.clear();
if !bvh.nodes.is_empty() {
stack.push(0);
}
'walk: while let Some(ni) = stack.pop() {
work += 1;
let node = &bvh.nodes[ni as usize];
let node_pad = 1e-4_f64.max(1e-5 * node.aabb.size().len());
if !ray_hits_aabb_padded(p, inv_dir, &node.aabb, node_pad) {
continue;
}
if node.count > 0 {
let s = node.left as usize;
let e = s + node.count as usize;
for &ti in &bvh.indices[s..e] {
let t = &tris[ti as usize];
let cj = t.tag_idx as usize;
if cj == ci || comp_vols[cj] <= 1e-12 {
continue;
}
let tri_pad = 1e-4_f64.max(1e-5 * t.aabb.size().len());
if !ray_hits_aabb_padded(p, inv_dir, &t.aabb, tri_pad) {
continue;
}
match ray_tri_intersect(p, *ray_dir, t.v[0], t.v[1], t.v[2]) {
RayHit::Hit => {
if crossings[cj] == 0 {
touched.push(cj as u32);
}
crossings[cj] += 1;
}
RayHit::Graze => {
grazing = true;
break 'walk;
}
RayHit::Miss => {}
}
}
} else {
stack.push(node.left);
stack.push(node.right);
}
}
if work > budget {
return None;
}
if !grazing {
resolved = true;
break;
}
}
if resolved {
if touched.iter().any(|&t| crossings[t as usize] & 1 == 1) {
return Some(OverlapCheck::Overlap);
}
} else {
// Every ray grazed an edge or vertex: exact generalized winding number per shell.
work += tris.len() as u64;
if work > budget {
return None;
}
let mut wn: Vec<f64> = vec![0.0; nc];
for t in &tris {
let cj = t.tag_idx as usize;
if cj == ci || comp_vols[cj] <= 1e-12 {
continue;
}
wn[cj] += tri_half_solid_angle(t, p);
}
let inv_2pi = 1.0 / (2.0 * PI);
if wn.iter().any(|w| (w * inv_2pi).abs() > 0.5) {
return Some(OverlapCheck::Overlap);
}
}
}
Some(OverlapCheck::Clear)
}
/// Fast BVH-accelerated geometric self-intersection detector for a single mesh.
/// Checks every pair of non-adjacent triangles (sharing zero vertex indices and no coincident
/// vertex coordinates) whose AABBs overlap, returning `true` if any pair crosses or overlaps in 3D.
pub fn has_self_intersections(mesh: &PolyMesh) -> bool {
check_self_intersections(mesh, u64::MAX) == OverlapCheck::Overlap
}
/// Candidate triangle-pair visits the strict/observe self-intersection check may spend.
pub const SELF_INTERSECTION_BUDGET: u64 = 40_000_000;
/// `has_self_intersections` with a work budget (candidate triangle pairs visited). Returns
/// `Unverified` when the budget runs out before the mesh could be cleared.
pub fn check_self_intersections(mesh: &PolyMesh, budget: u64) -> OverlapCheck {
check_self_intersections_with_witness(mesh, budget).0
}
/// Same as [`check_self_intersections`], also returning the world-space midpoint of the first
/// self-intersecting triangle pair when `OverlapCheck::Overlap` is found.
pub fn check_self_intersections_with_witness(mesh: &PolyMesh, budget: u64) -> (OverlapCheck, Option<Vec3>) {
// World axes first; thin diagonal geometry that defeats axis-aligned boxes gets fast
// probes in the dominant edge frame and deterministic fallback frames before spending the
// full budget.
let probe = budget.min(OVERLAP_WORLD_BUDGET);
let first = self_intersection_pass(mesh, None, probe);
if first.0 != OverlapCheck::Unverified || budget <= OVERLAP_WORLD_BUDGET {
return first;
}
let dom = dominant_edge_frame(mesh);
let second = self_intersection_pass(mesh, Some(dom), probe);
if second.0 != OverlapCheck::Unverified {
return second;
}
for fb in fallback_overlap_frames() {
let r = self_intersection_pass(mesh, Some(fb), probe);
if r.0 != OverlapCheck::Unverified {
return r;
}
}
self_intersection_pass(mesh, Some(dom), budget)
}
fn self_intersection_pass(mesh: &PolyMesh, frame: Option<[Vec3; 3]>, budget: u64) -> (OverlapCheck, Option<Vec3>) {
let mut work: u64 = 0;
if mesh.faces.len() < 2 {
return (OverlapCheck::Clear, None);
}
let bb = mesh.aabb();
if !bb.is_valid() {
return (OverlapCheck::Clear, None);
}
let extent = bb.size().x.max(bb.size().y).max(bb.size().z);
if !extent.is_finite() || extent <= 0.0 {
return (OverlapCheck::Clear, None);
}
let center = (bb.min + bb.max) * 0.5;
let shift = if center.x.abs().max(center.y.abs()).max(center.z.abs()) > 2.0 * extent {
center
} else {
Vec3::ZERO
};
let inv_scale = 1.0 / extent;
let xf = |p: Vec3| -> Vec3 {
let q = (p - shift) * inv_scale;
match &frame {
Some(f) => Vec3::new(q.dot(f[0]), q.dot(f[1]), q.dot(f[2])),
None => q,
}
};
let aabb_eps = 1e-6;
let weld_sq = (1e-5_f64).powi(2);
let mut tris: Vec<Tri> = Vec::with_capacity(mesh.faces.len() * 2);
let mut tri_v: Vec<[usize; 3]> = Vec::with_capacity(mesh.faces.len() * 2);
for fi in 0..mesh.faces.len() {
for [a, b, c] in mesh.triangulate_face(fi) {
if a == b || b == c || c == a {
continue;
}
if let Some(t) = Tri::from_verts_rel(xf(mesh.verts[a]), xf(mesh.verts[b]), xf(mesh.verts[c]), 0, 0, 0) {
tris.push(t);
tri_v.push([a, b, c]);
}
}
}
let nt = tris.len();
if nt < 2 {
return (OverlapCheck::Clear, None);
}
let bvh = TriBvh::build(&tris);
let mut hits: Vec<u32> = Vec::with_capacity(32);
for i in 0..nt {
let vi = tri_v[i];
let ti = &tris[i];
bvh.query_aabb(&ti.aabb, aabb_eps, &mut hits);
work = work.saturating_add(hits.len() as u64 + 1);
if work > budget {
return (OverlapCheck::Unverified, None);
}
for &j_u32 in &hits {
let j = j_u32 as usize;
if j <= i {
continue;
}
let vj = tri_v[j];
// Skip topologically adjacent triangles sharing any vertex
if vi[0] == vj[0] || vi[0] == vj[1] || vi[0] == vj[2]
|| vi[1] == vj[0] || vi[1] == vj[1] || vi[1] == vj[2]
|| vi[2] == vj[0] || vi[2] == vj[1] || vi[2] == vj[2]
{
continue;
}
let tj = &tris[j];
// Skip triangles meeting at a coincident unwelded vertex
let mut shares_pos = false;
'pos_chk: for p in &ti.v {
for q in &tj.v {
if (*p - *q).len_sq() <= weld_sq {
shares_pos = true;
break 'pos_chk;
}
}
}
if shares_pos {
continue;
}
if tris_overlap_3d(ti, tj, 1.0) {
let witness = (mesh.verts[vi[0]]
+ mesh.verts[vi[1]]
+ mesh.verts[vi[2]]
+ mesh.verts[vj[0]]
+ mesh.verts[vj[1]]
+ mesh.verts[vj[2]])
* (1.0 / 6.0);
return (OverlapCheck::Overlap, Some(witness));
}
}
}
(OverlapCheck::Clear, None)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn point_in_tri_tolerance_is_a_distance_even_past_a_short_edge() {
// A long sliver whose short edge, 1e-4 long, closes it at x = 1.
let t = Tri::from_verts(Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0), Vec3::new(1.0, 1e-4, 0.0), 0, 0, 0).unwrap();
assert!(point_in_tri_3d(Vec3::new(0.999, 0.5e-4, 0.0), &t));
// 1e-4 past the short edge, within the wedge of the long ones: outside.
assert!(!point_in_tri_3d(Vec3::new(1.0001, 0.5e-4, 0.0), &t));
// 1e-3 past its sharp corner, within 1e-7 of both long edges' lines: outside.
assert!(!point_in_tri_3d(Vec3::new(-1e-3, -0.5e-7, 0.0), &t));
// Within 1e-7 of an edge: in.
assert!(point_in_tri_3d(Vec3::new(0.5, -0.5e-7, 0.0), &t) && point_in_tri_3d(Vec3::new(-0.5e-7, 0.0, 0.0), &t));
}
#[test]
fn actionable_bad_edge_pair_and_self_intersection_diagnostics() {
// 1. Open box missing top face at z = +0.5 -> pinpoints centroid & coplanar plane
let mut open_box = crate::primitives::make_box(2.0, 2.0, 1.0, 1);
open_box.faces.retain(|f| !f.tags.iter().any(|t| t == "top"));
let bad_diag = diagnose_bad_edges(&open_box).expect("open box must report bad edges");
assert!(bad_diag.contains("at (0.000, 0.000, 0.500)"), "{bad_diag}");
assert!(bad_diag.contains("coplanar at z=0.500"), "{bad_diag}");
assert!(bad_diag.contains("extend cutter/overlap past z=0.500"), "{bad_diag}");
// Scene::set_part surfaces the diagnostic in InvariantViolation
let mut scene = crate::scene::Scene::new();
scene.strict_manifold = true;
let err = scene.set_part("open", open_box).unwrap_err().to_string();
assert!(err.contains("invariant violation on 'open'"), "{err}");
assert!(err.contains("coplanar at z=0.500"), "{err}");
// 2. Coplanar boolean pair detection
let plate = crate::primitives::make_box(4.0, 2.0, 0.4, 1);
let cutter = crate::primitives::make_cylinder(0.5, 0.4, 24, 2);
let pair_diag = diagnose_boolean_pair(&plate, &cutter, BoolOp::Difference)
.expect("coplanar caps must be diagnosed");
assert!(pair_diag.contains("z=-0.200 (min)") && pair_diag.contains("z=0.200 (max)"), "{pair_diag}");
assert!(pair_diag.contains("extend cutter past coplanar face"), "{pair_diag}");
// 3. Self-intersecting mesh witness coordinates in Scene::set_part (folded 3-ring loft passes through bottom)
let sq = vec![(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)];
let mut pinched = crate::primitives::make_loft(&[(0.0, sq.clone()), (1.0, sq.clone()), (2.0, sq)], 4, 2)
.expect("loft builds 3-ring box");
for v in &mut pinched.verts {
if v.z > 1.5 {
v.z = -0.5;
}
}
let (ov, witness) = check_self_intersections_with_witness(&pinched, SELF_INTERSECTION_BUDGET);
assert_eq!(ov, OverlapCheck::Overlap);
let pt = witness.expect("expected self-intersection witness point");
assert!(pt.is_finite() && pt.len() < 2.0, "unexpected witness {pt:?}");
let err2 = scene.set_part("pinched", pinched).unwrap_err().to_string();
assert!(err2.contains("self-intersecting surface") && err2.contains("near ("), "{err2}");
}
}