use std::collections::HashMap; use std::collections::VecDeque; use bytemuck::Pod; use bytemuck::Zeroable; use itertools::Itertools; use crate::voxel_cache::data::ExplicitNTreeNode; use crate::voxel_cache::data::StructurePointer; #[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)] #[repr(C)] pub struct Color(pub f32, pub f32, pub f32, pub f32); impl Color { pub fn average>(iter: I) -> Self { let mut c = Color(0., 0., 0., 0.); let mut count = 0; for Color(r, g, b, a) in iter { count += 1; c.0 += r; c.1 += g; c.2 += b; c.3 += a; } c.0 /= count as f32; c.1 /= count as f32; c.2 /= count as f32; c.3 /= count as f32; c } } #[derive(Debug, Clone)] pub struct NTree { map: HashMap, NTreeNode>, // Depth is the parameter such that // N^depth == max_number_of_voxels // one root => depth = 1 depth: usize, } pub struct NTreeIter<'a, const N: usize> { tree: &'a NTree, dfs_stack: Vec>, } #[derive(Debug, Clone, Copy)] pub struct NTreeNode { color: Color, subdivided: bool, } #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] pub struct NTreeNodeLocator(usize); impl NTree where [(); N * N * N]:, { pub fn constant(color: Color, depth: usize) -> Self { let mut map = HashMap::new(); let root = NTreeNode { color, subdivided: false, }; map.insert(NTreeNodeLocator::::root(), root); Self { map, depth } } pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color) { self.set_at_depth(x, y, z, self.depth, color); } pub fn get(&self, x: usize, y: usize, z: usize) -> Color { assert!(x < N.pow(self.depth as u32)); assert!(y < N.pow(self.depth as u32)); assert!(z < N.pow(self.depth as u32)); // Try to walk down the tree, and create necessary nodes let mut current_node_loc = NTreeNodeLocator::::root(); let mut current_node_size = N.pow(self.depth as u32); let mut current_node = self.map.get(¤t_node_loc).unwrap(); loop { if !current_node.subdivided { return current_node.color; } // Descend to relevant node, let child_node_size = current_node_size / N; let child_x = (x % current_node_size) / child_node_size; let child_y = (y % current_node_size) / child_node_size; let child_z = (z % current_node_size) / child_node_size; current_node_size = child_node_size; current_node_loc = current_node_loc.child(child_x, child_y, child_z); current_node = self.map.get(¤t_node_loc).unwrap(); } } pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, color: Color) { assert!(x < N.pow(depth as u32)); assert!(y < N.pow(depth as u32)); assert!(z < N.pow(depth as u32)); // Try to walk down the tree, and create necessary nodes let mut current_node_loc = NTreeNodeLocator::::root(); let mut current_node_size = N.pow(self.depth as u32); let mut current_depth = 0; let mut current_node = self.map.get_mut(¤t_node_loc).unwrap(); while current_depth != depth { if current_node.color == color { // Color is already correct, work is finished return; } // Current is not subdivided, and color is different => subdivide if !current_node.subdivided { current_node.subdivided = true; let new_nodes = NTreeNode { color: current_node.color, subdivided: false, }; current_node_loc.children().into_iter().for_each(|child| { self.map.insert(child, new_nodes); }); } // Descend to relevant node, let child_node_size = current_node_size / N; let child_x = (x % current_node_size) / child_node_size; let child_y = (y % current_node_size) / child_node_size; let child_z = (z % current_node_size) / child_node_size; current_node_size = child_node_size; current_depth += 1; current_node_loc = current_node_loc.child(child_x, child_y, child_z); current_node = self.map.get_mut(¤t_node_loc).unwrap(); } if current_node.subdivided { self.make_constant(current_node_loc, color); } else { current_node.color = color; } // We need to go back up the hierarchy to combine nodes // current_node is the modified node, go one up loop { // Go one node up current_depth -= 1; current_node_loc = current_node_loc.parent().unwrap(); //current_node_size *= N; // Access all children's colors let children_color_avg = current_node_loc .children() .iter() .map(|child_loc| self.map.get(child_loc).unwrap().color) // AGGREGATE AND AVERAGE HERE !! .next() .unwrap(); current_node = self.map.get_mut(¤t_node_loc).unwrap(); current_node.color = children_color_avg; if current_depth == 0 { break; } } } fn make_constant(&mut self, locator: NTreeNodeLocator, color: Color) { let mut dfs_stack = Vec::new(); dfs_stack.push(locator); while let Some(current) = dfs_stack.pop() { // Remove element let removed = self.map.remove(¤t); let handle_children = removed.is_some_and(|x| x.subdivided); // If children have to be handled, push on stack if handle_children { dfs_stack.extend(current.children()); } } self.map.insert( locator, NTreeNode { color, subdivided: false, }, ); } pub fn from_array(array: &[Color], depth: usize) -> Self { let mut structure = HashMap::new(); // Per voxel in the array : // 0 -> Voxel not merged yet // _ -> size of the block in which the voxel was merged let mut merged_size = vec![0; array.len()]; let width = N.pow(depth as u32); for (x, y) in (0..width).cartesian_product(0..width) { let mut z = 0; while z < width { if merged_size[x + y * width + z * width * width] != 0 { // If current voxel has already been accounted for -> skip // We stumbled on a big merged block, we can skip it as a whole on the inner // dimension z += merged_size[x + y * width + z * width * width]; continue; } // Check smallest depth aligned with current position let x_trailing = base_trailing_zeroes::(x).unwrap_or(depth as u32); let y_trailing = base_trailing_zeroes::(y).unwrap_or(depth as u32); let z_trailing = base_trailing_zeroes::(z).unwrap_or(depth as u32); // Biggest block size power of which this voxel can be a lower corner let block_power = x_trailing.min(y_trailing.min(z_trailing)); // Try to merge for each depth let mut max_power_merge = 0; // Single voxel can always be merged let color = array[x + y * width + z * width * width]; let mut locator = NTreeNodeLocator::::new(depth, x, y, z); 'power_search: for power in 1..=block_power { let block_size = N.pow(power); // Check if candidate block has the same color for ((merge_x, merge_y), merge_z) in (0..block_size) .cartesian_product(0..block_size) .cartesian_product(0..block_size) { if array [(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width] != color { break 'power_search; } } // Update biggest candidate block locator = locator.parent().unwrap(); max_power_merge = power; } // We know which size we can know merge // Say we accounted for those voxels : let block_size = N.pow(max_power_merge); for ((merge_x, merge_y), merge_z) in (0..block_size) .cartesian_product(0..block_size) .cartesian_product(0..block_size) { merged_size [(x + merge_x) + (y + merge_y) * width + (z + merge_z) * width * width] = block_size; } // Add new found block in our structure // If power is depth, this is the whole structure, thus depth is 0 let node = NTreeNode { color, subdivided: false, }; structure.insert(locator, node); z += block_size; } } // The structure now consists of the leaf most nodes, we need to rebuild the hierarchy // bottom up for current_power in 1..=depth { // Iterate on the blocks of this size let block_size = N.pow(current_power as u32); let block_count = width / block_size; for ((block_x, block_y), block_z) in (0..block_count) .cartesian_product(0..block_count) .cartesian_product(0..block_count) { // Check the lower corner of this block let corner = merged_size[(block_x * block_size) + (block_y * block_size) * width + (block_z * block_size) * width * width]; if corner >= block_size { // Children are merged in bigger block continue; } // Add hierarchy node let locator = NTreeNodeLocator::::new(depth - current_power, block_x, block_y, block_z); // Get average color of children let color = Color::average( locator .children() .iter() .map(|child_loc| structure.get(child_loc).unwrap().color), ); let hierarchy_node = NTreeNode { color, subdivided: true, }; structure.insert(locator, hierarchy_node); } } Self { map: structure, depth, } } /* pub fn as_explicit_structure(&self) -> (Color, Vec>) { let root = self.map.get(&NTreeNodeLocator::root()).unwrap(); if !root.subdivided { return (root.color, vec![]); } let new_node = ExplicitNTreeNode { structure: [StructurePointer(0); _], colors: [Color(0., 0., 0., 0.); _], }; let mut explicit_structure = vec![new_node.clone()]; let mut bfs_queue = VecDeque::new(); bfs_queue.push_back((NTreeNodeLocator::root(), 0)); while let Some((node_loc, explicit_loc)) = bfs_queue.pop_front() { // Iterate on children, that must exist for (i, child_loc) in node_loc.children().iter().enumerate() { let child_data = self.map.get(child_loc).unwrap(); explicit_structure[explicit_loc].colors[i] = child_data.color; if !child_data.subdivided { explicit_structure[explicit_loc].structure[i] = StructurePointer::new(false, true, 0); continue; } // Child is subdivided, it needs to be handled. let spot = explicit_structure.len(); explicit_structure.push(new_node.clone()); bfs_queue.push_back((*child_loc, spot)); explicit_structure[explicit_loc].structure[i] = StructurePointer::new(true, true, spot as u32); } } (root.color, explicit_structure) } */ } fn base_trailing_zeroes(mut number: usize) -> Option { if number == 0 { return None; } let mut trailing_zeroes = 0; while number % N == 0 { number /= N; trailing_zeroes += 1; } Some(trailing_zeroes) } impl NTreeNodeLocator { pub fn root() -> Self { Self(1) } pub fn from_usize(n: usize) -> Self { Self(n) } pub fn new(mut depth: usize, x: usize, y: usize, z: usize) -> Self { let mut loc = Self::root(); let mut size = N.pow(depth as u32); while depth != 0 { size /= N; let child_x = (x / size) % N; let child_y = (y / size) % N; let child_z = (z / size) % N; loc = loc.child(child_x, child_y, child_z); depth -= 1; } return loc; } pub fn depth(&self) -> usize { let mut n = self.0; let mut depth = 0; while n != 1 { n /= N * N * N; depth += 1; } depth } pub fn child_location(&self) -> (usize, usize, usize) { let mut n = self.0; let z = n % N; n /= N; let y = n % N; n /= N; let x = n % N; (x, y, z) } pub fn node_location(&self) -> (usize, usize, usize) { let mut locator = *self; let mut nx = 0; let mut ny = 0; let mut nz = 0; let mut size = 1; while locator.0 != 1 { let (cx, cy, cz) = locator.child_location(); nx += cx * size; ny += cy * size; nz += cz * size; size *= N; locator = locator.parent().unwrap(); } (nx, ny, nz) } pub fn as_usize(&self) -> usize { self.0 } pub fn parent(&self) -> Option { // Shift left by 3 digits in base N let loc = self.0 / (N * N * N); if loc == 0 { None } else { Some(Self(loc)) } } pub fn child(&self, x: usize, y: usize, z: usize) -> Self { assert!(x < N); assert!(y < N); assert!(z < N); let child_loc = (self.0 * N * N * N) + (x * N * N) + (y * N) + z; NTreeNodeLocator(child_loc) } pub fn children(&self) -> Vec { let mut children = vec![]; for x in 0..N { for y in 0..N { for z in 0..N { children.push(self.child(x, y, z)); } } } children } }