From 4ebc4db4bafc0e7f8ab82d5a5009ce655526afc1 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Wed, 25 Nov 2026 23:56:44 -0800 Subject: [PATCH 1/9] craft-mesh-ops: BVH rejects non-finite input and checks lengths and indices Bvh::new leaves out triangles with a non-finite corner or an index past the vertices, where it used to substitute the origin for a missing vertex. The tree holds at most MAX_BVH_TRIANGLES triangles, so its u32 node and triangle indices cannot wrap, and the triangle indices that hits and queries report are the mesh's own when triangles were left out. A mesh with no usable triangle gives a tree with no nodes. closest, closest_filtered and occluded find nothing for a non-finite origin or direction, a zero direction or a NaN distance. query_box finds nothing for a box with a NaN coordinate or a lower corner past the upper corner on any axis. The ray-triangle determinant cutoff scales with the edge and direction lengths, so rays hit triangles smaller than 1e-6. Centroids are computed in thirds when the sum overflows. --- crates/mesh-ops/src/bvh.rs | 146 ++++++++++++++++++++++++++++++++++--- 1 file changed, 137 insertions(+), 9 deletions(-) diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index 9b01c84155..ca4de74529 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -1,5 +1,8 @@ //! 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}; @@ -35,6 +38,9 @@ pub struct Bvh { const LEAF: usize = 4; +/// 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, entry distance): inline for typical depths (no allocation per /// ray), spilling to the heap for degenerate trees. struct Stack { @@ -79,19 +85,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]; @@ -222,8 +244,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 { @@ -232,7 +258,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)) } @@ -259,7 +285,10 @@ impl Bvh { let e2 = t[2] - t[0]; let p = d.cross(e2); let det = e1.dot(p); - if det.abs() < 1e-12 { + // A ray in the triangle's plane, or a triangle without area. The determinant is the + // product of the two edge lengths, the direction's length and the sines of the angles + // between them, so the cutoff shrinks with that product for small triangles. + if det.abs() < 1e-12 && (det == 0.0 || det.abs() < 1e-12 * (e1.length() * e2.length() * d.length()).min(1.0)) { return None; } let inv = 1.0 / det; @@ -281,6 +310,9 @@ impl Bvh { } fn traverse(&self, o: Vec3, d: Vec3, mut 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; + } let root = self.nodes.first().filter(|_| !self.tris.is_empty())?; let (oa, inv) = (Vec3A::from(o), Vec3A::ONE / Vec3A::from(d)); let mut best = None; @@ -378,8 +410,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 }; @@ -675,4 +711,96 @@ mod tests { assert_eq!(hit.tri, 500); 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 affected = (0..m.triangle_count()).filter(|&t| skipped(t)).count(); + 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)); + assert_eq!(found.len(), m.triangle_count() - affected); + 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]]); + } + } } From 8d578f08568ade3e91833fabd376474be988ac06 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:47:21 -0800 Subject: [PATCH 2/9] Expose mesh operations through the facade --- Cargo.lock | 1 + crates/craft/Cargo.toml | 2 ++ crates/craft/src/lib.rs | 2 ++ 3 files changed, 5 insertions(+) diff --git a/Cargo.lock b/Cargo.lock index 7625a0572b..dc78d6190b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1863,6 +1863,7 @@ dependencies = [ "craft-media-source", "craft-menu", "craft-mesh", + "craft-mesh-ops", "craft-metadata", "craft-metafile", "craft-midi", diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 81f53fd10e..507bd6a6d7 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -232,6 +232,7 @@ craft-sbs = { workspace = true, optional = true } craft-ease = { workspace = true, optional = true } craft-i18n-build = { workspace = true, optional = true } craft-pbr = { workspace = true, optional = true } +craft-mesh-ops = { workspace = true, optional = true } [features] ui = [ @@ -658,6 +659,7 @@ mesh-dae = ["mesh", "craft-mesh/dae"] mesh-fbx = ["mesh", "craft-mesh/fbx"] mesh-gltf = ["mesh", "craft-mesh/gltf"] mesh-obj = ["mesh", "craft-mesh/obj"] +mesh-ops = ["dep:craft-mesh-ops"] mesh-ply = ["mesh", "craft-mesh/ply"] mesh-stl = ["mesh", "craft-mesh/stl"] mesh-threemf = ["mesh", "craft-mesh/threemf"] diff --git a/crates/craft/src/lib.rs b/crates/craft/src/lib.rs index 8946df18b6..c0080e6353 100644 --- a/crates/craft/src/lib.rs +++ b/crates/craft/src/lib.rs @@ -247,6 +247,8 @@ pub use craft_media_source as media_source; pub use craft_menu as menu; #[cfg(feature = "mesh")] pub use craft_mesh as mesh; +#[cfg(feature = "mesh-ops")] +pub use craft_mesh_ops as mesh_ops; #[cfg(feature = "metadata")] pub use craft_metadata as metadata; #[cfg(feature = "metafile")] From b3ec74aeb49f356978025ab7aa5e21dce636c04a Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 13:49:21 -0800 Subject: [PATCH 3/9] Group mesh operations as a facade member --- crates/craft/Cargo.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/crates/craft/Cargo.toml b/crates/craft/Cargo.toml index 507bd6a6d7..23cd07b8f0 100644 --- a/crates/craft/Cargo.toml +++ b/crates/craft/Cargo.toml @@ -659,11 +659,12 @@ mesh-dae = ["mesh", "craft-mesh/dae"] mesh-fbx = ["mesh", "craft-mesh/fbx"] mesh-gltf = ["mesh", "craft-mesh/gltf"] mesh-obj = ["mesh", "craft-mesh/obj"] -mesh-ops = ["dep:craft-mesh-ops"] mesh-ply = ["mesh", "craft-mesh/ply"] mesh-stl = ["mesh", "craft-mesh/stl"] mesh-threemf = ["mesh", "craft-mesh/threemf"] +mesh-ops = ["dep:craft-mesh-ops"] + metadata = ["dep:craft-metadata"] metafile = ["dep:craft-metafile"] From 8f283813530328f46978f373128f69e7be62087b Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Thu, 26 Nov 2026 14:03:17 -0800 Subject: [PATCH 4/9] Preserve BVH ray hits across extreme scales and slab rounding --- crates/mesh-ops/README.md | 3 +- crates/mesh-ops/src/bvh.rs | 101 +++++++++++++++++++++++++++++++------ 2 files changed, 87 insertions(+), 17 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index d7b1852d6a..632fb580f6 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -19,7 +19,8 @@ crate has no UI, does no file or network I/O and has no `unsafe` code. File form the built-in scenes in `primitives::BUILTINS`. - **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 tests use double precision for non-finite intermediate values and hits near triangle + edges. Slab intervals include a floating-point rounding margin. - **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 ca4de74529..43899ccfcf 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -276,37 +276,71 @@ impl Bvh { 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); + (tn - margin <= tf + margin).then_some((tn - margin).max(0.0)) } /// Möller–Trumbore, double sided. fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { + const NEAR: f32 = 1e-4; let e1 = t[1] - t[0]; let e2 = t[2] - t[0]; let p = d.cross(e2); let det = e1.dot(p); - // A ray in the triangle's plane, or a triangle without area. The determinant is the - // product of the two edge lengths, the direction's length and the sines of the angles - // between them, so the cutoff shrinks with that product for small triangles. - if det.abs() < 1e-12 && (det == 0.0 || det.abs() < 1e-12 * (e1.length() * e2.length() * d.length()).min(1.0)) { + if !det.is_finite() || det.abs() <= 1e-6 * e1.length() * p.length() { + return Self::hit_tri_wide(t, o, d); + } + let inv = 1.0 / det; + if !inv.is_finite() { + return Self::hit_tri_wide(t, o, d); + } + let s = o - t[0]; + let u = s.dot(p) * inv; + let q = s.cross(e1); + let v = d.dot(q) * inv; + let w = 1.0 - u - v; + if !(u.is_finite() && v.is_finite() && w.is_finite()) { + return Self::hit_tri_wide(t, o, d); + } + if u.min(v).min(w) < -NEAR { + return None; + } + if u.min(v).min(w) <= NEAR { + return Self::hit_tri_wide(t, o, d); + } + let tt = e2.dot(q) * inv; + if !tt.is_finite() { + return Self::hit_tri_wide(t, o, d); + } + (tt > 0.0).then_some((tt, u, v)) + } + + fn hit_tri_wide(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { + const EDGE: f64 = 1e-9; + let (a, b, c) = (t[0].as_dvec3(), t[1].as_dvec3(), t[2].as_dvec3()); + let (o, d) = (o.as_dvec3(), d.as_dvec3()); + let (e1, e2) = (b - a, c - a); + let p = d.cross(e2); + let det = e1.dot(p); + let products = e1.abs().dot(glam::DVec3::new( + (d.y * e2.z).abs() + (d.z * e2.y).abs(), + (d.z * e2.x).abs() + (d.x * e2.z).abs(), + (d.x * e2.y).abs() + (d.y * e2.x).abs(), + )); + if det == 0.0 || det.abs() <= 8.0 * f64::EPSILON * products { 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 s = o - a; 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 { + if u < -EDGE || v < -EDGE || u + v > 1.0 + EDGE { return None; } let tt = e2.dot(q) * inv; - (tt > 0.0).then_some((tt, u, v)) + let distance = tt as f32; + (distance > 0.0 && distance.is_finite()).then_some((distance, u as f32, v as f32)) } fn traverse(&self, o: Vec3, d: Vec3, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { @@ -484,6 +518,40 @@ 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 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 nearest_point_matches_brute_force() { let m = primitives::builtin("torus").unwrap(); @@ -787,11 +855,12 @@ mod tests { 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 affected = (0..m.triangle_count()).filter(|&t| skipped(t)).count(); + 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)); - assert_eq!(found.len(), m.triangle_count() - affected); + found.sort_unstable(); + assert_eq!(found, expected); for (lo, hi, _, _) in bvh.nodes() { assert!(lo.is_finite() && hi.is_finite(), "{lo} {hi}"); } From 14598b12d1db7fcaa5a0dd96702ee97ddcb42a8d Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Sat, 28 Nov 2026 00:22:41 -0800 Subject: [PATCH 5/9] craft-mesh-ops: BVH slab test finds hits past the f32 range Bvh::slab computed (lo - o) * (1 / d) in f32. When a box and the ray origin were more than f32::MAX apart, or a direction component was subnormal so that its reciprocal overflowed, a finite entry time became infinite. The node was rejected before the triangle test ran, so the ray missed a triangle it hits. When an axis the ray moves along gives a non-finite time, the slab is computed again in f64, as hit_tri falls back to hit_tri_wide. The margin is the same, and the f64 entry time rounds to f32 within it, so the returned entry time is still at or before the box. Axes with a zero direction component keep the f32 path. --- crates/mesh-ops/src/bvh.rs | 53 ++++++++++++++++++++++++++++++++++---- 1 file changed, 48 insertions(+), 5 deletions(-) diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index 43899ccfcf..410d7cd5d9 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -268,9 +268,14 @@ 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(); @@ -280,6 +285,22 @@ impl Bvh { (tn - margin <= tf + margin).then_some((tn - margin).max(0.0)) } + 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) + } + /// Möller–Trumbore, double sided. fn hit_tri(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { const NEAR: f32 = 1e-4; @@ -348,10 +369,11 @@ impl Bvh { return None; } 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 entry distance: 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 }; @@ -373,8 +395,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)); @@ -530,6 +552,27 @@ mod tests { 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); From eddf1f9578a69fdc8095718e4c27f7eb3bf0c0e0 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:17:28 -0800 Subject: [PATCH 6/9] craft-mesh-ops: BVH queries keep hits at extreme scales and skip triangles with no area - Bvh::nearest finds nothing for a negative cutoff, keeps squared distances and the Voronoi region products in f64, and skips triangles with no area, which ray casts never hit either. - The double-precision ray-triangle test decides the crossing from exact edge-function signs, so a far origin that loses the triangle's offsets no longer reports a hit outside it. - A zero or subnormal distance numerator retries in double precision instead of reporting a miss. - A slab interval rejected in the subnormal range is checked again in double precision. --- crates/mesh-ops/README.md | 7 +- crates/mesh-ops/src/bvh.rs | 239 ++++++++++++++++++++++++++++++------- 2 files changed, 203 insertions(+), 43 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index abbf737599..bb94bc3880 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -31,8 +31,11 @@ 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. Ray tests use double precision for non-finite intermediate values and hits near triangle - edges. Slab intervals include a floating-point rounding margin. + queries. Ray tests use double precision for non-finite or underflowing intermediate values and + hits near triangle edges, where exact edge-function signs decide whether the ray crosses the + triangle. 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 75dd98dfd8..a2fff60daf 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -4,7 +4,7 @@ //! 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; @@ -45,22 +45,22 @@ const LEAF: usize = 4; /// 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): inline for typical depths (no allocation per -/// ray), spilling to the heap for degenerate trees. -struct Stack { - inline: [(u32, f32); 64], +/// 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; @@ -70,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() @@ -286,7 +286,14 @@ impl Bvh { 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); let margin = 4.0 * f32::EPSILON * tn.abs().max(tf.abs()).min(f32::MAX); - (tn - margin <= tf + margin).then_some((tn - margin).max(0.0)) + 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 + } } fn slab_wide(lo: Vec3A, hi: Vec3A, o: Vec3A, d: Vec3A, tmax: f32) -> Option { @@ -333,15 +340,19 @@ impl Bvh { if u.min(v).min(w) <= NEAR { return Self::hit_tri_wide(t, o, d); } - let tt = e2.dot(q) * inv; - if !tt.is_finite() { + let num = e2.dot(q); + let tt = num * inv; + // A zero or subnormal numerator or distance may have lost a positive distance to underflow. + if !num.is_normal() || !tt.is_normal() { return Self::hit_tri_wide(t, o, d); } (tt > 0.0).then_some((tt, u, v)) } + /// The double-precision test. Whether the ray's line crosses the triangle (edges included) + /// comes from the exact signs of the three edge functions, since `o - a` can lose the + /// triangle's offsets even in `f64` when the origin is far from it. fn hit_tri_wide(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { - const EDGE: f64 = 1e-9; let (a, b, c) = (t[0].as_dvec3(), t[1].as_dvec3(), t[2].as_dvec3()); let (o, d) = (o.as_dvec3(), d.as_dvec3()); let (e1, e2) = (b - a, c - a); @@ -355,14 +366,15 @@ impl Bvh { if det == 0.0 || det.abs() <= 8.0 * f64::EPSILON * products { return None; } - let inv = 1.0 / det; - let s = o - a; - let u = s.dot(p) * inv; - let q = s.cross(e1); - let v = d.dot(q) * inv; - if u < -EDGE || v < -EDGE || u + v > 1.0 + EDGE { + let signs = [edge_sign(a, b, o, d), edge_sign(b, c, o, d), edge_sign(c, a, o, d)]; + if signs.iter().any(|&s| s > 0.0) && signs.iter().any(|&s| s < 0.0) { return None; } + let inv = 1.0 / det; + let s = o - a; + let q = s.cross(e1); + let u = (s.dot(p) * inv).clamp(0.0, 1.0); + let v = (d.dot(q) * inv).clamp(0.0, 1.0 - u); let tt = e2.dot(q) * inv; let distance = tt as f32; (distance > 0.0 && distance.is_finite()).then_some((distance, u as f32, v as f32)) @@ -435,13 +447,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 >= 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 }; @@ -451,11 +471,11 @@ impl Bvh { if !filter(orig) { continue; } - let (q, u, v) = closest_on_triangle(p, tri); - let dd = (q - p).length_squared(); + let Some((q, u, v)) = closest_on_triangle(pd, tri) 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 { @@ -499,44 +519,107 @@ 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)] +} + +/// The sign of the exact sum of `terms`: Shewchuk's grow-expansion (Adaptive Precision +/// Floating-Point Arithmetic, 1997) keeps the sum as non-overlapping components in increasing +/// magnitude, so the last nonzero one carries the sign. +fn exact_sign(terms: &[f64; 36]) -> f64 { + let mut e = [0.0_f64; 36]; + 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()); + } + n.checked_sub(1).and_then(|i| e.get(i)).map_or(0.0, |c| c.signum()) +} + +/// The exact sign of `d · ((p0 - o) × (p1 - o))` for coordinates that are `f32` values: 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_sign(p0: DVec3, p1: DVec3, o: DVec3, d: DVec3) -> f64 { + // (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; + } + } + } + } + exact_sign(&terms) +} + /// 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 ab.cross(ac) == DVec3::ZERO { + return None; + } 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((a + ab * v, 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((a + ac * w, 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((b + (c - b) * w, 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)] @@ -599,6 +682,80 @@ mod tests { 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 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(); @@ -614,7 +771,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); From cd7e916b654360a18c673b3e781128d32b956edd Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 14:44:13 -0800 Subject: [PATCH 7/9] craft-mesh-ops: BVH barycentrics and area checks keep far triangle offsets - The double-precision ray-triangle test takes the barycentrics from the compensated values of the three edge functions, not from o - a, which loses the triangle's offsets when the origin is far from it. - Bvh::nearest treats a triangle as having no area only when the exact cross product of its edges is zero, so a triangle whose edges round to parallel vectors far from the origin is still found. --- crates/mesh-ops/src/bvh.rs | 91 ++++++++++++++++++++++++++++++-------- 1 file changed, 73 insertions(+), 18 deletions(-) diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index a2fff60daf..1b7bd82f14 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -350,8 +350,9 @@ impl Bvh { } /// The double-precision test. Whether the ray's line crosses the triangle (edges included) - /// comes from the exact signs of the three edge functions, since `o - a` can lose the - /// triangle's offsets even in `f64` when the origin is far from it. + /// comes from the exact signs of the three edge functions, and the barycentrics from their + /// compensated values, since `o - a` can lose the triangle's offsets even in `f64` when the + /// origin is far from it. fn hit_tri_wide(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { let (a, b, c) = (t[0].as_dvec3(), t[1].as_dvec3(), t[2].as_dvec3()); let (o, d) = (o.as_dvec3(), d.as_dvec3()); @@ -366,15 +367,21 @@ impl Bvh { if det == 0.0 || det.abs() <= 8.0 * f64::EPSILON * products { return None; } - let signs = [edge_sign(a, b, o, d), edge_sign(b, c, o, d), edge_sign(c, a, o, d)]; + // The edge functions opposite vertices a, b and c. + let edges = [expansion(&edge_terms(b, c, o, d)), expansion(&edge_terms(c, a, o, d)), expansion(&edge_terms(a, b, o, d))]; + let signs = edges.map(|(e, n)| expansion_sign(&e, n)); if signs.iter().any(|&s| s > 0.0) && signs.iter().any(|&s| s < 0.0) { return None; } + let [wa, wb, wc] = edges.map(|(e, n)| expansion_value(&e, n)); + 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 inv = 1.0 / det; - let s = o - a; - let q = s.cross(e1); - let u = (s.dot(p) * inv).clamp(0.0, 1.0); - let v = (d.dot(q) * inv).clamp(0.0, 1.0 - u); + let q = (o - a).cross(e1); let tt = e2.dot(q) * inv; let distance = tt as f32; (distance > 0.0 && distance.is_finite()).then_some((distance, u as f32, v as f32)) @@ -471,7 +478,10 @@ impl Bvh { if !filter(orig) { continue; } - let Some((q, u, v)) = closest_on_triangle(pd, tri) else { continue }; + // 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; @@ -525,10 +535,9 @@ fn two_product(a: f64, b: f64) -> [f64; 2] { [p, a.mul_add(b, -p)] } -/// The sign of the exact sum of `terms`: Shewchuk's grow-expansion (Adaptive Precision -/// Floating-Point Arithmetic, 1997) keeps the sum as non-overlapping components in increasing -/// magnitude, so the last nonzero one carries the sign. -fn exact_sign(terms: &[f64; 36]) -> f64 { +/// The exact sum of `terms` (at most 36) as `n` non-overlapping components in increasing +/// magnitude: Shewchuk's grow-expansion (Adaptive Precision Floating-Point Arithmetic, 1997). +fn expansion(terms: &[f64]) -> ([f64; 36], usize) { let mut e = [0.0_f64; 36]; let mut n = 0; for &t in terms { @@ -555,13 +564,35 @@ fn exact_sign(terms: &[f64; 36]) -> f64 { } n = m.min(e.len()); } + (e, n) +} + +/// The sign of an expansion: the last nonzero component carries it. +fn expansion_sign(e: &[f64; 36], n: usize) -> f64 { n.checked_sub(1).and_then(|i| e.get(i)).map_or(0.0, |c| c.signum()) } -/// The exact sign of `d · ((p0 - o) × (p1 - o))` for coordinates that are `f32` values: 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_sign(p0: DVec3, p1: DVec3, o: DVec3, d: DVec3) -> f64 { +/// An expansion rounded to one double, summing its components from the smallest. +fn expansion_value(e: &[f64; 36], 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(); @@ -575,7 +606,7 @@ fn edge_sign(p0: DVec3, p1: DVec3, o: DVec3, d: DVec3) -> f64 { } } } - exact_sign(&terms) + terms } /// The point of triangle `t` nearest to `p` and its barycentrics (weights of vertices 1 and 2), @@ -585,7 +616,8 @@ fn edge_sign(p0: DVec3, p1: DVec3, o: DVec3, d: DVec3) -> f64 { 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 ab.cross(ac) == DVec3::ZERO { + // Edges of a triangle far from the origin can round to parallel vectors. + if ab.cross(ac) == DVec3::ZERO && has_no_area(a, b, c) { return None; } let (d1, d2) = (ab.dot(ap), ac.dot(ap)); @@ -717,6 +749,29 @@ mod tests { 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 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)); + } + #[test] fn nearest_rejects_a_negative_cutoff() { let bvh = review_triangle([Vec3::ZERO, Vec3::X, Vec3::Y]); From 96cfc1d23579fb495694ca657a4eb448cd999c8c Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 15:15:30 -0800 Subject: [PATCH 8/9] craft-mesh-ops: BVH ray hits keep their distance for rays nearly along a triangle The single-precision Moller-Trumbore test accepted a determinant down to 1e-6 of its terms, so a ray nearly parallel to a triangle got a ray parameter and barycentrics with large errors: a ray along an edge, tilted by 2^-19, that crosses the triangle at t = 1 reported t = 1.067 and u = 0.4 instead of 0.25. The double-precision fallback returned no hit when its determinant was within 8 epsilon of its terms, which drops a real hit at the corner of a long thin triangle, and its ray parameter came from the same determinant. hit_tri now works in f64 only. The three edge functions and the numerator `(a - o) . ((b - o) x (c - o))` of the ray parameter are taken from plain f64 arithmetic when the value is larger than 2^26 times its rounding error bound, and otherwise summed exactly from the products of the f32 coordinates. The ray parameter is the numerator over the sum of the edge functions, and a ray in the triangle's plane, where all three edge functions are zero, misses. Ray casts on the built-in torus, sphere, material ball and crate meshes take 5% to 12% longer. Bvh::nearest tests a negative or NaN cutoff with is_nan and < 0 instead of a negated comparison, which clippy's neg_cmp_op_on_partial_ord rejects. --- crates/mesh-ops/README.md | 7 +- crates/mesh-ops/src/bvh.rs | 278 ++++++++++++++++++++++++++++--------- 2 files changed, 216 insertions(+), 69 deletions(-) diff --git a/crates/mesh-ops/README.md b/crates/mesh-ops/README.md index bb94bc3880..9fb4a2ae38 100644 --- a/crates/mesh-ops/README.md +++ b/crates/mesh-ops/README.md @@ -31,9 +31,10 @@ 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. Ray tests use double precision for non-finite or underflowing intermediate values and - hits near triangle edges, where exact edge-function signs decide whether the ray crosses the - triangle. Slab intervals include a floating-point rounding margin, and subnormal intervals are + 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. diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index 1b7bd82f14..22acfb09ed 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -312,78 +312,45 @@ impl Bvh { (tn - margin <= tf + margin).then_some((tn - margin).max(0.0) as f32) } - /// Möller–Trumbore, double sided. + /// 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<(f32, f32, f32)> { - const NEAR: f32 = 1e-4; - let e1 = t[1] - t[0]; - let e2 = t[2] - t[0]; - let p = d.cross(e2); - let det = e1.dot(p); - if !det.is_finite() || det.abs() <= 1e-6 * e1.length() * p.length() { - return Self::hit_tri_wide(t, o, d); - } - let inv = 1.0 / det; - if !inv.is_finite() { - return Self::hit_tri_wide(t, o, d); - } - let s = o - t[0]; - let u = s.dot(p) * inv; - let q = s.cross(e1); - let v = d.dot(q) * inv; - let w = 1.0 - u - v; - if !(u.is_finite() && v.is_finite() && w.is_finite()) { - return Self::hit_tri_wide(t, o, d); - } - if u.min(v).min(w) < -NEAR { - return None; - } - if u.min(v).min(w) <= NEAR { - return Self::hit_tri_wide(t, o, d); - } - let num = e2.dot(q); - let tt = num * inv; - // A zero or subnormal numerator or distance may have lost a positive distance to underflow. - if !num.is_normal() || !tt.is_normal() { - return Self::hit_tri_wide(t, o, d); - } - (tt > 0.0).then_some((tt, u, v)) - } - - /// The double-precision test. Whether the ray's line crosses the triangle (edges included) - /// comes from the exact signs of the three edge functions, and the barycentrics from their - /// compensated values, since `o - a` can lose the triangle's offsets even in `f64` when the - /// origin is far from it. - fn hit_tri_wide(t: &[Vec3; 3], o: Vec3, d: Vec3) -> Option<(f32, f32, f32)> { - let (a, b, c) = (t[0].as_dvec3(), t[1].as_dvec3(), t[2].as_dvec3()); + let [a, b, c] = t.map(|p| p.as_dvec3()); let (o, d) = (o.as_dvec3(), d.as_dvec3()); - let (e1, e2) = (b - a, c - a); - let p = d.cross(e2); - let det = e1.dot(p); - let products = e1.abs().dot(glam::DVec3::new( - (d.y * e2.z).abs() + (d.z * e2.y).abs(), - (d.z * e2.x).abs() + (d.x * e2.z).abs(), - (d.x * e2.y).abs() + (d.y * e2.x).abs(), - )); - if det == 0.0 || det.abs() <= 8.0 * f64::EPSILON * products { + 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; } - // The edge functions opposite vertices a, b and c. - let edges = [expansion(&edge_terms(b, c, o, d)), expansion(&edge_terms(c, a, o, d)), expansion(&edge_terms(a, b, o, d))]; - let signs = edges.map(|(e, n)| expansion_sign(&e, n)); - if signs.iter().any(|&s| s > 0.0) && signs.iter().any(|&s| s < 0.0) { + let wc = edge(pa, pb, a, b); + if opposite(wa, wc) || opposite(wb, wc) { return None; } - let [wa, wb, wc] = edges.map(|(e, n)| expansion_value(&e, n)); + // 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 inv = 1.0 / det; - let q = (o - a).cross(e1); - let tt = e2.dot(q) * inv; - let distance = tt as f32; + let volume = certain(pa.dot(pb.cross(pc)), 6.0 * m * m * m).unwrap_or_else(|| exact_sum(&volume_terms(a, b, c, o))); + let distance = (volume / total) as f32; (distance > 0.0 && distance.is_finite()).then_some((distance, u as f32, v as f32)) } @@ -458,7 +425,7 @@ impl Bvh { /// 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 >= 0.0) { + if max_dist.is_nan() || max_dist < 0.0 { return None; } let root = self.nodes.first().filter(|_| !self.tris.is_empty() && p.is_finite())?; @@ -535,10 +502,27 @@ fn two_product(a: f64, b: f64) -> [f64; 2] { [p, a.mul_add(b, -p)] } -/// The exact sum of `terms` (at most 36) as `n` non-overlapping components in increasing +/// 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; 36], usize) { - let mut e = [0.0_f64; 36]; +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; @@ -568,12 +552,12 @@ fn expansion(terms: &[f64]) -> ([f64; 36], usize) { } /// The sign of an expansion: the last nonzero component carries it. -fn expansion_sign(e: &[f64; 36], n: usize) -> f64 { +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; 36], n: usize) -> f64 { +fn expansion_value(e: &[f64; 48], n: usize) -> f64 { e.iter().take(n).sum() } @@ -609,6 +593,25 @@ fn edge_terms(p0: DVec3, p1: DVec3, o: DVec3, d: DVec3) -> [f64; 36] { 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 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), in `f64` so the region /// products of `f32` coordinates neither overflow nor underflow. `None` for a triangle with no @@ -763,6 +766,149 @@ mod tests { } } + #[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. From addaac29fe857267fb238c1f65528ac16d598ce4 Mon Sep 17 00:00:00 2001 From: dotCooCoo Date: Mon, 30 Nov 2026 17:59:19 -0800 Subject: [PATCH 9/9] craft-mesh-ops: BVH queries compare ray hits in f64 and keep nearest points on far triangles - traverse compares ray parameters in f64 and rounds to f32 only in the returned Hit, so two hits closer than an f32 step keep their order. - nearest checks for zero area exactly unless the plain f64 cross product is larger than its rounding error bound. - A triangle whose edges round to nearly parallel vectors takes its nearest point from its three edges. - An edge point past the middle of the edge is measured from the far end, so a fraction that rounds to 1 keeps its offset. --- crates/mesh-ops/src/bvh.rs | 120 +++++++++++++++++++++++++++++++++---- 1 file changed, 107 insertions(+), 13 deletions(-) diff --git a/crates/mesh-ops/src/bvh.rs b/crates/mesh-ops/src/bvh.rs index 22acfb09ed..e8a7816a78 100644 --- a/crates/mesh-ops/src/bvh.rs +++ b/crates/mesh-ops/src/bvh.rs @@ -320,7 +320,7 @@ impl Bvh { /// 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<(f32, f32, f32)> { + 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); @@ -350,14 +350,20 @@ impl Bvh { 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))); - let distance = (volume / total) as f32; - (distance > 0.0 && distance.is_finite()).then_some((distance, u as f32, v as f32)) + // 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, mut tmax: f32, any: bool, filter: &dyn Fn(u32) -> bool) -> Option { + 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, da) = (Vec3A::from(o), Vec3A::from(d)); let inv = Vec3A::ONE / da; @@ -366,17 +372,19 @@ impl Bvh { 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; } @@ -612,6 +620,45 @@ fn volume_terms(a: DVec3, b: DVec3, c: DVec3, o: DVec3) -> [f64; 48] { 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), in `f64` so the region /// products of `f32` coordinates neither overflow nor underflow. `None` for a triangle with no @@ -619,10 +666,28 @@ fn volume_terms(a: DVec3, b: DVec3, c: DVec3, o: DVec3) -> [f64; 48] { 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); - // Edges of a triangle far from the origin can round to parallel vectors. - if ab.cross(ac) == DVec3::ZERO && has_no_area(a, b, c) { + 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 Some((a, 0.0, 0.0)); @@ -635,7 +700,7 @@ fn closest_on_triangle(p: DVec3, t: &[Vec3; 3]) -> Option<(DVec3, f64, f64)> { let vc = d1 * d4 - d3 * d2; if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 { let v = d1 / (d1 - d3); - return Some((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)); @@ -645,12 +710,12 @@ fn closest_on_triangle(p: DVec3, t: &[Vec3; 3]) -> Option<(DVec3, f64, f64)> { let vb = d5 * d2 - d1 * d6; if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 { let w = d2 / (d2 - d6); - return Some((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 Some((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); @@ -916,6 +981,34 @@ mod tests { 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] @@ -1034,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))); } }