1use glam::DVec3;
8
9use crate::geometry::model::Transform;
10
11#[derive(Debug, Copy, Clone, PartialEq)]
13pub struct Aabb {
14 pub min : DVec3,
15 pub max : DVec3,
16}
17
18impl Aabb {
19 pub const EMPTY : Self = Self {
22 min : DVec3::splat(f64::INFINITY),
23 max : DVec3::splat(f64::NEG_INFINITY),
24 };
25
26 pub fn from_points(points : impl IntoIterator<Item = DVec3>) -> Self {
27 let mut aabb = Self::EMPTY;
28 for p in points {
29 aabb.grow(p);
30 }
31 aabb
32 }
33
34 pub fn is_empty(&self) -> bool {
35 self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z
36 }
37
38 pub fn grow(&mut self, p : DVec3) {
39 self.min = self.min.min(p);
40 self.max = self.max.max(p);
41 }
42
43 pub fn merge(&mut self, other : &Aabb) {
44 self.min = self.min.min(other.min);
45 self.max = self.max.max(other.max);
46 }
47
48 pub fn intersection(&self, other : &Aabb) -> Aabb {
49 Aabb {
50 min : self.min.max(other.min),
51 max : self.max.min(other.max),
52 }
53 }
54
55 pub fn expanded(&self, margin : f64) -> Aabb {
57 Aabb {
58 min : self.min - DVec3::splat(margin),
59 max : self.max + DVec3::splat(margin),
60 }
61 }
62
63 pub fn center(&self) -> DVec3 {
64 0.5*(self.min + self.max)
65 }
66
67 pub fn surface_area(&self) -> f64 {
68 if self.is_empty() {
69 return 0.0;
70 }
71 let d = self.max - self.min;
72 2.0*(d.x*d.y + d.y*d.z + d.z*d.x)
73 }
74
75 pub fn transformed(&self, t : &Transform) -> Aabb {
78 if self.is_empty() {
79 return *self;
80 }
81 let corners = (0..8).map(|k| DVec3::new(
82 if k & 1 == 0 { self.min.x } else { self.max.x },
83 if k & 2 == 0 { self.min.y } else { self.max.y },
84 if k & 4 == 0 { self.min.z } else { self.max.z },
85 ));
86 Aabb::from_points(corners.map(|c| t.apply_point(c)))
87 }
88
89 pub fn clip_line(&self, origin : DVec3, dir : DVec3, tmin : f64, tmax : f64) -> Option<(f64, f64)> {
93 let (mut t0, mut t1) = (tmin, tmax);
94 for k in 0..3 {
95 if dir[k] == 0.0 {
96 if origin[k] < self.min[k] || origin[k] > self.max[k] {
97 return None;
98 }
99 continue;
100 }
101 let inv = 1.0/dir[k];
102 let (mut ta, mut tb) = ((self.min[k] - origin[k])*inv, (self.max[k] - origin[k])*inv);
103 if ta > tb {
104 std::mem::swap(&mut ta, &mut tb);
105 }
106 t0 = t0.max(ta);
107 t1 = t1.min(tb);
108 if t0 > t1 {
109 return None;
110 }
111 }
112 Some((t0, t1))
113 }
114}
115
116const MAX_LEAF_SIZE : usize = 4;
120const N_BINS : usize = 16;
122
123#[derive(Debug, Clone, PartialEq)]
124struct BvhNode {
125 aabb : Aabb,
126 first : u32,
130 count : u32,
132}
133
134#[derive(Debug, Clone, PartialEq)]
137pub struct Bvh {
138 nodes : Vec<BvhNode>,
139 indices : Vec<u32>,
142}
143
144impl Bvh {
145 pub fn build(boxes : &[Aabb]) -> Self {
146 let mut bvh = Self {
147 nodes : Vec::with_capacity(2*boxes.len()/MAX_LEAF_SIZE + 1),
148 indices : (0..boxes.len() as u32).collect(),
149 };
150 let centers : Vec<DVec3> = boxes.iter().map(|b| b.center()).collect();
151 bvh.nodes.push(BvhNode { aabb : Aabb::EMPTY, first : 0, count : boxes.len() as u32 });
152 bvh.subdivide(0, boxes, ¢ers);
153 bvh
154 }
155
156 pub fn bounds(&self) -> Aabb {
157 self.nodes[0].aabb
158 }
159
160 fn subdivide(&mut self, node : usize, boxes : &[Aabb], centers : &[DVec3]) {
161 let first = self.nodes[node].first as usize;
162 let count = self.nodes[node].count as usize;
163 let range = first..first + count;
164 let mut aabb = Aabb::EMPTY;
165 let mut centroid = Aabb::EMPTY;
166 for &i in &self.indices[range.clone()] {
167 aabb.merge(&boxes[i as usize]);
168 centroid.grow(centers[i as usize]);
169 }
170 self.nodes[node].aabb = aabb;
171 if count <= MAX_LEAF_SIZE {
172 return;
173 }
174 let Some((axis, split)) = Self::find_split(&self.indices[range.clone()], boxes, centers, ¢roid, aabb.surface_area()*count as f64) else {
175 return;
176 };
177 let (mut i, mut j) = (first, first + count);
179 while i < j {
180 if centers[self.indices[i] as usize][axis] < split {
181 i += 1;
182 } else {
183 j -= 1;
184 self.indices.swap(i, j);
185 }
186 }
187 let n_left = i - first;
188 if n_left == 0 || n_left == count {
189 return;
190 }
191 let left = self.nodes.len();
192 self.nodes.push(BvhNode { aabb : Aabb::EMPTY, first : first as u32, count : n_left as u32 });
193 self.nodes.push(BvhNode { aabb : Aabb::EMPTY, first : i as u32, count : (count - n_left) as u32 });
194 self.nodes[node].first = left as u32;
195 self.nodes[node].count = 0;
196 self.subdivide(left, boxes, centers);
197 self.subdivide(left + 1, boxes, centers);
198 }
199
200 fn find_split(indices : &[u32], boxes : &[Aabb], centers : &[DVec3], centroid : &Aabb, leaf_cost : f64) -> Option<(usize, f64)> {
203 let mut best : Option<(usize, f64)> = None;
204 let mut best_cost = leaf_cost;
205 for axis in 0..3 {
206 let (lo, hi) = (centroid.min[axis], centroid.max[axis]);
207 if hi <= lo {
208 continue;
209 }
210 let scale = N_BINS as f64/(hi - lo);
211 let mut bins = [(Aabb::EMPTY, 0usize); N_BINS];
212 for &i in indices {
213 let b = (((centers[i as usize][axis] - lo)*scale) as usize).min(N_BINS - 1);
214 bins[b].0.merge(&boxes[i as usize]);
215 bins[b].1 += 1;
216 }
217 let mut left_cost = [0.0; N_BINS - 1];
220 let (mut aabb, mut n) = (Aabb::EMPTY, 0);
221 for k in 0..N_BINS - 1 {
222 aabb.merge(&bins[k].0);
223 n += bins[k].1;
224 left_cost[k] = aabb.surface_area()*n as f64;
225 }
226 let (mut aabb, mut n) = (Aabb::EMPTY, 0);
227 for k in (1..N_BINS).rev() {
228 aabb.merge(&bins[k].0);
229 n += bins[k].1;
230 let cost = left_cost[k - 1] + aabb.surface_area()*n as f64;
231 if cost < best_cost {
232 best_cost = cost;
233 best = Some((axis, lo + k as f64/scale));
234 }
235 }
236 }
237 best
238 }
239
240 pub fn traverse(&self, origin : DVec3, dir : DVec3, tmin : f64, tmax : f64, mut f : impl FnMut(u32)) {
244 if self.indices.is_empty() {
245 return;
246 }
247 let mut stack = vec![0usize];
248 while let Some(k) = stack.pop() {
249 let node = &self.nodes[k];
250 if node.aabb.clip_line(origin, dir, tmin, tmax).is_none() {
251 continue;
252 }
253 if node.count > 0 {
254 let first = node.first as usize;
255 for &i in &self.indices[first..first + node.count as usize] {
256 f(i);
257 }
258 } else {
259 stack.push(node.first as usize);
260 stack.push(node.first as usize + 1);
261 }
262 }
263 }
264}
265
266#[cfg(test)]
269mod tests {
270 use super::*;
271
272 #[test]
273 fn clip_line() {
274 let b = Aabb { min : DVec3::splat(-1.0), max : DVec3::splat(1.0) };
275 assert_eq!(b.clip_line(DVec3::new(-5.0, 0.0, 0.0), DVec3::X, f64::NEG_INFINITY, f64::INFINITY), Some((4.0, 6.0)));
276 assert_eq!(b.clip_line(DVec3::new(-5.0, 0.0, 0.0), DVec3::X, 0.0, 4.5), Some((4.0, 4.5)));
277 assert_eq!(b.clip_line(DVec3::new(-5.0, 2.0, 0.0), DVec3::X, f64::NEG_INFINITY, f64::INFINITY), None);
278 }
279
280 #[test]
281 fn traverse_finds_all_hit_boxes() {
282 let mut boxes : Vec<Aabb> = (0..100).map(|i| Aabb {
284 min : DVec3::new(i as f64, 0.0, 0.0),
285 max : DVec3::new(i as f64 + 1.0, 1.0, 1.0),
286 }).collect();
287 boxes.push(Aabb { min : DVec3::new(50.0, 50.0, 0.0), max : DVec3::new(51.0, 51.0, 1.0) });
288 let bvh = Bvh::build(&boxes);
289 let mut hits = Vec::new();
290 bvh.traverse(DVec3::new(-1.0, 0.5, 0.5), DVec3::X, 0.0, 10.5, |i| hits.push(i));
291 hits.sort();
294 for i in 0..10 {
295 assert!(hits.contains(&i));
296 }
297 assert!(!hits.contains(&100));
298 }
299}