diff --git a/src/acceleration_data.rs b/src/acceleration_data.rs index 83ff513..b1ac865 100644 --- a/src/acceleration_data.rs +++ b/src/acceleration_data.rs @@ -8,12 +8,13 @@ use crate::ray::Ray; use crate::triangle::Triangle; pub struct AccelerationData<'a> { + recursive: bool, triangles: &'a [Triangle], data: [AABB; 1024], } impl<'a> AccelerationData<'a> { - pub fn create_tree(input_data: &'a [Triangle], triangles_per_as: u32) -> Self { + pub fn create_tree(input_data: &'a [Triangle], triangles_per_as: u32, recursive: bool) -> Self { // we are creating the tree from the bottom up // create our slice @@ -32,6 +33,7 @@ impl<'a> AccelerationData<'a> { // return result AccelerationData { + recursive, triangles: input_data, data, } @@ -42,7 +44,7 @@ impl<'a> AccelerationData<'a> { let mut closest_distance = MAX; let mut barycentric = Vector2::zero(); - self.traverse_tree(|_, aabb| { + self.traverse_tree(&mut |_, aabb| { if aabb.intersect(ray) { // check if node is a leaf if aabb.start_index != -1 { @@ -78,7 +80,7 @@ impl<'a> AccelerationData<'a> { } pub fn print_tree(&self) { - self.traverse_tree(|index, aabb| { + self.traverse_tree(&mut |index, aabb| { print_aabb(index, aabb); true }) @@ -87,7 +89,35 @@ impl<'a> AccelerationData<'a> { // private impl<'a> AccelerationData<'a> { - fn traverse_tree(&self, mut f: F) + fn traverse_tree(&self, f: &mut F) + where + F: FnMut(usize, &AABB) -> bool, + { + if self.recursive { + self.traverse_tree_recursively(f, 0); + } else { + self.traverse_tree_iteratively(f); + } + } + + fn traverse_tree_recursively(&self, f: &mut F, index: usize) + where + F: FnMut(usize, &AABB) -> bool, + { + if (*f)(index, &self.data[index]) { + let left_child = self.data[index].left_child; + if left_child != -1 { + self.traverse_tree_recursively(f, left_child as usize); + } + + let right_child = self.data[index].right_child; + if right_child != -1 { + self.traverse_tree_recursively(f, right_child as usize); + } + } + } + + fn traverse_tree_iteratively(&self, f: &mut F) where F: FnMut(usize, &AABB) -> bool, { @@ -106,7 +136,7 @@ impl<'a> AccelerationData<'a> { discovered[v] = true; - if (f)(v, &self.data[v]) { + if (*f)(v, &self.data[v]) { let left_child = self.data[v].left_child; if left_child != -1 { if !discovered[left_child as usize] { diff --git a/src/main.rs b/src/main.rs index 65a9c74..edf613b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -67,7 +67,7 @@ fn f_to_u(color: f32) -> u8 { fn debug_raytracer_camera(dim_x: u32, dim_y: u32, camera: &Camera, data: &[Triangle]) { let mut imgbuf = ImageBuffer::new(dim_x, dim_y); - let acceleration_data = AccelerationData::create_tree(data, 8); + let acceleration_data = AccelerationData::create_tree(data, 8, true); acceleration_data.print_tree();