feat: sparse_tree is now generic

This commit is contained in:
2026-11-16 10:58:24 +01:00
parent 828806fbc8
commit cbb3b4eaf0
3 changed files with 112 additions and 79 deletions
+2 -1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
vxls-production = { src = "../vxls-production" }
vxls-production = { path = "../vxls-production" }
bytemuck.workspace = true
itertools.workspace = true
+34 -11
View File
@@ -1,3 +1,5 @@
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
//!
//! This crate contains types and structures to store voxel data
//!
@@ -5,20 +7,41 @@
pub mod sparse_tree;
/// A voxel attribute must be able to be turned into bytes, and just be a bit of data
pub trait Attribute: bytemuck::Pod + bytemuck::Zeroable + Clone + Copy + 'static
{
// Whether the two attributes can be merged into one single voxel
pub fn mergeable(&self, other: &Self) -> bool;
pub trait Attribute:
// An attribute can be turned into predictable, safe, raw bytes
bytemuck::Pod +
bytemuck::Zeroable +
pub fn merge(&self, other: &Self) -> Self;
pub fn merge_iter<I: Iterator<Item = S>, S: AsRef<Self>>(iter: I) -> Option<Self>
{
iter.reduce(<Self as Attribute>::merge).map(|x| *x.as_ref())
}
// It can be compared with itself, equal attributes mean they can be merged in a sparse structure
PartialEq +
Eq +
// It can be crated by anybody, without knowing what is inside
Default +
// It can be moved arround without problems, and does not depend on anything
Clone +
Copy +
Send +
Sync +
'static
{
/// Many attributes can be averaged together
fn average(attributes: &[Self]) -> Self;
}
pub trait Has<A: Attribute>
{
fn get(&self) -> &A;
fn get_mut(&mut self) -> &mut A;
fn get(&self) -> &A;
fn get_mut(&mut self) -> &mut A;
fn get_bytes(&self) -> &[u8]
{
bytemuck::bytes_of(self.get())
}
fn get_bytes_mut(&mut self) -> &mut [u8]
{
bytemuck::bytes_of_mut(self.get_mut())
}
}
+76 -67
View File
@@ -1,5 +1,4 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
@@ -7,31 +6,45 @@ use itertools::Itertools;
use vxls_production::tree_locator::TreeLocator;
#[derive(Debug, Clone, Copy, PartialEq, Pod, Zeroable)]
use crate::Attribute;
#[derive(Debug, Clone, Copy, PartialEq, Default, Pod, Zeroable)]
#[repr(C)]
pub struct Color(pub f32, pub f32, pub f32, pub f32);
impl Color
// `Attribute` requires `Eq`. `Color` is only ever constructed from finite,
// non-NaN values in this crate, so equality is well-behaved here.
impl Eq for Color {}
impl Attribute for Color
{
pub fn average<I: Iterator<Item = Color>>(iter: I) -> Self
fn average(attributes: &[Self]) -> Self
{
let mut c = Color(0., 0., 0., 0.);
let mut count = 0;
for Color(r, g, b, a) in iter
if attributes.is_empty()
{
count += 1;
c.0 += r;
c.1 += g;
c.2 += b;
c.3 += a;
return Self::default();
}
c.0 /= count as f32;
c.1 /= count as f32;
c.2 /= count as f32;
c.3 /= count as f32;
let mut c = Self::default();
for color in attributes
{
c.0 += color.0;
c.1 += color.1;
c.2 += color.2;
c.3 += color.3;
}
let count = attributes.len() as f32;
c.0 /= count;
c.1 /= count;
c.2 /= count;
c.3 /= count;
c
}
}
impl Color
{
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
@@ -43,9 +56,9 @@ impl Color
}
#[derive(Debug, Clone)]
pub struct NTree<const N: usize>
pub struct NTree<const N: usize, T: Attribute>
{
map: HashMap<TreeLocator<N>, NTreeNode>,
map: HashMap<TreeLocator<N>, NTreeNode<T>>,
// Depth is the parameter such that
// N^depth == max_number_of_voxels
@@ -53,40 +66,41 @@ pub struct NTree<const N: usize>
depth: usize,
}
pub struct NTreeIter<'a, const N: usize>
pub struct NTreeIter<'a, const N: usize, T: Attribute>
{
tree: &'a NTree<N>,
tree: &'a NTree<N, T>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
pub struct NTreeNode<T: Attribute>
{
pub color: Color,
pub attribute: T,
pub subdivided: bool,
}
impl<const N: usize> NTree<N>
impl<const N: usize, T> NTree<N, T>
where
[(); N * N * N]:,
T: Attribute,
{
pub fn constant(color: Color, depth: usize) -> Self
pub fn constant(value: T, depth: usize) -> Self
{
let mut map = HashMap::new();
let root = NTreeNode {
color,
attribute: value,
subdivided: false,
};
map.insert(TreeLocator::<N>::root(), root);
Self { map, depth }
}
pub fn set(&mut self, x: usize, y: usize, z: usize, color: Color)
pub fn set(&mut self, x: usize, y: usize, z: usize, value: T)
{
self.set_at_depth(x, y, z, self.depth, color);
self.set_at_depth(x, y, z, self.depth, value);
}
pub fn get(&self, x: usize, y: usize, z: usize) -> Color
pub fn get(&self, x: usize, y: usize, z: usize) -> T
{
assert!(x < N.pow(self.depth as u32));
assert!(y < N.pow(self.depth as u32));
@@ -101,7 +115,7 @@ where
{
if !current_node.subdivided
{
return current_node.color;
return current_node.attribute;
}
// Descend to relevant node,
@@ -117,7 +131,7 @@ where
}
}
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, color: Color)
pub fn set_at_depth(&mut self, x: usize, y: usize, z: usize, depth: usize, value: T)
{
assert!(x < N.pow(depth as u32));
assert!(y < N.pow(depth as u32));
@@ -131,18 +145,18 @@ where
while current_depth != depth
{
if current_node.color == color
if current_node.attribute == value
{
// Color is already correct, work is finished
// Attribute is already correct, work is finished
return;
}
// Current is not subdivided, and color is different => subdivide
// Current is not subdivided, and attribute is different => subdivide
if !current_node.subdivided
{
current_node.subdivided = true;
let new_nodes = NTreeNode {
color: current_node.color,
attribute: current_node.attribute,
subdivided: false,
};
current_node_loc.children().for_each(|child| {
@@ -165,11 +179,11 @@ where
if current_node.subdivided
{
self.make_constant(current_node_loc, color);
self.make_constant(current_node_loc, value);
}
else
{
current_node.color = color;
current_node.attribute = value;
}
// We need to go back up the hierarchy to combine nodes
@@ -182,16 +196,15 @@ where
current_node_loc = current_node_loc.parent().unwrap();
//current_node_size *= N;
// Access all children's colors
let children_color_avg = current_node_loc
// Access all children's attributes
let children_attributes = current_node_loc
.children()
.map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
.map(|child_loc| self.map.get(&child_loc).unwrap().attribute)
.collect::<Vec<_>>();
let children_attribute_avg = T::average(&children_attributes);
current_node = self.map.get_mut(&current_node_loc).unwrap();
current_node.color = children_color_avg;
current_node.attribute = children_attribute_avg;
if current_depth == 0
{
@@ -200,7 +213,7 @@ where
}
}
fn make_constant(&mut self, locator: TreeLocator<N>, color: Color)
fn make_constant(&mut self, locator: TreeLocator<N>, value: T)
{
let mut dfs_stack = Vec::new();
dfs_stack.push(locator);
@@ -221,13 +234,13 @@ where
self.map.insert(
locator,
NTreeNode {
color,
attribute: value,
subdivided: false,
},
);
}
pub fn from_array(array: &[Color], depth: usize) -> Self
pub fn from_array(array: &[T], depth: usize) -> Self
{
let mut structure = HashMap::new();
// Per voxel in the array :
@@ -260,20 +273,20 @@ where
// 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 attribute = array[x + y * width + z * width * width];
let mut locator =
TreeLocator::<N>::from_node_coords(depth as u32, x as u32, y as u32, z as u32);
'power_search: for power in 1..=block_power
{
let block_size = N.pow(power);
// Check if candidate block has the same color
// Check if candidate block has the same attribute
for ((merge_z, merge_y), merge_x) 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
!= attribute
{
break 'power_search;
}
@@ -299,7 +312,7 @@ where
// Add new found block in our structure
// If power is depth, this is the whole structure, thus depth is 0
let node = NTreeNode {
color,
attribute,
subdivided: false,
};
structure.insert(locator, node);
@@ -337,15 +350,15 @@ where
block_z as u32,
);
// Get average color of children
let color = Color::average(
locator
.children()
.map(|child_loc| structure.get(&child_loc).unwrap().color),
);
// Get average attribute of children
let children = locator
.children()
.map(|child_loc| structure.get(&child_loc).unwrap().attribute)
.collect::<Vec<_>>();
let attribute = T::average(&children);
let hierarchy_node = NTreeNode {
color,
attribute,
subdivided: true,
};
structure.insert(locator, hierarchy_node);
@@ -358,7 +371,7 @@ where
}
}
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
pub fn get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode<T>>
{
self.map.get(&locator).copied()
}
@@ -380,13 +393,13 @@ fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
Some(trailing_zeroes)
}
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N, Color>
where
[(); N * N * N]:,
{
let file = std::fs::read_to_string(path).unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
let mut colors = vec![Color::default(); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
@@ -399,22 +412,18 @@ where
colors[index as usize] = Color(1., 1., 1., 1.);
}
NTree::from_array(&colors, 4)
NTree::<N, Color>::from_array(&colors, 4)
}
mod test
{
use glam::Vec3;
use rand::random;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
use vxls_production::tree_locator::TreeLocator;
#[test]
fn constant_set()
{
let mut tree = NTree::<4>::constant(Color(0., 0., 0., 0.), 4);
let mut tree = NTree::<4, Color>::constant(Color(0., 0., 0., 0.), 4);
assert!(tree.get(0, 0, 0) == Color(0., 0., 0., 0.));
tree.set(0, 0, 0, Color(1., 1., 1., 1.));
assert!(tree.get(0, 0, 0) == Color(1., 1., 1., 1.));
@@ -441,7 +450,7 @@ mod test
}
println!("building tree");
let tree = NTree::<4>::from_array(&colors, 4);
let tree = NTree::<4, Color>::from_array(&colors, 4);
println!("ok");
for x in 0..256