diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index d04e44ecc0..bca6228940 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -46,7 +46,12 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form Lathe profile lengths and direction normalization use `f64` before the UVs and normals are stored as `f32`. - **BVH.** `Bvh` is a binned SAH tree on all three axes with a median split when no split beats a leaf. It answers closest-hit, any-hit and filtered ray casts, nearest-point queries and box - queries. + queries. Ray and triangle tests run in double precision and sum a value exactly when it is too + close to zero for its rounding error, so the edge-function signs that decide whether the ray + crosses the triangle are exact and a ray nearly along a triangle keeps its hit distance. Slab + intervals include a floating-point rounding margin, and subnormal intervals are + checked again in double precision. Nearest-point queries keep squared distances in double + precision, skip triangles with no area, and find nothing for a negative distance. - **Camera.** `OrbitCamera` and `Ray` give an orbit view and picking rays. `GeomError::Invalid` is the one error type. `rayon` parallelizes the UV G-buffer, and `serde` diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index 404cd07efb..e8a7816a78 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -1,7 +1,10 @@ //! Bounding volume hierarchy over a mesh's triangles: closest-hit and any-hit ray casts, and //! box queries (used by picking, baking and brush stamps). +//! +//! Triangles with a non-finite corner are left out, and a query with a non-finite origin, +//! direction or point, a zero direction, a NaN distance or a NaN box finds nothing. -use glam::{Vec3, Vec3A}; +use glam::{DVec3, Vec3, Vec3A}; use crate::Mesh; @@ -39,22 +42,25 @@ pub struct Bvh { const LEAF: usize = 4; -/// Traversal stack of (node, ray parameter at entry): inline for typical depths (no allocation per -/// ray), spilling to the heap for degenerate trees. -struct Stack { - inline: [(u32, f32); 64], +/// Most triangles one tree holds: its node indices (up to twice the triangle count) are `u32`. +pub const MAX_BVH_TRIANGLES: usize = (u32::MAX / 2) as usize; + +/// Traversal stack of (node, ray parameter at entry or squared box distance): inline for typical +/// depths (no allocation per query), spilling to the heap for degenerate trees. +struct Stack { + inline: [(u32, T); 64], len: usize, - spill: Vec<(u32, f32)>, + spill: Vec<(u32, T)>, } -impl Default for Stack { +impl Default for Stack { fn default() -> Self { - Stack { inline: [(0, 0.0); 64], len: 0, spill: Vec::new() } + Stack { inline: [(0, T::default()); 64], len: 0, spill: Vec::new() } } } -impl Stack { - fn push(&mut self, v: (u32, f32)) { +impl Stack { + fn push(&mut self, v: (u32, T)) { match self.inline.get_mut(self.len) { Some(slot) if self.spill.is_empty() => { *slot = v; @@ -64,7 +70,7 @@ impl Stack { } } - fn pop(&mut self) -> Option<(u32, f32)> { + fn pop(&mut self) -> Option<(u32, T)> { self.spill.pop().or_else(|| { self.len = self.len.checked_sub(1)?; self.inline.get(self.len).copied() @@ -83,19 +89,35 @@ fn area(lo: Vec3, hi: Vec3) -> f32 { d.x * d.y + d.y * d.z + d.z * d.x } +/// The centroid of a triangle; thirds first when the sum would overflow. +fn centroid(t: &[Vec3; 3]) -> Vec3 { + let c = (t[0] + t[1] + t[2]) / 3.0; + if c.is_finite() { c } else { t[0] / 3.0 + t[1] / 3.0 + t[2] / 3.0 } +} + impl Bvh { + /// The tree over a mesh's triangles. Triangles with a non-finite corner or an index out of + /// range are left out, as is every triangle past [`MAX_BVH_TRIANGLES`]. pub fn new(mesh: &Mesh) -> Bvh { - let triangle_count = mesh.triangle_count(); + let triangle_count = mesh.triangle_count().min(MAX_BVH_TRIANGLES); let mut tris = Vec::with_capacity(triangle_count); + let mut ids: Vec = Vec::with_capacity(triangle_count); for triangle in 0..triangle_count { let Some([a, b, c]) = mesh.tri(triangle) else { continue }; - let position = |i: usize| mesh.positions.get(i).copied().unwrap_or(Vec3::ZERO); - tris.push([position(a), position(b), position(c)]); + let (Some(a), Some(b), Some(c)) = (mesh.positions.get(a), mesh.positions.get(b), mesh.positions.get(c)) else { continue }; + if a.is_finite() && b.is_finite() && c.is_finite() { + tris.push([*a, *b, *c]); + ids.push(triangle as u32); + } + } + + if tris.is_empty() { + return Bvh { nodes: Vec::new(), tris, order: ids }; } let mut order: Vec = (0..tris.len() as u32).collect(); - let centroids: Vec = tris.iter().map(|t| (t[0] + t[1] + t[2]) / 3.0).collect(); + let centroids: Vec = tris.iter().map(centroid).collect(); let mut nodes = vec![Node { lo: Vec3A::ZERO, hi: Vec3A::ZERO, first: 0, count: tris.len() as u32 }]; let mut stack = vec![0usize]; @@ -226,8 +248,12 @@ impl Bvh { stack.push(left_child + 1); } - let tris = order.iter().map(|t| tris[*t as usize]).collect(); - Bvh { nodes, tris, order } + let sorted = order.iter().map(|t| tris[*t as usize]).collect(); + // The triangle indices replace the positions in `order` one by one. + for t in &mut order { + *t = ids[*t as usize]; + } + Bvh { nodes, tris: sorted, order } } pub fn is_empty(&self) -> bool { @@ -236,7 +262,7 @@ impl Bvh { /// The flattened tree (for GPU traversal), root first: bounds, then for a leaf the range /// `first..first + count` of [`Bvh::triangles`], for an inner node (`count` 0) the children - /// `first` and `first + 1`. + /// `first` and `first + 1`. A tree without triangles has no nodes. pub fn nodes(&self) -> impl ExactSizeIterator + '_ { self.nodes.iter().map(|n| (n.lo.into(), n.hi.into(), n.first, n.count)) } @@ -246,63 +272,119 @@ impl Bvh { (&self.tris, &self.order) } - fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, inv: Vec3A, tmax: f32) -> Option { + fn slab(lo: Vec3A, hi: Vec3A, o: Vec3A, d: Vec3A, inv: Vec3A, tmax: f32) -> Option { let t0 = (lo - o) * inv; let t1 = (hi - o) * inv; + // On an axis the ray moves along, a difference or a reciprocal past the f32 range gives an + // infinite or NaN time where the real time may be finite. + if !((t0.is_finite_mask() & t1.is_finite_mask()) | d.cmpeq(Vec3A::ZERO)).all() { + return Self::slab_wide(lo, hi, o, d, tmax); + } // A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does // not bound the hit. let open = t0.is_nan_mask() | t1.is_nan_mask(); let tn = Vec3A::select(open, Vec3A::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); let tf = Vec3A::select(open, Vec3A::INFINITY, t0.max(t1)).min_element().min(tmax); - (tn <= tf).then_some(tn) + let margin = 4.0 * f32::EPSILON * tn.abs().max(tf.abs()).min(f32::MAX); + if tn - margin <= tf + margin { + Some((tn - margin).max(0.0)) + } else if tn < f32::MIN_POSITIVE { + // Subnormal times round by a fixed step that the relative margin does not cover. + Self::slab_wide(lo, hi, o, d, tmax) + } else { + None + } } - /// Möller–Trumbore, double sided. - fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { - let e1 = t[1] - t[0]; - let e2 = t[2] - t[0]; - let p = d.cross(e2); - let det = e1.dot(p); - if det.abs() < 1e-12 { - return None; - } - let inv = 1.0 / det; - let s = o - t[0]; - // A little slack on the edges: rays through a shared edge must not slip between its - // two triangles to a surface behind. - const EDGE: f32 = 1e-5; - let u = s.dot(p) * inv; - if !(-EDGE..=1.0 + EDGE).contains(&u) { - return None; - } - let q = s.cross(e1); - let v = d.dot(q) * inv; - if v < -EDGE || u + v > 1.0 + EDGE { - return None; - } - let tt = e2.dot(q) * inv; - (tt > 0.0).then_some((tt, u, v)) + fn slab_wide(lo: Vec3A, hi: Vec3A, o: Vec3A, d: Vec3A, tmax: f32) -> Option { + let (lo, hi, o) = (Vec3::from(lo).as_dvec3(), Vec3::from(hi).as_dvec3(), Vec3::from(o).as_dvec3()); + let inv = glam::DVec3::ONE / Vec3::from(d).as_dvec3(); + let t0 = (lo - o) * inv; + let t1 = (hi - o) * inv; + // A ray lying in a slab plane gives 0·∞ = NaN: it is inside that slab, so the axis does + // not bound the hit. + let open = t0.is_nan_mask() | t1.is_nan_mask(); + let tn = glam::DVec3::select(open, glam::DVec3::NEG_INFINITY, t0.min(t1)).max_element().max(0.0); + let tf = glam::DVec3::select(open, glam::DVec3::INFINITY, t0.max(t1)).min_element().min(f64::from(tmax)); + let margin = 4.0 * f64::from(f32::EPSILON) * tn.abs().max(tf.abs()).min(f64::MAX); + // Rounding to f32 moves the entry time by less than the margin, so it stays at or before + // the box. + (tn - margin <= tf + margin).then_some((tn - margin).max(0.0) as f32) } - fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + /// Ray and triangle, double sided, in `f64`. The three edge functions + /// `d · ((p - o) × (q - o))` of the edges `p → q` decide whether the ray's line crosses the + /// triangle (edges included): it does when no two have opposite signs and not all three are + /// zero, so a ray in the triangle's plane misses. Each edge function, and the numerator + /// `(a - o) · ((b - o) × (c - o))` of the ray parameter, is taken from plain `f64` arithmetic + /// when its rounding error bound is below 2^-26 of its size, and otherwise summed exactly from + /// its products of `f32` coordinates. The ray parameter is that numerator over the sum of the + /// edge functions, and the barycentrics are the edge functions over their sum. + fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f64, f32, f32)> { + let [a, b, c] = t.map(|p| p.as_dvec3()); + let (o, d) = (o.as_dvec3(), d.as_dvec3()); + let [pa, pb, pc] = [a, b, c].map(|p| p - o); + // With m the largest coordinate of a corner less the origin, an edge function's sum of + // absolute products is at most 2·m²·|d|₁, and the numerator's at most 6·m³. + let m = pa.abs().max(pb.abs()).max(pc.abs()).max_element(); + let edge_permanent = 2.0 * m * m * d.abs().element_sum(); + let edge = |p: DVec3, q: DVec3, p0: DVec3, p1: DVec3| { + certain(d.dot(p.cross(q)), edge_permanent).unwrap_or_else(|| exact_sum(&edge_terms(p0, p1, o, d))) + }; + let opposite = |x: f64, y: f64| (x < 0.0 && y > 0.0) || (x > 0.0 && y < 0.0); + // The edge functions opposite vertices a, b and c. The exact sum rounds to a value with + // the exact sign. + let (wa, wb) = (edge(pb, pc, b, c), edge(pc, pa, c, a)); + if opposite(wa, wb) { + return None; + } + let wc = edge(pa, pb, a, b); + if opposite(wa, wc) || opposite(wb, wc) { + return None; + } + // The three share a sign, so the sum is zero only when all three are. + let total = wa + wb + wc; + if total == 0.0 || !total.is_finite() { + return None; + } + let u = (wb / total).clamp(0.0, 1.0); + let v = (wc / total).clamp(0.0, 1.0 - u); + let volume = certain(pa.dot(pb.cross(pc)), 6.0 * m * m * m).unwrap_or_else(|| exact_sum(&volume_terms(a, b, c, o))); + // The distance stays in `f64` so that two hits closer together than an `f32` step are + // still told apart; a distance that rounds to zero or past the range as `f32` is a miss. + let distance = volume / total; + let rounded = distance as f32; + (rounded > 0.0 && rounded.is_finite()).then_some((distance, u as f32, v as f32)) + } + + fn traverse(&self, o: Vec3, d: Vec3, tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + if !o.is_finite() || !d.is_finite() || d == Vec3::ZERO || tmax.is_nan() { + return None; + } + // Hits are compared in `f64` and rounded to `f32` only in the returned `Hit`. + let mut tmax_wide = f64::from(tmax); + let mut tmax = tmax; let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; - let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); + let (oa, da) = (Vec3A::from(o), Vec3A::from(d)); + let inv = Vec3A::ONE / da; let mut best = None; let mut stack = Stack::default(); - stack.push((0, Self::slab(root.lo, root.hi, oa, inv, tmax)?)); + stack.push((0, Self::slab(root.lo, root.hi, oa, da, inv, tmax)?)); // Entries carry their ray parameter at entry: nodes behind a closer hit are skipped unopened. while let Some((ni, tn)) = stack.pop() { - let Some(n) = self.nodes.get(ni as usize).filter(|_| tn <= tmax) else { continue }; + let Some(n) = self.nodes.get(ni as usize).filter(|_| f64::from(tn) <= tmax_wide) else { continue }; if n.count > 0 { let (f, c) = (n.first as usize, n.count as usize); for i in f..(f + c).min(self.tris.len()) { let (Some(tri), Some(&orig)) = (self.tris.get(i), self.order.get(i)) else { continue }; if let Some((t, u, v)) = Self::hit_tri(tri, o, d) - && t < tmax + && t < tmax_wide && filter(orig) { - tmax = t; - best = Some(Hit { t, tri: orig, u, v }); + tmax_wide = t; + // The slab test's relative margin covers this rounding. + tmax = t as f32; + best = Some(Hit { t: t as f32, tri: orig, u, v }); if any { return best; } @@ -311,8 +393,8 @@ impl Bvh { } else { // Visit the nearer child first. let (l, r) = (n.first, n.first + 1); - let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); - let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, inv, tmax)); + let dl = self.nodes.get(l as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, da, inv, tmax)); + let dr = self.nodes.get(r as usize).and_then(|c| Self::slab(c.lo, c.hi, oa, da, inv, tmax)); match (dl, dr) { (Some(a), Some(b)) if a <= b => { stack.push((r, b)); @@ -347,13 +429,21 @@ impl Bvh { } /// The point nearest to `p` within `max_dist` on a triangle accepted by `filter` (original - /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. + /// index): a [`Hit`] with the distance in `t` and the barycentrics of vertices 1 and 2. A + /// negative or NaN `max_dist` finds nothing, and triangles with no area are never nearest. + /// Squared distances are kept in `f64`. pub fn nearest(&self, p: Vec3, max_dist: f32, filter: &dyn Fn(u32) -> bool) -> Option { + if max_dist.is_nan() || max_dist < 0.0 { + return None; + } let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; - let pa = Vec3A::from(p); - let box_d2 = |n: &Node| (n.lo - pa).max(pa - n.hi).max(Vec3A::ZERO).length_squared(); - let (mut best_d2, mut best) = (max_dist * max_dist, None); - let mut stack = Stack::default(); + let pd = p.as_dvec3(); + let box_d2 = |n: &Node| { + let (lo, hi) = (Vec3::from(n.lo).as_dvec3(), Vec3::from(n.hi).as_dvec3()); + (lo - pd).max(pd - hi).max(DVec3::ZERO).length_squared() + }; + let (mut best_d2, mut best) = (f64::from(max_dist) * f64::from(max_dist), None); + let mut stack = Stack::::default(); stack.push((0, box_d2(root))); while let Some((ni, d2)) = stack.pop() { let Some(n) = self.nodes.get(ni as usize).filter(|_| d2 <= best_d2) else { continue }; @@ -363,11 +453,14 @@ impl Bvh { if !filter(orig) { continue; } - let (q, u, v) = closest_on_triangle(p, tri); - let dd = (q - p).length_squared(); + // Edges that round to parallel vectors can leave a region ratio of 0 / 0. + let Some((q, u, v)) = closest_on_triangle(pd, tri).filter(|(q, u, v)| q.is_finite() && u.is_finite() && v.is_finite()) else { + continue; + }; + let dd = (q - pd).length_squared(); if dd < best_d2 { best_d2 = dd; - best = Some(Hit { t: dd.sqrt(), tri: orig, u, v }); + best = Some(Hit { t: dd.sqrt() as f32, tri: orig, u: u as f32, v: v as f32 }); } } } else { @@ -382,8 +475,12 @@ impl Bvh { best } - /// Call `f` with every triangle (original index) whose bounds overlap the box. + /// Call `f` with every triangle (original index) whose bounds overlap the box. A box with a + /// NaN coordinate, or a lower corner past the upper corner on any axis, overlaps nothing. pub fn query_box(&self, lo: Vec3, hi: Vec3, mut f: impl FnMut(u32)) { + if lo.is_nan() || hi.is_nan() || lo.cmpgt(hi).any() { + return; + } let mut stack = vec![0u32]; while let Some(i) = stack.pop() { let Some(n) = self.nodes.get(i as usize) else { continue }; @@ -407,44 +504,222 @@ impl Bvh { } } +/// `a·b` as an unevaluated sum of two doubles, exact when neither part leaves the `f64` range. +fn two_product(a: f64, b: f64) -> [f64; 2] { + let p = a * b; + [p, a.mul_add(b, -p)] +} + +/// A triple product computed in `f64` from `f32` coordinates, when its rounding error is below +/// 2^-26 of its size. `permanent` is at least the same sum with every product taken as positive; +/// the differences, products and sums move the value by less than 8 ε of it. +fn certain(value: f64, permanent: f64) -> Option { + // 8 ε × 2^26. + const BOUND: f64 = 8.0 * f64::EPSILON * 67_108_864.0; + (value.abs() > BOUND * permanent).then_some(value) +} + +/// The exact sum of `terms`, rounded to one double with its exact sign. +#[cold] +#[inline(never)] +fn exact_sum(terms: &[f64]) -> f64 { + let (e, n) = expansion(terms); + expansion_value(&e, n) +} + +/// The exact sum of `terms` (at most 48) as `n` non-overlapping components in increasing +/// magnitude: Shewchuk's grow-expansion (Adaptive Precision Floating-Point Arithmetic, 1997). +fn expansion(terms: &[f64]) -> ([f64; 48], usize) { + let mut e = [0.0_f64; 48]; + let mut n = 0; + for &t in terms { + let mut q = t; + let mut m = 0; + for i in 0..n { + let Some(&c) = e.get(i) else { break }; + let s = q + c; + let bv = s - q; + let err = (q - (s - bv)) + (c - bv); + q = s; + if err != 0.0 { + if let Some(slot) = e.get_mut(m) { + *slot = err; + } + m += 1; + } + } + if q != 0.0 { + if let Some(slot) = e.get_mut(m) { + *slot = q; + } + m += 1; + } + n = m.min(e.len()); + } + (e, n) +} + +/// The sign of an expansion: the last nonzero component carries it. +fn expansion_sign(e: &[f64; 48], n: usize) -> f64 { + n.checked_sub(1).and_then(|i| e.get(i)).map_or(0.0, |c| c.signum()) +} + +/// An expansion rounded to one double, summing its components from the smallest. +fn expansion_value(e: &[f64; 48], n: usize) -> f64 { + e.iter().take(n).sum() +} + +/// Whether the triangle `a b c` of `f32` coordinates has no area: every component of +/// `(b - a) × (c - a) = a × b + b × c + c × a` is exactly zero. Each term is a product of two +/// `f32` values, which is exact in `f64`. +fn has_no_area(a: DVec3, b: DVec3, c: DVec3) -> bool { + let pairs = [(a, b), (b, c), (c, a)]; + let component = |f: &dyn Fn(DVec3, DVec3) -> [f64; 2]| { + let (e, n) = expansion(pairs.map(|(x, y)| f(x, y)).as_flattened()); + expansion_sign(&e, n) == 0.0 + }; + component(&|x, y| [x.y * y.z, -(x.z * y.y)]) && component(&|x, y| [x.z * y.x, -(x.x * y.z)]) && component(&|x, y| [x.x * y.y, -(x.y * y.x)]) +} + +/// The terms of `d · ((p0 - o) × (p1 - o))` for coordinates that are `f32` values, whose sign +/// tells on which side of the edge `p0 → p1` the line through `o` along `d` passes. The expression +/// expands to 18 products of three coordinates, each held exactly as two doubles. +fn edge_terms(p0: DVec3, p1: DVec3, o: DVec3, d: DVec3) -> [f64; 36] { + // (p0 - o) × (p1 - o) = p0 × p1 + o × p0 + p1 × o. + let mut terms = [0.0_f64; 36]; + let mut slots = terms.iter_mut(); + for (x, y) in [(p0, p1), (o, p0), (p1, o)] { + for (di, plus, minus) in [(d.x, x.y * y.z, x.z * y.y), (d.y, x.z * y.x, x.x * y.z), (d.z, x.x * y.y, x.y * y.x)] { + // A product of two `f32` values is exact in `f64`. + for part in two_product(di, plus).into_iter().chain(two_product(di, -minus)) { + if let Some(slot) = slots.next() { + *slot = part; + } + } + } + } + terms +} + +/// The terms of `(a - o) · ((b - o) × (c - o)) = a · (b × c) - o · (a × b + b × c + c × a)` for +/// coordinates that are `f32` values: 24 products of three coordinates, each held exactly as two +/// doubles. +fn volume_terms(a: DVec3, b: DVec3, c: DVec3, o: DVec3) -> [f64; 48] { + let mut terms = [0.0_f64; 48]; + let mut slots = terms.iter_mut(); + for (r, x, y) in [(a, b, c), (-o, a, b), (-o, b, c), (-o, c, a)] { + for (ri, plus, minus) in [(r.x, x.y * y.z, x.z * y.y), (r.y, x.z * y.x, x.x * y.z), (r.z, x.x * y.y, x.y * y.x)] { + // A product of two `f32` values is exact in `f64`. + for part in two_product(ri, plus).into_iter().chain(two_product(ri, -minus)) { + if let Some(slot) = slots.next() { + *slot = part; + } + } + } + } + terms +} + +/// The point at fraction `near / (near + far)` from `s` to `e`, both parts at least zero. A point +/// past the middle is measured back from `e`, so that a fraction that rounds to 1 still gives a +/// point next to `e` rather than `e` itself. +fn along(s: DVec3, e: DVec3, near: f64, far: f64) -> DVec3 { + let total = near + far; + if near <= far { s + (e - s) * (near / total) } else { e + (s - e) * (far / total) } +} + +/// The point of the segment `s → e` nearest to `p`, and its fraction from `s`. +fn closest_on_segment(p: DVec3, s: DVec3, e: DVec3) -> (DVec3, f64) { + let se = e - s; + let (near, far) = (se.dot(p - s), -se.dot(p - e)); + if near <= 0.0 { + (s, 0.0) + } else if far <= 0.0 { + (e, 1.0) + } else { + (along(s, e, near, far), near / (near + far)) + } +} + +/// Whether the plain `f64` cross product `a × b + b × c + c × a` of `f32` coordinates has a +/// component larger than its rounding error bound, which shows the triangle has area. The six +/// products of a component are exact, and the five sums move it by less than 4 ε of the sum of +/// their magnitudes. +fn area_is_certain(a: DVec3, b: DVec3, c: DVec3) -> bool { + let pairs = [(a, b), (b, c), (c, a)]; + let component = |f: &dyn Fn(DVec3, DVec3) -> (f64, f64)| { + let (mut value, mut permanent) = (0.0, 0.0); + for (x, y) in pairs { + let (plus, minus) = f(x, y); + value += plus - minus; + permanent += plus.abs() + minus.abs(); + } + value.abs() > 8.0 * f64::EPSILON * permanent + }; + component(&|x, y| (x.y * y.z, x.z * y.y)) || component(&|x, y| (x.z * y.x, x.x * y.z)) || component(&|x, y| (x.x * y.y, x.y * y.x)) +} + /// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), -/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5). Degenerate triangles give -/// a non-finite distance and are never nearest. -fn closest_on_triangle(p: Vec3, t: &[Vec3; 3]) -> (Vec3, f32, f32) { - let [a, b, c] = *t; +/// by Voronoi region (Ericson, Real-Time Collision Detection, 5.1.5), in `f64` so the region +/// products of `f32` coordinates neither overflow nor underflow. `None` for a triangle with no +/// area. +fn closest_on_triangle(p: DVec3, t: &[Vec3; 3]) -> Option<(DVec3, f64, f64)> { + let [a, b, c] = t.map(|v| v.as_dvec3()); let (ab, ac, ap) = (b - a, c - a, p - a); + if !area_is_certain(a, b, c) && has_no_area(a, b, c) { + return None; + } + // Edges of a triangle far from the origin can round to nearly parallel vectors, and the region + // tests below then cannot tell the regions apart. Such a triangle is thinner than the rounding + // of its edges, so its nearest point is the nearest point of its edges. + let n = ab.cross(ac); + if n.length() <= 64.0 * f64::EPSILON * ab.length() * ac.length() { + let candidates = [(a, b, 0), (a, c, 1), (b, c, 2)].map(|(s, e, which)| { + let (q, f) = closest_on_segment(p, s, e); + let (u, v) = match which { + 0 => (f, 0.0), + 1 => (0.0, f), + _ => (1.0 - f, f), + }; + (q, u, v) + }); + return candidates + .into_iter() + .filter(|(q, _, _)| q.is_finite()) + .min_by(|x, y| (x.0 - p).length_squared().total_cmp(&(y.0 - p).length_squared())); + } let (d1, d2) = (ab.dot(ap), ac.dot(ap)); if d1 <= 0.0 && d2 <= 0.0 { - return (a, 0.0, 0.0); + return Some((a, 0.0, 0.0)); } let bp = p - b; let (d3, d4) = (ab.dot(bp), ac.dot(bp)); if d3 >= 0.0 && d4 <= d3 { - return (b, 1.0, 0.0); + return Some((b, 1.0, 0.0)); } let vc = d1 * d4 - d3 * d2; if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { let v = d1 / (d1 - d3); - return (a + ab * v, v, 0.0); + return Some((along(a, b, d1, -d3), v, 0.0)); } let cp = p - c; let (d5, d6) = (ab.dot(cp), ac.dot(cp)); if d6 >= 0.0 && d5 <= d6 { - return (c, 0.0, 1.0); + return Some((c, 0.0, 1.0)); } let vb = d5 * d2 - d1 * d6; if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { let w = d2 / (d2 - d6); - return (a + ac * w, 0.0, w); + return Some((along(a, c, d2, -d6), 0.0, w)); } let va = d3 * d6 - d5 * d4; if va <= 0.0 && d4 - d3 >= 0.0 && d5 - d6 >= 0.0 { let w = (d4 - d3) / ((d4 - d3) + (d5 - d6)); - return (b + (c - b) * w, 1.0 - w, w); + return Some((along(b, c, d4 - d3, d5 - d6), 1.0 - w, w)); } let denom = 1.0 / (va + vb + vc); let (v, w) = (vb * denom, vc * denom); - (a + ab * v + ac * w, v, w) + Some((a + ab * v + ac * w, v, w)) } #[cfg(test)] @@ -452,6 +727,329 @@ mod tests { use super::*; use crate::primitives; + fn review_triangle(points: [Vec3; 3]) -> Bvh { + Bvh::new(&Mesh { positions: points.to_vec(), indices: vec![0, 1, 2], ..Mesh::default() }) + } + + #[test] + fn review_slab_accepts_an_exact_vertex_hit() { + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + let hit = bvh.closest(Vec3::new(-1.0, 0.0, 41.0), Vec3::new(1.0, 0.0, -41.0), 2.0).unwrap(); + assert!((hit.t - 1.0).abs() < 1e-6); + assert!(bvh.closest(Vec3::new(-1.0, -0.1, 41.0), Vec3::new(1.0, 0.0, -41.0), 2.0).is_none()); + } + + #[test] + fn slab_times_stay_finite_when_the_origin_is_past_the_f32_range_from_the_box() { + // The origin and the triangle are 2^128 apart, past f32::MAX. + let h = 2.0_f32.powi(127); + let bvh = review_triangle([Vec3::new(0.0, 0.0, -h), Vec3::new(1.0, 0.0, -h), Vec3::new(0.0, 1.0, -h)]); + let hit = bvh.closest(Vec3::new(0.25, 0.25, h), Vec3::new(0.0, 0.0, -h), 3.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (2.0, 0.25, 0.25)); + assert!(bvh.occluded(Vec3::new(0.25, 0.25, h), Vec3::new(0.0, 0.0, -h), 3.0)); + assert!(bvh.closest(Vec3::new(0.25, 0.25, h), Vec3::new(0.0, 0.0, -h), 1.5).is_none()); + } + + #[test] + fn slab_times_stay_finite_for_a_subnormal_direction() { + // The reciprocal of the direction is past f32::MAX. + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + let s = 2.0_f32.powi(-70) * 2.0_f32.powi(-70); + let hit = bvh.closest(Vec3::new(0.25, 0.25, 2.0 * s), Vec3::new(0.0, 0.0, -s), 3.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (2.0, 0.25, 0.25)); + assert!(bvh.closest(Vec3::new(0.25, 0.25, 2.0 * s), Vec3::new(0.0, 0.0, -s), 1.5).is_none()); + } + + #[test] + fn review_ray_intersections_preserve_large_scales() { + let scale = 2.0_f32.powi(65); + let bvh = review_triangle([Vec3::ZERO, Vec3::X * scale, Vec3::Z * scale]); + let hit = bvh.closest(Vec3::new(scale / 4.0, 1.0, scale / 4.0), -Vec3::Y, 2.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.25, 0.25)); + } + + #[test] + fn review_ray_intersections_preserve_small_scales() { + let scale = 2.0_f32.powi(-65); + let bvh = review_triangle([Vec3::ZERO, Vec3::X * scale, Vec3::Z * scale]); + let hit = bvh.closest(Vec3::new(scale / 4.0, 1.0, scale / 4.0), -Vec3::Y, 2.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.25, 0.25)); + } + + #[test] + fn positive_ray_distances_that_underflow_are_not_zero_hits() { + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + assert!(bvh.closest(Vec3::new(0.0, 0.25, 1e-10), Vec3::new(0.0, 0.0, -f32::MAX), 1.0).is_none()); + } + + #[test] + fn ray_hits_past_a_distance_numerator_that_underflows() { + let s = 2.0_f32.powi(-60); + let bvh = review_triangle([Vec3::ZERO, Vec3::X * s, Vec3::Y]); + let o = Vec3::new(2.0_f32.powi(-62), 0.25, 2.0_f32.powi(-100)); + let hit = bvh.closest(o, -Vec3::Z, 1.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (2.0_f32.powi(-100), 0.25, 0.25)); + assert!(bvh.occluded(o, -Vec3::Z, 1.0)); + } + + #[test] + fn slab_retries_times_that_round_apart_in_the_subnormal_range() { + let m = f32::from_bits(1); + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + let (o, d) = (Vec3::new(-3.0 * m, 0.25, 75.0 * m), Vec3::new(2.0, 0.0, -50.0)); + let hit = bvh.closest(o, d, 1.0).unwrap(); + assert_eq!(hit.tri, 0); + assert!(hit.t > 0.0 && hit.t <= 2.0 * m); + assert!(bvh.occluded(o, d, 1.0)); + } + + #[test] + fn far_ray_origin_keeps_the_triangle_offsets() { + // From (h, h, h) along (-h, -h, -h) the ray meets z = 0 at the origin: outside the first + // triangle, at a vertex of the second. + let h = 2.0_f32.powi(60); + let (o, d) = (Vec3::splat(h), Vec3::splat(-h)); + let offset = review_triangle([Vec3::new(1.0, 1.0, 0.0), Vec3::new(2.0, 1.0, 0.0), Vec3::new(1.0, 2.0, 0.0)]); + assert!(offset.closest(o, d, 2.0).is_none()); + assert!(!offset.occluded(o, d, 2.0)); + let at_origin = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + assert_eq!(at_origin.closest(o, d, 2.0).map(|hit| hit.t), Some(1.0)); + assert!(at_origin.occluded(o, d, 2.0)); + } + + #[test] + fn far_ray_origin_keeps_the_offsets_in_the_barycentrics() { + // `o - a` rounds the triangle's unit offsets away on the axes where the origin is far. + let h = 2.0_f32.powi(127); + let bvh = review_triangle([Vec3::new(-1.0, -1.0, 0.0), Vec3::new(2.0, -1.0, 0.0), Vec3::new(-1.0, 2.0, 0.0)]); + for (o, d, u, v) in + [(Vec3::splat(h), Vec3::splat(-h), 1.0 / 3.0, 1.0 / 3.0), (Vec3::new(h, -0.5, h), Vec3::new(-h, 0.0, -h), 1.0 / 3.0, 1.0 / 6.0)] + { + let hit = bvh.closest(o, d, 2.0).unwrap(); + assert!((hit.t - 1.0).abs() < 1e-6, "{hit:?}"); + assert!((hit.u - u).abs() < 1e-6 && (hit.v - v).abs() < 1e-6, "{hit:?}"); + } + } + + #[test] + fn ray_parameters_stay_exact_for_rays_nearly_along_a_triangle() { + // The ray runs along edge 0 → 1, tilted by 2^-19, and crosses the triangle at + // p = (2·a + b + c) / 4 at t = 1. Single-precision Möller–Trumbore puts the hit near t = 1.067. + let bvh = review_triangle([Vec3::new(3.0, -7.0, 6.0), Vec3::new(2.0, -7.0, 6.0), Vec3::new(7.0, 8.0, -8.0)]); + let d = Vec3::new(-1.0, 0.0, 2.0_f32.powi(-19)); + let o = Vec3::new(3.75, -3.25, 2.5) - d; + assert_eq!(o + d, Vec3::new(3.75, -3.25, 2.5)); + let hit = bvh.closest(o, d, 3.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.25, 0.25)); + } + + #[test] + fn rays_just_outside_an_edge_miss_the_triangle() { + // Triangle 0 is [0, X, Y] at z = 0. Triangle 1 lies at y > 2 and reaches x = -1, so the + // leaf's bounds take in the points beside triangle 0's edges. + let m = Mesh { + positions: vec![Vec3::ZERO, Vec3::X, Vec3::Y, Vec3::new(-1.0, 3.0, 0.0), Vec3::new(1.0, 3.0, 0.0), Vec3::new(0.0, 4.0, 0.0)], + indices: vec![0, 1, 2, 3, 4, 5], + ..Mesh::default() + }; + let bvh = Bvh::new(&m); + let only_first = |t: u32| t == 0; + let gap = 2.0_f32.powi(-32); + // Points just outside the edges x = 0, y = 0 and x + y = 1, and just inside them. + let outside = [Vec3::new(-gap, 0.25, 0.0), Vec3::new(0.25, -gap, 0.0), Vec3::new(gap, 1.0, 0.0), Vec3::new(-2.0_f32.powi(-20), 0.25, 0.0)]; + let inside = [Vec3::new(gap, 0.25, 0.0), Vec3::new(0.25, gap, 0.0), Vec3::new(0.0, 1.0, 0.0), Vec3::new(0.25, 0.0, 0.0)]; + // Straight down, and slanted. The origin is a short step above the point, so that it is + // exact in f32 and the ray passes through the point itself. + let step = 2.0_f32.powi(-8); + for d in [Vec3::NEG_Z, Vec3::new(0.25, -0.125, -1.0), Vec3::new(-0.5, 0.375, -1.0)] { + let origin = |p: Vec3| { + let o = p - d * step; + assert_eq!(o + d * step, p, "{p} along {d}"); + o + }; + for p in outside { + let o = origin(p); + assert!(bvh.closest_filtered(o, d, 10.0, &only_first).is_none(), "{p} along {d}"); + assert!(bvh.closest(o, d, 10.0).is_none(), "{p} along {d}"); + assert!(!bvh.occluded(o, d, 10.0), "{p} along {d}"); + } + for p in inside { + let o = origin(p); + let hit = bvh.closest_filtered(o, d, 10.0, &only_first).unwrap_or_else(|| panic!("{p} along {d}")); + assert_eq!(hit.tri, 0, "{p} along {d}"); + assert!((hit.t - step).abs() < 1e-9, "{p} along {d}: {hit:?}"); + assert!((hit.u - p.x).abs() < 1e-6 && (hit.v - p.y).abs() < 1e-6, "{p} along {d}: {hit:?}"); + } + } + } + + #[test] + fn rays_from_far_away_keep_hits_on_small_triangles() { + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + // Through the corner at the origin, from 2^30 and 2^60 away on every axis. + for exponent in [30, 60] { + let o = Vec3::splat(2.0_f32.powi(exponent)); + let hit = bvh.closest(o, -o, 2.0).unwrap_or_else(|| panic!("2^{exponent}")); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.0, 0.0), "2^{exponent}"); + } + // Through a point inside and a point outside, from 2^20 away. + let far = Vec3::splat(2.0_f32.powi(20)); + let hit = bvh.closest(Vec3::new(0.25, 0.25, 0.0) + far, -far, 2.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.25, 0.25)); + assert!(bvh.closest(Vec3::new(-0.25, 0.25, 0.0) + far, -far, 2.0).is_none()); + } + + #[test] + fn ray_parameters_stay_exact_for_long_thin_triangles() { + // The ray reaches corner 1 at t = 2, nearly along the triangle's plane; the normal from + // rounded edges puts the hit near t = 0.0001. + let big = 2.0_f32.powi(48); + let bvh = review_triangle([Vec3::new(-3.0 * big, -7.0 * big, 0.0), Vec3::new(3.0, 7.0, 0.0), Vec3::new(1.0, 1.0, 15.0)]); + let (o, d) = (Vec3::new(-3.0, -7.0, 2.0_f32.powi(-59)), Vec3::new(3.0, 7.0, -2.0_f32.powi(-60))); + assert!(!bvh.occluded(o, d, 1.0)); + let hit = bvh.closest(o, d, 3.0).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (2.0, 1.0, 0.0)); + } + + #[test] + fn rays_in_the_plane_of_a_triangle_miss_it() { + // Each ray passes through corner 0 and lies in the triangle's plane: in the second case, + // the edge values rounded to f64 are -512, -256 and -256 instead of 0. + let cases = [ + ([Vec3::ZERO, Vec3::new(-9.0, -31.0, 0.0), Vec3::new(33.0, -44.0, -41.0)], Vec3::new(-48.0, 150.0, 82.0), Vec3::new(24.0, -75.0, -41.0)), + ( + [Vec3::new(45676.0, 910461.0, -1853839.0), Vec3::new(1854449.0, 902514.0, -3516015.0), Vec3::new(-735712.0, -237051.0, -832163.0)], + Vec3::new(-981709.0, 2065920.0, -1213339.0), + Vec3::new(1027385.0, -1155459.0, -640500.0), + ), + ]; + for (corners, o, d) in cases { + // The coordinates are integers below 2^24, so the exact normal fits in i128. + let [a, b, c] = corners.map(|p| p.to_array().map(|x| x as i128)); + let int = |v: Vec3| v.to_array().map(|x| x as i128); + let sub = |p: [i128; 3], q: [i128; 3]| [p[0] - q[0], p[1] - q[1], p[2] - q[2]]; + let (e1, e2) = (sub(b, a), sub(c, a)); + let n = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; + let dot = |v: [i128; 3]| n[0] * v[0] + n[1] * v[1] + n[2] * v[2]; + assert_eq!((dot(int(d)), dot(sub(int(o), a))), (0, 0), "{o} {d}"); + let bvh = review_triangle(corners); + assert!(bvh.closest(o, d, 10.0).is_none(), "{o} {d}"); + assert!(!bvh.occluded(o, d, 10.0), "{o} {d}"); + } + } + + #[test] + fn rays_through_shared_edges_and_corners_hit_one_of_the_triangles() { + // A plane of 8 × 8 quads, each split into two triangles, with a plate below it. + let mut m = primitives::plane(2.0, 8); + let first = m.positions.len() as u32; + m.positions.extend([Vec3::new(-5.0, -1.0, -5.0), Vec3::new(5.0, -1.0, -5.0), Vec3::new(0.0, -1.0, 5.0)]); + m.indices.extend([first, first + 1, first + 2]); + let plate = m.triangle_count() as u32 - 1; + let bvh = Bvh::new(&m); + let mut seed = 11u32; + let mut rnd = move || { + seed = seed.wrapping_mul(1_664_525).wrapping_add(1_013_904_223); + (seed >> 8) as f32 / (1u32 << 24) as f32 * 2.0 - 1.0 + }; + let mut tested = 0; + for t in 0..plate as usize { + let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]); + // The middle of each edge, and each corner. + for p in [(a + b) * 0.5, (b + c) * 0.5, (c + a) * 0.5, a, b, c] { + // Corners and edges on the plane's border have nothing on their outer side. + if p.x.abs() >= 0.999 || p.z.abs() >= 0.999 { + continue; + } + for _ in 0..4 { + let o = p + Vec3::new(rnd() * 3.0, 1.0 + rnd().abs() * 3.0, rnd() * 3.0); + let d = p - o; + let hit = bvh.closest(o, d, 10.0).unwrap_or_else(|| panic!("{p} from {o}")); + assert_ne!(hit.tri, plate, "{p} from {o} slipped through to the plate"); + assert!((hit.t - 1.0).abs() < 1e-5, "{p} from {o}: {hit:?}"); + tested += 1; + } + } + } + assert!(tested > 1000, "{tested}"); + } + + #[test] + fn nearest_keeps_triangles_whose_edges_round_to_parallel() { + // b - a and c - a both round to (-h, -h, 0), but the triangle has area. + let h = 2.0_f32.powi(60); + let bvh = review_triangle([Vec3::new(h, h, 0.0), Vec3::X, Vec3::Y]); + let hit = bvh.nearest(Vec3::new(1.0, 0.0, 1.0), 2.0, &|_| true).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 1.0, 0.0)); + // The nearest point is the middle of the edge between vertices 1 and 2. + let hit = bvh.nearest(Vec3::new(0.5, 0.5, 1.0), 1.125, &|_| true).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.5, 0.5)); + } + + #[test] + fn nearest_skips_collinear_triangles_whose_cross_product_rounds_to_nonzero() { + let h = 2.0_f32.powi(60); + let bvh = review_triangle([Vec3::new(3.0 * h, 9.0 * h, 0.0), Vec3::new(512.0, 1536.0, 0.0), Vec3::ZERO]); + assert!(bvh.nearest(Vec3::new(512.0, 1536.0, 0.0), 1.0, &|_| true).is_none()); + } + + #[test] + fn nearest_edge_points_near_the_far_end_keep_their_offset() { + let h = 2.0_f32.powi(60); + let bvh = review_triangle([Vec3::new(h, 0.0, 0.0), Vec3::ZERO, Vec3::new(0.0, h, 0.0)]); + let hit = bvh.nearest(Vec3::new(1.0, 0.0, 1.0), 1.125, &|_| true).unwrap(); + assert_eq!(hit.t, 1.0); + } + + #[test] + fn closest_tells_apart_hits_closer_than_an_f32_step() { + let z = 2.0_f32.powi(-26); + let tri = [Vec3::ZERO, Vec3::X, Vec3::Y]; + let positions = [tri, tri.map(|p| p + Vec3::Z * z)].concat(); + let bvh = Bvh::new(&Mesh { positions, indices: vec![0, 1, 2, 3, 4, 5], ..Mesh::default() }); + let hit = bvh.closest(Vec3::new(0.25, 0.25, 1.0), -Vec3::Z, 2.0).unwrap(); + assert_eq!(hit.tri, 1); + } + + #[test] + fn nearest_rejects_a_negative_cutoff() { + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + let p = Vec3::new(0.25, 0.25, 1.0); + assert!(bvh.nearest(p, -2.0, &|_| true).is_none()); + assert!(bvh.nearest(p, f32::NAN, &|_| true).is_none()); + assert_eq!(bvh.nearest(p, 2.0, &|_| true).map(|hit| hit.t), Some(1.0)); + } + + #[test] + fn nearest_skips_triangles_with_no_area() { + let far = [Vec3::new(0.0, 0.0, 5.0), Vec3::new(1.0, 0.0, 5.0), Vec3::new(0.0, 1.0, 5.0)]; + let positions = [vec![Vec3::ZERO; 3], far.to_vec()].concat(); + let bvh = Bvh::new(&Mesh { positions, indices: vec![0, 1, 2, 3, 4, 5], ..Mesh::default() }); + let hit = bvh.nearest(Vec3::new(0.1, 0.1, 0.5), f32::MAX, &|_| true).unwrap(); + assert_eq!(hit.tri, 1); + let segment = review_triangle([Vec3::ZERO, Vec3::ZERO, Vec3::X]); + assert!(segment.nearest(Vec3::new(0.5, 1.0, 0.0), f32::MAX, &|_| true).is_none()); + } + + #[test] + fn nearest_region_products_do_not_overflow() { + let s = 2.0_f32.powi(40); + let bvh = review_triangle([Vec3::ZERO, Vec3::X * s, Vec3::Y * s]); + let p = Vec3::new(2.0_f32.powi(38), 2.0_f32.powi(38), 1.0); + let hit = bvh.nearest(p, 2.0, &|_| true).unwrap(); + assert_eq!((hit.t, hit.u, hit.v), (1.0, 0.25, 0.25)); + } + + #[test] + fn nearest_squared_distances_stay_in_range() { + let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); + for (e, cutoff) in [(65, 66), (-80, -79)] { + let p = Vec3::new(0.25, 0.25, 2.0_f32.powi(e)); + let hit = bvh.nearest(p, 2.0_f32.powi(cutoff), &|_| true); + assert_eq!(hit.map(|hit| hit.t), Some(2.0_f32.powi(e)), "2^{e}"); + } + } + #[test] fn nearest_point_matches_brute_force() { let m = primitives::builtin("torus").unwrap(); @@ -467,7 +1065,7 @@ mod tests { let brute = (0..m.triangle_count()) .map(|t| { let [a, b, c] = m.tri(t).unwrap().map(|i| m.positions[i]); - (closest_on_triangle(p, &[a, b, c]).0 - p).length() + closest_on_triangle(p.as_dvec3(), &[a, b, c]).map_or(f32::MAX, |(q, ..)| (q - p.as_dvec3()).length() as f32) }) .fold(f32::MAX, f32::min); assert!((hit.t - brute).abs() < 1e-5, "{} vs {brute}", hit.t); @@ -529,6 +1127,7 @@ mod tests { for t in 0..m.triangle_count() { let [x, y, z] = m.tri(t).unwrap(); if let Some((tt, _, _)) = Bvh::hit_tri(&[m.positions[x], m.positions[y], m.positions[z]], o, d) { + let tt = tt as f32; slow = Some(slow.map_or(tt, |s: f32| s.min(tt))); } } @@ -680,6 +1279,99 @@ mod tests { assert_eq!(hit.t, 10.0); } + #[test] + fn bvh_rejects_non_finite_queries_without_callbacks() { + let m = primitives::plane(2.0, 4); + let bvh = Bvh::new(&m); + let mut calls = 0; + bvh.query_box(Vec3::new(f32::NAN, -1.0, -1.0), Vec3::ONE, |_| calls += 1); + bvh.query_box(Vec3::splat(-1.0), Vec3::new(1.0, f32::NAN, 1.0), |_| calls += 1); + // A box whose lower corner is past its upper corner on one axis is empty, even where a + // triangle spans both values. + bvh.query_box(Vec3::new(0.3, -1.0, -1.0), Vec3::new(0.2, 1.0, 1.0), |_| calls += 1); + bvh.query_box(Vec3::new(-1.0, -1.0, 0.3), Vec3::new(1.0, 1.0, 0.2), |_| calls += 1); + assert_eq!(calls, 0); + // An infinite box is a valid query and finds everything. + bvh.query_box(Vec3::NEG_INFINITY, Vec3::INFINITY, |_| calls += 1); + assert_eq!(calls, m.triangle_count()); + + let (o, d) = (Vec3::new(0.0, 1.0, 0.0), Vec3::NEG_Y); + assert!(bvh.closest(o, d, 10.0).is_some()); + let counted = std::cell::Cell::new(0); + let filter = |_: u32| { + counted.set(counted.get() + 1); + true + }; + for (o, d, tmax) in + [(Vec3::NAN, d, 10.0), (o, Vec3::new(0.0, f32::NAN, 0.0), 10.0), (o, Vec3::ZERO, 10.0), (o, Vec3::NEG_INFINITY, 10.0), (o, d, f32::NAN)] + { + assert!(bvh.closest_filtered(o, d, tmax, &filter).is_none(), "{o} {d} {tmax}"); + assert!(!bvh.occluded(o, d, tmax)); + } + assert_eq!(counted.get(), 0); + } + + #[test] + fn ray_hits_do_not_depend_on_the_size_of_the_triangle() { + for exponent in [-10, -7, -3, 0, 3, 7, 10] { + let s = 10f32.powi(exponent); + let m = Mesh { positions: vec![Vec3::ZERO, Vec3::new(s, 0.0, 0.0), Vec3::new(0.0, 0.0, s)], indices: vec![0, 1, 2], ..Mesh::default() }; + let bvh = Bvh::new(&m); + // Straight down onto the triangle, from one triangle size above it. + let o = Vec3::new(0.25 * s, s, 0.25 * s); + let hit = bvh.closest(o, Vec3::NEG_Y, f32::MAX).unwrap_or_else(|| panic!("no hit at 1e{exponent}")); + assert!((hit.t / s - 1.0).abs() < 1e-4, "1e{exponent}: {hit:?}"); + assert!((hit.u - 0.25).abs() < 1e-4 && (hit.v - 0.25).abs() < 1e-4, "1e{exponent}: {hit:?}"); + assert!(bvh.occluded(o, Vec3::NEG_Y, 2.0 * s), "1e{exponent}"); + // Beside the triangle, and along its plane. + assert!(bvh.closest(Vec3::new(0.75 * s, s, 0.75 * s), Vec3::NEG_Y, f32::MAX).is_none(), "1e{exponent}"); + assert!(bvh.closest(Vec3::new(-s, 0.0, 0.25 * s), Vec3::X, f32::MAX).is_none(), "1e{exponent}"); + } + } + + #[test] + fn a_tree_without_triangles_has_no_nodes() { + assert_eq!(Bvh::new(&Mesh::default()).nodes().len(), 0); + // Every triangle is left out: one corner is not finite. + let rejected = Mesh { positions: vec![Vec3::ZERO, Vec3::X, Vec3::new(f32::NAN, 0.0, 0.0)], indices: vec![0, 1, 2], ..Mesh::default() }; + let bvh = Bvh::new(&rejected); + assert_eq!(bvh.nodes().len(), 0); + assert!(bvh.is_empty()); + assert!(bvh.closest(Vec3::Z, Vec3::NEG_Z, 10.0).is_none()); + assert!(bvh.nearest(Vec3::ZERO, 10.0, &|_| true).is_none()); + let mut found = 0; + bvh.query_box(Vec3::splat(-1.0), Vec3::ONE, |_| found += 1); + assert_eq!(found, 0); + } + + #[test] + fn bvh_leaves_out_non_finite_triangles_and_keeps_original_indices() { + let mut m = primitives::plane(2.0, 4); + // Vertex 0 is the corner of one triangle only. + m.positions[0] = Vec3::new(f32::NAN, 0.0, 0.0); + m.positions[24] = Vec3::new(0.0, f32::INFINITY, 0.0); + // One triangle's index points past the vertices. + let out_of_range = m.triangle_count() - 1; + m.indices[out_of_range * 3] = m.positions.len() as u32; + let skipped = |t: usize| m.tri(t).is_some_and(|c| c.contains(&0) || c.contains(&24) || c.iter().any(|&i| i >= m.positions.len())); + let expected: Vec<_> = (0..m.triangle_count()).filter(|&t| !skipped(t)).map(|t| t as u32).collect(); + let bvh = Bvh::new(&m); + let mut found = Vec::new(); + bvh.query_box(Vec3::splat(-10.0), Vec3::splat(10.0), |t| found.push(t)); + found.sort_unstable(); + assert_eq!(found, expected); + for (lo, hi, _, _) in bvh.nodes() { + assert!(lo.is_finite() && hi.is_finite(), "{lo} {hi}"); + } + let (tris, order) = bvh.triangles(); + assert!(order.iter().all(|&t| !skipped(t as usize))); + // Each triangle is stored with the corners of the mesh triangle its index names. + for (corners, &t) in tris.iter().zip(order) { + let [a, b, c] = m.tri(t as usize).unwrap(); + assert_eq!(*corners, [m.positions[a], m.positions[b], m.positions[c]]); + } + } + #[test] fn ray_hit_t_is_the_parameter_of_the_direction_given() { let m = Mesh {