use crate::{Bounds3d, Vertex3d};
const LEAF_SIZE: u32 = 4;
const BINS: usize = 12;
const STACK_DEPTH: usize = 64;
#[derive(Clone, Copy, Debug, PartialEq)]
struct Node {
min: [f32; 3],
max: [f32; 3],
first: u32,
count: u32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BvhHit3d {
pub triangle: u32,
pub t: f32,
}
#[derive(Clone, Debug)]
pub struct Bvh3d {
nodes: Vec<Node>,
order: Vec<u32>,
triangles: u32,
depth: u32,
bounds: Option<Bounds3d>,
}
impl PartialEq for Bvh3d {
fn eq(&self, other: &Self) -> bool {
self.nodes == other.nodes && self.order == other.order
}
}
impl Bvh3d {
pub fn build(vertices: &[Vertex3d], indices: &[u32]) -> Self {
let count = (indices.len() / 3) as u32;
let mut order: Vec<u32> = (0..count).collect();
let mut nodes = Vec::with_capacity(count as usize * 2);
let mut depth = 0;
let bounds = if count == 0 {
None
} else {
let centroids: Vec<[f32; 3]> = (0..count as usize)
.map(|i| centroid(vertices, indices, i))
.collect();
build_node(
vertices,
indices,
¢roids,
&mut order,
0..count,
&mut nodes,
0,
&mut depth,
);
total_bounds(&nodes)
};
Self {
nodes,
order,
triangles: count,
depth,
bounds,
}
}
pub fn refit(&mut self, vertices: &[Vertex3d], indices: &[u32]) -> bool {
if indices.len() / 3 != self.triangles as usize || self.nodes.is_empty() {
return false;
}
let mut bounds = vec![[0.0f32; 6]; self.nodes.len()];
for index in (0..self.nodes.len()).rev() {
let node = self.nodes[index];
if node.count > 0 {
let start = node.first as usize;
let end = start + node.count as usize;
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for &triangle in &self.order[start..end] {
for corner in triangle_positions(vertices, indices, triangle as usize) {
for axis in 0..3 {
min[axis] = min[axis].min(corner[axis]);
max[axis] = max[axis].max(corner[axis]);
}
}
}
if !min[0].is_finite() {
min = node.min;
max = node.max;
}
bounds[index] = [min[0], min[1], min[2], max[0], max[1], max[2]];
} else {
let left = bounds[index + 1];
let right = bounds[node.first as usize];
bounds[index] = [
left[0].min(right[0]),
left[1].min(right[1]),
left[2].min(right[2]),
left[3].max(right[3]),
left[4].max(right[4]),
left[5].max(right[5]),
];
}
}
for (node, boxed) in self.nodes.iter_mut().zip(bounds) {
node.min = [boxed[0], boxed[1], boxed[2]];
node.max = [boxed[3], boxed[4], boxed[5]];
}
self.bounds = total_bounds(&self.nodes);
true
}
pub fn triangle_count(&self) -> u32 {
self.triangles
}
pub fn depth(&self) -> u32 {
self.depth
}
pub fn bounds(&self) -> Option<Bounds3d> {
self.bounds
}
#[allow(clippy::too_many_arguments)]
pub fn ray_cast(
&self,
vertices: &[Vertex3d],
indices: &[u32],
origin: [f32; 3],
direction: [f32; 3],
t_min: f32,
t_max: f32,
sign: f32,
) -> Option<BvhHit3d> {
self.ray_cast_counted(vertices, indices, origin, direction, t_min, t_max, sign)
.0
}
#[allow(clippy::too_many_arguments)]
pub fn ray_cast_counted(
&self,
vertices: &[Vertex3d],
indices: &[u32],
origin: [f32; 3],
direction: [f32; 3],
t_min: f32,
t_max: f32,
sign: f32,
) -> (Option<BvhHit3d>, u32) {
let Some(root) = self.nodes.first() else {
return (None, 0);
};
let mut best: Option<BvhHit3d> = None;
let mut limit = t_max;
let mut tested = 0u32;
let mut stack = [(0u32, 0.0f32); STACK_DEPTH];
let mut top = 0usize;
if slab(root, origin, direction, t_min, limit).is_some() {
stack[0] = (0, 0.0);
top = 1;
}
while top > 0 {
top -= 1;
let (index, _) = stack[top];
let node = &self.nodes[index as usize];
if node.count == 0 {
let left = index + 1;
let right = node.first;
for child in [left, right] {
let Some(child_node) = self.nodes.get(child as usize) else {
continue;
};
if slab(child_node, origin, direction, t_min, limit).is_some()
&& top < STACK_DEPTH
{
stack[top] = (child, 0.0);
top += 1;
}
}
continue;
}
let start = node.first as usize;
let end = start + node.count as usize;
for &triangle in &self.order[start..end] {
let [a, b, c] = triangle_positions(vertices, indices, triangle as usize);
tested += 1;
if let Some(t) = intersect_triangle(a, b, c, origin, direction, t_min, limit, sign)
&& t < limit
{
limit = t;
best = Some(BvhHit3d { triangle, t });
}
}
}
(best, tested)
}
}
#[allow(clippy::too_many_arguments)]
fn build_node(
vertices: &[Vertex3d],
indices: &[u32],
centroids: &[[f32; 3]],
order: &mut [u32],
range: std::ops::Range<u32>,
nodes: &mut Vec<Node>,
level: u32,
depth: &mut u32,
) -> u32 {
let index = nodes.len() as u32;
*depth = (*depth).max(level);
nodes.push(Node {
min: [0.0; 3],
max: [0.0; 3],
first: 0,
count: 0,
});
let bounds = triangle_bounds_range(
vertices,
indices,
&order[range.start as usize..range.end as usize],
);
let size = range.end - range.start;
debug_assert!(size > 0);
nodes[index as usize] = Node {
min: bounds.min,
max: bounds.max,
first: range.start,
count: size,
};
if size <= LEAF_SIZE {
return index;
}
let Some((split_axis, split_pos)) =
best_split(vertices, indices, centroids, order, range.clone())
else {
return index; };
let slice = &mut order[range.start as usize..range.end as usize];
let mid = slice
.iter()
.position(|&t| centroids[t as usize][split_axis] >= split_pos)
.unwrap_or(slice.len());
let mid = if mid == 0 || mid == slice.len() {
slice.len() / 2
} else {
mid
};
let (left, right) = slice.split_at_mut(mid);
left.sort_unstable_by(|a, b| {
centroids[*a as usize][split_axis].total_cmp(¢roids[*b as usize][split_axis])
});
right.sort_unstable_by(|a, b| {
centroids[*a as usize][split_axis].total_cmp(¢roids[*b as usize][split_axis])
});
let left_count = mid as u32;
build_node(
vertices,
indices,
centroids,
order,
range.start..range.start + left_count,
nodes,
level + 1,
depth,
);
let right_index = build_node(
vertices,
indices,
centroids,
order,
range.start + left_count..range.end,
nodes,
level + 1,
depth,
);
nodes[index as usize] = Node {
min: bounds.min,
max: bounds.max,
first: right_index,
count: 0,
};
index
}
fn best_split(
vertices: &[Vertex3d],
indices: &[u32],
centroids: &[[f32; 3]],
order: &[u32],
range: std::ops::Range<u32>,
) -> Option<(usize, f32)> {
let slice = &order[range.start as usize..range.end as usize];
let mut cmin = [f32::INFINITY; 3];
let mut cmax = [f32::NEG_INFINITY; 3];
for &t in slice {
let c = centroids[t as usize];
for axis in 0..3 {
cmin[axis] = cmin[axis].min(c[axis]);
cmax[axis] = cmax[axis].max(c[axis]);
}
}
let extent = [cmax[0] - cmin[0], cmax[1] - cmin[1], cmax[2] - cmin[2]];
let axis = (0..3).max_by(|a, b| extent[*a].total_cmp(&extent[*b]))?;
if !extent[axis].is_finite() || extent[axis] <= 0.0 {
return None;
}
let scale = BINS as f32 / extent[axis];
let mut bin_count = [0u32; BINS];
let mut bin_bounds = [[[0.0f32; 3]; 2]; BINS];
for bin in bin_bounds.iter_mut() {
bin[0] = [f32::INFINITY; 3];
bin[1] = [f32::NEG_INFINITY; 3];
}
for &t in slice {
let bin = (((centroids[t as usize][axis] - cmin[axis]) * scale) as usize).min(BINS - 1);
bin_count[bin] += 1;
for position in triangle_positions(vertices, indices, t as usize) {
for (axis_index, value) in position.iter().enumerate() {
bin_bounds[bin][0][axis_index] = bin_bounds[bin][0][axis_index].min(*value);
bin_bounds[bin][1][axis_index] = bin_bounds[bin][1][axis_index].max(*value);
}
}
}
let mut left_area = [0.0f32; BINS];
let mut left_count = [0u32; BINS];
let mut acc_min = [f32::INFINITY; 3];
let mut acc_max = [f32::NEG_INFINITY; 3];
let mut count = 0u32;
for bin in 0..BINS {
for axis_index in 0..3 {
acc_min[axis_index] = acc_min[axis_index].min(bin_bounds[bin][0][axis_index]);
acc_max[axis_index] = acc_max[axis_index].max(bin_bounds[bin][1][axis_index]);
}
count += bin_count[bin];
left_count[bin] = count;
left_area[bin] = area(acc_min, acc_max);
}
let mut right_area = [0.0f32; BINS];
let mut right_count = [0u32; BINS];
acc_min = [f32::INFINITY; 3];
acc_max = [f32::NEG_INFINITY; 3];
count = 0;
for bin in (0..BINS).rev() {
for axis_index in 0..3 {
acc_min[axis_index] = acc_min[axis_index].min(bin_bounds[bin][0][axis_index]);
acc_max[axis_index] = acc_max[axis_index].max(bin_bounds[bin][1][axis_index]);
}
count += bin_count[bin];
right_count[bin] = count;
right_area[bin] = area(acc_min, acc_max);
}
let mut best: Option<(usize, f32)> = None;
for bin in 0..BINS - 1 {
if left_count[bin] == 0 || right_count[bin + 1] == 0 {
continue;
}
let cost = left_area[bin] * left_count[bin] as f32
+ right_area[bin + 1] * right_count[bin + 1] as f32;
if best.is_none_or(|(_, best_cost)| cost < best_cost) {
best = Some((bin, cost));
}
}
let (bin, _) = best?;
Some((
axis,
cmin[axis] + extent[axis] * (bin + 1) as f32 / BINS as f32,
))
}
fn triangle_positions(vertices: &[Vertex3d], indices: &[u32], triangle: usize) -> [[f32; 3]; 3] {
let mut out = [[0.0f32; 3]; 3];
for (slot, corner) in out.iter_mut().enumerate() {
let Some(&vertex_index) = indices.get(triangle * 3 + slot) else {
continue;
};
if let Some(vertex) = vertices.get(vertex_index as usize) {
*corner = vertex.position;
}
}
out
}
fn centroid(vertices: &[Vertex3d], indices: &[u32], triangle: usize) -> [f32; 3] {
let [a, b, c] = triangle_positions(vertices, indices, triangle);
std::array::from_fn(|axis| (a[axis] + b[axis] + c[axis]) / 3.0)
}
fn area(min: [f32; 3], max: [f32; 3]) -> f32 {
if !min[0].is_finite() || !max[0].is_finite() || min[0] > max[0] {
return 0.0;
}
let d = [max[0] - min[0], max[1] - min[1], max[2] - min[2]];
2.0 * (d[0] * d[1] + d[1] * d[2] + d[2] * d[0])
}
fn triangle_bounds_range(vertices: &[Vertex3d], indices: &[u32], order: &[u32]) -> Bounds3d {
let mut min = [f32::INFINITY; 3];
let mut max = [f32::NEG_INFINITY; 3];
for &triangle in order {
for position in triangle_positions(vertices, indices, triangle as usize) {
for axis in 0..3 {
min[axis] = min[axis].min(position[axis]);
max[axis] = max[axis].max(position[axis]);
}
}
}
if min[0] > max[0] {
return Bounds3d {
min: [0.0; 3],
max: [0.0; 3],
};
}
Bounds3d { min, max }
}
fn total_bounds(nodes: &[Node]) -> Option<Bounds3d> {
let root = nodes.first()?;
Some(Bounds3d {
min: root.min,
max: root.max,
})
}
fn slab(node: &Node, origin: [f32; 3], direction: [f32; 3], t_min: f32, t_max: f32) -> Option<f32> {
let mut near = t_min;
let mut far = t_max;
for axis in 0..3 {
let d = direction[axis];
let o = origin[axis];
if d.abs() < 1e-12 {
if o < node.min[axis] || o > node.max[axis] {
return None;
}
continue;
}
let inv = 1.0 / d;
let mut t0 = (node.min[axis] - o) * inv;
let mut t1 = (node.max[axis] - o) * inv;
if t0 > t1 {
std::mem::swap(&mut t0, &mut t1);
}
near = near.max(t0);
far = far.min(t1);
if near > far {
return None;
}
}
Some(near)
}
#[allow(clippy::too_many_arguments)]
fn intersect_triangle(
a: [f32; 3],
b: [f32; 3],
c: [f32; 3],
origin: [f32; 3],
direction: [f32; 3],
t_min: f32,
t_max: f32,
sign: f32,
) -> Option<f32> {
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
let p = [
direction[1] * e2[2] - direction[2] * e2[1],
direction[2] * e2[0] - direction[0] * e2[2],
direction[0] * e2[1] - direction[1] * e2[0],
];
let determinant = e1[0] * p[0] + e1[1] * p[1] + e1[2] * p[2];
let edge_area = (e1[0] * e1[0] + e1[1] * e1[1] + e1[2] * e1[2]).sqrt()
* (e2[0] * e2[0] + e2[1] * e2[1] + e2[2] * e2[2]).sqrt();
if !determinant.is_finite() || determinant * sign <= edge_area * 1e-7 {
return None;
}
let t = [origin[0] - a[0], origin[1] - a[1], origin[2] - a[2]];
let u = (t[0] * p[0] + t[1] * p[1] + t[2] * p[2]) / determinant;
if !(0.0..=1.0).contains(&u) {
return None;
}
let q = [
t[1] * e1[2] - t[2] * e1[1],
t[2] * e1[0] - t[0] * e1[2],
t[0] * e1[1] - t[1] * e1[0],
];
let v = (direction[0] * q[0] + direction[1] * q[1] + direction[2] * q[2]) / determinant;
if v < 0.0 || u + v > 1.0 {
return None;
}
let distance = (e2[0] * q[0] + e2[1] * q[1] + e2[2] * q[2]) / determinant;
(distance.is_finite() && distance >= t_min && distance <= t_max).then_some(distance)
}
#[cfg(test)]
mod tests {
use super::*;
fn triangle(offset: [f32; 3]) -> Vec<Vertex3d> {
vec![
Vertex3d {
position: [offset[0] - 0.5, offset[1] - 0.5, offset[2]],
normal: [0.0, 0.0, 1.0],
},
Vertex3d {
position: [offset[0] + 0.5, offset[1] - 0.5, offset[2]],
normal: [0.0, 0.0, 1.0],
},
Vertex3d {
position: [offset[0], offset[1] + 0.5, offset[2]],
normal: [0.0, 0.0, 1.0],
},
]
}
fn identity(count: usize) -> Vec<u32> {
(0..count as u32).collect()
}
fn brute(
vertices: &[Vertex3d],
indices: &[u32],
origin: [f32; 3],
direction: [f32; 3],
sign: f32,
) -> Option<BvhHit3d> {
let mut best: Option<BvhHit3d> = None;
for index in 0..indices.len() / 3 {
let [a, b, c] = triangle_positions(vertices, indices, index);
if let Some(t) = intersect_triangle(a, b, c, origin, direction, 0.0, 1000.0, sign)
&& best.is_none_or(|b| t < b.t)
{
best = Some(BvhHit3d {
triangle: index as u32,
t,
});
}
}
best
}
#[test]
fn empty_mesh_has_no_hit() {
let bvh = Bvh3d::build(&[], &[]);
assert_eq!(bvh.triangle_count(), 0);
assert!(bvh.bounds().is_none());
assert!(
bvh.ray_cast(&[], &[], [0.0, 0.0, 5.0], [0.0, 0.0, -1.0], 0.0, 100.0, 1.0)
.is_none()
);
}
#[test]
fn grid_matches_brute_force_and_prunes() {
let mut vertices = Vec::new();
let mut indices = Vec::new();
for y in 0..40 {
for x in 0..40 {
let z = (x % 3) as f32 * 0.5;
let base = vertices.len() as u32;
vertices.extend([
Vertex3d {
position: [x as f32 - 0.2, y as f32 - 0.2, z],
normal: [0.0, 0.0, 1.0],
},
Vertex3d {
position: [x as f32 + 0.2, y as f32 - 0.2, z],
normal: [0.0, 0.0, 1.0],
},
Vertex3d {
position: [x as f32, y as f32 + 0.2, z],
normal: [0.0, 0.0, 1.0],
},
]);
indices.extend([base, base + 1, base + 2]);
}
}
let bvh = Bvh3d::build(&vertices, &indices);
assert_eq!(bvh.triangle_count(), 1600);
assert!(bvh.depth() <= 24, "退化树深度 {}", bvh.depth());
let origin = [23.05, 12.03, 5.0];
let direction = [0.0, 0.0, -1.0];
let (hit, tested) =
bvh.ray_cast_counted(&vertices, &indices, origin, direction, 0.0, 100.0, 1.0);
let expect = brute(&vertices, &indices, origin, direction, 1.0);
assert_eq!(hit.map(|h| h.triangle), expect.map(|h| h.triangle));
assert!(tested <= 32, "粗筛未生效:精确测试 {tested} 个三角形");
}
#[test]
fn direction_away_from_scene_misses_fast() {
let mut vertices = Vec::new();
let mut indices = Vec::new();
for i in 0..500 {
let base = vertices.len() as u32;
vertices.extend(triangle([i as f32, 0.0, 0.0]));
indices.extend([base, base + 1, base + 2]);
}
let bvh = Bvh3d::build(&vertices, &indices);
let (hit, tested) = bvh.ray_cast_counted(
&vertices,
&indices,
[0.0, 0.0, 5.0],
[0.0, 0.0, 1.0],
0.0,
100.0,
1.0,
);
assert!(hit.is_none());
assert_eq!(tested, 0, "整棵树应被根节点粗筛拒绝");
}
#[test]
fn mirrored_winding_rejects_back_faces() {
let vertices = triangle([0.0, 0.0, 0.0]);
let indices = identity(3);
let bvh = Bvh3d::build(&vertices, &indices);
let origin = [0.0, 0.0, 5.0];
let direction = [0.0, 0.0, -1.0];
assert!(
bvh.ray_cast(&vertices, &indices, origin, direction, 0.0, 100.0, 1.0)
.is_some()
);
assert!(
bvh.ray_cast(&vertices, &indices, origin, direction, 0.0, 100.0, -1.0)
.is_none()
);
}
#[test]
fn refit_tracks_deformation_without_rebuilding() {
let mut vertices = Vec::new();
let mut indices = Vec::new();
for i in 0..64 {
let base = vertices.len() as u32;
vertices.extend(triangle([i as f32, 0.0, 0.0]));
indices.extend([base, base + 1, base + 2]);
}
let mut bvh = Bvh3d::build(&vertices, &indices);
let depth = bvh.depth();
let order = bvh.order.clone();
assert!(bvh.bounds().unwrap().max[2] < 0.001);
for vertex in &mut vertices {
vertex.position[2] += 5.0;
}
assert!(bvh.refit(&vertices, &indices));
assert_eq!(bvh.depth(), depth, "refit 不应改变拓扑");
assert_eq!(bvh.order, order);
assert!((bvh.bounds().unwrap().min[2] - 5.0).abs() < 1e-5);
let origin = [31.05, 0.03, 15.0];
let direction = [0.0, 0.0, -1.0];
let hit = bvh
.ray_cast(&vertices, &indices, origin, direction, 0.0, 100.0, 1.0)
.expect("变形后仍应命中");
let expect = brute(&vertices, &indices, origin, direction, 1.0).unwrap();
assert!((hit.t - expect.t).abs() < 1e-4);
}
#[test]
fn refit_rejects_changed_topology() {
let vertices = triangle([0.0, 0.0, 0.0]);
let mut bvh = Bvh3d::build(&vertices, &identity(3));
assert!(!bvh.refit(&vertices, &[0, 1, 2, 0, 1, 2]));
}
}