refactor: Splitting into crates

This commit is contained in:
2026-11-15 20:36:43 +01:00
parent c13a04c8e2
commit 828806fbc8
68 changed files with 929 additions and 330 deletions
+13
View File
@@ -0,0 +1,13 @@
[package]
name = "vxls-bvh"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
egui.workspace = true
glam.workspace = true
wgpu.workspace = true
vxls-profiler = { path = "../vxls-profiler" }
vxls-production = { path = "../vxls-production" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
+468
View File
@@ -0,0 +1,468 @@
//! Axis aligned bounding box used by the BVH build.
use glam::Mat4;
use glam::Vec3;
/// An axis aligned bounding box.
///
/// A box is empty when `min` is greater than `max` on any axis. [`Aabb::EMPTY`]
/// uses inverted infinities, which makes it the identity element for
/// [`Aabb::union`] and [`Aabb::union_point`].
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
pub struct Aabb
{
min: Vec3,
max: Vec3,
}
impl Aabb
{
/// The empty box: it contains no point and is the identity element for
/// union operations.
pub const EMPTY: Self = Self {
min: Vec3::INFINITY,
max: Vec3::NEG_INFINITY,
};
/// The local voxel chunk space is [0,1]^3.
/// This is the box that encompasses that block.
pub const CHUNK: Self = Self {
min: Vec3::ZERO,
max: Vec3::ONE,
};
/// Builds a box from its corners.
///
/// No validation is performed so that [`Aabb::EMPTY`] can be built; use
/// [`Aabb::is_empty`] to check the result.
pub const fn new(min: Vec3, max: Vec3) -> Self
{
Self { min, max }
}
/// Builds a box from a center and the half extents along each axis.
pub fn from_center_half_extents(center: Vec3, half_extents: Vec3) -> Self
{
Self {
min: center - half_extents,
max: center + half_extents,
}
}
/// Builds the tightest box containing every point.
///
/// An empty iterator produces [`Aabb::EMPTY`].
pub fn from_points(points: impl IntoIterator<Item = Vec3>) -> Self
{
let mut aabb = Self::EMPTY;
for point in points
{
aabb.union_point(point);
}
aabb
}
pub const fn min(&self) -> Vec3
{
self.min
}
pub const fn max(&self) -> Vec3
{
self.max
}
/// Center of the box. Not meaningful for an empty box.
pub fn center(&self) -> Vec3
{
(self.min + self.max) * 0.5
}
/// Full extent of the box along each axis (`max - min`).
pub fn size(&self) -> Vec3
{
self.max - self.min
}
/// Half extent of the box along each axis.
pub fn half_size(&self) -> Vec3
{
self.size() * 0.5
}
/// Surface area of the box, used by SAH heuristics.
pub fn surface_area(&self) -> f32
{
let size = self.size();
2.0 * (size.x * size.y + size.y * size.z + size.z * size.x)
}
pub fn volume(&self) -> f32
{
self.size().element_product()
}
/// Index of the axis with the largest extent (0 = x, 1 = y, 2 = z).
///
/// Ties are broken in favor of the lower axis.
pub fn longest_axis(&self) -> usize
{
let size = self.size();
if size.x >= size.y && size.x >= size.z
{
0
}
else if size.y >= size.z
{
1
}
else
{
2
}
}
/// Returns `true` when the box contains no point.
pub fn is_empty(&self) -> bool
{
self.min.x > self.max.x || self.min.y > self.max.y || self.min.z > self.max.z
}
/// Returns `true` when both corners are finite.
pub fn is_finite(&self) -> bool
{
self.min.is_finite() && self.max.is_finite()
}
pub fn contains_point(&self, point: Vec3) -> bool
{
point.cmpge(self.min).all() && point.cmple(self.max).all()
}
/// Returns `true` when `other` is fully inside `self`.
///
/// An empty `other` is contained in every box.
pub fn contains(&self, other: &Self) -> bool
{
other.is_empty() || (self.min.cmple(other.min).all() && self.max.cmpge(other.max).all())
}
/// Returns `true` when both boxes share at least one point.
///
/// Boxes touching exactly on a face, edge or corner do intersect.
pub fn intersects(&self, other: &Self) -> bool
{
!self.is_empty()
&& !other.is_empty()
&& self.min.cmple(other.max).all()
&& other.min.cmple(self.max).all()
}
/// Overlap of both boxes.
///
/// The result is empty when the boxes do not intersect.
pub fn intersection(&self, other: &Self) -> Self
{
Self {
min: self.min.max(other.min),
max: self.max.min(other.max),
}
}
/// Grows the box to contain `point`.
pub fn union_point(&mut self, point: Vec3)
{
self.min = self.min.min(point);
self.max = self.max.max(point);
}
/// Grows the box to contain `other`.
pub fn union(&mut self, other: &Self)
{
self.min = self.min.min(other.min);
self.max = self.max.max(other.max);
}
/// Returns a copy of the box grown by `margin` on every side.
pub fn expanded(&self, margin: f32) -> Self
{
let margin = Vec3::splat(margin);
Self {
min: self.min - margin,
max: self.max + margin,
}
}
/// Returns a copy of the box with every axis at least `min_size` long,
/// keeping the center unchanged.
///
/// This avoids degenerate (flat) boxes, which are problematic for SAH
/// splitting. An empty box is returned unchanged.
pub fn padded_to_min_size(&self, min_size: f32) -> Self
{
if self.is_empty()
{
return Self::EMPTY;
}
let half_extents = self.half_size().max(Vec3::splat(min_size * 0.5));
Self::from_center_half_extents(self.center(), half_extents)
}
/// Returns an iterator over all of the corner points of the box
pub fn corner_points(&self) -> impl Iterator<Item = Vec3>
{
(0..=7).map(|i| {
let a = &self.min;
let b = &self.max;
Vec3::new(
if i & 1 == 0 { a.x } else { b.x },
if i & 2 == 0 { a.y } else { b.y },
if i & 4 == 0 { a.z } else { b.z },
)
})
}
/// Returns the Aabb bounding box of the box transformed by `transformed`
pub fn as_transformed_by(&self, transform: &Mat4) -> Self
{
Self::from_points(
self.corner_points()
.map(|point| transform.transform_point3(point)),
)
}
}
impl Default for Aabb
{
fn default() -> Self
{
Self::EMPTY
}
}
#[cfg(test)]
mod tests
{
use super::*;
const EPSILON: f32 = 1e-6;
fn assert_vec3_eq(a: Vec3, b: Vec3)
{
assert!(
(a - b).abs().max_element() <= EPSILON,
"expected {b:?}, got {a:?}"
);
}
#[test]
fn empty_box_contains_nothing()
{
let aabb = Aabb::EMPTY;
assert!(aabb.is_empty());
assert!(!aabb.contains_point(Vec3::ZERO));
assert!(!aabb.intersects(&Aabb::new(Vec3::ZERO, Vec3::ONE)));
}
#[test]
fn empty_is_identity_for_union()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE);
let mut grown = Aabb::EMPTY;
grown.union(&aabb);
assert_eq!(grown, aabb);
let mut grown = aabb;
grown.union(&Aabb::EMPTY);
assert_eq!(grown, aabb);
}
#[test]
fn from_points_of_empty_iterator_is_empty()
{
assert!(Aabb::from_points(std::iter::empty()).is_empty());
}
#[test]
fn from_points_bounds_all_points()
{
let points = [
Vec3::new(1.0, -2.0, 3.0),
Vec3::new(-4.0, 5.0, -6.0),
Vec3::new(0.0, 0.0, 0.0),
];
let aabb = Aabb::from_points(points);
assert_eq!(aabb.min(), Vec3::new(-4.0, -2.0, -6.0));
assert_eq!(aabb.max(), Vec3::new(1.0, 5.0, 3.0));
for point in points
{
assert!(aabb.contains_point(point));
}
}
#[test]
fn center_and_size()
{
let aabb = Aabb::new(Vec3::new(-1.0, 0.0, 2.0), Vec3::new(3.0, 4.0, 6.0));
assert_vec3_eq(aabb.center(), Vec3::new(1.0, 2.0, 4.0));
assert_vec3_eq(aabb.size(), Vec3::new(4.0, 4.0, 4.0));
assert_vec3_eq(aabb.half_size(), Vec3::new(2.0, 2.0, 2.0));
}
#[test]
fn from_center_half_extents_round_trips()
{
let aabb = Aabb::from_center_half_extents(Vec3::new(1.0, 2.0, 3.0), Vec3::splat(2.0));
assert_eq!(aabb.min(), Vec3::new(-1.0, 0.0, 1.0));
assert_eq!(aabb.max(), Vec3::new(3.0, 4.0, 5.0));
}
#[test]
fn union_grows_to_contain_both_boxes()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::splat(2.0), Vec3::splat(4.0));
let mut union = a;
union.union(&b);
assert_eq!(union.min(), Vec3::ZERO);
assert_eq!(union.max(), Vec3::splat(4.0));
assert!(union.contains(&a));
assert!(union.contains(&b));
}
#[test]
fn contains_point_respects_faces()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE);
assert!(aabb.contains_point(Vec3::ZERO));
assert!(aabb.contains_point(Vec3::ONE));
assert!(aabb.contains_point(Vec3::splat(0.5)));
assert!(!aabb.contains_point(Vec3::splat(-EPSILON)));
assert!(!aabb.contains_point(Vec3::splat(1.0 + EPSILON)));
}
#[test]
fn contains_box()
{
let outer = Aabb::new(Vec3::ZERO, Vec3::splat(4.0));
let inner = Aabb::new(Vec3::ONE, Vec3::splat(3.0));
assert!(outer.contains(&inner));
assert!(!inner.contains(&outer));
assert!(outer.contains(&Aabb::EMPTY));
}
#[test]
fn separated_boxes_do_not_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::new(2.0, 0.0, 0.0), Vec3::new(3.0, 1.0, 1.0));
assert!(!a.intersects(&b));
assert!(!b.intersects(&a));
assert!(a.intersection(&b).is_empty());
}
#[test]
fn touching_boxes_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::ONE);
let b = Aabb::new(Vec3::new(1.0, 0.0, 0.0), Vec3::new(2.0, 1.0, 1.0));
assert!(a.intersects(&b));
assert_eq!(a.intersection(&b).size(), Vec3::new(0.0, 1.0, 1.0));
}
#[test]
fn overlapping_boxes_intersect()
{
let a = Aabb::new(Vec3::ZERO, Vec3::splat(2.0));
let b = Aabb::new(Vec3::ONE, Vec3::splat(3.0));
assert!(a.intersects(&b));
let intersection = a.intersection(&b);
assert_eq!(intersection.min(), Vec3::ONE);
assert_eq!(intersection.max(), Vec3::splat(2.0));
}
#[test]
fn surface_area_and_volume()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::new(2.0, 3.0, 4.0));
assert!((aabb.volume() - 24.0).abs() <= EPSILON);
assert!((aabb.surface_area() - 52.0).abs() <= EPSILON);
}
#[test]
fn longest_axis_picks_largest_extent()
{
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(3.0, 1.0, 2.0)).longest_axis(),
0
);
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(1.0, 3.0, 2.0)).longest_axis(),
1
);
assert_eq!(
Aabb::new(Vec3::ZERO, Vec3::new(1.0, 2.0, 3.0)).longest_axis(),
2
);
}
#[test]
fn expanded_adds_margin_on_every_side()
{
let aabb = Aabb::new(Vec3::ZERO, Vec3::ONE).expanded(0.5);
assert_eq!(aabb.min(), Vec3::splat(-0.5));
assert_eq!(aabb.max(), Vec3::splat(1.5));
assert!(aabb.contains(&Aabb::new(Vec3::ZERO, Vec3::ONE)));
}
#[test]
fn padded_to_min_size_keeps_flat_box_usable()
{
let flat = Aabb::new(Vec3::new(0.0, 0.0, 5.0), Vec3::new(2.0, 2.0, 5.0));
let padded = flat.padded_to_min_size(1.0);
assert!(!padded.is_empty());
assert!((padded.size().z - 1.0).abs() <= EPSILON);
assert_eq!(padded.size().x, 2.0);
assert_eq!(padded.size().y, 2.0);
assert_vec3_eq(padded.center(), flat.center());
assert!(padded.contains(&flat));
}
#[test]
fn padded_empty_box_stays_empty()
{
assert!(Aabb::EMPTY.padded_to_min_size(1.0).is_empty());
}
#[test]
fn default_is_empty()
{
assert_eq!(Aabb::default(), Aabb::EMPTY);
assert!(Aabb::default().is_empty());
}
#[test]
fn layout_is_two_vec3s()
{
assert_eq!(std::mem::size_of::<Aabb>(), 24);
assert_eq!(bytemuck::bytes_of(&Aabb::EMPTY).len(), 24);
}
}
+382
View File
@@ -0,0 +1,382 @@
//! Implementation of fast binary BVH build with binned SAH
//!
use std::num::NonZero;
use egui::emath::OrderedFloat;
use crate::gpu::GpuBvhNode;
use super::aabb::Aabb;
macro_rules! get_dim {
($v:expr, $d:expr) => {
match $d
{
0 => $v.x,
1 => $v.y,
_ => $v.z,
}
};
}
// Sah heuristic parameters
/// Intersection time
const SAH_INTERSECT: f32 = 1.;
/// Bin count
const SAH_BIN_COUNT: usize = 16;
#[derive(Clone, Copy)]
pub struct BvhNode
{
/// The bounding box of this bvh node
aabb: Aabb,
/// 0 if this is not a leaf
/// n if it is a leaf containing objects
count: u32,
/// If this node is not a leaf, the index in the list of nodes of the left node
/// Otherwise the index in the list of primitive of the first object
first_or_left: u32,
}
impl From<GpuBvhNode> for BvhNode
{
fn from(value: GpuBvhNode) -> Self
{
Self {
aabb: value.aabb.into(),
count: value.count,
first_or_left: value.first_or_left,
}
}
}
impl From<BvhNode> for GpuBvhNode
{
fn from(value: BvhNode) -> Self
{
GpuBvhNode {
aabb: value.aabb.into(),
count: value.count,
first_or_left: value.first_or_left,
_pad2: [0; 2],
}
}
}
impl BvhNode
{
pub fn internal(aabb: Aabb, left: u32) -> BvhNode
{
Self {
aabb,
count: 0,
first_or_left: left,
}
}
pub fn leaf(aabb: Aabb, count: NonZero<u32>, first_index: u32) -> BvhNode
{
Self {
aabb,
count: count.into(),
first_or_left: first_index,
}
}
pub fn is_internal(&self) -> bool
{
self.count == 0
}
pub fn is_leaf(&self) -> bool
{
self.count != 0
}
pub fn first(&self) -> Option<u32>
{
if !self.is_leaf()
{
None
}
else
{
Some(self.first_or_left)
}
}
pub fn count(&self) -> Option<u32>
{
if !self.is_leaf()
{
None
}
else
{
Some(self.count)
}
}
pub fn left(&self) -> Option<u32>
{
if !self.is_internal()
{
None
}
else
{
Some(self.first_or_left)
}
}
pub fn right(&self) -> Option<u32>
{
self.left().map(|x| x + 1)
}
}
pub struct BvhPrimitive<T>
{
pub aabb: Aabb,
pub handle: T,
}
pub struct Bvh
{
/// List of the bvh's nodes
pub nodes: Vec<BvhNode>,
pub depth: usize,
}
pub fn build_bvh<T>(primitives: &mut [BvhPrimitive<T>], leaf_max: usize) -> Bvh
{
let mut nodes = Vec::new();
//let mut prim_indices = Vec::new();
if primitives.is_empty()
{
return Bvh {
nodes,
depth: 1,
//prim_indices,
};
}
// Build root node
let mut aabb = Aabb::EMPTY;
primitives.iter().for_each(|p| aabb.union(&p.aabb));
nodes.push(BvhNode::leaf(
aabb,
NonZero::new(primitives.len() as u32).unwrap(),
0,
));
let mut max_depth = 0usize;
build_node(0, primitives, &mut nodes, leaf_max, 0, &mut max_depth);
println!("Max depth {}", max_depth);
Bvh {
nodes,
depth: max_depth,
}
}
pub fn build_node<T>(
node_index: usize,
primitives: &mut [BvhPrimitive<T>],
nodes: &mut Vec<BvhNode>,
leaf_max: usize,
depth: usize,
max_depth: &mut usize,
)
{
// We only extend a leaf if necessary
assert!(nodes[node_index].is_leaf());
let offset = nodes[node_index].first().expect("Node is leaf");
let count = nodes[node_index].count().expect("Node is leaf");
// Primitives owned by this node
let node_primitives = &mut primitives[(offset as usize)..((offset + count) as usize)];
// We must now decide to keep the node as a leaf, or split using the heuristic:
let split = sah_split(node_primitives, leaf_max);
match split
{
Some((split_dimension, split_plane)) =>
{
// Sah says split, do the split
// We sort along the split dimension
node_primitives.sort_unstable_by_key(|primitive| {
OrderedFloat(get_dim!(primitive.aabb.center(), split_dimension))
});
// We now now that the split_plane splits node_primitives into two subslices
let mut left_count = 0u32;
let mut left_aabb = Aabb::EMPTY;
let mut right_aabb = Aabb::EMPTY;
for primitive in node_primitives.iter()
{
if get_dim!(primitive.aabb.center(), split_dimension) < split_plane
{
left_count += 1;
left_aabb.union(&primitive.aabb);
}
else
{
right_aabb.union(&primitive.aabb);
}
}
let right_count = node_primitives.len() as u32 - left_count;
let left_node = BvhNode::leaf(
left_aabb,
NonZero::new(left_count).expect("Empty leaf impossible."),
offset,
);
let right_node = BvhNode::leaf(
right_aabb,
NonZero::new(right_count).expect("Empty leaf impossible."),
offset + left_count, // As the slice is sorted
);
// Allocate spot in the node array
let left_index = nodes.len();
// Left and right are contiguous
nodes.push(left_node);
nodes.push(right_node);
// Change this node to be internal
nodes[node_index] = BvhNode::internal(nodes[node_index].aabb, left_index as u32);
// Build children
build_node(
left_index,
primitives,
nodes,
leaf_max,
depth + 1,
max_depth,
);
build_node(
left_index + 1,
primitives,
nodes,
leaf_max,
depth + 1,
max_depth,
);
}
None =>
{
// Sah says keep as leaf, do nothing
if depth > *max_depth
{
*max_depth = depth;
}
}
}
}
/// Returns Some if SAH says split, none if it wants a leaf
pub fn sah_split<T>(primitives: &[BvhPrimitive<T>], leaf_max: usize) -> Option<(usize, f32)>
{
// Don't even bother, spliting it does nothing
if primitives.len() <= 2
{
return None;
}
// Cost if this node was a leaf
let leaf_sah = primitives.len() as f32 * SAH_INTERSECT;
// Compute the bounding box contains the centroids of the primitives
let mut centroid_bounds = Aabb::EMPTY;
primitives
.iter()
.for_each(|prim| centroid_bounds.union_point(prim.aabb.center()));
// Evaluate sah per dimension
let mut best_dimension = 0;
let mut minimum_cost = f32::INFINITY;
let mut minimum_split_plane = 0.;
for dimension in 0..3usize
{
let cetroid_min = get_dim!(centroid_bounds.min(), dimension);
// The size of a bin in this dimension
let bin_width = get_dim!(centroid_bounds.size(), dimension) / SAH_BIN_COUNT as f32;
// Indicies of elements per bin
let mut bins: [Aabb; SAH_BIN_COUNT] = Default::default();
let mut bin_counts: [usize; SAH_BIN_COUNT] = Default::default();
// Bin elements
for primitive in primitives.iter()
{
let centroid = get_dim!(primitive.aabb.center(), dimension);
let bin_index =
(((centroid - cetroid_min) / bin_width) as usize).clamp(0, SAH_BIN_COUNT - 1);
// Put it into its bin
bins[bin_index].union(&primitive.aabb);
bin_counts[bin_index] += 1;
}
// Build prefix and suffix bins
let mut prefix: [Aabb; SAH_BIN_COUNT] = bins;
let mut prefix_counts: [usize; SAH_BIN_COUNT] = bin_counts;
let mut suffix: [Aabb; SAH_BIN_COUNT] = bins;
let mut suffix_counts: [usize; SAH_BIN_COUNT] = bin_counts;
// We build prefix and suffix simultaneously
for i in 1..SAH_BIN_COUNT
{
let prefix_previous = prefix[i - 1];
prefix[i].union(&prefix_previous);
prefix_counts[i] += prefix_counts[i - 1];
let suffix_previous = suffix[SAH_BIN_COUNT - i];
suffix[SAH_BIN_COUNT - 1 - i].union(&suffix_previous);
suffix_counts[SAH_BIN_COUNT - 1 - i] += suffix_counts[SAH_BIN_COUNT - i];
}
// Chose a split
// We iterate only up to SAH_BIN_COUNT - 1
// as we dont want to put all primitves on the left or right
for i in 0..(SAH_BIN_COUNT - 1)
{
let left_sah = prefix[i].surface_area() * prefix_counts[i] as f32;
let right_sah = suffix[i + 1].surface_area() * suffix_counts[i + 1] as f32;
let split_sah = left_sah + right_sah;
if split_sah < minimum_cost
{
best_dimension = dimension;
minimum_cost = split_sah;
// Take bin boundary as split point
minimum_split_plane = cetroid_min + (i + 1) as f32 * bin_width;
}
}
}
if leaf_sah < minimum_cost && primitives.len() <= leaf_max
{
// SAH requires leaf
None
}
else
{
// SAH requires split
Some((best_dimension, minimum_split_plane))
}
}
+251
View File
@@ -0,0 +1,251 @@
//! Contains rendering code to display a debug overlay for the BVH.
use glam::Mat4;
use wgpu::BlendState;
// debug.wgsl mirrors the GPU structs manually. Keep the array strides in sync:
// WGSL rounds structs containing vec3 up to a 16-byte alignment, so a node's
// 40 bytes of data become a 48-byte array stride.
const _: () = {
assert!(size_of::<crate::gpu::GpuBvhNode>() == 48);
assert!(size_of::<crate::gpu::GpuObject>() == 144);
};
/// Renders a GPU BVH as debug geometry.
///
/// Every node's AABB is drawn as a wireframe box. Leaves additionally draw one
/// filled box per object, using the object's `local_to_world` transform on the
/// local `[0, 1]^3` cube.
///
/// One instance is one `GpuBvhNode`; the shader generates all vertices, so no
/// vertex or index buffer is needed.
pub struct BvhDebugPipeline
{
solid_pipeline: wgpu::RenderPipeline,
line_pipeline: wgpu::RenderPipeline,
bind_group_layout: wgpu::BindGroupLayout,
view_proj_buffer: wgpu::Buffer,
}
impl BvhDebugPipeline
{
/// `color_format` must match the render pass attachment, including its sRGB
/// suffix. `depth_format` must match `depth_view` in [`Self::render`].
pub fn new(
device: &wgpu::Device,
color_format: wgpu::TextureFormat,
depth_format: wgpu::TextureFormat,
) -> Self
{
let shader = device.create_shader_module(wgpu::include_wgsl!("debug.wgsl"));
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("bvh_debug_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::VERTEX,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: wgpu::BufferSize::new(size_of::<Mat4>() as u64),
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("bvh_debug_pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: 0,
});
let view_proj_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("bvh_debug_view_proj_buffer"),
size: size_of::<Mat4>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let create_pipeline = |label: &str,
vertex_entry: &str,
fragment_entry: &str,
topology: wgpu::PrimitiveTopology,
depth_write_enabled: bool|
-> wgpu::RenderPipeline {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pipeline_layout),
vertex: wgpu::VertexState {
module: &shader,
entry_point: Some(vertex_entry),
compilation_options: Default::default(),
buffers: &[],
},
primitive: wgpu::PrimitiveState {
topology,
strip_index_format: None,
front_face: wgpu::FrontFace::Ccw,
// Boxes stay visible even when the camera is inside one.
cull_mode: None,
unclipped_depth: false,
polygon_mode: wgpu::PolygonMode::Fill,
conservative: false,
},
depth_stencil: Some(wgpu::DepthStencilState {
format: depth_format,
depth_write_enabled: Some(depth_write_enabled),
depth_compare: Some(wgpu::CompareFunction::LessEqual),
stencil: wgpu::StencilState::default(),
bias: wgpu::DepthBiasState::default(),
}),
multisample: wgpu::MultisampleState::default(),
fragment: Some(wgpu::FragmentState {
module: &shader,
entry_point: Some(fragment_entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format: color_format,
blend: Some(wgpu::BlendState {
color: wgpu::BlendComponent::OVER,
alpha: wgpu::BlendComponent::OVER,
}),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
})
};
let solid_pipeline = create_pipeline(
"bvh_debug_solid_pipeline",
"vs_solids",
"fs_solids",
wgpu::PrimitiveTopology::TriangleList,
true,
);
let line_pipeline = create_pipeline(
"bvh_debug_line_pipeline",
"vs_lines",
"fs_lines",
wgpu::PrimitiveTopology::LineList,
false,
);
Self {
solid_pipeline,
line_pipeline,
bind_group_layout,
view_proj_buffer,
}
}
/// Records a debug render pass into `encoder`.
///
/// The pass loads the existing color contents, overlays the BVH, and clears
/// the depth buffer before drawing. Record it after the scene has been
/// written to `color_view` and before the UI is drawn.
///
/// `max_objects_per_leaf` is the leaf capacity used when building the BVH
/// (the `leaf_max` argument of `build_bvh`), currently `2`.
#[allow(clippy::too_many_arguments)]
pub fn render(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
color_view: &wgpu::TextureView,
depth_view: &wgpu::TextureView,
view_proj: Mat4,
node_buffer: &wgpu::Buffer,
object_buffer: &wgpu::Buffer,
node_count: u32,
max_objects_per_leaf: u32,
)
{
if node_count == 0
{
return;
}
queue.write_buffer(&self.view_proj_buffer, 0, bytemuck::bytes_of(&view_proj));
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("bvh_debug_bind_group"),
layout: &self.bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: node_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: object_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.view_proj_buffer.as_entire_binding(),
},
],
});
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("bvh_debug_render_pass"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: color_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment {
view: depth_view,
depth_ops: Some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
store: wgpu::StoreOp::Store,
}),
stencil_ops: None,
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_bind_group(0, &bind_group, &[]);
// Filled object boxes first so the wireframes can depth-test against
// them.
if max_objects_per_leaf > 0
{
pass.set_pipeline(&self.solid_pipeline);
pass.draw(0..36 * max_objects_per_leaf, 0..node_count);
}
pass.set_pipeline(&self.line_pipeline);
pass.draw(0..24, 0..node_count);
}
}
+198
View File
@@ -0,0 +1,198 @@
//! Debug rendering for the GPU BVH.
//!
//! Every box is generated procedurally from the vertex index, so there is no
//! mesh or vertex buffer. One instance is one `GpuBvhNode`.
struct GpuBvhNode
{
// vec3 members align to 16 bytes, so this struct has a 48-byte array
// stride. The Rust `GpuBvhNode` is padded to the same size.
min: vec3<f32>,
_pad0: u32,
max: vec3<f32>,
_pad1: u32,
count: u32,
first_or_left: u32,
_pad2: vec2<u32>,
};
struct GpuObject
{
local_to_world: mat4x4<f32>,
world_to_local: mat4x4<f32>,
table_slot: u32,
_pad0: u32,
_pad1: u32,
_pad2: u32,
};
@group(0) @binding(0) var<storage, read> nodes: array<GpuBvhNode>;
@group(0) @binding(1) var<storage, read> objects: array<GpuObject>;
@group(0) @binding(2) var<uniform> view_proj: mat4x4<f32>;
struct VertexOutput
{
@builtin(position) clip_position: vec4<f32>,
@location(0) color: vec4<f32>,
@location(1) normal: vec3<f32>,
};
const INTERNAL_NODE_COLOR = vec4<f32>(0.15, 0.70, 1.0, 1.0);
const LEAF_NODE_COLOR = vec4<f32>(1.0, 0.85, 0.20, 1.0);
const OBJECT_COLOR = vec4<f32>(1.0, 0.45, 0.12, 0.5);
// Pushed fully outside the clip volume so skipped nodes/objects produce no
// fragments.
const DEGENERATE_POSITION = vec4<f32>(2.0, 2.0, 2.0, 1.0);
const VERTICES_PER_OBJECT: u32 = 36u;
// Corner numbering: bit 0 = x, bit 1 = y, bit 2 = z.
const EDGE_CORNERS = array<u32, 24>(
// -Z face
0u, 1u, 1u, 3u, 3u, 2u, 2u, 0u,
// +Z face
4u, 5u, 5u, 7u, 7u, 6u, 6u, 4u,
// vertical edges
0u, 4u, 1u, 5u, 2u, 6u, 3u, 7u,
);
const TRIANGLE_CORNERS = array<u32, 36>(
// -Z
0u, 2u, 1u, 1u, 2u, 3u,
// +Z
4u, 5u, 6u, 5u, 7u, 6u,
// -Y
0u, 1u, 4u, 1u, 5u, 4u,
// +Y
2u, 6u, 3u, 3u, 6u, 7u,
// -X
0u, 4u, 2u, 2u, 4u, 6u,
// +X
1u, 3u, 5u, 3u, 7u, 5u,
);
const FACE_NORMALS = array<vec3<f32>, 6>(
vec3<f32>(0.0, 0.0, -1.0),
vec3<f32>(0.0, 0.0, 1.0),
vec3<f32>(0.0, -1.0, 0.0),
vec3<f32>(0.0, 1.0, 0.0),
vec3<f32>(-1.0, 0.0, 0.0),
vec3<f32>(1.0, 0.0, 0.0),
);
fn corner_position(min_corner: vec3<f32>, max_corner: vec3<f32>, corner: u32) -> vec3<f32>
{
return vec3<f32>(
select(min_corner.x, max_corner.x, (corner & 1u) != 0u),
select(min_corner.y, max_corner.y, (corner & 2u) != 0u),
select(min_corner.z, max_corner.z, (corner & 4u) != 0u),
);
}
@vertex
fn vs_lines(
@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32,
) -> VertexOutput
{
var out: VertexOutput;
out.clip_position = DEGENERATE_POSITION;
out.color = INTERNAL_NODE_COLOR;
out.normal = vec3<f32>(0.0, 0.0, 1.0);
if instance_index >= arrayLength(&nodes)
{
return out;
}
let node = nodes[instance_index];
let min_corner = node.min;
let max_corner = node.max;
let world_position = corner_position(
min_corner,
max_corner,
EDGE_CORNERS[vertex_index],
);
out.clip_position = view_proj * vec4<f32>(world_position, 1.0);
if node.count != 0u
{
out.color = LEAF_NODE_COLOR;
}
return out;
}
@vertex
fn vs_solids(
@builtin(vertex_index) vertex_index: u32,
@builtin(instance_index) instance_index: u32,
) -> VertexOutput
{
var out: VertexOutput;
out.clip_position = DEGENERATE_POSITION;
out.color = OBJECT_COLOR;
out.normal = vec3<f32>(0.0, 0.0, 1.0);
if instance_index >= arrayLength(&nodes)
{
return out;
}
let node = nodes[instance_index];
// Only leaves own objects.
if node.count == 0u
{
return out;
}
let object_index = vertex_index / VERTICES_PER_OBJECT;
if object_index >= node.count
{
return out;
}
let object_array_index = node.first_or_left + object_index;
if object_array_index >= arrayLength(&objects)
{
return out;
}
let object = objects[object_array_index];
let local_vertex_index = vertex_index % VERTICES_PER_OBJECT;
let local_position = corner_position(
vec3<f32>(0.0, 0.0, 0.0),
vec3<f32>(1.0, 1.0, 1.0),
TRIANGLE_CORNERS[local_vertex_index],
);
let world_position = object.local_to_world * vec4<f32>(local_position, 1.0);
out.clip_position = view_proj * world_position;
// normals transform with the inverse transpose of local_to_world, which is
// transpose(world_to_local).
let face = local_vertex_index / 6u;
out.normal = normalize(
(transpose(object.world_to_local) * vec4<f32>(FACE_NORMALS[face], 0.0)).xyz,
);
return out;
}
@fragment
fn fs_lines(input: VertexOutput) -> @location(0) vec4<f32>
{
return input.color;
}
@fragment
fn fs_solids(input: VertexOutput) -> @location(0) vec4<f32>
{
let normal = normalize(input.normal);
let light_direction = normalize(vec3<f32>(0.45, 0.80, 0.55));
let diffuse = max(dot(normal, light_direction), 0.0);
return vec4<f32>(input.color * (0.35 + 0.65 * diffuse));
}
+84
View File
@@ -0,0 +1,84 @@
//! GPU ready structures for the BVH representation
use glam::Mat4;
use glam::Vec3;
use crate::aabb::Aabb;
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuAabb
{
pub min: Vec3,
_pad0: u32, // On the GPU vec3 are aligned to 4 u32
pub max: Vec3,
_pad1: u32,
}
/// Follow the same documentation as [`BvhNode`]
///
/// The trailing padding keeps the array stride at 48 bytes. On the GPU a struct
/// containing `vec3` has a 16-byte alignment, so the shader rounds the 40 bytes
/// of data up to a 48-byte stride.
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuBvhNode
{
pub aabb: GpuAabb,
pub count: u32,
pub first_or_left: u32,
pub(crate) _pad2: [u32; 2],
}
/// To be a leaf of a GPU BVH
#[derive(Debug, Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
pub struct GpuObject
{
local_to_world: Mat4, // Tranform
world_to_local: Mat4, // Ray to chunk
table_slot: u32,
_pad0: [u32; 3],
}
impl From<Aabb> for GpuAabb
{
fn from(value: Aabb) -> Self
{
Self::new(value.min(), value.max())
}
}
impl From<GpuAabb> for Aabb
{
fn from(value: GpuAabb) -> Self
{
Aabb::new(value.min, value.max)
}
}
impl GpuObject
{
pub fn new(slot: u32, transform: Mat4) -> Self
{
GpuObject {
local_to_world: transform,
world_to_local: transform.inverse(),
table_slot: slot,
_pad0: Default::default(),
}
}
}
impl GpuAabb
{
pub fn new(min: Vec3, max: Vec3) -> Self
{
Self {
min,
_pad0: Default::default(),
max,
_pad1: Default::default(),
}
}
}
+476
View File
@@ -0,0 +1,476 @@
#![feature(generic_const_exprs)]
//! This is an implementation of a BVH2 as a top level ray acceleration
//! structure for objects in a scene.
//! The build is done only on CPU and uploaded on GPU.
use std::collections::HashMap;
use std::mem::size_of;
use glam::Mat4;
use crate::aabb::Aabb;
use crate::build::BvhPrimitive;
use crate::build::build_bvh;
use crate::gpu::GpuBvhNode;
use crate::gpu::GpuObject;
use vxls_profiler::ScopeEncoder;
use vxls_production::ProducerId;
use vxls_production::StructureAnchor;
use vxls_voxel_cache::CacheInvalidable;
use vxls_voxel_cache::eviction::CacheEvictor;
use vxls_voxel_cache::insertion::CacheInsertionData;
use vxls_voxel_cache::requests::CacheRequestBuffer;
use vxls_voxel_cache::tables::DynamicStructureTable;
pub mod aabb;
pub mod build;
pub mod debug;
pub mod gpu;
/// To handle an object stored in the bvh
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct BvhHandle
{
pub anchor: StructureAnchor,
pub producer_id: ProducerId,
/// Key discriminator, there might be multiple objects with the same anchor and producer_id
/// within the bvh
pub key: u64,
}
/// An object that is stored by the BVH structure
pub struct BvhObject
{
/// Identity of the voxel data
pub anchor: StructureAnchor,
pub producer_id: ProducerId,
/// The transform of the object in the BvhSpace
pub transform: Mat4,
/// A object is a voxel chunk, which in local space is in the [0,1]^3 cube
/// This bounding_box wraps more tightly arround the actual data stored.
pub bounding_box: Aabb,
}
impl BvhObject
{
pub fn world_bounding_box(&self) -> Aabb
{
self.bounding_box.as_transformed_by(&self.transform)
}
pub fn structure_anchor(&self) -> StructureAnchor
{
self.anchor
}
}
/// A BVH-backed structure table.
///
/// GPU state is uploaded lazily: host-side mutations mark the table dirty and
/// [`Self::rebuild_if_dirty`] must be called between frames before using the
/// raytrace bind group. Buffers and the bind group may be recreated when the
/// BVH or the inner table grows, so re-fetch them after each rebuild.
///
/// Raytrace bindings:
/// 0 = `GpuBvhNode[]` (read-only), 1 = `GpuObject[]` (read-only),
/// 2 = inner structure-table pointers, 3 = inner structure-table requests.
pub struct BvhStructureTable
{
/// Handle to object in the bvh
objects: HashMap<BvhHandle, BvhObject>,
/// Objects alive in the bvh have a slot in the dynamic table
slots: HashMap<BvhHandle, u32>,
structure_table: DynamicStructureTable,
/// discriminator key allocator
current_key: u64,
/// GPU BVH nodes, indexed by [`GpuBvhNode`] order.
bvh_nodes: wgpu::Buffer,
/// GPU BVH objects, indexed by leaf `first_or_left`.
bvh_objects: wgpu::Buffer,
node_capacity: usize,
object_capacity: usize,
node_count: u32,
object_count: u32,
raytrace_bind_group_layout: wgpu::BindGroupLayout,
raytrace_bind_group: wgpu::BindGroup,
/// True when the CPU BVH no longer matches the GPU buffers.
dirty: bool,
}
#[allow(dead_code)]
impl BvhStructureTable
{
pub fn new(device: &wgpu::Device, initial_capacity: usize, max_requests: usize) -> Self
{
let structure_table = DynamicStructureTable::new(device, initial_capacity, max_requests, 0);
let raytrace_bind_group_layout = create_bvh_raytrace_bind_group_layout(device);
let bvh_nodes = create_bvh_buffer::<GpuBvhNode>(device, 1, "bvh_nodes");
let bvh_objects = create_bvh_buffer::<GpuObject>(device, 1, "bvh_objects");
let raytrace_bind_group = create_bvh_raytrace_bind_group(
device,
&raytrace_bind_group_layout,
&bvh_nodes,
&bvh_objects,
structure_table.pointers_buffer(),
structure_table.request_pages_buffer(),
);
Self {
objects: Default::default(),
slots: Default::default(),
structure_table,
current_key: 0,
bvh_nodes,
bvh_objects,
node_capacity: 1,
object_capacity: 1,
node_count: 0,
object_count: 0,
raytrace_bind_group_layout,
raytrace_bind_group,
dirty: false,
}
}
pub fn add(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
object: BvhObject,
) -> BvhHandle
{
let key = self.current_key;
self.current_key += 1;
let handle = BvhHandle {
anchor: object.anchor,
producer_id: object.producer_id,
key,
};
let slot = self
.structure_table
.allocate_or_grow(device, queue, object.anchor)
.unwrap();
self.slots.insert(handle, slot);
self.objects.insert(handle, object);
self.dirty = true;
handle
}
pub fn build(&self) -> (Vec<GpuBvhNode>, Vec<GpuObject>)
{
// Collect primitives
let mut primitives = self
.objects
.iter()
.map(|(handle, object)| BvhPrimitive {
aabb: object.world_bounding_box(),
handle: *handle,
})
.collect::<Vec<_>>();
let bvh = build_bvh(&mut primitives, 2);
// Build gpu bvh
let gpu_nodes = bvh
.nodes
.iter()
.map(|node| (*node).into())
.collect::<Vec<GpuBvhNode>>();
let gpu_primitives = primitives
.iter()
.map(|primitive| {
GpuObject::new(
*self.slots.get(&primitive.handle).expect("Unallocated slot"),
self.objects
.get(&primitive.handle)
.expect("Object removed")
.transform,
)
})
.collect::<Vec<_>>();
(gpu_nodes, gpu_primitives)
}
/// Marks the CPU BVH as changed. The GPU buffers are rebuilt on the next
/// [`Self::rebuild_if_dirty`] call.
pub fn mark_dirty(&mut self)
{
self.dirty = true;
}
/// Returns true if the GPU buffers no longer match the CPU BVH.
pub fn is_dirty(&self) -> bool
{
self.dirty
}
/// Rebuilds the CPU BVH and uploads it to the GPU.
pub fn rebuild(&mut self, device: &wgpu::Device, queue: &wgpu::Queue)
{
let (nodes, objects) = self.build();
self.upload(device, queue, &nodes, &objects);
}
/// Rebuilds only if the BVH changed since the last upload.
pub fn rebuild_if_dirty(&mut self, device: &wgpu::Device, queue: &wgpu::Queue)
{
if self.dirty
{
self.rebuild(device, queue);
}
}
fn upload(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
nodes: &[GpuBvhNode],
objects: &[GpuObject],
)
{
let node_capacity = grown_capacity(self.node_capacity, nodes.len());
if node_capacity > self.node_capacity
{
self.node_capacity = node_capacity;
self.bvh_nodes = create_bvh_buffer::<GpuBvhNode>(device, node_capacity, "bvh_nodes");
}
let object_capacity = grown_capacity(self.object_capacity, objects.len());
if object_capacity > self.object_capacity
{
self.object_capacity = object_capacity;
self.bvh_objects =
create_bvh_buffer::<GpuObject>(device, object_capacity, "bvh_objects");
}
if !nodes.is_empty()
{
queue.write_buffer(&self.bvh_nodes, 0, bytemuck::cast_slice(nodes));
}
if !objects.is_empty()
{
queue.write_buffer(&self.bvh_objects, 0, bytemuck::cast_slice(objects));
}
self.node_count = nodes.len() as u32;
self.object_count = objects.len() as u32;
// The inner table may have grown (replacing its buffers) since the last
// bind group was created, so always recreate it after an upload.
let raytrace_bind_group = create_bvh_raytrace_bind_group(
device,
&self.raytrace_bind_group_layout,
&self.bvh_nodes,
&self.bvh_objects,
self.structure_table.pointers_buffer(),
self.structure_table.request_pages_buffer(),
);
self.raytrace_bind_group = raytrace_bind_group;
self.dirty = false;
}
pub fn bvh_nodes(&self) -> &wgpu::Buffer
{
&self.bvh_nodes
}
pub fn bvh_objects(&self) -> &wgpu::Buffer
{
&self.bvh_objects
}
pub fn node_count(&self) -> u32
{
self.node_count
}
pub fn object_count(&self) -> u32
{
self.object_count
}
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
{
&self.raytrace_bind_group_layout
}
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
{
&self.raytrace_bind_group
}
/// Gathers the root requests emitted by the inner structure table into
/// `request_buffer`.
pub fn gather_requests(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
request_buffer: &CacheRequestBuffer,
)
{
self.structure_table
.gather_requests(device, encoder, request_buffer);
}
/// Writes the cache page pointers produced by an external insertion into
/// the inner structure table.
pub fn insert<const N: usize>(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
) where
[(); N * N * N]:,
{
self.structure_table.insert(device, encoder, insertion);
}
pub fn get(&self, handle: &BvhHandle) -> Option<&BvhObject>
{
self.objects.get(handle)
}
pub fn get_mut(&mut self, handle: &BvhHandle) -> Option<&mut BvhObject>
{
self.objects.get_mut(handle)
}
}
impl<const N: usize> CacheInvalidable<N> for BvhStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
insertion: &CacheInsertionData<N>,
)
{
self.structure_table
.validate_insertion(device, encoder, insertion);
}
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<wgpu::CommandEncoder>,
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
)
{
self.structure_table
.invalidate(encoder, cache_evictor, invalid_timestamp);
}
}
fn create_bvh_buffer<T>(device: &wgpu::Device, capacity: usize, label: &str) -> wgpu::Buffer
{
let capacity = capacity.max(1);
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(label),
size: (capacity * size_of::<T>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
fn grown_capacity(current: usize, required: usize) -> usize
{
if required <= current
{
return current;
}
let mut capacity = current.max(1);
while capacity < required
{
capacity = capacity.saturating_mul(2);
}
capacity
}
fn create_bvh_raytrace_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
let storage = |read_only: bool| wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only },
has_dynamic_offset: false,
min_binding_size: None,
};
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("BvhStructureTable::raytrace_bind_group_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(true),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(true),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(false),
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::COMPUTE,
ty: storage(false),
count: None,
},
],
})
}
fn create_bvh_raytrace_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
nodes: &wgpu::Buffer,
objects: &wgpu::Buffer,
structure_pointers: &wgpu::Buffer,
structure_requests: &wgpu::Buffer,
) -> wgpu::BindGroup
{
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("BvhStructureTable::raytrace_bind_group"),
layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: nodes.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: objects.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: structure_pointers.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: structure_requests.as_entire_binding(),
},
],
})
}
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "vxls-data"
version = "0.1.0"
edition = "2024"
[dependencies]
vxls-production = { src = "../vxls-production" }
bytemuck.workspace = true
itertools.workspace = true
+24
View File
@@ -0,0 +1,24 @@
//!
//! This crate contains types and structures to store voxel data
//!
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 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())
}
}
pub trait Has<A: Attribute>
{
fn get(&self) -> &A;
fn get_mut(&mut self) -> &mut A;
}
+461
View File
@@ -0,0 +1,461 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
use itertools::Itertools;
use vxls_production::tree_locator::TreeLocator;
#[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<I: Iterator<Item = Color>>(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
}
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
}
}
#[derive(Debug, Clone)]
pub struct NTree<const N: usize>
{
map: HashMap<TreeLocator<N>, 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<N>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
{
pub color: Color,
pub subdivided: bool,
}
impl<const N: usize> NTree<N>
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(TreeLocator::<N>::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 = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_node = self.map.get(&current_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 as u32, child_y as u32, child_z as u32);
current_node = self.map.get(&current_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 = TreeLocator::<N>::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(&current_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().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 as u32, child_y as u32, child_z as u32);
current_node = self.map.get_mut(&current_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()
.map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
current_node = self.map.get_mut(&current_node_loc).unwrap();
current_node.color = children_color_avg;
if current_depth == 0
{
break;
}
}
}
fn make_constant(&mut self, locator: TreeLocator<N>, 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(&current);
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 (z, y) in (0..width).cartesian_product(0..width)
{
let mut x = 0;
while x < 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
x += merged_size[x + y * width + z * width * width];
continue;
}
// Check smallest depth aligned with current position
let x_trailing = base_trailing_zeroes::<N>(x).unwrap_or(depth as u32);
let y_trailing = base_trailing_zeroes::<N>(y).unwrap_or(depth as u32);
let z_trailing = base_trailing_zeroes::<N>(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 =
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
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
{
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_z, merge_y), merge_x) 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);
x += 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 = TreeLocator::<N>::from_node_coords(
(depth - current_power) as u32,
block_x as u32,
block_y as u32,
block_z as u32,
);
// Get average color of children
let color = Color::average(
locator
.children()
.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 get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
{
self.map.get(&locator).copied()
}
}
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
{
if number == 0
{
return None;
}
let mut trailing_zeroes = 0;
while number % N == 0
{
number /= N;
trailing_zeroes += 1;
}
Some(trailing_zeroes)
}
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
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];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
NTree::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);
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.));
}
#[test]
fn load_read_same()
{
let file =
std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/../../dragon.txt"))
.unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
println!("building tree");
let tree = NTree::<4>::from_array(&colors, 4);
println!("ok");
for x in 0..256
{
for y in 0..256
{
for z in 0..256
{
let index = x + y * 256 + z * 256 * 256;
let color = colors[index];
let t = tree.get(x, y, z);
assert!(t == color);
}
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "vxls-gpu"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
itertools.workspace = true
wgpu.workspace = true
[dev-dependencies]
pollster.workspace = true
+268
View File
@@ -0,0 +1,268 @@
use bytemuck::bytes_of;
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferSlice;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::ShaderStages;
use wgpu::util::DeviceExt;
pub struct NonZeroBufferCompactor
{
size: usize,
block_count: usize,
reduced_buffer: Buffer,
sum_buffer: Buffer,
count_buffer_bg_layout: BindGroupLayout,
compaction_bg: BindGroup,
reduce_sum_pipeline: ComputePipeline,
partial_sum_pipeline: ComputePipeline,
scatter_pipeline: ComputePipeline,
}
impl NonZeroBufferCompactor
{
const THREAD_COUNT: usize = 256;
pub fn new(device: &Device, size: usize) -> Self
{
let block_count = size.div_ceil(Self::THREAD_COUNT * 2);
let reduced_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("indirect_buffer_reduced"),
contents: bytemuck::cast_slice(vec![0u32; block_count + 1].as_slice()),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
let sum_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("indirect_buffer_sum"),
contents: bytemuck::cast_slice(
vec![0u32; block_count * Self::THREAD_COUNT * 2].as_slice(),
),
usage: BufferUsages::STORAGE,
});
let count_buffer_bg_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("count_buffer_bg_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Optional compacted layout
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let compaction_bg_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("count_buffer_bg_layout"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let compaction_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("compaction_bg"),
layout: &compaction_bg_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: reduced_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: sum_buffer.as_entire_binding(),
},
],
});
let compaction_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("compaction_pipeline_layout"),
bind_group_layouts: &[Some(&count_buffer_bg_layout), Some(&compaction_bg_layout)],
immediate_size: size_of::<u32>() as u32, // Bool : Write to compacted buffer ?
});
let compaction_shader_module = unsafe {
device.create_shader_module_trusted(
wgpu::ShaderModuleDescriptor {
label: Some("compaction_shader_layout"),
source: wgpu::ShaderSource::SpirV(wgpu::__macro_helpers::Cow::Borrowed(
wgpu::include_spirv_source!("../../../shaders/out/compaction.spv"),
)),
},
wgpu::ShaderRuntimeChecks {
bounds_checks: false,
force_loop_bounding: false,
ray_query_initialization_tracking: false,
task_shader_dispatch_tracking: false,
mesh_shader_primitive_indices_clamp: false,
int_div_checks: false,
},
)
};
let reduce_sum_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("reduce_sum_pipeline"),
layout: Some(&compaction_pipeline_layout),
module: &compaction_shader_module,
entry_point: Some("block_sum"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let partial_sum_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("partial_sum_pipeline "),
layout: Some(&compaction_pipeline_layout),
module: &compaction_shader_module,
entry_point: Some("linear_reduced_sum"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let scatter_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("uniform_add_pipeline"),
layout: Some(&compaction_pipeline_layout),
module: &compaction_shader_module,
entry_point: Some("scatter"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
NonZeroBufferCompactor {
size,
block_count,
reduced_buffer,
sum_buffer,
count_buffer_bg_layout,
compaction_bg,
reduce_sum_pipeline,
partial_sum_pipeline,
scatter_pipeline,
}
}
pub fn total_sum_buffer(&self) -> BufferSlice<'_>
{
self.reduced_buffer
.slice(((size_of::<u32>() * self.block_count) as u64)..)
}
pub fn copy_count_to_buffer(&self, encoder: &mut CommandEncoder, target: &Buffer)
{
encoder.copy_buffer_to_buffer(
&self.reduced_buffer,
(size_of::<u32>() * self.block_count) as u64,
target,
0,
size_of::<u32>() as u64,
);
}
pub fn compact_buffer(
&self,
device: &Device,
encoder: &mut CommandEncoder,
count_buffer: &Buffer,
index_buffer: &Buffer,
compact_buffer: Option<&Buffer>,
)
{
let count_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("count_buffer_bind_group"),
layout: &self.count_buffer_bg_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: count_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: index_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: compact_buffer.unwrap_or(&count_buffer).as_entire_binding(),
},
],
});
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("buffer_compactor_compute_pass"),
timestamp_writes: None,
});
compute_pass.set_bind_group(0, &count_buffer_bind_group, &[]);
compute_pass.set_bind_group(1, &self.compaction_bg, &[]);
// Perform local running sum, then reduce
compute_pass.set_pipeline(&self.reduce_sum_pipeline);
compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1);
// Partial sums are now in the reuced sum buffer. Perform linear naive runnig sum on it
compute_pass.set_pipeline(&self.partial_sum_pipeline);
compute_pass.dispatch_workgroups(1, 1, 1);
// We can now reapply the partial running sum on the subblocks
compute_pass.set_pipeline(&self.scatter_pipeline);
compute_pass.set_immediates(
0,
if compact_buffer.is_some()
{
bytes_of(&1)
}
else
{
bytes_of(&0)
},
);
compute_pass.dispatch_workgroups(self.block_count as u32, 1, 1);
}
}
+166
View File
@@ -0,0 +1,166 @@
use wgpu::Buffer;
use wgpu::CommandEncoder;
/// Provides utility object to manage indirect dispatches workgroup count computations on the GPU
/// Takes in a single u32, and computes the amount of workgroups to dispatch given a workgroup size
pub struct IndirectBuffer1D
{
/// Buffer used in the indirect dispatch command
indirect_buffer: wgpu::Buffer,
/// Buffer visible from compute shaders to compute the amount
indirect_storage: wgpu::Buffer,
indirect_storage_bind_group: wgpu::BindGroup,
bind_group_layout: wgpu::BindGroupLayout,
compute_pipeline: wgpu::ComputePipeline,
}
impl IndirectBuffer1D
{
pub fn new(device: &wgpu::Device) -> Self
{
let indirect_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("IndirectBuffer1D::indirect_buffer"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
usage: wgpu::BufferUsages::INDIRECT | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let indirect_storage = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("IndirectBuffer1D::indirect_storage"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("IndirectBuffer1D::bind_group_layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}],
});
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("IndirectBuffer1D::bind_group"),
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: indirect_storage.as_entire_binding(),
}],
});
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("IndirectBuffer1D::shader_module"),
source: wgpu::ShaderSource::Wgsl(
"
struct IndirectDispatchArgs
{
x: u32,
y: u32,
z: u32
}
@group(0) @binding(0) var<storage, read_write> indirect_storage: IndirectDispatchArgs;
@group(1) @binding(0) var<storage, read_write> user_count: u32;
var<immediate> workgroup_size: u32;
@compute
@workgroup_size(1, 1, 1)
fn main()
{
let workgroup_count = (user_count / workgroup_size) + select(u32(1), u32(0), user_count % workgroup_size == 0);
var args: IndirectDispatchArgs;
args.x = workgroup_count;
args.y = 1;
args.z = 1;
indirect_storage = args;
}
".into(),
),
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("IndirectBuffer1D::pipeline_layout"),
bind_group_layouts: &[
// Group 0: indirect args buffer
Some(&bind_group_layout),
// Group 1: user count buffer
Some(&bind_group_layout),
],
// workgroup size
immediate_size: size_of::<u32>() as u32,
});
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("IndirectBuffer1D::pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("main"),
compilation_options: Default::default(),
cache: None,
});
Self {
indirect_buffer,
indirect_storage,
indirect_storage_bind_group: bind_group,
bind_group_layout,
compute_pipeline: pipeline,
}
}
pub fn workgroup_count(
&self,
device: &wgpu::Device,
encoder: &mut CommandEncoder,
count_buffer: &Buffer,
workgroup_size: u32,
) -> &Buffer
{
// Transient bind group
let user_count_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("IndirectBuffer1D::bind_group"),
layout: &self.bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: count_buffer.as_entire_binding(),
}],
});
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("IndirectBuffer1D::compute_pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.compute_pipeline);
pass.set_bind_group(0, &self.indirect_storage_bind_group, &[]);
pass.set_bind_group(1, &user_count_bind_group, &[]);
pass.set_immediates(0, bytemuck::bytes_of(&workgroup_size));
pass.dispatch_workgroups(1, 1, 1);
}
encoder.copy_buffer_to_buffer(
&self.indirect_storage,
0,
&self.indirect_buffer,
0,
Some(self.indirect_storage.size()),
);
&self.indirect_buffer
}
}
+65
View File
@@ -0,0 +1,65 @@
// Main common gpu parallel algorithms
pub mod buffer_compactor;
pub mod indirect_buffer;
pub mod radix_sort;
pub mod top_k;
// Utilities
pub fn create_multi_buffers_bind_group_layout(
device: &wgpu::Device,
count: u32,
label: Option<&str>,
) -> wgpu::BindGroupLayout
{
let entries = (0..count)
.map(|i| wgpu::BindGroupLayoutEntry {
binding: i,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
})
.collect::<Vec<_>>();
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label,
entries: &entries,
})
}
pub fn create_multi_buffers_bind_group(
device: &wgpu::Device,
layout: &wgpu::BindGroupLayout,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> wgpu::BindGroup
{
let entries = buffers
.iter()
.enumerate()
.map(|(i, buffer)| wgpu::BindGroupEntry {
binding: i as u32,
resource: buffer.as_entire_binding(),
})
.collect::<Vec<_>>();
device.create_bind_group(&wgpu::BindGroupDescriptor {
label,
layout,
entries: &entries,
})
}
pub fn create_multi_buffers_bg_bg_layout(
device: &wgpu::Device,
buffers: &[&wgpu::Buffer],
label: Option<&str>,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
{
let layout = create_multi_buffers_bind_group_layout(device, buffers.len() as u32, label);
let bg = create_multi_buffers_bind_group(device, &layout, buffers, label);
(layout, bg)
}
+473
View File
@@ -0,0 +1,473 @@
use std::num::NonZero;
use itertools::Itertools;
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePass;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::QuerySet;
use wgpu::ShaderStages;
use wgpu::include_spirv;
use wgpu::util::DeviceExt;
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum RadixSortDirection
{
Ascending,
Descending,
}
#[derive(Clone, Copy, bytemuck::Zeroable, bytemuck::Pod)]
#[repr(C)]
struct PassParameters
{
pass_index: u32,
descending: u32,
digit_stride: u32,
}
pub struct RadixSorter
{
max_size: usize,
histogram_count: usize,
histo_block_count: usize,
histograms: Buffer,
histograms_bind_group: BindGroup,
data_bind_group_layout: BindGroupLayout,
double_buffer_keys: Buffer,
double_buffer_values: Buffer,
double_buffer_bind_group: BindGroup,
// Counts buffer
element_counts_buffer: Buffer,
indirect_counts_storage: Buffer,
indirect_counts: Buffer,
histogram_pass: ComputePipeline,
prefix_sum_pass: ComputePipeline,
total_prefix_sum_pass: ComputePipeline,
scatter_pass: ComputePipeline,
compute_counts_pass: ComputePipeline,
timing_query_set: QuerySet,
pub timing_buffer: Buffer,
}
impl RadixSorter
{
// How many total digits u32 => 32
const TOTAL_BIN_DIGIT_COUNT: usize = 32;
// The size of a digit sorted per pass
const DIGIT_SIZE: usize = 8;
// The amounts of value for this digit size : base
const VALUE_COUNT: usize = 1 << Self::DIGIT_SIZE;
// Numbers of passes for full sort
const PASS_COUNT: usize = Self::TOTAL_BIN_DIGIT_COUNT / Self::DIGIT_SIZE;
// Thread count per work group
const WG_THREAD_COUNT: usize = 256;
// Elements managed per thread for histo build
const WE_HISTO_ELEMENTS: usize = 16;
// Elements managed per workgroup for histo build
const WG_HISTO_ELEMENTS: usize = Self::WG_THREAD_COUNT * Self::WE_HISTO_ELEMENTS;
pub fn new(device: &Device, max_size: usize) -> Self
{
// How many blocks (workgroups) for histobuild
let histo_block_count = max_size.div_ceil(Self::WG_HISTO_ELEMENTS);
// Number of histograms to allocate
let histogram_count = histo_block_count + 1;
let histograms = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("histograms_buffer"),
size: (histogram_count * size_of::<u32>() * Self::VALUE_COUNT) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let histograms_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("RadixSorter::histograms_bind_group_layout"),
entries: &[
// Histrograms
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let histograms_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::histograms_bind_group"),
layout: &histograms_bind_group_layout,
entries: &[
// Histrograms
wgpu::BindGroupEntry {
binding: 0,
resource: histograms.as_entire_binding(),
},
],
});
let double_buffer_keys = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::double_buffer_keys"),
size: (size_of::<u32>() * max_size) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let double_buffer_values = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::double_buffer_values"),
size: (size_of::<u32>() * max_size) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let element_counts_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::element_counts_buffer"),
size: size_of::<u32>() as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let indirect_counts_storage = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::element_counts_buffer"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let indirect_counts = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::element_counts_buffer"),
size: size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
usage: BufferUsages::INDIRECT | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let data_bind_group_layout =
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("RadixSorter::data_bind_group_layout"),
entries: &[
// Keys
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Values
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let double_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::double_buffer_bind_group"),
layout: &data_bind_group_layout,
entries: &[
// Keys
wgpu::BindGroupEntry {
binding: 0,
resource: double_buffer_keys.as_entire_binding(),
},
// Values
wgpu::BindGroupEntry {
binding: 1,
resource: double_buffer_values.as_entire_binding(),
},
],
});
let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("RadixSorter::pipelines_layout"),
bind_group_layouts: &[
Some(&histograms_bind_group_layout),
// Double buffering :
// Source buffer
Some(&data_bind_group_layout),
// Dest buffer
Some(&data_bind_group_layout),
// Counts buffer
Some(&data_bind_group_layout),
],
immediate_size: size_of::<PassParameters>() as u32, // for the pass number
});
let radix_sort_shader_module =
device.create_shader_module(include_spirv!("../../../shaders/out/radix_sort.spv"));
let compilation_options = wgpu::PipelineCompilationOptions {
zero_initialize_workgroup_memory: false,
..Default::default()
};
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::histogram_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("histogram_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let prefix_sum_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::prefix_sum_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("prefix_sum_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let total_prefix_sum_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::total_prefix_sum_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("total_prefix_sum_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let scatter_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::scatter_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("scatter_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let compute_counts_pass =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("RadixSorter::compute_counts_pass"),
layout: Some(&pipelines_layout),
module: &radix_sort_shader_module,
entry_point: Some("compute_counts_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let timing_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("RadixSorter::timing_buffer"),
size: (size_of::<u64>() * 2) as u64,
usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let timing_query_set = device.create_query_set(&wgpu::QuerySetDescriptor {
label: Some("RadixSorter::timing_query_set"),
ty: wgpu::QueryType::Timestamp,
count: 2,
});
RadixSorter {
max_size,
histo_block_count,
histogram_count,
histograms,
histograms_bind_group,
data_bind_group_layout,
double_buffer_keys,
double_buffer_values,
double_buffer_bind_group,
element_counts_buffer,
indirect_counts_storage,
indirect_counts,
histogram_pass,
prefix_sum_pass,
total_prefix_sum_pass,
scatter_pass,
compute_counts_pass,
timing_buffer,
timing_query_set,
}
}
/// Performs a radix sort on the `key` based on the `values`.
/// The keys are paired one-to-one with the values. At the end both keys and values are sorted.
/// An indirect count can be passed in `indirect` as a buffer of a single u32 on GPU.
/// A CPU side length can be passed in `direct_length`
/// `sort_direction` dictates the direction of the sort.
pub fn sort(
&self,
device: &Device,
keys: &Buffer,
values: &Buffer,
indirect: Option<&Buffer>,
direct_length: Option<usize>,
encoder: &mut CommandEncoder,
sort_direction: RadixSortDirection,
)
{
let data_buffer_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::data_buffer_bind_group"),
layout: &self.data_bind_group_layout,
entries: &[
// Keys
wgpu::BindGroupEntry {
binding: 0,
resource: keys.as_entire_binding(),
},
// Values
wgpu::BindGroupEntry {
binding: 1,
resource: values.as_entire_binding(),
},
],
});
let counts_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("RadixSorter::double_buffer_bind_group"),
layout: &self.data_bind_group_layout,
entries: &[
// Keys
wgpu::BindGroupEntry {
binding: 0,
resource: indirect
.unwrap_or(&self.element_counts_buffer)
.as_entire_binding(),
},
// Values
wgpu::BindGroupEntry {
binding: 1,
resource: self.indirect_counts_storage.as_entire_binding(),
},
],
});
let bg = [&data_buffer_bind_group, &self.double_buffer_bind_group];
// Compute counts
{
let mut counts_compute_pass =
encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("RadixSorter::counts_compute_pass"),
timestamp_writes: None,
});
let parameters = PassParameters {
pass_index: if indirect.is_some()
{
0
}
else
{
direct_length.unwrap_or(self.max_size) as u32
},
descending: 0,
digit_stride: 0,
};
let bytes = bytemuck::bytes_of(&parameters);
counts_compute_pass.set_pipeline(&self.compute_counts_pass);
counts_compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]);
counts_compute_pass.set_bind_group(1, bg[0], &[]);
counts_compute_pass.set_bind_group(2, bg[1], &[]);
counts_compute_pass.set_bind_group(3, &counts_bind_group, &[]);
counts_compute_pass.set_immediates(0, bytes);
counts_compute_pass.dispatch_workgroups(1, 1, 1);
}
// Copy indrect counts to indrect compatible buffer
encoder.copy_buffer_to_buffer(
&self.indirect_counts_storage,
0,
&self.indirect_counts,
0,
size_of::<wgpu::util::DispatchIndirectArgs>() as u64,
);
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("RadixSorter::compute_pass"),
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
query_set: &self.timing_query_set,
beginning_of_pass_write_index: Some(0),
end_of_pass_write_index: Some(1),
}),
});
for i in 0..Self::PASS_COUNT
{
let parameters = PassParameters {
pass_index: i as u32,
descending: match sort_direction
{
RadixSortDirection::Ascending => 0,
RadixSortDirection::Descending => 1,
},
digit_stride: self.histogram_count as u32,
};
let bytes = bytemuck::bytes_of(&parameters);
compute_pass.set_bind_group(0, &self.histograms_bind_group, &[]);
compute_pass.set_bind_group(1, bg[i % 2], &[]);
compute_pass.set_bind_group(2, bg[1 - (i % 2)], &[]);
compute_pass.set_bind_group(3, &counts_bind_group, &[]);
// ~~ Histogram pass
compute_pass.set_pipeline(&self.histogram_pass);
compute_pass.set_immediates(0, bytes);
compute_pass.dispatch_workgroups_indirect(&self.indirect_counts, 0);
//compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1);
// ~~ Prefix sum pass
compute_pass.set_pipeline(&self.prefix_sum_pass);
compute_pass.set_immediates(0, bytes);
compute_pass.dispatch_workgroups(Self::VALUE_COUNT as u32, 1, 1);
compute_pass.set_pipeline(&self.total_prefix_sum_pass);
compute_pass.set_immediates(0, bytes);
compute_pass.dispatch_workgroups(1, 1, 1);
// ~~ Scatter pass
compute_pass.set_pipeline(&self.scatter_pass);
compute_pass.set_immediates(0, bytes);
compute_pass.dispatch_workgroups_indirect(&self.indirect_counts, 0);
//compute_pass.dispatch_workgroups(self.histo_block_count as u32, 1, 1);
}
// Even number of passes => data is in the user buffer
drop(compute_pass);
encoder.resolve_query_set(&self.timing_query_set, 0..2, &self.timing_buffer, 0);
}
}
+143
View File
@@ -0,0 +1,143 @@
// Top-k selection over a dense array of u32 request counts.
//
// The Rust side prepends the following constants:
// const BIN_COUNT: u32;
// const SUB_BINS: u32;
// const LOG_SUB_BINS: u32;
// const WORKGROUP_SIZE: u32;
@group(0) @binding(0) var<storage, read> requests: array<u32>;
@group(0) @binding(1) var<storage, read_write> histogram: array<atomic<u32>>;
@group(0) @binding(2) var<storage, read_write> threshold: i32;
@group(0) @binding(3) var<storage, read_write> selected_count: atomic<u32>;
@group(0) @binding(4) var<storage, read_write> selected_indices: array<u32>;
// Threshold fill state:
// [0] = free slots for the threshold bin (k - above_count)
// [1] = threshold-bin candidates claimed so far
@group(0) @binding(5) var<storage, read_write> fill_state: array<atomic<u32>>;
struct TopKParams
{
element_count: u32,
k: u32,
}
var<immediate> params: TopKParams;
// Monotonic log-scale quantization. Counts of zero are never candidates, but
// the function is kept total so it is safe to call with any value.
fn quantize(count: u32) -> u32
{
if (count == 0u)
{
return 0u;
}
let exponent = 31u - countLeadingZeros(count);
var extra: u32;
if (exponent >= LOG_SUB_BINS)
{
extra = (count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1u);
}
else
{
extra = (count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1u);
}
return exponent * SUB_BINS + extra;
}
// Pass 1: quantize every non-zero count and accumulate the global histogram.
@compute
@workgroup_size(WORKGROUP_SIZE, 1, 1)
fn histogram_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
{
let index = global_id.x;
if (index >= params.element_count)
{
return;
}
let count = requests[index];
if (count == 0u)
{
return;
}
let bin = quantize(count);
atomicAdd(&histogram[bin], 1u);
}
// Pass 2: scan the histogram from the highest bin down until adding the
// current bin would reach k. The current bin becomes the threshold.
// A threshold of -1 means that every non-zero element is selected.
//
// `sum` is the number of elements in bins strictly above the threshold. It is
// also the number of slots already guaranteed, so the threshold bin has
// `k - sum` free slots left to fill.
@compute
@workgroup_size(1, 1, 1)
fn threshold_pass()
{
var sum: u32 = 0u;
var threshold_bin: i32 = -1;
for (var bin: u32 = BIN_COUNT; bin > 0u; bin = bin - 1u)
{
let count = atomicLoad(&histogram[bin - 1u]);
if (sum + count >= params.k)
{
threshold_bin = i32(bin - 1u);
break;
}
sum = sum + count;
}
threshold = threshold_bin;
atomicStore(&fill_state[0], params.k - min(params.k, sum));
atomicStore(&fill_state[1], 0u);
atomicStore(&selected_count, 0u);
}
// Pass 3: emit every index whose quantized bin is strictly above the
// threshold, then fill the remaining slots from the threshold bin in arbitrary
// order. Together these emit exactly `min(k, non-zero count)` indices.
@compute
@workgroup_size(WORKGROUP_SIZE, 1, 1)
fn select_pass(@builtin(global_invocation_id) global_id: vec3<u32>)
{
let index = global_id.x;
if (index >= params.element_count)
{
return;
}
let count = requests[index];
if (count == 0u)
{
return;
}
let bin = i32(quantize(count));
if (bin > threshold)
{
// Unconditionally selected.
let slot = atomicAdd(&selected_count, 1u);
selected_indices[slot] = index;
}
else if (bin == threshold)
{
// Fill the remaining slots from the threshold bin, in arbitrary order.
let remaining = atomicLoad(&fill_state[0]);
let offset = atomicAdd(&fill_state[1], 1u);
if (offset < remaining)
{
let slot = atomicAdd(&selected_count, 1u);
selected_indices[slot] = index;
}
}
}
+718
View File
@@ -0,0 +1,718 @@
//! GPU top-k selection over a dense array of `u32` request counts.
//!
//! The selector runs three compute passes:
//! 1. Quantize every non-zero count into [`BIN_COUNT`] log-scale bins and build
//! a global histogram.
//! 2. Scan the histogram from the highest bin down until adding the current bin
//! would reach `k`, producing a threshold bin.
//! 3. Emit every index whose bin is strictly above the threshold bin, then fill
//! the remaining slots from the threshold bin.
//!
//! The number of selected elements is therefore exactly
//! `min(k, number of non-zero elements)`. Elements taken from the threshold bin
//! are chosen in arbitrary order; the caller is expected to sort the output if
//! an ordering is required.
//!
//! The output list is unordered: indices are appended with atomics.
//!
//! The selector uses shader immediates, so the device must enable
//! [`wgpu::Features::IMMEDIATES`] and expose a `max_immediate_size` of at least
//! `size_of::<TopKParams>()` (8 bytes).
use bytemuck::bytes_of;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::ShaderStages;
use wgpu::util::DeviceExt;
/// Number of quantization bins.
pub const BIN_COUNT: u32 = 256;
/// Number of sub-bins per power-of-two octave.
const SUB_BINS: u32 = BIN_COUNT / 32;
/// Number of mantissa bits kept by the quantizer.
const LOG_SUB_BINS: u32 = SUB_BINS.trailing_zeros();
/// Threads per workgroup for the histogram and selection passes.
const WORKGROUP_SIZE: u32 = 256;
const _: () = assert!(BIN_COUNT % 32 == 0);
const _: () = assert!(SUB_BINS.is_power_of_two());
/// Parameters passed to the shader through immediates.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
struct TopKParams
{
element_count: u32,
k: u32,
}
/// GPU top-k selector over a dense array of request counts.
///
/// The selector owns its scratch and output buffers, so a single instance
/// cannot be used for two overlapping selections. Create one instance per
/// concurrent selection, or copy the results before the next call.
pub struct TopKSelector
{
max_selected: u32,
histogram: Buffer,
threshold: Buffer,
selected_count: Buffer,
selected_indices: Buffer,
/// `[0]` free threshold-bin slots, `[1]` claimed threshold-bin candidates.
fill_state: Buffer,
bind_group_layout: BindGroupLayout,
histogram_pass: ComputePipeline,
threshold_pass: ComputePipeline,
select_pass: ComputePipeline,
}
impl TopKSelector
{
/// Creates a selector that can output at most `max_selected` indices.
pub fn new(device: &Device, max_selected: u32) -> Self
{
assert!(
device.features().contains(wgpu::Features::IMMEDIATES),
"TopKSelector requires the IMMEDIATES feature"
);
assert!(
device.limits().max_immediate_size >= size_of::<TopKParams>() as u32,
"TopKSelector requires a max_immediate_size of at least {} bytes",
size_of::<TopKParams>()
);
let histogram = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("TopKSelector::histogram"),
size: (BIN_COUNT as u64) * (size_of::<u32>() as u64),
usage: BufferUsages::STORAGE | BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let threshold = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::threshold"),
contents: bytes_of(&-1i32),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
let selected_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::selected_count"),
contents: bytes_of(&0u32),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
// Avoid zero-sized buffers when `max_selected == 0`.
let selected_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("TopKSelector::selected_indices"),
size: (max_selected.max(1) as u64) * (size_of::<u32>() as u64),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
// [0] free threshold-bin slots, [1] claimed threshold-bin candidates.
// Both are reset by `threshold_pass` on every call.
let fill_state = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::fill_state"),
contents: bytemuck::cast_slice(&[0u32; 2]),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
});
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("TopKSelector::bind_group_layout"),
entries: &[
// Requests: read-only dense array of counts
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Histogram
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Threshold bin
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Selected count
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Selected indices
wgpu::BindGroupLayoutEntry {
binding: 4,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Threshold fill state
wgpu::BindGroupLayoutEntry {
binding: 5,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
],
});
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("TopKSelector::pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: size_of::<TopKParams>() as u32,
});
// Inject the quantization constants so the Rust and WGSL sides cannot
// drift apart.
let header = format!(
"const BIN_COUNT: u32 = {}u;\n\
const SUB_BINS: u32 = {}u;\n\
const LOG_SUB_BINS: u32 = {}u;\n\
const WORKGROUP_SIZE: u32 = {}u;\n",
BIN_COUNT, SUB_BINS, LOG_SUB_BINS, WORKGROUP_SIZE
);
let mut shader_source = String::with_capacity(header.len() + 2048);
shader_source.push_str(&header);
shader_source.push_str(include_str!("./shaders/top_k.wgsl"));
let shader_module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("TopKSelector::shader_module"),
source: wgpu::ShaderSource::Wgsl(shader_source.into()),
});
let compilation_options = wgpu::PipelineCompilationOptions::default();
let histogram_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("TopKSelector::histogram_pass"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("histogram_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let threshold_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("TopKSelector::threshold_pass"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("threshold_pass"),
compilation_options: compilation_options.clone(),
cache: None,
});
let select_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("TopKSelector::select_pass"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("select_pass"),
compilation_options,
cache: None,
});
Self {
max_selected,
histogram,
threshold,
selected_count,
selected_indices,
fill_state,
bind_group_layout,
histogram_pass,
threshold_pass,
select_pass,
}
}
/// Runs the three top-k passes over `requests[0..element_count]`.
///
/// `k` is the requested number of elements and must not exceed the
/// `max_selected` capacity given to [`TopKSelector::new`].
///
/// After this call:
/// - [`Self::selected_count_buffer`] contains
/// `min(k, number of non-zero elements)`.
/// - [`Self::selected_indices_buffer`] contains that many indices, in an
/// arbitrary order.
/// - [`Self::threshold_buffer`] contains the threshold bin, or `-1` if all
/// non-zero elements were selected.
pub fn select(
&self,
device: &Device,
encoder: &mut CommandEncoder,
requests: &Buffer,
element_count: u32,
k: u32,
)
{
assert!(
k <= self.max_selected,
"TopKSelector: k ({k}) exceeds the max_selected capacity ({})",
self.max_selected
);
assert!(
requests.size() >= (element_count as u64) * (size_of::<u32>() as u64),
"TopKSelector: requests buffer is too small for {element_count} elements"
);
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("TopKSelector::bind_group"),
layout: &self.bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: requests.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: self.histogram.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.threshold.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: self.selected_count.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.selected_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: self.fill_state.as_entire_binding(),
},
],
});
// The histogram is rebuilt from scratch on every call.
encoder.clear_buffer(&self.histogram, 0, None);
let params = TopKParams { element_count, k };
let params_bytes = bytes_of(&params);
let workgroup_count = element_count.div_ceil(WORKGROUP_SIZE).max(1);
let mut compute_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("TopKSelector::select"),
timestamp_writes: None,
});
compute_pass.set_bind_group(0, &bind_group, &[]);
compute_pass.set_pipeline(&self.histogram_pass);
compute_pass.set_immediates(0, params_bytes);
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
compute_pass.set_pipeline(&self.threshold_pass);
compute_pass.set_immediates(0, params_bytes);
compute_pass.dispatch_workgroups(1, 1, 1);
compute_pass.set_pipeline(&self.select_pass);
compute_pass.set_immediates(0, params_bytes);
compute_pass.dispatch_workgroups(workgroup_count, 1, 1);
}
/// Number of indices emitted by the last [`Self::select`] call.
pub fn selected_count_buffer(&self) -> &Buffer
{
&self.selected_count
}
/// Indices emitted by the last [`Self::select`] call, in arbitrary order.
pub fn selected_indices_buffer(&self) -> &Buffer
{
&self.selected_indices
}
/// Threshold bin of the last [`Self::select`] call, or `-1` if every
/// non-zero element was selected.
pub fn threshold_buffer(&self) -> &Buffer
{
&self.threshold
}
/// Maximum number of indices this selector can emit.
pub fn max_selected(&self) -> u32
{
self.max_selected
}
}
#[cfg(test)]
mod tests
{
use super::*;
/// CPU mirror of the WGSL quantizer.
fn quantize_cpu(count: u32) -> u32
{
if count == 0
{
return 0;
}
let exponent = 31 - count.leading_zeros();
let extra = if exponent >= LOG_SUB_BINS
{
(count >> (exponent - LOG_SUB_BINS)) & (SUB_BINS - 1)
}
else
{
(count << (LOG_SUB_BINS - exponent)) & (SUB_BINS - 1)
};
exponent * SUB_BINS + extra
}
/// CPU mirror of the three passes.
fn select_cpu(counts: &[u32], k: u32) -> (Vec<u32>, i32)
{
let mut histogram = vec![0u32; BIN_COUNT as usize];
for &count in counts
{
if count != 0
{
histogram[quantize_cpu(count) as usize] += 1;
}
}
let mut sum = 0u32;
let mut threshold = -1i32;
for bin in (0..BIN_COUNT as usize).rev()
{
let count = histogram[bin];
if sum + count >= k
{
threshold = bin as i32;
break;
}
sum += count;
}
let remaining = k.saturating_sub(sum);
let mut selected = counts
.iter()
.enumerate()
.filter(|&(_, &count)| count != 0 && quantize_cpu(count) as i32 > threshold)
.map(|(index, _)| index as u32)
.collect::<Vec<_>>();
// Fill the remaining slots from the threshold bin. The GPU picks these
// in arbitrary order; the CPU mirror fills them in index order so the
// tests stay deterministic.
if threshold >= 0
{
let mut slots = remaining;
for (index, &count) in counts.iter().enumerate()
{
if slots == 0
{
break;
}
if count != 0 && quantize_cpu(count) as i32 == threshold
{
selected.push(index as u32);
slots -= 1;
}
}
}
(selected, threshold)
}
fn next_random(state: &mut u64) -> u32
{
*state ^= *state << 13;
*state ^= *state >> 7;
*state ^= *state << 17;
(*state >> 32) as u32
}
#[test]
fn quantize_is_monotonic()
{
let mut previous = 0;
for count in 1..100_000u32
{
let bin = quantize_cpu(count);
assert!(bin >= previous, "quantize({count}) = {bin} < {previous}");
assert!(bin < BIN_COUNT);
previous = bin;
}
let mut state = 0x1234_5678_9abc_def0u64;
let mut values = (0..10_000)
.map(|_| next_random(&mut state))
.collect::<Vec<_>>();
values.sort_unstable();
let mut previous = 0;
for count in values
{
let bin = quantize_cpu(count);
assert!(bin >= previous);
assert!(bin < BIN_COUNT);
previous = bin;
}
}
#[test]
fn quantize_handles_zero_and_max()
{
assert_eq!(quantize_cpu(0), 0);
assert!(quantize_cpu(u32::MAX) < BIN_COUNT);
}
#[test]
fn selection_selects_exactly_min_k_and_non_zero()
{
let mut state = 0x0ddc_0ffe_e15e_beefu64;
for _ in 0..100
{
let len = 1 + (next_random(&mut state) % 1000) as usize;
let counts = (0..len)
.map(|_| next_random(&mut state) % 64)
.collect::<Vec<_>>();
let non_zero = counts.iter().filter(|&&count| count != 0).count();
for k in 0..=20
{
let (selected, threshold) = select_cpu(&counts, k);
assert_eq!(selected.len(), (k as usize).min(non_zero));
let mut sorted = selected.clone();
sorted.sort_unstable();
sorted.dedup();
assert_eq!(sorted.len(), selected.len(), "duplicate indices");
for &index in &selected
{
let count = counts[index as usize];
assert!(count != 0);
assert!(quantize_cpu(count) as i32 >= threshold);
}
}
}
}
#[test]
fn selection_fills_threshold_bin_to_exactly_k()
{
let counts = [1, 5, 3, 5, 2];
let (selected, _) = select_cpu(&counts, 3);
// The two 5s are above the threshold bin; the 3 fills the last slot.
let mut sorted = selected;
sorted.sort_unstable();
assert_eq!(sorted, vec![1, 2, 3]);
}
#[test]
fn selection_with_fewer_candidates_than_k()
{
let counts = [1, 0, 2, 0, 3];
let (selected, threshold) = select_cpu(&counts, 10);
assert_eq!(threshold, -1);
assert_eq!(selected.len(), 3);
}
#[test]
fn selection_with_k_zero()
{
let counts = [1, 2, 3];
let (selected, _) = select_cpu(&counts, 0);
assert!(selected.is_empty());
}
#[test]
fn selection_with_all_equal_counts_selects_k()
{
let counts = [7, 7, 7, 7];
let (selected, threshold) = select_cpu(&counts, 2);
// Every element is in the threshold bin, so the first two are taken.
assert_eq!(threshold, quantize_cpu(7) as i32);
assert_eq!(selected, vec![0, 1]);
}
#[test]
fn selection_with_all_zero_counts()
{
let counts = [0, 0, 0, 0];
let (selected, threshold) = select_cpu(&counts, 2);
assert_eq!(threshold, -1);
assert!(selected.is_empty());
}
#[test]
#[ignore = "requires a GPU adapter with the IMMEDIATES feature"]
fn gpu_selection_smoke_test()
{
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter =
pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default()))
.expect("no GPU adapter available");
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
required_features: wgpu::Features::IMMEDIATES,
required_limits: wgpu::Limits {
max_immediate_size: 112,
..Default::default()
},
..Default::default()
}))
.expect("failed to create GPU device");
let counts: [u32; 5] = [1, 5, 3, 5, 2];
let requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::test_requests"),
contents: bytemuck::cast_slice(&counts),
usage: BufferUsages::STORAGE,
});
let selector = TopKSelector::new(&device, 8);
// Run the selection twice to verify that the histogram and fill state
// are reset between calls.
for _ in 0..2
{
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("TopKSelector::test_encoder"),
});
selector.select(&device, &mut encoder, &requests, counts.len() as u32, 3);
queue.submit([encoder.finish()]);
let (count, indices) = read_selection(&device, &queue, &selector);
// The two 5s are above the threshold bin; the 3 fills the last slot.
assert_eq!(count, 3);
assert_eq!(indices, vec![1, 2, 3]);
}
// All-equal counts: the threshold bin must fill every slot.
let equal_counts: [u32; 4] = [7, 7, 7, 7];
let equal_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("TopKSelector::test_equal_requests"),
contents: bytemuck::cast_slice(&equal_counts),
usage: BufferUsages::STORAGE,
});
let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
label: Some("TopKSelector::test_encoder"),
});
selector.select(
&device,
&mut encoder,
&equal_requests,
equal_counts.len() as u32,
2,
);
queue.submit([encoder.finish()]);
let (count, indices) = read_selection(&device, &queue, &selector);
assert_eq!(count, 2);
assert_eq!(indices.len(), 2);
assert!(
indices
.iter()
.all(|&index| index < equal_counts.len() as u32)
);
}
/// Reads back the selected count and the sorted selected indices.
fn read_selection(
device: &wgpu::Device,
queue: &wgpu::Queue,
selector: &TopKSelector,
) -> (u32, Vec<u32>)
{
let count = std::sync::Arc::new(std::sync::Mutex::new(None));
let count_clone = count.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&selector.selected_count_buffer().slice(..),
move |buffer| {
let bytes = buffer.unwrap();
*count_clone.lock().unwrap() = Some(bytemuck::pod_read_unaligned::<u32>(&bytes));
},
);
let indices = std::sync::Arc::new(std::sync::Mutex::new(None));
let indices_clone = indices.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&selector.selected_indices_buffer().slice(..),
move |buffer| {
let bytes = buffer.unwrap();
*indices_clone.lock().unwrap() =
Some(bytemuck::pod_collect_to_vec::<u8, u32>(&bytes));
},
);
device
.poll(wgpu::wgt::PollType::wait_indefinitely())
.unwrap();
let count = *count.lock().unwrap().as_ref().unwrap();
let mut indices = indices.lock().unwrap().as_ref().unwrap()[0..count as usize].to_vec();
indices.sort_unstable();
(count, indices)
}
}
+11
View File
@@ -0,0 +1,11 @@
[package]
name = "vxls-production"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
itertools.workspace = true
rayon.workspace = true
wgpu.workspace = true
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
@@ -0,0 +1,69 @@
use rayon::ThreadPool;
use rayon::iter::IndexedParallelIterator;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::IntoParallelRefMutIterator;
use rayon::iter::ParallelIterator;
use crate::VoxelProducer;
use vxls_voxel_cache::insertion::CacheInsertionData;
use vxls_voxel_cache::requests::CacheRequestBuffer;
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::RequestInformation;
/// Handles requests made by the cache on the host
pub struct HostRequestHandler<const N: usize, P: VoxelProducer<N>>
where
[(); N * N * N]:,
{
producer: P,
thread_pool: ThreadPool,
}
impl<const N: usize, P: VoxelProducer<N> + Sync> HostRequestHandler<N, P>
where
[(); N * N * N]:,
{
pub fn new(producer: P, thread_pool: ThreadPool) -> Self
{
Self {
producer,
thread_pool,
}
}
pub fn fullfill(
&self,
device: &wgpu::Device,
queue: &wgpu::Queue,
request_buffer: &CacheRequestBuffer,
insertion: &CacheInsertionData<N>,
)
{
request_buffer.host_download_requests(device, queue, |_requests, _metas| {});
}
pub fn produce_requests(
&self,
requests: &[RequestInformation],
informations: &mut [InsertionInformation<N>],
attributes: &mut [[P::Output; N * N * N]],
)
{
self.thread_pool.install(|| {
requests
.par_iter()
.zip(informations.par_iter_mut())
.zip(attributes.par_iter_mut())
.for_each(|((request, dest_information), dest_attributes)| {
let (info, attributes) = self.producer.produce(
super::ProducerId(0),
request.anchor,
super::StructureLocator(request.node_id),
);
*dest_information = info;
*dest_attributes = attributes;
});
})
}
}
+63
View File
@@ -0,0 +1,63 @@
#![feature(generic_const_exprs)]
use bytemuck::Pod;
use bytemuck::Zeroable;
use vxls_voxel_cache::schema::InsertionInformation;
pub use vxls_voxel_cache::schema::StructureAnchor;
/// A structure locator format to locate node within an ntree
pub mod tree_locator;
/// Facilities for voxel production on the host (CPU) side
pub mod host_production;
/// Bounded, deduplicating, priority-ordered cache request queue
pub mod request_queue;
/// This module contains definition and common logic to produce voxel data to feed a [`VoxelCache`]
/// A cache might hold data owned by multiple different producers. To discriminate where to route the
/// request, a node is always tagged by a [`ProducerId`].
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct ProducerId(pub u32);
/// A request can come from anywhere inside the structure. The producer can thus tag each node with
/// a locator, to know where the request was issued.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct StructureLocator(pub u32);
/// For structs which can be used as a voxel attribute source
pub trait VoxelAttributes<const N: usize>: 'static + Clone + Send + Sync
{
/// The amount of attributes this struct holds
fn attribute_count() -> usize;
/// Must returns the words for a single attribute.
fn attribute(&self, attribute_index: usize) -> &[u32];
}
/// Represents something that can produce a voxel node.
pub trait VoxelProducer<const N: usize>
where
[(); N * N * N]:,
{
/// The voxel data produced by this producer
type Output: VoxelAttributes<N>;
/// A pure function that can produce a voxel node based on the owner producer
/// id, requesting structure, and the requesting location within the structure.
///
/// `anchor` is the table-defined content identity of the structure. Producers
/// must derive world position/content from it rather than from any table
/// slot: slots are placement and may change while the anchor stays stable.
fn produce(
&self,
producer_id: ProducerId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
}
File diff suppressed because it is too large Load Diff
+441
View File
@@ -0,0 +1,441 @@
use itertools::Itertools;
use crate::StructureLocator;
/// Compact location of a specific node within a Voxel tree data strcutrure : depth + location
///
/// The location is encoded as one number per coordinate.
/// A coordinate is interpreted as base `N` number.
/// The base `N` digits represent the path take from the root down to the node, therminated by a
/// `1` digit.
///
/// Thus a encoded location of `1` refers to the root : Only node of depth 0
///
/// An encoded location of `1032` for a 4-tree, refers to from the root : going into the 0th
/// child, then 3rd child, then 2nd child. It refers to a node of depth 3.
///
#[derive(Clone, Copy, Hash, PartialEq, Eq, Debug)]
pub struct TreeLocator<const N: usize>
{
x: u32,
y: u32,
z: u32,
}
impl<const N: usize> From<StructureLocator> for TreeLocator<N>
{
fn from(value: StructureLocator) -> Self
{
let mut value = value.0;
let mut locator = Self::root();
let n = N as u32;
while value != 1
{
let z = value % n;
value /= n;
let y = value % n;
value /= n;
let x = value % n;
value /= n;
locator = locator.child(x, y, z)
}
locator
}
}
impl<const N: usize> From<TreeLocator<N>> for StructureLocator
{
fn from(mut value: TreeLocator<N>) -> StructureLocator
{
let mut locator = 1u32;
while !value.is_root()
{
let (x, y, z) = value.local_coords();
value = value.parent().unwrap();
locator *= N as u32;
locator += x;
locator *= N as u32;
locator += y;
locator *= N as u32;
locator += z;
}
StructureLocator(locator)
}
}
impl<const N: usize> TreeLocator<N>
{
pub const ROOT: TreeLocator<N> = TreeLocator { x: 1, y: 1, z: 1 };
pub fn root() -> Self
{
Self::ROOT
}
/// Returns the locator of node at `depth`, with coordinates, in that depth coordinate space,
/// `node_x` `node_y` `node_z`.
///
/// The `node_*` must be in the `0..N^depth` range.
pub fn from_node_coords(depth: u32, node_x: u32, node_y: u32, node_z: u32) -> Self
{
// Check coordinate bounds
assert!(
node_x < N.pow(depth) as u32,
"Node coordinates out of bounds."
);
assert!(
node_y < N.pow(depth) as u32,
"Node coordinates out of bounds."
);
assert!(
node_z < N.pow(depth) as u32,
"Node coordinates out of bounds."
);
if depth == 0
{
return Self::ROOT;
}
// Puts a one in base-N on the Nth digit
let one = N.pow(depth) as u32;
Self {
x: one + node_x,
y: one + node_y,
z: one + node_z,
}
}
/// Computes the maximum depth supported for this tree arity
pub fn max_depth() -> u32
{
(u32::MAX as usize).ilog(N) - 1
}
pub fn is_root(&self) -> bool
{
self.x == 1 && self.y == 1 && self.z == 1
}
/// Returns the depth of the node located by `self`, 0 being the root
pub fn depth(&self) -> u32
{
// A number k takes floor(log_n(k)) + 1 digits in base n
// This is digits - 1 as the locator contains a 1 on the front
self.x.ilog(N as u32)
}
/// Returns the size in voxels of this node considering that a node at `max_depth` represents 1
/// voxel
pub fn node_size(&self, max_depth: u32) -> u32
{
let depth = self.depth();
// 0 if voxel, max_depth if root
let height = max_depth - depth;
N.pow(height) as u32
}
/// Returns the locator of this node's parent, `None` if `self` is the root
pub fn parent(&self) -> Option<Self>
{
if self.is_root()
{
None
}
else
{
Some(Self {
x: self.x / N as u32,
y: self.y / N as u32,
z: self.z / N as u32,
})
}
}
/// Returns the [`TreeLocator`] of the children of this node with coordinates `child_x`,
/// `child_y`, `child_z` within this node.
///
/// The `child_*` coordinates must be in the `0..N` range.
pub fn child(&self, child_x: u32, child_y: u32, child_z: u32) -> Self
{
// Check children bounds
assert!(child_x < N as u32, "Out of bounds child coordinate.");
assert!(child_y < N as u32, "Out of bounds child coordinate.");
assert!(child_z < N as u32, "Out of bounds child coordinate.");
// Check depth bounds
assert!(
self.x.checked_mul(N as u32).is_some(),
"TreeLocator too deep"
);
assert!(
self.y.checked_mul(N as u32).is_some(),
"TreeLocator too deep"
);
assert!(
self.z.checked_mul(N as u32).is_some(),
"TreeLocator too deep"
);
let n = N as u32;
Self {
x: self.x * n + child_x,
y: self.y * n + child_y,
z: self.z * n + child_z,
}
}
/// Returns an iterator on the children of this node
pub fn children(&self) -> impl Iterator<Item = Self>
{
(0..N as u32)
.cartesian_product(0..N as u32)
.cartesian_product(0..N as u32)
.map(|((z, y), x)| self.child(x, y, z))
}
/// Returns the coordinate of this node inside its parent.
/// The returned coordinate are in `0..N`
pub fn local_coords(&self) -> (u32, u32, u32)
{
if self.is_root()
{
return (0, 0, 0);
}
let x = self.x % N as u32;
let y = self.y % N as u32;
let z = self.z % N as u32;
(x, y, z)
}
/// Returns the location of this node at in the space of this depth
pub fn node_location(&self) -> (u32, u32, u32)
{
let depth = self.depth();
// Puts a one in base-N on the Nth digit
let one = N.pow(depth) as u32;
(self.x % one, self.y % one, self.z % one)
}
}
#[cfg(test)]
mod tests
{
use super::*;
fn raw<const N: usize>(l: TreeLocator<N>) -> (u32, u32, u32)
{
(l.x, l.y, l.z)
}
#[test]
fn root_is_depth_zero()
{
let r = TreeLocator::<4>::root();
assert!(r.is_root());
assert_eq!(r.depth(), 0);
assert_eq!(raw(r), (1, 1, 1));
assert!(r.parent().is_none());
assert_eq!(r.local_coords(), (0, 0, 0));
}
#[test]
fn child_encoding_matches_doc_example()
{
// Doc: `1032` in base 4 => child 0, then 3, then 2 => depth 3.
let l = TreeLocator::<4>::root()
.child(0, 0, 0)
.child(3, 3, 3)
.child(2, 2, 2);
// 0b1032 in base 4 = 1*64 + 0*16 + 3*4 + 2 = 78
assert_eq!(raw(l), (78, 78, 78));
assert_eq!(l.depth(), 3);
assert!(!l.is_root());
}
#[test]
fn child_uses_independent_coordinates()
{
let c = TreeLocator::<4>::root().child(1, 2, 3);
assert_eq!(raw(c), (4 + 1, 4 + 2, 4 + 3));
assert_eq!(c.depth(), 1);
assert_eq!(c.local_coords(), (1, 2, 3));
}
#[test]
fn parent_undoes_child()
{
let root = TreeLocator::<4>::root();
let c = root.child(3, 0, 2);
let gc = c.child(1, 1, 0);
assert_eq!(raw(gc.parent().unwrap()), raw(c));
assert_eq!(raw(c.parent().unwrap()), raw(root));
}
#[test]
fn from_node_coords_depth_zero_is_root()
{
let l = TreeLocator::<4>::from_node_coords(0, 0, 0, 0);
assert!(l.is_root());
}
#[test]
fn from_node_coords_matches_child_walk()
{
// Node (5, 2, 7) at depth 2 in a 4-tree (coords in 0..16).
// Base 4: x = 11, y = 02, z = 13.
let direct = TreeLocator::<4>::from_node_coords(2, 5, 2, 7);
let walked = TreeLocator::<4>::root().child(1, 0, 1).child(1, 2, 3);
assert_eq!(raw(direct), raw(walked));
assert_eq!(direct.depth(), 2);
}
#[test]
fn from_node_coords_parent_is_coarser_node()
{
let l = TreeLocator::<4>::from_node_coords(3, 37, 12, 63);
let p = TreeLocator::<4>::from_node_coords(2, 37 / 4, 12 / 4, 63 / 4);
assert_eq!(raw(l.parent().unwrap()), raw(p));
}
#[test]
fn roundtrip_via_local_coords()
{
let original = TreeLocator::<3>::from_node_coords(4, 50, 7, 80);
// Walk up to the root, collecting local coords at each level.
let mut path = Vec::new();
let mut cur = original;
while let Some(parent) = cur.parent()
{
path.push(cur.local_coords());
cur = parent;
}
assert!(cur.is_root());
assert_eq!(path.len() as u32, original.depth());
// Walk back down and rebuild.
let mut rebuilt = TreeLocator::<3>::root();
for (x, y, z) in path.into_iter().rev()
{
rebuilt = rebuilt.child(x, y, z);
}
assert_eq!(raw(rebuilt), raw(original));
}
#[test]
fn children_are_complete_distinct_and_valid()
{
let parent = TreeLocator::<3>::root().child(2, 1, 0);
let kids: Vec<_> = parent.children().collect();
assert_eq!(kids.len(), 27);
let mut seen = std::collections::HashSet::new();
let mut locals = std::collections::HashSet::new();
for k in &kids
{
assert_eq!(k.depth(), parent.depth() + 1);
assert_eq!(raw(k.parent().unwrap()), raw(parent));
assert!(seen.insert(raw(*k)), "duplicate child");
locals.insert(k.local_coords());
}
// Every (x, y, z) in 0..3 appears exactly once as a local coordinate.
assert_eq!(locals.len(), 27);
}
#[test]
fn node_size_scales_with_depth()
{
let max_depth = 3;
let root = TreeLocator::<4>::root();
assert_eq!(root.node_size(max_depth), 64); // 4^3
assert_eq!(root.child(0, 0, 0).node_size(max_depth), 16); // 4^2
assert_eq!(root.child(0, 0, 0).child(1, 1, 1).node_size(max_depth), 4);
assert_eq!(
root.child(0, 0, 0)
.child(1, 1, 1)
.child(2, 2, 2)
.node_size(max_depth),
1
);
}
#[test]
fn max_depth_is_reachable_without_overflow()
{
// `max_depth` may be conservative, but it must always be safe to reach.
fn check<const N: usize>()
{
let max = TreeLocator::<N>::max_depth();
let last = N as u32 - 1;
let mut l = TreeLocator::<N>::root();
for _ in 0..max
{
l = l.child(last, last, last);
}
assert_eq!(l.depth(), max);
// Largest coordinates at that depth must also be constructible.
let top = (N as u32).pow(max) - 1;
let direct = TreeLocator::<N>::from_node_coords(max, top, top, top);
assert_eq!(raw(direct), raw(l));
}
check::<2>();
check::<3>();
check::<4>();
check::<8>();
}
#[test]
#[should_panic(expected = "Out of bounds child coordinate.")]
fn child_rejects_out_of_range_coordinate()
{
TreeLocator::<4>::root().child(0, 4, 0);
}
#[test]
#[should_panic(expected = "Node coordinates out of bounds.")]
fn from_node_coords_rejects_out_of_range_coordinate()
{
// Depth 2 in a 4-tree allows 0..16.
TreeLocator::<4>::from_node_coords(2, 0, 16, 0);
}
#[test]
#[should_panic(expected = "TreeLocator too deep")]
fn child_rejects_overflowing_depth()
{
let mut l = TreeLocator::<2>::root();
for _ in 0..40
{
l = l.child(1, 1, 1);
}
}
#[test]
fn node_at_depth_roundtrip()
{
let l = TreeLocator::<4>::from_node_coords(3, 8, 1, 18);
let (nx, ny, nz) = l.node_location();
let l2 = TreeLocator::<4>::from_node_coords(3, nx, ny, nz);
assert!(l == l2);
}
}
+9
View File
@@ -0,0 +1,9 @@
[package]
name = "vxls-profiler"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
egui.workspace = true
wgpu.workspace = true
+714
View File
@@ -0,0 +1,714 @@
use std::marker::PhantomData;
use std::ops::Deref;
use std::ops::DerefMut;
use egui::Ui;
use egui::vec2;
use wgpu::Buffer;
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePass;
use wgpu::Device;
use wgpu::QuerySet;
use wgpu::Queue;
pub mod memory_profiler;
#[macro_export]
macro_rules! begin_frame {
($encoder:ident) => {
let mut $encoder = $encoder.begin_frame(None);
};
($encoder:ident, $name:literal) => {
let mut $encoder = $encoder.begin_frame(Some($name));
};
}
#[macro_export]
macro_rules! begin_scope {
($scope:ident, $name:literal) => {
let mut $scope = $scope.begin_scope($name);
};
}
pub struct ScopeEncoder<'enc, 'prof_enc, T>
{
encoder: &'prof_enc mut ProfilingEncoder<'enc>,
scope_index: usize,
_phantom: PhantomData<T>,
}
pub struct Scope
{
name: &'static str,
start_index: QuerySetHandle,
end_index: Option<QuerySetHandle>,
children: Vec<usize>,
}
pub struct ProfilingEncoder<'enc>
{
device: Device,
encoder: &'enc mut CommandEncoder,
query_set_allocator: QuerySetAllocator,
scopes: Vec<Scope>,
index_stack: Vec<usize>,
// Stores a compute pass when currently in one
compute_pass: Option<(usize, ComputePass<'static>)>,
}
pub struct GpuProfile
{
scopes: Vec<Scope>,
timestamps: Buffer,
}
pub struct Frame
{
pub name: &'static str,
pub children: Vec<usize>,
pub start_timestamp: u64,
pub end_timestamp: u64,
}
#[derive(Default)]
pub struct Profile
{
pub frames: Vec<Frame>,
}
impl<'enc> ProfilingEncoder<'enc>
{
pub fn new(device: &Device, encoder: &'enc mut CommandEncoder) -> Self
{
Self {
encoder,
query_set_allocator: QuerySetAllocator::new(device),
scopes: Vec::new(),
device: device.clone(),
index_stack: Vec::new(),
compute_pass: None,
}
}
pub fn begin_frame<'prof_enc>(
&'prof_enc mut self,
frame_name: Option<&'static str>,
) -> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
let scope_index = self.begin_scope(None, frame_name.unwrap_or("Frame"));
self.index_stack.push(scope_index);
ScopeEncoder {
encoder: self,
scope_index,
_phantom: Default::default(),
}
}
fn begin_scope(&mut self, scope_index: Option<usize>, name: &'static str) -> usize
{
let begin_query = self.query_set_allocator.allocate();
if let Some((_, pass)) = &mut self.compute_pass
{
self.query_set_allocator
.write_compute_timestamp(pass, &begin_query);
}
else
{
self.query_set_allocator
.write_timestamp(self.encoder, &begin_query);
}
let scope = Scope {
name,
start_index: begin_query,
end_index: None,
children: Vec::new(),
};
let new_scope_index = self.scopes.len();
self.scopes.push(scope);
self.index_stack.push(new_scope_index);
// Add this new stack to parent
if let Some(scope_index) = scope_index
{
self.scopes[scope_index].children.push(new_scope_index);
}
new_scope_index
}
fn end_scope(&mut self, scope_index: usize)
{
let end_query = self.query_set_allocator.allocate();
if let Some((_, pass)) = &mut self.compute_pass
{
self.query_set_allocator
.write_compute_timestamp(pass, &end_query);
}
else
{
self.query_set_allocator
.write_timestamp(self.encoder, &end_query);
}
let scope = &mut self.scopes[scope_index];
let pop = self.index_stack.pop().unwrap();
assert_eq!(
pop, scope_index,
"Scopes must be defined in a stack fashion."
);
scope.end_index = Some(end_query);
}
pub fn finish_profiler(self) -> GpuProfile
{
let timestamp_count = self.query_set_allocator.allocated_count();
let resolve_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ProfilingEncoder::resolve_buffer"),
size: size_of::<u64>() as u64 * timestamp_count as u64,
usage: BufferUsages::QUERY_RESOLVE | BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
self.query_set_allocator
.resolve_all(self.encoder, &resolve_buffer);
GpuProfile {
scopes: self.scopes,
timestamps: resolve_buffer,
}
}
}
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
pub fn begin_profiled_compute_pass<'scope>(
&'scope mut self,
label: &'static str,
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
{
let new_scope = self.encoder.begin_scope(Some(self.scope_index), label);
let compute_pass = self
.encoder
.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some(label),
timestamp_writes: None,
})
.forget_lifetime();
self.encoder.compute_pass = Some((new_scope, compute_pass));
ScopeEncoder {
encoder: self.encoder,
scope_index: new_scope,
_phantom: Default::default(),
}
}
pub fn begin_scope<'scope>(
&'scope mut self,
name: &'static str,
) -> ScopeEncoder<'enc, 'scope, CommandEncoder>
where
'prof_enc: 'scope,
{
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
ScopeEncoder {
encoder: self.encoder,
scope_index,
_phantom: Default::default(),
}
}
pub fn end_scope(self)
{
drop(self);
}
}
impl<'enc, 'prof_enc> ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
{
pub fn begin_scope<'scope>(
&'scope mut self,
name: &'static str,
) -> ScopeEncoder<'enc, 'scope, ComputePass<'static>>
where
'prof_enc: 'scope,
{
let scope_index = self.encoder.begin_scope(Some(self.scope_index), name);
ScopeEncoder {
encoder: self.encoder,
scope_index,
_phantom: Default::default(),
}
}
pub fn end_scope(self)
{
drop(self);
}
}
impl<'enc, 'prof_enc, T> Drop for ScopeEncoder<'enc, 'prof_enc, T>
{
fn drop(&mut self)
{
if let Some((parent_scope, _)) = self.encoder.compute_pass
&& parent_scope == self.scope_index
{
// Finish compute pass by droping it
self.encoder.compute_pass = None;
}
self.encoder.end_scope(self.scope_index);
}
}
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
&mut *self.encoder
}
}
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, CommandEncoder>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
{
&*self.encoder
}
}
impl<'enc, 'prof_enc> DerefMut for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
&mut self.encoder.compute_pass.as_mut().unwrap().1
}
}
impl<'enc, 'prof_enc> Deref for ScopeEncoder<'enc, 'prof_enc, ComputePass<'static>>
{
type Target = ComputePass<'static>;
fn deref(&self) -> &Self::Target
{
&self.encoder.compute_pass.as_ref().unwrap().1
}
}
impl<'enc> DerefMut for ProfilingEncoder<'enc>
{
fn deref_mut(&mut self) -> &mut Self::Target
{
self.encoder
}
}
impl<'enc> Deref for ProfilingEncoder<'enc>
{
type Target = CommandEncoder;
fn deref(&self) -> &Self::Target
{
self.encoder
}
}
struct QuerySetAllocator
{
device: Device,
current_size: u32,
current_id: u32,
query_sets: Vec<(u32, u32, QuerySet)>,
}
#[derive(PartialEq, Eq)]
struct QuerySetHandle(usize, u32, u32);
impl QuerySetHandle
{
pub fn index(&self) -> usize
{
self.2 as usize
}
}
impl PartialOrd for QuerySetHandle
{
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering>
{
Some(self.cmp(other))
}
}
impl Ord for QuerySetHandle
{
fn cmp(&self, other: &Self) -> std::cmp::Ordering
{
match self.0.cmp(&other.0)
{
core::cmp::Ordering::Equal =>
{}
ord => return ord,
}
self.1.cmp(&other.1)
}
}
impl QuerySetAllocator
{
pub fn new(device: &Device) -> Self
{
let current_size = 32;
let query_sets = vec![(
0,
current_size,
Self::new_query_set(device, current_size, 0),
)];
QuerySetAllocator {
query_sets,
current_size,
current_id: 0,
device: device.clone(),
}
}
pub fn allocated_count(&self) -> u32
{
self.query_sets
.iter()
.map(|(allocated, _, _)| *allocated)
.sum()
}
pub fn resolve_all(&self, encoder: &mut CommandEncoder, target: &Buffer)
{
let mut offset = 0;
for (allocated, _, query_set) in self.query_sets.iter()
{
encoder.resolve_query_set(query_set, 0..*allocated, target, offset);
offset += *allocated as u64 * size_of::<u64>() as u64;
}
}
pub fn allocate(&mut self) -> QuerySetHandle
{
// Check if allocation is possible
if self
.query_sets
.last()
.is_some_and(|(allocated, available, _)| allocated == available)
{
// No more room, allocate new query set
self.current_size *= 2;
self.query_sets.push((
0,
self.current_size,
Self::new_query_set(&self.device, self.current_size, self.query_sets.len()),
));
}
// Last allocation is guaranteed to have room
let (allocated, _available, _query_set) = self.query_sets.last_mut().unwrap();
let query_index = *allocated;
*allocated += 1;
let query_set_index = self.query_sets.len() - 1;
let id = self.current_id;
self.current_id += 1;
QuerySetHandle(query_set_index, query_index, id)
}
fn new_query_set(device: &Device, size: u32, index: usize) -> QuerySet
{
device.create_query_set(&wgpu::QuerySetDescriptor {
label: Some(format!("QuerySetAllocator::query_set_{index}").as_str()),
ty: wgpu::QueryType::Timestamp,
count: size,
})
}
fn write_timestamp(&mut self, encoder: &mut CommandEncoder, handle: &QuerySetHandle)
{
let query_set = &self.query_sets[handle.0].2;
encoder.write_timestamp(query_set, handle.1);
}
fn write_compute_timestamp(&mut self, pass: &mut ComputePass, handle: &QuerySetHandle)
{
let query_set = &self.query_sets[handle.0].2;
pass.write_timestamp(query_set, handle.1);
}
}
impl GpuProfile
{
pub fn read_back(
self,
device: &Device,
queue: &Queue,
mut callback: impl FnMut(Profile) + Send + Sync + 'static,
)
{
// Readback timestamps
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.timestamps.slice(..),
move |buffer| {
let buffer = buffer.unwrap();
let timestamps: Vec<u64> = bytemuck::pod_collect_to_vec(&buffer);
let start = timestamps.first().copied().unwrap_or(0);
let frames = self
.scopes
.into_iter()
.map(|scope| Frame {
name: scope.name,
children: scope.children,
start_timestamp: timestamps[scope.start_index.index()] - start,
end_timestamp: timestamps[scope.end_index.unwrap().index()] - start,
})
.collect::<Vec<_>>();
callback(Profile { frames });
},
);
}
}
impl Profile
{
pub fn to_display_string(&self, q: f32) -> String
{
let mut str = String::new();
self.frames[0].build_string(&self.frames, 0, q, &mut str);
str
}
pub fn show(&self, ui: &mut Ui, q: f32)
{
if !self.frames.is_empty()
{
self.frames[0].show(ui, q, &self.frames);
}
}
}
impl Frame
{
fn time(&self, q: f32) -> f32
{
(self.end_timestamp - self.start_timestamp) as f32 * q
}
fn start(&self, q: f32) -> f32
{
self.start_timestamp as f32 * q
}
fn end(&self, q: f32) -> f32
{
self.end_timestamp as f32 * q
}
fn build_string(&self, frames: &Vec<Frame>, depth: usize, q: f32, str: &mut String)
{
let mut depth_string = String::new();
(0..depth).for_each(|_| depth_string.push_str(" "));
let time = (self.end_timestamp - self.start_timestamp) as f32 * q;
str.push_str(&format!("{depth_string}{}: {:.2}\n", self.name, time));
self.children
.iter()
.for_each(|c| frames[*c].build_string(frames, depth + 1, q, str));
}
pub fn show(&self, ui: &mut Ui, q: f32, frames: &Vec<Frame>)
{
let id = ui.make_persistent_id(self.name);
egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, true)
.show_header(ui, |ui| {
ui.horizontal(|ui| {
ui.label(self.name);
// Right-aligned label, laid out first from the right edge
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(format!("{:.2}ms", self.time(q)));
// Whatever space remains between the two labels:
// draw a thin line across it, vertically centered.
let rect = ui.available_rect_before_wrap();
let y = rect.center().y;
ui.painter().hline(
rect.x_range(),
y,
ui.visuals().widgets.noninteractive.bg_stroke,
);
});
});
})
.body(|ui| {
self.children
.iter()
.for_each(|i| frames[*i].show(ui, q, frames));
});
}
}
impl Profile
{
// Clauderies
pub fn show_flamegraph(&self, id: egui::Id, q: f32, ui: &mut Ui) -> egui::Response
{
if self.frames.is_empty()
{
return ui.label("empty");
}
let row_height = 20.;
// Full time range and max depth of the tree.
let mut full = (f64::INFINITY, f64::NEG_INFINITY);
let mut max_depth = 0usize;
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
while let Some((i, d)) = stack.pop()
{
let s = &self.frames[i];
full = (full.0.min(s.start(q) as f64), full.1.max(s.end(q) as f64));
max_depth = max_depth.max(d);
stack.extend(s.children.iter().map(|&c| (c, d + 1)));
}
if full.0 >= full.1
{
full = (0.0, 1.0); // empty or degenerate input
}
// The view is stored as fractions of the full range (not absolute times), so it
// stays valid when the data changes from frame to frame.
let fspan = full.1 - full.0;
let norm: (f64, f64) = ui.data_mut(|d| d.get_temp(id)).unwrap_or((0.0, 1.0));
let mut view = (full.0 + norm.0 * fspan, full.0 + norm.1 * fspan);
if !(view.1 > view.0) || !view.0.is_finite() || !view.1.is_finite()
{
view = full;
}
let size = vec2(ui.available_width(), (max_depth + 1) as f32 * row_height);
let (resp, painter) = ui.allocate_painter(size, egui::Sense::click_and_drag());
let rect = resp.rect;
let w = rect.width().max(1.0) as f64;
// --- interaction ---
let mut span = view.1 - view.0;
if resp.dragged()
{
let dt = -(resp.drag_delta().x as f64) / w * span;
view = (view.0 + dt, view.1 + dt);
}
if let Some(p) = resp.hover_pos()
{
let (zoom, scroll) = ui.input(|i| (i.zoom_delta(), i.smooth_scroll_delta.y));
let z = zoom as f64 * (scroll as f64 * 0.005).exp();
if (z - 1.0).abs() > 1e-6
{
let frac = ((p.x - rect.left()) as f64 / w).clamp(0.0, 1.0);
let t_cursor = view.0 + frac * span;
span = (span / z).clamp((full.1 - full.0) * 1e-6, (full.1 - full.0) * 10.0);
view = (t_cursor - frac * span, t_cursor + (1.0 - frac) * span);
}
}
if resp.double_clicked()
{
view = full;
}
//ui.data_mut(|d| d.insert_temp(id, view));
ui.data_mut(|d| d.insert_temp(id, ((view.0 - full.0) / fspan, (view.1 - full.0) / fspan)));
let span = view.1 - view.0;
let to_x = |t: f64| rect.left() + ((t - view.0) / span) as f32 * rect.width();
// --- drawing ---
painter.rect_filled(rect, 0.0, ui.visuals().extreme_bg_color);
let font = egui::FontId::proportional(12.0);
let hover = resp.hover_pos();
let mut hovered: Option<usize> = None;
let mut stack: Vec<(usize, usize)> = [0].iter().map(|&r| (r, 0)).collect();
while let Some((i, depth)) = stack.pop()
{
let s = &self.frames[i];
let start = s.start(q) as f64;
let end = s.end(q) as f64;
if end < view.0 || start > view.1
{
continue; // off-screen: children are inside the parent, skip them too
}
let (x0, x1) = (to_x(start).max(rect.left()), to_x(end).min(rect.right()));
if x1 - x0 < 0.5
{
continue; // too thin to see
}
let y = rect.top() + depth as f32 * row_height;
let r = egui::Rect::from_min_max(egui::pos2(x0, y), egui::pos2(x1, y + row_height))
.shrink2(vec2(0.5, 0.5));
let is_hovered = hover.is_some_and(|p| r.contains(p));
if is_hovered
{
hovered = Some(i);
}
let mut color = color_for(&s.name);
if is_hovered
{
color = color.gamma_multiply(1.15);
}
painter.rect_filled(r, 2.0, color);
if r.width() > 24.0
{
painter.with_clip_rect(r).text(
r.left_center() + vec2(3.0, 0.0),
egui::Align2::LEFT_CENTER,
&s.name,
font.clone(),
egui::Color32::BLACK,
);
}
stack.extend(s.children.iter().map(|&c| (c, depth + 1)));
}
if let Some(i) = hovered
{
let s = &self.frames[i];
let start = s.start(q) as f64;
let end = s.end(q) as f64;
resp.clone().on_hover_ui_at_pointer(|ui| {
ui.strong(s.name);
ui.label(format!("duration: {:.3}", end - start));
ui.label(format!("start: {:.3} end: {:.3}", start, end));
});
}
resp
}
}
/// Stable pastel color derived from the scope name.
fn color_for(name: &str) -> egui::Color32
{
let mut h: u32 = 2166136261; // FNV-1a
for b in name.bytes()
{
h = (h ^ b as u32).wrapping_mul(16777619);
}
egui::ecolor::Hsva::new((h % 360) as f32 / 360.0, 0.45, 0.9, 1.0).into()
}
+205
View File
@@ -0,0 +1,205 @@
use std::ops::Deref;
use wgpu::util::DeviceExt;
pub struct Buffer
{
pub label: String,
pub size: usize,
}
pub struct Group
{
pub label: &'static str,
size: Option<usize>,
pub buffers: Vec<Buffer>,
pub sub_groups: Vec<Group>,
}
impl Group
{
pub fn new(label: &'static str) -> Self
{
Self {
label,
size: None,
buffers: Vec::new(),
sub_groups: Vec::new(),
}
}
pub fn size(&self) -> usize
{
self.size.unwrap_or_else(|| {
self.buffers.iter().map(|b| b.size).sum::<usize>()
+ self.sub_groups.iter().map(Self::size).sum::<usize>()
})
}
pub fn size_mut(&mut self) -> usize
{
*self.size.get_or_insert_with(|| {
self.buffers.iter().map(|b| b.size).sum::<usize>()
+ self
.sub_groups
.iter_mut()
.map(Self::size_mut)
.sum::<usize>()
})
}
}
pub struct MemoryProfile
{
stack: Vec<Group>,
}
pub struct Device<'a>
{
device: wgpu::Device,
profile: &'a mut MemoryProfile,
}
impl<'a> Device<'a>
{
pub fn create_buffer(&mut self, desc: &wgpu::BufferDescriptor) -> wgpu::Buffer
{
let buffer = self.device.create_buffer(desc);
self.profile.add_buffer(Buffer {
label: desc.label.unwrap_or("Unnamed").into(),
size: desc.size as usize,
});
buffer
}
pub fn create_buffer_init(&mut self, desc: &wgpu::util::BufferInitDescriptor) -> wgpu::Buffer
{
let buffer = self.device.create_buffer_init(desc);
self.profile.add_buffer(Buffer {
label: desc.label.unwrap_or("Unnamed").into(),
size: desc.contents.len(),
});
buffer
}
pub fn group<'b>(&'b mut self, group_label: &'static str) -> Device<'b>
where
'a: 'b,
{
self.profile.open_group(group_label);
Device {
device: self.device.clone(),
profile: self.profile,
}
}
}
impl<'a> Drop for Device<'a>
{
fn drop(&mut self)
{
self.profile.close_group();
}
}
impl Deref for Device<'_>
{
type Target = wgpu::Device;
fn deref(&self) -> &Self::Target
{
&self.device
}
}
impl MemoryProfile
{
pub fn new(label: &'static str) -> Self
{
Self {
stack: vec![Group::new(label)],
}
}
pub fn begin(&mut self, device: &wgpu::Device) -> Device
{
Device {
device: device.clone(),
profile: self,
}
}
pub fn terminate(mut self) -> Group
{
self.stack.pop().unwrap()
}
fn open_group(&mut self, label: &'static str)
{
self.stack.push(Group::new(label));
}
fn close_group(&mut self)
{
let mut group = self.stack.pop().unwrap();
let _ = group.size_mut();
// Add it to parent if it exists
if let Some(parent) = self.stack.last_mut()
{
parent.sub_groups.push(group);
}
else
{
self.stack.push(group);
}
}
fn add_buffer(&mut self, buffer: Buffer)
{
self.stack.last_mut().unwrap().buffers.push(buffer);
}
}
use std::fmt;
impl fmt::Display for Group
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result
{
self.fmt_with_indent(f, 0)
}
}
impl Group
{
fn fmt_with_indent(&self, f: &mut fmt::Formatter<'_>, indent: usize) -> fmt::Result
{
let prefix = " ".repeat(indent);
writeln!(
f,
"{}{} ({} bytes)",
prefix,
self.label,
self.size.unwrap_or_else(|| self.size())
)?;
// Print buffers
for buffer in &self.buffers
{
writeln!(
f,
"{} ├── {} ({} bytes)",
prefix, buffer.label, buffer.size
)?;
}
// Print subgroups
for (i, group) in self.sub_groups.iter().enumerate()
{
group.fmt_with_indent(f, indent + 1)?;
}
Ok(())
}
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "vxls-terrain"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
glam.workspace = true
wgpu.workspace = true
vxls-gpu = { path = "../vxls-gpu" }
vxls-profiler = { path = "../vxls-profiler" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
+365
View File
@@ -0,0 +1,365 @@
#![feature(generic_const_exprs)]
use std::iter::FusedIterator;
use bytemuck::Pod;
use bytemuck::Zeroable;
use glam::Vec3;
use wgpu::CommandEncoder;
use wgpu::include_wgsl;
use vxls_gpu::create_multi_buffers_bind_group_layout;
use vxls_voxel_cache;
use vxls_voxel_cache::schema::StructureAnchor;
use vxls_voxel_cache::tables::FixedStructureTable;
/// A torroidal structure table for "infinite" world purposes.
/// Allows rendering a X*Y*Z block of chunks arround a position, like for example arround a player.
///
/// When the player moves, crossing a chunk boundary, chunks behind disapear, chunks in front
/// appear. The torroidal nature of the table (modulo on the coordinates) allows reusing the
/// disapearing chunks for the new chunks appearing in front.
pub struct ToroidalStructureTable
{
/// Size of the torroidal structure : how many chunks in each direction can be rendered at once
extent: (usize, usize, usize),
fixed_structure_table: FixedStructureTable,
position: Vec3,
current_offset: (isize, isize, isize),
invalidation_pass: wgpu::ComputePipeline,
}
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
struct ToroidalInvalidationImmediates
{
extent: [u32; 3],
_pad1: u32,
previous_offset: [i32; 3],
_pad2: u32,
offset: [i32; 3],
_pad3: u32,
}
impl ToroidalStructureTable
{
pub fn new(
device: &wgpu::Device,
extent: (usize, usize, usize),
initial_position: Vec3,
max_requests: usize,
producer_id: u32,
) -> Self
{
let size = extent.0 * extent.1 * extent.2;
assert!(size <= (u32::MAX as usize));
let current_offset = Self::offset_from_center(extent, initial_position);
// Initial anchor of every slot is its world position in the starting
// window. Structure ids are table-internal and start at `0..size`.
let anchors = (0..size)
.map(|slot| {
let (x, y, z) = Self::position_for_offset(extent, slot, current_offset);
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
})
.collect();
let bind_group_layout = create_multi_buffers_bind_group_layout(
device,
1,
Some("ToroidalStructureTable::bind_group_layout"),
);
let invalidation_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("ToroidalStructureTable::invalidation_pipeline_layout"),
bind_group_layouts: &[Some(&bind_group_layout)],
immediate_size: size_of::<ToroidalInvalidationImmediates>() as u32,
});
let shader_module =
device.create_shader_module(include_wgsl!("./shaders/toroidal_structure.wgsl"));
let invalidation_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("ToroidalStructureTable::invalidation_pass"),
layout: Some(&invalidation_pipeline_layout),
module: &shader_module,
entry_point: Some("invalidate_new"),
compilation_options: Default::default(),
cache: None,
});
ToroidalStructureTable {
extent,
fixed_structure_table: FixedStructureTable::new_with_anchors(
device,
size,
max_requests,
producer_id,
anchors,
),
position: initial_position,
current_offset,
invalidation_pass,
}
}
/// Moves the center position to `new_position`.
/// This requires updating the structure table to remove disapearing chunks.
///
/// Slots whose world position changed get a new anchor. Anchors that remain
/// in view keep their identity; anchors that leave are retired. The
/// invalidation pass resets the pointers of moved slots so their roots are
/// requested again.
///
/// Returns the retired anchors. The host may use them to cancel speculative
/// queue work; correctness does not depend on it because GPU insertion
/// validates the anchor/slot.
pub fn move_position(
&mut self,
queue: &wgpu::Queue,
encoder: &mut CommandEncoder,
new_position: Vec3,
) -> Vec<StructureAnchor>
{
let previous_offset = self.current_offset;
let new_offset = Self::offset_from_center(self.extent, new_position);
self.current_offset = new_offset;
self.position = new_position;
let mut retired = Vec::new();
if previous_offset != new_offset
{
let size = self.extent.0 * self.extent.1 * self.extent.2;
let new_anchors: Vec<StructureAnchor> = (0..size)
.map(|slot| {
let (x, y, z) = Self::position_for_offset(self.extent, slot, new_offset);
StructureAnchor::from_world(x as i32, y as i32, z as i32, 0)
})
.collect();
retired = self
.fixed_structure_table
.reassign_slots(queue, &new_anchors);
}
let invalidation_parameters = ToroidalInvalidationImmediates {
extent: [
self.extent.0 as u32,
self.extent.1 as u32,
self.extent.2 as u32,
],
_pad1: 0,
previous_offset: [
previous_offset.0 as i32,
previous_offset.1 as i32,
previous_offset.2 as i32,
],
_pad2: 0,
offset: [
self.current_offset.0 as i32,
self.current_offset.1 as i32,
self.current_offset.2 as i32,
],
_pad3: 0,
};
let mut invalidation_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ToroidalStructureTable::invalidation_pass"),
timestamp_writes: None,
});
invalidation_pass.set_pipeline(&self.invalidation_pass);
invalidation_pass.set_bind_group(0, self.fixed_structure_table.pointers_bind_group(), &[]);
invalidation_pass.set_immediates(0, bytemuck::bytes_of(&invalidation_parameters));
invalidation_pass.dispatch_workgroups(
self.extent.0.div_ceil(4) as u32,
self.extent.1.div_ceil(4) as u32,
self.extent.2.div_ceil(4) as u32,
);
retired
}
/// Returns the world position encoded in a table anchor.
pub fn position_for_anchor(&self, anchor: StructureAnchor) -> (isize, isize, isize)
{
let (x, y, z, _version) = anchor.world();
(x as isize, y as isize, z as isize)
}
/// Canonical table slot of the visible block's minimum corner.
///
/// The render shader uses this to advance its table slot incrementally, so
/// the ray traversal does not have to perform an integer modulo per chunk.
pub fn base_slot(&self) -> [u32; 3]
{
let (ox, oy, oz) = self.current_offset;
let (ex, ey, ez) = self.extent;
[
ox.rem_euclid(ex as isize) as u32,
oy.rem_euclid(ey as isize) as u32,
oz.rem_euclid(ez as isize) as u32,
]
}
fn position_for_offset(
extent: (usize, usize, usize),
slot: usize,
offset: (isize, isize, isize),
) -> (isize, isize, isize)
{
let (ex, ey, ez) = (extent.0 as isize, extent.1 as isize, extent.2 as isize);
let id = slot as isize;
let sx = id % ex;
let sz = (id / ex) % ez;
let sy = id / (ex * ez);
let (ox, oy, oz) = offset;
(
ox + (sx - ox).rem_euclid(ex),
oy + (sy - oy).rem_euclid(ey),
oz + (sz - oz).rem_euclid(ez),
)
}
fn offset_from_center(extent: (usize, usize, usize), position: Vec3) -> (isize, isize, isize)
{
(
position.x.floor() as isize - (extent.0 as isize / 2),
position.y.floor() as isize - (extent.1 as isize / 2),
position.z.floor() as isize - (extent.2 as isize / 2),
)
}
// Function calls through to fixed_structure_table
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
{
self.fixed_structure_table.raytrace_bind_group()
}
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
{
self.fixed_structure_table.raytrace_bind_group_layout()
}
pub fn insert<const N: usize>(
&self,
device: &wgpu::Device,
encoder: &mut vxls_profiler::ScopeEncoder<wgpu::CommandEncoder>,
insertion: &vxls_voxel_cache::insertion::CacheInsertionData<N>,
) where
[(); N * N * N]:,
{
self.fixed_structure_table
.insert(device, encoder, insertion);
}
pub fn gather_requests(
&self,
device: &wgpu::Device,
encoder: &mut vxls_profiler::ScopeEncoder<wgpu::CommandEncoder>,
request_buffer: &vxls_voxel_cache::requests::CacheRequestBuffer,
)
{
self.fixed_structure_table
.gather_requests(device, encoder, request_buffer);
}
}
impl<const N: usize> vxls_voxel_cache::CacheInvalidable<N> for ToroidalStructureTable
where
[(); N * N * N]:,
{
fn validate_insertion(
&mut self,
device: &wgpu::Device,
encoder: &mut vxls_profiler::ScopeEncoder<CommandEncoder>,
insertion: &vxls_voxel_cache::insertion::CacheInsertionData<N>,
) {
self.fixed_structure_table
.validate_insertion(device, encoder, insertion);
}
fn invalidate(
&mut self,
encoder: &mut vxls_profiler::ScopeEncoder<CommandEncoder>,
cache_evictor: &vxls_voxel_cache::eviction::CacheEvictor,
invalid_timestamp: u32,
)
{
self.fixed_structure_table
.invalidate(encoder, cache_evictor, invalid_timestamp);
}
}
pub struct CenterChunkIter
{
center_chunk: (isize, isize, isize),
extent: (usize, usize, usize),
block_corner: (isize, isize, isize),
current: usize,
length: usize,
}
impl CenterChunkIter
{
pub fn new(center_chunk: (isize, isize, isize), extent: (usize, usize, usize)) -> Self
{
let half_extent = (extent.0 / 2, extent.1 / 2, extent.2 / 2);
let block_corner = (
center_chunk.0 - half_extent.0 as isize,
center_chunk.1 - half_extent.1 as isize,
center_chunk.2 - half_extent.2 as isize,
);
Self {
center_chunk,
extent,
block_corner,
current: 0,
length: extent.0 * extent.1 * extent.2,
}
}
}
impl FusedIterator for CenterChunkIter {}
impl ExactSizeIterator for CenterChunkIter {}
impl Iterator for CenterChunkIter
{
type Item = (isize, isize, isize);
fn next(&mut self) -> Option<Self::Item>
{
if self.current >= self.length
{
None
}
else
{
let x = self.current % self.extent.0;
let y = (self.current / self.extent.0) % self.extent.1;
let z = self.current / (self.extent.0 * self.extent.1);
self.current += 1;
Some((
x as isize + self.block_corner.0,
y as isize + self.block_corner.1,
z as isize + self.block_corner.2,
))
}
}
fn size_hint(&self) -> (usize, Option<usize>)
{
let remaining = self.length - self.current;
(remaining, Some(remaining))
}
}
@@ -0,0 +1,46 @@
@group(0) @binding(0) var<storage, read_write> table_pointers: array<u32>;
struct InvalidationImmediates
{
extent: vec3<u32>,
pevious_offset: vec3<i32>,
offset: vec3<i32>,
}
var<immediate> immediates: InvalidationImmediates;
@compute
@workgroup_size(4, 4, 4)
fn invalidate_new(@builtin(global_invocation_id) gid: vec3<u32>)
{
if(any(gid >= immediates.extent))
{
return;
}
// Check whether this invocation lies within a pointer to be renewed
let igid = vec3<i32>(gid);
let previous_pos = get_position(igid, immediates.pevious_offset);
let pos = get_position(igid, immediates.offset);
if(any(previous_pos != pos))
{
// Invalidate pointer
let index = gid.x + gid.z * immediates.extent.x + gid.y * immediates.extent.x * immediates.extent.z;
table_pointers[index] = u32(1) << 31;
}
}
fn get_position(block_position: vec3<i32>, offset: vec3<i32>) -> vec3<i32>
{
return offset + imodv((block_position - offset), vec3<i32>(immediates.extent));
}
fn imod(x: i32, n: i32) -> i32 {
return ((x % n) + n) % n;
}
fn imodv(x: vec3<i32>, n: vec3<i32>) -> vec3<i32> {
return vec3<i32>(imod(x.x, n.x), imod(x.y, n.y), imod(x.z, n.z));
}
+10
View File
@@ -0,0 +1,10 @@
[package]
name = "vxls-voxel-cache"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
wgpu.workspace = true
vxls-gpu = { path = "../vxls-gpu" }
vxls-profiler = { path = "../vxls-profiler" }
+96
View File
@@ -0,0 +1,96 @@
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use vxls_profiler::memory_profiler;
use crate::layout::CacheLayout;
/// Contains instanciated gpu buffers to hold data for cache attributes
pub struct CacheAttributes<const N: usize>
{
attribute_buffers: Vec<wgpu::Buffer>,
bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
}
impl<const N: usize> CacheAttributes<N>
{
pub fn from_cache_layout(
device: &mut memory_profiler::Device,
layout: &CacheLayout,
page_count: usize,
) -> Self
{
let attribute_buffers = layout
.attributes
.iter()
.map(|attribute| {
attribute.create_buffer_profiled(
device,
N * N * N,
page_count,
BufferUsages::STORAGE,
)
})
.collect::<Vec<_>>();
let bind_group_layout = Self::create_bind_group_layout(device, layout);
let bind_group_bindings = attribute_buffers
.iter()
.map(|buffer| buffer.as_entire_buffer_binding())
.collect::<Vec<_>>();
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("CacheAttributes::bind_group"),
layout: &bind_group_layout,
entries: &[wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
}],
});
CacheAttributes {
attribute_buffers,
bind_group_layout,
bind_group,
}
}
pub fn create_bind_group_layout(device: &wgpu::Device, layout: &CacheLayout)
-> BindGroupLayout
{
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("CacheAttributes::bind_group_layout"),
entries: &[wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: Some(
std::num::NonZero::new(layout.attributes.len() as u32)
.expect("Cannot create cache attributes with no attributes"),
),
}],
})
}
pub fn bind_group_layout(&self) -> &wgpu::BindGroupLayout
{
&self.bind_group_layout
}
pub fn bind_group(&self) -> &wgpu::BindGroup
{
&self.bind_group
}
pub fn attribute_buffers(&self) -> &[Buffer]
{
&self.attribute_buffers
}
}
+230
View File
@@ -0,0 +1,230 @@
/// Contains structure and logic related to eviction logic in the cache.
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::include_wgsl;
use wgpu::util::DeviceExt;
use vxls_gpu::create_multi_buffers_bind_group;
use vxls_gpu::radix_sort;
use vxls_profiler::ScopeEncoder;
use vxls_profiler::memory_profiler;
use vxls_profiler::{self};
use crate::CacheRessources;
use crate::create_multi_buffers_bind_group_layout;
use crate::structure::CacheStructure;
/// Retains usage information about pages in the cache under the form of timestamps.
/// Produces an eviction order from which the cache can pull pages to recycle.
///
/// The list is ordered by timestamp first (least recently used first). Ties are
/// broken by depth, deepest first. This works because the timestamp pass is a
/// stable radix sort applied after a descending depth sort: pages that share a
/// timestamp keep the deepest-first order established by the depth pass.
pub struct CacheEvictor
{
page_count: usize,
/// Contains a u32 timestamp per page, so that we know when a page was last used
timestamp_pages: wgpu::Buffer,
/// Contains page indices in eviction order: least recently used first.
/// Among pages with equal timestamps, deeper pages come first.
lru_list: wgpu::Buffer,
/// When reusing pages, count of lru pages consumed
consumed_count: wgpu::Buffer,
/// To reset lru indices between insertions
reset_lru_pass: wgpu::ComputePipeline,
/// To copy corresponding timestamp values after the descending depth sort
indirect_copy_pass: wgpu::ComputePipeline,
pipelines_dispatch_count: u32,
// For external passes
bind_group_layout: BindGroupLayout,
bind_group: BindGroup,
}
impl CacheEvictor
{
pub fn new(
device: &mut memory_profiler::Device,
page_count: usize,
initial_timestamp: u32,
) -> Self
{
let timestamp_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheUsage::timestamp_pages"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
contents: bytemuck::cast_slice(&vec![initial_timestamp; page_count]),
});
let lru_list = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheUsage::lru_list"),
usage: wgpu::BufferUsages::STORAGE,
size: (page_count * size_of::<u32>()) as u64,
mapped_at_creation: false,
});
let consumed_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheUsage::consumed_count"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::bytes_of(&0u32),
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&timestamp_pages, &lru_list, &consumed_count],
Some("CacheEvictor::bind_group"),
);
let pipelines_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheEvictor::reset_lru_list_pipeline_layout"),
bind_group_layouts: &[
Some(&bind_group_layout),
Some(&CacheStructure::<1>::create_bind_group_layout(device)),
Some(&CacheRessources::<1>::create_scratch_buffer_bind_group_layout(device)),
],
immediate_size: 0,
});
let shader_module = device.create_shader_module(include_wgsl!("./shaders/eviction.wgsl"));
let reset_lru_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheEvictor::reset_lru_pass"),
layout: Some(&pipelines_layout),
module: &shader_module,
entry_point: Some("reset_lru_list"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let indirect_copy_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheEvictor::indirect_copy_pass"),
layout: Some(&pipelines_layout),
module: &shader_module,
entry_point: Some("indirect_copy"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
Self {
page_count,
timestamp_pages,
lru_list,
consumed_count,
reset_lru_pass,
indirect_copy_pass,
pipelines_dispatch_count: page_count.div_ceil(256) as u32,
bind_group_layout,
bind_group,
}
}
pub fn prepare_eviction_list<const N: usize>(
&self,
device: &wgpu::Device,
ressources: &CacheRessources<N>,
structure: &CacheStructure<N>,
encoder: &mut ScopeEncoder<CommandEncoder>,
) where
[(); N * N * N]:,
{
vxls_profiler::begin_scope!(encoder, "CacheEvictor::prepare_eviction_list");
// Reset lru list
{
let mut reset_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheEvictor::reset_pass"),
timestamp_writes: None,
});
reset_pass.set_bind_group(0, Some(&self.bind_group), &[]);
reset_pass.set_bind_group(1, Some(structure.bind_group()), &[]);
reset_pass.set_bind_group(2, Some(ressources.scratch_buffer_bind_group()), &[]);
reset_pass.set_pipeline(&self.reset_lru_pass);
reset_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
}
// First sort nodes by depth, deepest first. This is the tie-breaker:
// the timestamp sort below is stable, so it preserves this order for
// pages that share a timestamp.
//
// Consuming the list in order then reuses the deepest pages first among
// equal timestamps. Since a page's resident children are deeper, they
// appear earlier in the list and are reused first (provided their
// timestamp is equal or older), instead of being orphaned when the
// parent is recycled.
{
vxls_profiler::begin_scope!(encoder, "depth radix");
encoder.copy_buffer_to_buffer(
structure.depth_pages(),
0,
&ressources.scratch_buffer,
0,
structure.depth_pages().size(),
);
ressources.radix_sorter.sort(
device,
&ressources.scratch_buffer,
&self.lru_list,
None,
Some(self.page_count),
&mut encoder,
radix_sort::RadixSortDirection::Descending,
);
}
{
vxls_profiler::begin_scope!(encoder, "indirect copy");
let mut indirect_copy_pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheEvictor::indirect_copy_pass"),
timestamp_writes: None,
});
indirect_copy_pass.set_bind_group(0, Some(&self.bind_group), &[]);
indirect_copy_pass.set_bind_group(1, Some(structure.bind_group()), &[]);
indirect_copy_pass.set_bind_group(2, Some(ressources.scratch_buffer_bind_group()), &[]);
indirect_copy_pass.set_pipeline(&self.indirect_copy_pass);
indirect_copy_pass.dispatch_workgroups(self.pipelines_dispatch_count, 1, 1);
}
// Then sort by timestamp, oldest first. The radix sort is stable, so
// equal timestamps retain the deepest-first order from the depth sort.
// The resulting list is LRU-first with deepest-first ties.
{
vxls_profiler::begin_scope!(encoder, "timestamp radix");
ressources.radix_sorter.sort(
device,
&ressources.scratch_buffer,
&self.lru_list,
None,
Some(self.page_count),
&mut encoder,
radix_sort::RadixSortDirection::Ascending,
);
}
}
pub fn bind_group(&self) -> &BindGroup
{
&self.bind_group
}
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
{
create_multi_buffers_bind_group_layout(device, 3, Some("CacheEvictor::bind_group_layout"))
}
pub fn timestamp_pages_buffer(&self) -> &wgpu::Buffer
{
&self.timestamp_pages
}
}
+299
View File
@@ -0,0 +1,299 @@
use std::num::NonZero;
use wgpu::BindGroupLayout;
use wgpu::BufferUsages;
use wgpu::ShaderStages;
use crate::layout::CacheLayout;
use crate::schema::InsertionInformation;
use crate::schema::InsertionParent;
use crate::schema::LocationPage;
/// Data to be inserted in a cache insertion operation
pub struct CacheInsertionData<const N: usize>
where
[(); N * N * N]:,
{
/// The amount of pages to insert this structure can hold
max_page_count: usize,
/// Amount of pages that the structure actually contains
page_count_buffer: wgpu::Buffer,
/// Information about inserted pages : dense array of [`InsertionInformation<N>`] structs
insertion_information: wgpu::Buffer,
/// Location of the new nodes : dense array of [`LocationPage`] structs
location_pages: wgpu::Buffer,
/// Contains the attributes to import in the cache.
attributes: Vec<wgpu::Buffer>,
/// Contains the indicies of the page in which the data was written
destination_indices: wgpu::Buffer,
/// Parent/attachment information for every entry : dense array of [`InsertionParent`]
insertion_parents: wgpu::Buffer,
/// Indices of the entries that passed validation, written by the validation pass
valid_indices: wgpu::Buffer,
/// Amount of entries written to [`Self::valid_indices`]
valid_count: wgpu::Buffer,
bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
bind_group_no_attributes: wgpu::BindGroup,
}
impl<const N: usize> CacheInsertionData<N>
where
[(); N * N * N]:,
{
pub fn new(device: &wgpu::Device, max_page_count: usize, layout: &CacheLayout) -> Self
{
let page_count_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::page_count_buffer"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: size_of::<u32>() as u64,
});
let insertion_information = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::insertion_information"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<InsertionInformation<N>>() * max_page_count) as u64,
});
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::location_pages"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<LocationPage>() * max_page_count) as u64,
});
let destination_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::destination_indices"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<u32>() * max_page_count) as u64,
});
let insertion_parents = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::insertion_parents"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: (size_of::<InsertionParent>() * max_page_count) as u64,
});
let valid_indices = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::valid_indices"),
usage: wgpu::BufferUsages::STORAGE,
mapped_at_creation: false,
size: (size_of::<u32>() * max_page_count) as u64,
});
let valid_count = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheInsertionData::valid_count"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
size: size_of::<u32>() as u64,
});
let attributes = layout
.attributes
.iter()
.map(|attribute| {
attribute.create_buffer(
device,
N * N * N,
max_page_count,
BufferUsages::STORAGE | BufferUsages::COPY_DST,
)
})
.collect::<Vec<_>>();
let bind_group_bindings = attributes
.iter()
.map(|buffer| buffer.as_entire_buffer_binding())
.collect::<Vec<_>>();
let mut entries = vec![
wgpu::BindGroupEntry {
binding: 0,
resource: page_count_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: insertion_information.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: location_pages.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: destination_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: insertion_parents.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 5,
resource: valid_indices.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 6,
resource: valid_count.as_entire_binding(),
},
];
let bind_group_layout_no_attributes = Self::create_bind_group_layout(device, None);
let bind_group_no_attributes = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("CacheInsertionData::bind_group_no_attributes"),
layout: &bind_group_layout_no_attributes,
entries: &entries,
});
entries.push(wgpu::BindGroupEntry {
binding: 7,
resource: wgpu::BindingResource::BufferArray(&bind_group_bindings),
});
let bind_group_layout = Self::create_bind_group_layout(device, Some(layout));
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("CacheInsertionData::bind_group"),
layout: &bind_group_layout,
entries: &entries,
});
Self {
page_count_buffer,
max_page_count,
insertion_information,
location_pages,
destination_indices,
insertion_parents,
valid_indices,
valid_count,
attributes,
bind_group_layout,
bind_group,
bind_group_no_attributes,
}
}
/// Creates a bindgroup layout to bind the insertion data :
/// - Page count buffer (u32)
/// - Insertion information
/// - Location pages
/// - Destination indicies
/// - (Optional) attributes
///
/// An applcation that does not need the the attributes can pass `None` to layout.
/// It can then use [`CacheInsertionData::<_>::bind_group_no_attributes(...)`] to get the
/// corresponding bind group, otherwise use [`CacheInsertionData::<_>::bind_group(...)`]
///
pub fn create_bind_group_layout(
device: &wgpu::Device,
layout: Option<&CacheLayout>,
) -> BindGroupLayout
{
let storage_entry = |binding: u32| wgpu::BindGroupLayoutEntry {
binding,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
let mut entries = vec![
storage_entry(0), // page count
storage_entry(1), // insertion information
storage_entry(2), // location pages
storage_entry(3), // destination indices
storage_entry(4), // insertion parents
storage_entry(5), // valid indices
storage_entry(6), // valid count
];
if let Some(layout) = layout
{
entries.push(wgpu::BindGroupLayoutEntry {
binding: 7,
visibility: ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: Some(NonZero::new(layout.attributes.len() as u32).unwrap()),
});
}
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("CacheInsertionData::bind_group_layout"),
entries: &entries,
})
}
pub fn bind_group(&self) -> &wgpu::BindGroup
{
&self.bind_group
}
pub fn bind_group_no_attributes(&self) -> &wgpu::BindGroup
{
&self.bind_group_no_attributes
}
pub fn page_count(&self) -> usize
{
self.max_page_count
}
pub fn page_count_buffer(&self) -> &wgpu::Buffer
{
&self.page_count_buffer
}
pub fn insertion_information_buffer(&self) -> &wgpu::Buffer
{
&self.insertion_information
}
pub fn location_pages_buffer(&self) -> &wgpu::Buffer
{
&self.location_pages
}
pub fn destination_indices_buffer(&self) -> &wgpu::Buffer
{
&self.destination_indices
}
pub fn insertion_parents_buffer(&self) -> &wgpu::Buffer
{
&self.insertion_parents
}
pub fn valid_indices_buffer(&self) -> &wgpu::Buffer
{
&self.valid_indices
}
pub fn valid_count_buffer(&self) -> &wgpu::Buffer
{
&self.valid_count
}
pub fn attributes_buffers(&self) -> &[wgpu::Buffer]
{
&self.attributes
}
}
+153
View File
@@ -0,0 +1,153 @@
use wgpu::BufferUsages;
use vxls_profiler::memory_profiler;
/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum CacheAttributeInit
{
/// Attribute is external : it is copied from the insertion operation
External,
/// Attribute will not be touched by the cache mechanism. It is left to the discrecy of the
/// cache user.
///
/// Some applications requires pieces of data into the resident data of the cache that are
/// computed on the fly : e.g. global illumination
DontTouch,
}
/// Describes an attribute of a [`VoxelCache`]
#[derive(Clone, Copy, Debug)]
pub struct CacheAttribute
{
pub label: Option<&'static str>,
pub word_count: u32,
pub init: CacheAttributeInit,
}
impl CacheAttribute
{
pub fn create_buffer_profiled(
&self,
device: &mut memory_profiler::Device,
child_count: usize,
page_count: usize,
usage: wgpu::BufferUsages,
) -> wgpu::Buffer
{
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(
format!(
"VoxelCacheAttribute ({}) {} word(s)",
self.label.unwrap_or("no-name"),
self.word_count
)
.as_str(),
),
size: (self.word_count as usize * page_count * child_count * size_of::<u32>()) as u64,
usage,
mapped_at_creation: false,
})
}
/// Creates the wgpu buffer necessary to store this attribute in the cache
pub fn create_buffer(
&self,
device: &wgpu::Device,
child_count: usize,
page_count: usize,
usage: wgpu::BufferUsages,
) -> wgpu::Buffer
{
device.create_buffer(&wgpu::BufferDescriptor {
label: Some(
format!(
"VoxelCacheAttribute ({}) {} word(s)",
self.label.unwrap_or("no-name"),
self.word_count
)
.as_str(),
),
size: (self.word_count as usize * page_count * child_count * size_of::<u32>()) as u64,
usage,
mapped_at_creation: false,
})
}
}
#[derive(Clone, Default)]
pub struct CacheLayout
{
pub(super) attributes: Vec<CacheAttribute>,
}
impl CacheLayout
{
/// Adds a new [`VoxelCacheAttribute`] in the layout
///
/// Attributes are added starting from 0 counting up
///
/// Returns the index of the new added attirbute
pub fn add_attribute(&mut self, attribute: CacheAttribute) -> usize
{
let index = self.attributes.len();
self.attributes.push(attribute);
index
}
/// Produces a wgsl declaration describing this layout :
///
/// ```wgsl
///
/// const ATTRIBUTE_COUNT: u32 = /* attribute count */;
/// const ATTRIBUTE_WORD_COUNTS: array<u32, ...> = {
/// /* word count for attribute 0 */,
/// /* word count for attribute 1 */,
/// ...
/// };
///
/// const ATTRIBUTE_COPY: array<bool, ...> = {
/// /* external? for attribute 0 */,
/// /* external? for attribute 1 */,
/// ...
/// };
///
/// ```
pub fn wgsl_layout_decl(&self) -> String
{
let mut decl = String::new();
decl += &format!("const ATTRIBUTE_COUNT: u32 = {};", self.attributes.len());
// Word counts
decl += &format!(
"const ATTRIBUTE_WORD_COUNTS: array<u32, {}> = array<u32, {}>(",
self.attributes.len(),
self.attributes.len()
);
for attribute in self.attributes.iter()
{
decl += &format!(" {},", attribute.word_count);
}
decl += ");";
// Copy
decl += &format!(
"const ATTRIBUTE_COPY: array<bool, {}> = array<bool, {}>(",
self.attributes.len(),
self.attributes.len()
);
for attribute in self.attributes.iter()
{
decl += &format!(" {},", attribute.init == CacheAttributeInit::External);
}
decl += ");";
decl
}
}
+451
View File
@@ -0,0 +1,451 @@
#![feature(generic_const_exprs)]
use std::num::NonZero;
use wgpu::CommandEncoder;
use wgpu::Device;
use vxls_gpu::create_multi_buffers_bg_bg_layout;
use vxls_gpu::create_multi_buffers_bind_group_layout;
use vxls_gpu::radix_sort::RadixSorter;
use vxls_profiler;
use vxls_profiler::ScopeEncoder;
use vxls_profiler::memory_profiler;
use vxls_profiler::memory_profiler::MemoryProfile;
use crate::attributes::CacheAttributes;
use crate::eviction::CacheEvictor;
use crate::insertion::CacheInsertionData;
use crate::pipelines::CacheInsertionPass;
use crate::pipelines::CacheInvalidationPass;
use crate::pipelines::WritePointersPass;
use crate::pipelines::WriteRequestsPass;
use crate::requests::CacheRequestBuffer;
use crate::requests::CacheRequestHandler;
use crate::structure::CacheStructure;
pub mod attributes;
pub mod eviction;
pub mod insertion;
pub mod layout;
pub mod pipelines;
pub mod requests;
pub mod schema;
pub mod structure;
pub mod tables;
pub use layout::CacheAttribute;
pub use layout::CacheAttributeInit;
pub use layout::CacheLayout;
/// Stores some ressources that can be reused throughout the modules of the cache
struct CacheRessources<const N: usize>
{
scratch_buffer: wgpu::Buffer,
scratch_buffer_bind_group: wgpu::BindGroup,
radix_sorter: RadixSorter,
}
impl<const N: usize> CacheRessources<N>
{
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
{
let scratch_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheRessources::scratch_buffer"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
size: (size_of::<u32>() * page_count * N * N * N) as u64,
mapped_at_creation: false,
});
let radix_sorter = RadixSorter::new(device, page_count * N * N * N);
let (_, scratch_buffer_bind_group) = create_multi_buffers_bg_bg_layout(
device,
&[&scratch_buffer],
Some("CacheRessources::scratch_buffer_bind_group"),
);
Self {
scratch_buffer,
scratch_buffer_bind_group,
radix_sorter,
}
}
pub fn create_scratch_buffer_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
create_multi_buffers_bind_group_layout(
device,
1,
Some("CacheRessources::scratch_buffer_bind_group_layout"),
)
}
pub fn scratch_buffer_bind_group(&self) -> &wgpu::BindGroup
{
&self.scratch_buffer_bind_group
}
}
pub struct VoxelCache<const N: usize>
where
[(); N * N * N]:,
{
page_count: usize,
structure: CacheStructure<N>,
attributes: CacheAttributes<N>,
request_handler: CacheRequestHandler<N>,
evictor: CacheEvictor,
common_ressources: CacheRessources<N>,
// Operations
write_requests_pass: WriteRequestsPass<N>,
cache_insertion_pass: CacheInsertionPass<N>,
cache_invalidation_pass: CacheInvalidationPass<N>,
write_pointers_pass: WritePointersPass<N>,
// Raytracing
raytrace_bind_group_layout: wgpu::BindGroupLayout,
raytrace_bind_group: wgpu::BindGroup,
frame_timestamp: u32,
}
pub trait CacheInvalidable<const N: usize>
where
[(); N * N * N]:,
{
fn invalidate(
&mut self,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_evictor: &CacheEvictor,
invalid_timestamp: u32,
);
/// Validates an external insertion batch against the structure table and
/// compacts the valid entries before the cache allocates pages for them.
fn validate_insertion(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertion: &CacheInsertionData<N>,
);
}
pub enum VoxelCacheInsertion<'a, const N: usize>
where
[(); N * N * N]:,
{
ExternalRequest(&'a CacheInsertionData<N>, &'a mut dyn CacheInvalidable<N>),
InternalRequest(&'a CacheInsertionData<N>),
}
impl<const N: usize> VoxelCache<N>
where
[(); N * N * N]:,
{
pub fn new(
device: &Device,
page_count: usize,
max_requests: usize,
layout: &CacheLayout,
) -> Self
{
let mut cache_memory_profile = MemoryProfile::new("VoxelCache");
let mut mem_device = cache_memory_profile.begin(device);
let structure = CacheStructure::new(&mut mem_device.group("CacheStructure"), page_count);
let attributes = CacheAttributes::from_cache_layout(
&mut mem_device.group("CacheAttributes"),
layout,
page_count,
);
let request_handler = CacheRequestHandler::new(
&mut mem_device.group("CacheRequestHandler"),
page_count,
max_requests as u32,
);
let evictor = CacheEvictor::new(&mut mem_device.group("CacheEvictor"), page_count, 0u32);
let common_ressources =
CacheRessources::new(&mut mem_device.group("CacheRessources"), page_count);
let write_requests_pass = WriteRequestsPass::new(device, page_count, layout);
let cache_insertion_pass = CacheInsertionPass::new(device, page_count, layout);
let cache_invalidation_pass = CacheInvalidationPass::new(device, page_count, layout);
let write_pointers_pass = WritePointersPass::new(device, page_count, layout);
let (raytrace_bind_group_layout, raytrace_bind_group) = Self::create_raytrace_bind_group(
device,
&structure,
&attributes,
&request_handler,
&evictor,
);
drop(mem_device);
let mut root_group = cache_memory_profile.terminate();
println!("{}", root_group);
Self {
page_count,
structure,
attributes,
request_handler,
evictor,
common_ressources,
write_requests_pass,
cache_insertion_pass,
cache_invalidation_pass,
write_pointers_pass,
raytrace_bind_group_layout,
raytrace_bind_group,
frame_timestamp: 0,
}
}
pub fn gather_requests(
&self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
request_buffer: &CacheRequestBuffer,
)
{
vxls_profiler::begin_scope!(encoder, "gather_requests");
self.request_handler.sort_requests(
device,
&self.common_ressources,
&mut encoder,
request_buffer.max_requests as u32,
);
self.write_requests_pass.encode(
&mut encoder,
device,
&self.structure,
&self.request_handler,
request_buffer,
);
self.request_handler.reset(&mut encoder);
}
/// Inserts new pages into the cache. Two insertion modes are available:
///
/// External: Inserts brand new pages, regardless of the misses in the cache. This can be used
/// to bring external requests into the cache
///
/// Internal: This is the response to requests emited inside the cache (gotten through the
/// gather requests method)
pub fn insert(
&mut self,
device: &Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
insertions: &mut [&mut VoxelCacheInsertion<N>],
)
{
vxls_profiler::begin_scope!(encoder, "insertion");
let new_timestamp = self.frame_timestamp + 1;
self.evictor.prepare_eviction_list(
device,
&self.common_ressources,
&self.structure,
&mut encoder,
);
// Validate everything before allocating any page, so stale insertions
// can never consume a recycled page.
for insertion in insertions.iter_mut()
{
match insertion
{
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, invalidable) =>
{
invalidable.validate_insertion(device, &mut encoder, cache_insertion_data);
}
VoxelCacheInsertion::InternalRequest(cache_insertion_data) =>
{
self.cache_insertion_pass.encode_validation(
device,
&mut encoder,
&self.attributes,
&self.structure,
cache_insertion_data,
&self.evictor,
);
}
}
}
for insertion in insertions.iter()
{
match insertion
{
VoxelCacheInsertion::ExternalRequest(cache_insertion_data, _)
| VoxelCacheInsertion::InternalRequest(cache_insertion_data) =>
{
self.cache_insertion_pass.encode(
device,
&mut encoder,
&self.attributes,
&self.structure,
cache_insertion_data,
&self.evictor,
new_timestamp,
);
}
}
}
// Invalidate external structures pointing inside the cache
for insertion in insertions.iter_mut()
{
if let VoxelCacheInsertion::ExternalRequest(_, invalidable) = insertion
{
invalidable.invalidate(&mut encoder, &self.evictor, new_timestamp);
}
}
// Invalidate cache pages
self.cache_invalidation_pass.encode(
&mut encoder,
&self.structure,
&self.evictor,
new_timestamp,
);
// Write internal requests pointers
for insertion in insertions.iter_mut()
{
if let VoxelCacheInsertion::InternalRequest(insertion) = insertion
{
self.write_pointers_pass.encode(
&mut encoder,
device,
&self.structure,
insertion,
);
}
}
// Proceed to new frame
self.frame_timestamp = new_timestamp;
}
pub fn current_timestamp(&self) -> u32
{
self.frame_timestamp
}
fn create_raytrace_bind_group(
device: &wgpu::Device,
structure: &CacheStructure<N>,
attributes: &CacheAttributes<N>,
request_handler: &CacheRequestHandler<N>,
evictor: &CacheEvictor,
) -> (wgpu::BindGroupLayout, wgpu::BindGroup)
{
let attribute_count = attributes.attribute_buffers().len();
let bind_group_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("VoxelCache::raytrace_bind_group_layout"),
entries: &[
// Structure pointers
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Request pages
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Usage pages
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
// Attributes
wgpu::BindGroupLayoutEntry {
binding: 3,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: false },
has_dynamic_offset: false,
min_binding_size: None,
},
count: Some(
NonZero::new(attribute_count as u32)
.expect("Null amount of cache attributes."),
),
},
],
});
let attributes_bindings = attributes
.attribute_buffers()
.iter()
.map(|buffer| buffer.as_entire_buffer_binding())
.collect::<Vec<_>>();
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("VoxelCache::raytrace_bind_group"),
layout: &bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: structure.pointer_pages().as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: request_handler.request_pages_buffer().as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: evictor.timestamp_pages_buffer().as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: wgpu::BindingResource::BufferArray(&attributes_bindings),
},
],
});
(bind_group_layout, bind_group)
}
pub fn raytrace_bind_group_layout(&self) -> &wgpu::BindGroupLayout
{
&self.raytrace_bind_group_layout
}
pub fn raytrace_bind_group(&self) -> &wgpu::BindGroup
{
&self.raytrace_bind_group
}
// For debugging
pub fn usage_timestamps(&self) -> &wgpu::Buffer
{
self.evictor.timestamp_pages_buffer()
}
}
+515
View File
@@ -0,0 +1,515 @@
use wgpu::BufferUsages;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::util::DeviceExt;
use vxls_gpu::indirect_buffer::IndirectBuffer1D;
use vxls_profiler;
use vxls_profiler::ScopeEncoder;
use crate::attributes::CacheAttributes;
use crate::create_multi_buffers_bg_bg_layout;
use crate::eviction::CacheEvictor;
use crate::insertion::CacheInsertionData;
use crate::layout::CacheLayout;
use crate::requests::CacheRequestBuffer;
use crate::requests::CacheRequestHandler;
use crate::structure::CacheStructure;
macro_rules! programmatic_common_wgsl {
($children_count:ident, $page_count:ident, $cache_layout:ident) => {
format!(
"
const CHILDREN_COUNT: u32 = u32({});
const PAGE_COUNT: u32 = u32({});
// Cache layout
{}
",
$children_count * $children_count * $children_count,
$page_count,
$cache_layout.wgsl_layout_decl()
)
.as_str()
};
}
macro_rules! include_cache_wgsl {
($path:literal, $children_count:ident, $page_count:ident, $cache_layout:ident) => {{
let mut full_shader = String::new();
full_shader.push_str(include_str!("./shaders/common.wgsl"));
full_shader.push_str(programmatic_common_wgsl!(
$children_count,
$page_count,
$cache_layout
));
full_shader.push_str(include_str!("./shaders/cache_common.wgsl"));
full_shader.push_str(include_str!($path));
wgpu::ShaderModuleDescriptor {
label: Some($path),
source: wgpu::ShaderSource::Wgsl(full_shader.into()),
}
}};
}
pub(super) use include_cache_wgsl;
pub struct WriteRequestsPass<const N: usize>
where
[(); N * N * N]:,
{
pipeline: ComputePipeline,
// To compute indirect dispatch count from request count
indirect_buffer: IndirectBuffer1D,
}
impl<const N: usize> WriteRequestsPass<N>
where
[(); N * N * N]:,
{
pub fn new(device: &Device, page_count: usize, cache_layout: &CacheLayout) -> Self
{
// Binds
// - structure
// - request buffer
let bindings = [
// To get the location information
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
// To get which pages have had a request issued on them
Some(&CacheRequestHandler::<N>::create_bind_group_layout(device)),
// To write the request information to target
Some(&CacheRequestBuffer::create_bind_group_layout(device)),
];
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("WriteRequestsPass::pipeline_layout"),
bind_group_layouts: &bindings,
immediate_size: 0,
});
let shader_module = device.create_shader_module(include_cache_wgsl!(
"./shaders/write_requests.wgsl",
N,
page_count,
cache_layout
));
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("WriteRequestsPass::pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("write_requests"),
compilation_options: Default::default(),
cache: None,
});
Self {
pipeline,
indirect_buffer: IndirectBuffer1D::new(device),
}
}
pub fn encode(
&self,
encoder: &mut ScopeEncoder<CommandEncoder>,
device: &Device,
cache_structure: &CacheStructure<N>,
cache_request_handler: &CacheRequestHandler<N>,
target_request_buffer: &CacheRequestBuffer,
)
{
vxls_profiler::begin_scope!(encoder, "WriteRequests");
let indirect_dispatch_buffer = self.indirect_buffer.workgroup_count(
device,
&mut encoder,
cache_request_handler.request_count_buffer(),
256,
);
encoder.copy_buffer_to_buffer(
cache_request_handler.request_count_buffer(),
0,
&target_request_buffer.request_count,
0,
cache_request_handler.request_count_buffer().size(),
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("WriteRequestsPass::pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
pass.set_bind_group(1, cache_request_handler.bind_group(), &[]);
pass.set_bind_group(2, target_request_buffer.bind_group(), &[]);
pass.dispatch_workgroups_indirect(indirect_dispatch_buffer, 0);
}
}
/// Inserts new pages in the cache
pub struct CacheInsertionPass<const N: usize>
where
[(); N * N * N]:,
{
/// Copies new pages into cache using LRU order
write_pipeline: ComputePipeline,
/// Validates internal insertions and compacts their indices
validate_internal_pipeline: ComputePipeline,
/// u32 buffer containing amount of inserted data of current pass
inserted_count: wgpu::Buffer,
inserted_count_bind_group: wgpu::BindGroup,
/// Reports the consumed pages to the evictor by incrementing the consumed pages count
consume_pipeline: ComputePipeline,
/// To dispatch the correct amount of writters depending on the amout of pages to insert
indirect_dispatcher: IndirectBuffer1D,
}
impl<const N: usize> CacheInsertionPass<N>
where
[(); N * N * N]:,
{
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
{
// Binds
// - structure
// - request buffer
let inserted_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheInsertionPass::inserted_count"),
contents: bytemuck::bytes_of(&0u32),
usage: BufferUsages::STORAGE,
});
let (inserted_count_bind_group_layout, inserted_count_bind_group) =
create_multi_buffers_bg_bg_layout(
device,
&[&inserted_count],
Some("CacheInsertionPass::inserted_count_bind_group"),
);
let bindings = [
// To write the new attributes
Some(&CacheAttributes::<N>::create_bind_group_layout(
device, layout,
)),
// To write the new locations, pointers
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
// New incoming attributes
Some(&CacheInsertionData::<N>::create_bind_group_layout(
device,
Some(layout),
)),
// To get recyclable pages, and mark pages dirty
Some(&CacheEvictor::create_bind_group_layout(device)),
Some(&inserted_count_bind_group_layout),
];
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheInsertionPass::pipeline_layout"),
bind_group_layouts: &bindings,
// To pass the new timestamp
immediate_size: size_of::<u32>() as u32,
});
let shader_module = device.create_shader_module(include_cache_wgsl!(
"./shaders/insertion.wgsl",
N,
page_count,
layout
));
let write_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheInsertionPass::write_pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("insertion"),
compilation_options: Default::default(),
cache: None,
});
let consume_pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheInsertionPass::consume_pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("consume"),
compilation_options: Default::default(),
cache: None,
});
let validate_internal_pipeline =
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheInsertionPass::validate_internal_pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("validate_internal"),
compilation_options: Default::default(),
cache: None,
});
Self {
write_pipeline,
validate_internal_pipeline,
consume_pipeline,
inserted_count,
inserted_count_bind_group,
indirect_dispatcher: IndirectBuffer1D::new(device),
}
}
/// Validates internal insertions and compacts them into the insertion data's
/// `valid_indices` buffer.
///
/// External roots are validated by the structure table that requested them.
#[allow(clippy::too_many_arguments)]
pub fn encode_validation(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_attributes: &CacheAttributes<N>,
cache_structure: &CacheStructure<N>,
insertion_data: &CacheInsertionData<N>,
cache_evictor: &CacheEvictor,
)
{
vxls_profiler::begin_scope!(encoder, "PageInsertionValidation");
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
device,
&mut encoder,
insertion_data.page_count_buffer(),
256,
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheInsertionPass::validation_pass"),
timestamp_writes: None,
});
pass.set_bind_group(0, cache_attributes.bind_group(), &[]);
pass.set_bind_group(1, cache_structure.bind_group(), &[]);
pass.set_bind_group(2, insertion_data.bind_group(), &[]);
pass.set_bind_group(3, cache_evictor.bind_group(), &[]);
pass.set_bind_group(4, &self.inserted_count_bind_group, &[]);
pass.set_pipeline(&self.validate_internal_pipeline);
pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0);
}
#[allow(clippy::too_many_arguments)]
pub fn encode(
&self,
device: &wgpu::Device,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_attributes: &CacheAttributes<N>,
cache_structure: &CacheStructure<N>,
insertion_data: &CacheInsertionData<N>,
cache_evictor: &CacheEvictor,
timestamp: u32,
)
{
vxls_profiler::begin_scope!(encoder, "PageInsertion");
let indirect_write_dispatch = self.indirect_dispatcher.workgroup_count(
device,
&mut encoder,
insertion_data.page_count_buffer(),
256,
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheInsertionPass::pass"),
timestamp_writes: None,
});
pass.set_bind_group(0, cache_attributes.bind_group(), &[]);
pass.set_bind_group(1, cache_structure.bind_group(), &[]);
pass.set_bind_group(2, insertion_data.bind_group(), &[]);
pass.set_bind_group(3, cache_evictor.bind_group(), &[]);
pass.set_bind_group(4, &self.inserted_count_bind_group, &[]);
// Write pass
pass.set_pipeline(&self.write_pipeline);
pass.set_immediates(0, bytemuck::bytes_of(&timestamp));
pass.dispatch_workgroups_indirect(indirect_write_dispatch, 0);
// Consume pass
pass.set_pipeline(&self.consume_pipeline);
pass.set_immediates(0, bytemuck::bytes_of(&0u32)); // Unused
pass.dispatch_workgroups(1, 1, 1);
}
}
/// Invalidates pointers that are pointing to recycled pages
pub struct CacheInvalidationPass<const N: usize>
where
[(); N * N * N]:,
{
workgroup_count: u32,
pipeline: ComputePipeline,
}
impl<const N: usize> CacheInvalidationPass<N>
where
[(); N * N * N]:,
{
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
{
// Binds
// - structure
// - request buffer
let bindings = [
// To find where pages are pointing
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
// To read timestamp on which invalidation is marked
Some(&CacheEvictor::create_bind_group_layout(device)),
];
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheInvalidationPass::pipeline_layout"),
bind_group_layouts: &bindings,
// For setting the correct timestamp after invalidation
immediate_size: size_of::<u32>() as u32,
});
let shader_module = device.create_shader_module(include_cache_wgsl!(
"./shaders/invalidation.wgsl",
N,
page_count,
layout
));
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheInvalidationPass::pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("invalidation"),
compilation_options: Default::default(),
cache: None,
});
Self {
workgroup_count: page_count.div_ceil(256) as u32,
pipeline,
}
}
pub fn encode(
&self,
encoder: &mut ScopeEncoder<CommandEncoder>,
cache_structure: &CacheStructure<N>,
cache_evictor: &CacheEvictor,
timestamp: u32,
)
{
vxls_profiler::begin_scope!(encoder, "CacheInvalidation");
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("CacheInvalidationPass::pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
pass.set_bind_group(1, cache_evictor.bind_group(), &[]);
pass.set_immediates(0, bytemuck::bytes_of(&timestamp));
pass.dispatch_workgroups(self.workgroup_count, 1, 1);
}
}
/// Points the pages to the newly cached pages
pub struct WritePointersPass<const N: usize>
where
[(); N * N * N]:,
{
pipeline: ComputePipeline,
indirect_buffer: IndirectBuffer1D,
}
impl<const N: usize> WritePointersPass<N>
where
[(); N * N * N]:,
{
pub fn new(device: &Device, page_count: usize, layout: &CacheLayout) -> Self
{
let bindings = [
// To find where pages are pointing
Some(&CacheStructure::<N>::create_bind_group_layout(device)),
// To find where the request's response went
Some(&CacheInsertionData::<N>::create_bind_group_layout(
device,
Some(layout),
)),
];
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("WritePointersPass::pipeline_layout"),
bind_group_layouts: &bindings,
immediate_size: 0,
});
let shader_module = device.create_shader_module(include_cache_wgsl!(
"./shaders/write_pointers.wgsl",
N,
page_count,
layout
));
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("WritePointersPass::pipeline"),
layout: Some(&pipeline_layout),
module: &shader_module,
entry_point: Some("write_pointers"),
compilation_options: Default::default(),
cache: None,
});
Self {
pipeline,
indirect_buffer: IndirectBuffer1D::new(device),
}
}
pub fn encode(
&self,
encoder: &mut ScopeEncoder<CommandEncoder>,
device: &Device,
cache_structure: &CacheStructure<N>,
cache_insertion_data: &CacheInsertionData<N>,
)
{
vxls_profiler::begin_scope!(encoder, "WritePointers");
let indirect_buffer = self.indirect_buffer.workgroup_count(
device,
&mut encoder,
cache_insertion_data.page_count_buffer(),
256,
);
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("WritePointersPass::pass"),
timestamp_writes: None,
});
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, cache_structure.bind_group(), &[]);
pass.set_bind_group(1, cache_insertion_data.bind_group(), &[]);
pass.dispatch_workgroups_indirect(indirect_buffer, 0);
}
}
+510
View File
@@ -0,0 +1,510 @@
use std::sync::Arc;
use std::sync::Mutex;
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::CommandEncoder;
use wgpu::ComputePipeline;
use wgpu::Device;
use wgpu::include_wgsl;
use wgpu::util::DeviceExt;
use vxls_gpu::create_multi_buffers_bind_group;
use vxls_gpu::indirect_buffer::IndirectBuffer1D;
use vxls_gpu::radix_sort::{self};
use vxls_gpu::top_k::TopKSelector;
use vxls_profiler::ScopeEncoder;
use vxls_profiler::memory_profiler;
use vxls_profiler::{self};
use crate::CacheRessources;
use crate::create_multi_buffers_bg_bg_layout;
use crate::create_multi_buffers_bind_group_layout;
use crate::schema::RequestInformation;
use crate::schema::RequestMeta;
/// Records, handles, and produces a list of requested data inside the cache
pub struct CacheRequestHandler<const N: usize>
{
/// Contains a u32 per pointer of the cache, that records an amount of request by the cache user.
/// This can then be used to prioritize request based on demand
request_counts_pages: wgpu::Buffer,
/// Ultimately contains sorted requests
sorted_requests: wgpu::Buffer,
/// Number of requests
request_count: wgpu::Buffer,
/// Number of request counts in `request_counts_pages`
element_count: u32,
/// Selects the most requested pages
top_k: TopKSelector,
/// Gathers the selected counts and indices into contiguous sort buffers
gather_pass: ComputePipeline,
gather_pass_bind_group_layout: BindGroupLayout,
gather_indirect_buffer: IndirectBuffer1D,
// Pass to reset the requests
reset_pass_bind_group: BindGroup,
reset_pass: ComputePipeline,
reset_pass_dispatch: u32,
// External bind group
bind_group_layout: BindGroupLayout,
bind_group: BindGroup,
}
/// Records requests made by the cache
pub struct CacheRequestBuffer
{
pub max_requests: usize,
/// Buffer containing the amount of requests made by the cache, under max requsets
pub request_count: wgpu::Buffer,
/// Buffer containing the requsets made by the cache, a dense array of [`voxel_cache::schema::RequestInformation`]
pub request_informations: wgpu::Buffer,
/// Buffer containing the meta information about the requests, a dense array of [`voxel_cache::schema::RequestMeta`]
request_meta: wgpu::Buffer,
bind_group_layout: wgpu::BindGroupLayout,
bind_group: wgpu::BindGroup,
}
impl<const N: usize> CacheRequestHandler<N>
{
pub fn new(device: &mut memory_profiler::Device, page_count: usize, max_selected: u32) -> Self
{
let element_count = page_count * N * N * N;
assert!(
element_count <= u32::MAX as usize,
"CacheRequestHandler: too many request pages ({element_count})"
);
let element_count = element_count as u32;
let request_counts_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheRequestHandler::request_counts_pages"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]),
});
let sorted_requests = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheRequestHandler::sorted_requests"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::cast_slice(&vec![0u32; element_count as usize]),
});
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheRequestHandler::request_count"),
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_DST
| wgpu::BufferUsages::COPY_SRC,
contents: bytemuck::bytes_of(&0u32),
});
let top_k = TopKSelector::new(device, max_selected);
let gather_pass_bind_group_layout = Self::create_gather_bind_group_layout(device);
let gather_pass_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheRequestHandler::gather_pass_pipeline_layout"),
bind_group_layouts: &[Some(&gather_pass_bind_group_layout)],
immediate_size: 0,
});
let gather_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheRequestHandler::gather_pass"),
layout: Some(&gather_pass_pipeline_layout),
module: &device.create_shader_module(include_wgsl!("./shaders/gather_requests.wgsl")),
entry_point: Some("gather_requests"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let (reset_pass_bg_layout, reset_pass_bind_group) = create_multi_buffers_bg_bg_layout(
device,
&[&request_counts_pages],
Some("CacheRequestHandler::reset_pass_bind_group"),
);
let reset_pass_pipeline_layout =
device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("CacheRequestHandler::reset_pass_pipeline_layout"),
bind_group_layouts: &[Some(&reset_pass_bg_layout)],
immediate_size: 0,
});
let reset_pass = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("CacheRequestHandler::reset_pass"),
layout: Some(&reset_pass_pipeline_layout),
module: &device.create_shader_module(include_wgsl!("./shaders/requests.wgsl")),
entry_point: Some("reset_requests"),
compilation_options: wgpu::PipelineCompilationOptions::default(),
cache: None,
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&request_count, &sorted_requests, &request_counts_pages],
Some("CacheRequestHandler::bind_group"),
);
Self {
request_counts_pages,
sorted_requests,
request_count,
element_count,
top_k,
gather_pass,
gather_pass_bind_group_layout,
gather_indirect_buffer: IndirectBuffer1D::new(device),
reset_pass_bind_group,
reset_pass,
reset_pass_dispatch: element_count.div_ceil(256),
bind_group_layout,
bind_group,
}
}
fn create_gather_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
{
let entry = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
};
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("CacheRequestHandler::gather_pass_bind_group_layout"),
entries: &[
entry(0, true), // requests
entry(1, true), // selected_indices
entry(2, true), // selected_count
entry(3, false), // keys
entry(4, false), // values
],
})
}
/// Sorts the requests currently held by the request handler in order to process them.
///
/// Uses both the sorter and the scratch buffer in the ressources
///
/// The `request_count` buffer will contain the amount of request produced this time.
pub fn sort_requests(
&self,
device: &wgpu::Device,
ressources: &CacheRessources<N>,
encoder: &mut ScopeEncoder<CommandEncoder>,
k: u32,
)
{
vxls_profiler::begin_scope!(encoder, "RequestHandler::sort_requests");
// Select the most requested pages.
{
vxls_profiler::begin_scope!(encoder, "top_k");
self.top_k.select(
device,
&mut encoder,
&self.request_counts_pages,
self.element_count,
k,
);
}
// Gather the selected counts and indices into contiguous sort buffers.
{
vxls_profiler::begin_scope!(encoder, "gather");
let gather_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("CacheRequestHandler::gather_bind_group"),
layout: &self.gather_pass_bind_group_layout,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: self.request_counts_pages.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 1,
resource: self.top_k.selected_indices_buffer().as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 2,
resource: self.top_k.selected_count_buffer().as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 3,
resource: ressources.scratch_buffer.as_entire_binding(),
},
wgpu::BindGroupEntry {
binding: 4,
resource: self.sorted_requests.as_entire_binding(),
},
],
});
let gather_dispatch = self.gather_indirect_buffer.workgroup_count(
device,
&mut encoder,
self.top_k.selected_count_buffer(),
256,
);
let mut compute_pass = encoder.begin_profiled_compute_pass("gather");
compute_pass.set_pipeline(&self.gather_pass);
compute_pass.set_bind_group(0, &gather_bind_group, &[]);
compute_pass.dispatch_workgroups_indirect(gather_dispatch, 0);
}
// Sort the selected requests by descending request count. The scratch
// buffer holds the keys (counts) and `sorted_requests` the values
// (indices). `selected_count` is the indirect element count.
{
vxls_profiler::begin_scope!(encoder, "radix");
ressources.radix_sorter.sort(
device,
&ressources.scratch_buffer,
&self.sorted_requests,
Some(self.top_k.selected_count_buffer()),
None,
&mut encoder,
radix_sort::RadixSortDirection::Descending,
);
}
// Publish the amount of selected requests for downstream passes.
encoder.copy_buffer_to_buffer(
self.top_k.selected_count_buffer(),
0,
&self.request_count,
0,
size_of::<u32>() as u64,
);
}
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
{
create_multi_buffers_bind_group_layout(
device,
3,
Some("CacheRequestHandler::bind_group_layout"),
)
}
pub fn bind_group(&self) -> &BindGroup
{
&self.bind_group
}
pub fn request_count_buffer(&self) -> &wgpu::Buffer
{
&self.request_count
}
pub fn request_pages_buffer(&self) -> &wgpu::Buffer
{
&self.request_counts_pages
}
/// Resets the RequestHandlers request buffer for a next cache usage.
pub fn reset(&self, encoder: &mut ScopeEncoder<CommandEncoder>)
{
let mut compute_pass = encoder.begin_profiled_compute_pass("CacheRequestHandler::reset");
compute_pass.set_pipeline(&self.reset_pass);
compute_pass.set_bind_group(0, Some(&self.reset_pass_bind_group), &[]);
compute_pass.dispatch_workgroups(self.reset_pass_dispatch, 1, 1);
}
}
impl CacheRequestBuffer
{
/// Creates a request buffer that can contain at most `max_amount` requests
pub fn new(device: &Device, max_requests: usize) -> Self
{
let request_count = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheRequestBuffer::request_count"),
usage: wgpu::BufferUsages::STORAGE
| wgpu::BufferUsages::COPY_SRC
| wgpu::BufferUsages::COPY_DST,
contents: bytemuck::bytes_of(&0u32),
});
let request_informations = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheRequestBuffer::request_informations"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
size: (size_of::<RequestInformation>() * max_requests) as u64,
mapped_at_creation: false,
});
let request_meta = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheRequestBuffer::request_meta"),
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC,
size: (size_of::<RequestMeta>() * max_requests) as u64,
mapped_at_creation: false,
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&request_count, &request_informations, &request_meta],
Some("CacheRequestBuffer::bind_group"),
);
Self {
max_requests,
request_count,
request_informations,
request_meta,
bind_group_layout,
bind_group,
}
}
pub fn create_bind_group_layout(device: &Device) -> BindGroupLayout
{
create_multi_buffers_bind_group_layout(
device,
3,
Some("CacheRequestBuffer::bind_group_layout"),
)
}
pub fn bind_group(&self) -> &BindGroup
{
&self.bind_group
}
pub fn host_download_requests<
F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static,
>(
&self,
device: &Device,
queue: &wgpu::Queue,
callback: F,
)
{
// Once the three required buffers have been mapped, the requestMapState will automatically
// fire the callback
let request_map_state = Arc::new(Mutex::new(RequestMapState::new(callback)));
let request_map_state_1 = request_map_state.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.request_count.slice(..),
move |buffer| {
let mapped_buffer = buffer.expect("Could not map request buffer (count).");
let request_count: u32 = bytemuck::pod_read_unaligned(&mapped_buffer);
request_map_state_1
.lock()
.unwrap()
.set_request_count(request_count as usize);
},
);
let request_map_state_2 = request_map_state.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.request_informations.slice(..),
move |buffer| {
let mapped_buffer = buffer.expect("Could not map request buffer (informations).");
let request_infos: Vec<RequestInformation> =
bytemuck::pod_collect_to_vec(&mapped_buffer);
request_map_state_2
.lock()
.unwrap()
.set_request_infos(request_infos);
},
);
let request_map_state_3 = request_map_state.clone();
wgpu::util::DownloadBuffer::read_buffer(
device,
queue,
&self.request_meta.slice(..),
move |buffer| {
let mapped_buffer = buffer.expect("Could not map request buffer (meta).");
let request_metas: Vec<RequestMeta> =
bytemuck::pod_collect_to_vec(&mapped_buffer);
request_map_state_3
.lock()
.unwrap()
.set_request_metas(request_metas);
},
);
}
}
struct RequestMapState<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static>
{
request_count: Option<usize>,
request_infos: Option<Vec<RequestInformation>>,
request_metas: Option<Vec<RequestMeta>>,
callback: F,
}
impl<F: FnMut(&[RequestInformation], &[RequestMeta]) + Send + Sync + 'static> RequestMapState<F>
{
pub fn new(callback: F) -> Self
{
Self {
request_count: None,
request_infos: None,
request_metas: None,
callback,
}
}
fn try_callback(&mut self)
{
if let (Some(request_count), Some(request_infos), Some(request_metas)) = (
self.request_count,
&self.request_infos,
&self.request_metas,
)
{
(self.callback)(
&request_infos[0..request_count],
&request_metas[0..request_count],
)
}
}
pub fn set_request_count(&mut self, request_count: usize)
{
self.request_count = Some(request_count);
self.try_callback();
}
pub fn set_request_infos(&mut self, request_infos: Vec<RequestInformation>)
{
self.request_infos = Some(request_infos);
self.try_callback();
}
pub fn set_request_metas(&mut self, request_metas: Vec<RequestMeta>)
{
self.request_metas = Some(request_metas);
self.try_callback();
}
}
+420
View File
@@ -0,0 +1,420 @@
/// Contains definitions of the data layouts for the cache
use std::ops::BitOr;
use bytemuck::Pod;
use bytemuck::Zeroable;
/// CachePointer represents a pointer in the [`VoxelCache`]
///
/// Pointers are used in the structure pool of the cache and encodes the N-tree itself
///
/// Three states are possible :
///
/// - unsubdivisable: This children of the node cannot be subdivided further
/// - subdivisable: This children of the node can be subdivided further ...
/// - unavailable: ... but is not currently available in the cache
/// - available: ... is currently available in the cache and the pointer is valid
///
///
/// The layout is the following
///
/// - bit 31: subdivisable?
/// - bit 30: available?
/// - bit 0..29: pointer (only relevant if available is 1)
///
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct CachePointer(u32);
impl CachePointer
{
/// First option represents subdivisability
/// Second option represents availability
///
/// None -> unsubdivisable
/// Some(None) -> subdivisable not available
/// Some(Some(ptr)) -> subdivisable, available a pointer ptr
pub fn new(value: Option<Option<u32>>) -> Self
{
CachePointer(match value
{
Some(available) => match available
{
Some(pointer) =>
{
assert_eq!(
pointer >> 30,
0,
"Provided pointer is to big and does not fit in CachePointer. Last two bits must be null."
);
(1 << 31) | (1 << 30) | pointer
}
None => 1 << 31,
},
None => 0,
})
}
pub fn as_option(&self) -> Option<Option<u32>>
{
let subdivisable = (self.0 >> 31) != 0;
let available = ((self.0 >> 30) & 1) != 0;
let pointer = self.0 & 0x3FFFFFFF;
match (subdivisable, available)
{
(false, true) => panic!("Invalid cache pointer. (not subdivisable and available)"),
(false, _) if pointer != 0 =>
{
panic!("Invalid cache pointer. (non null unsubdivisable pointer)")
}
(false, _) => None,
(true, false) => Some(None),
(true, true) => Some(Some(pointer)),
}
}
}
impl From<u32> for CachePointer
{
fn from(value: u32) -> Self
{
CachePointer(value)
}
}
/// Pages encoding the structure of the trees in the cache.
/// Occupancy mask is a mask containing a bit per children, based on whether it can be skipped
/// during raytracing. This can help faster tracing, and coalesce skips.
#[derive(Debug, Clone, Copy, Zeroable)]
#[repr(C)]
pub struct StructurePage<const N: usize>
where
[(); N * N * N]:,
{
pub occupancy_mask: u64,
pub pointers: [CachePointer; N * N * N],
}
// SAFETY: u64, then packed u32s ([`CachePointer`]s), so no padding, all bit patterns are allowed
unsafe impl<const N: usize> Pod for StructurePage<N> where [(); N * N * N]: {}
/// Number of `u32` words in a [`StructureAnchor`].
pub const ANCHOR_WORDS: usize = 4;
/// Sentinel used in [`RequestMeta::table_slot`] and
/// [`InsertionParent::table_slot`] to mark an insertion that is not attached to
/// a structure-table slot (internal requests).
pub const NO_TABLE_SLOT: u32 = u32::MAX;
/// Opaque, table-defined identity of a structure's *content*.
///
/// The cache and the request queue never interpret these words. A table decides
/// what an anchor means (for example a world position plus a version) and is
/// responsible for never exposing two live slots with the same anchor. The
/// anchor travels on the wire so producers stay stateless and so stale
/// insertions can be rejected against the current table state.
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct StructureAnchor
{
pub words: [u32; ANCHOR_WORDS],
}
impl StructureAnchor
{
/// Convenience anchor used by tests and by tables that do not need a
/// distinguishable identity at startup.
#[allow(dead_code)]
pub const ZERO: Self = Self {
words: [0; ANCHOR_WORDS],
};
/// Table-defined helper for world-position anchors: `(x, y, z, version)`.
pub fn from_world(x: i32, y: i32, z: i32, version: u32) -> Self
{
Self {
words: [x as u32, y as u32, z as u32, version],
}
}
pub fn world(self) -> (i32, i32, i32, u32)
{
(
self.words[0] as i32,
self.words[1] as i32,
self.words[2] as i32,
self.words[3],
)
}
}
/// Data stored alongside cache structure so that application can locate a
/// particular request
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
pub struct LocationPage
{
/// Identifier for locating this particular node within the structure
pub node_id: u32,
/// Identifier of the producer that owns this node
pub producer_id: u32,
/// Opaque content identity inherited from the root request.
pub anchor: StructureAnchor,
}
/// Page storing the depth of the current node related to its root.
/// - 0xFFFFFFFF: Page unused
/// - 0..0xFFFFFFFF(excl): Depth
///
/// An external insertion gets the 0 depth.
/// Internal insertions get the parent's depth plus one.
///
/// As such, when inserting pages in the cache, we first sort the lru pages by
/// depth, deepest first, then apply a stable radix sort by timestamp. The final
/// order is least-recently-used first, with deepest pages first among equal
/// timestamps. Reusing deepest pages first means that a page's resident children
/// are deeper, so they appear earlier in the list and are reused first (provided
/// their timestamp is equal or older) instead of being orphaned when their
/// parent is recycled.
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
pub struct DepthPage(pub u32);
impl DepthPage
{
pub const PAGE_UNUSED: Self = DepthPage(u32::MAX);
}
/// When the cache requests some information, it produces this structure,
/// which contains the node on which a subdivision is requested, as well which particular
/// children is needed
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
pub struct RequestInformation
{
/// Identifier for locating this particular node within the structure
pub node_id: u32,
/// The index of the children on which the request was issued
pub children_index: u32,
/// Identifier of the producer that owns the requesting node
pub producer_id: u32,
/// The amount of times this request was emitted this frame. Higher means more urgent.
pub demand: u32,
/// Opaque content identity of the structure this request belongs to.
pub anchor: StructureAnchor,
}
/// Metainformation kept along each request, to know which node made the demand
#[derive(Debug, Clone, Copy, Zeroable, Pod)]
#[repr(C)]
pub struct RequestMeta
{
/// The page on which the request was issued, with the special value 0xFFFFFFFF if the request
/// is external
pub page_index: u32,
/// The children on which the request was issued
pub children_index: u32,
/// The depth on which the request was issued
pub depth: u32,
/// Table slot for an external root request; [`NO_TABLE_SLOT`] for internal
/// requests.
pub table_slot: u32,
}
/// Sentinel used in [`RequestMeta::page_index`] and [`InsertionParent::page_index`] to mark a
/// request/insertion that has no cache parent (an external root requested by a structure table).
pub const NO_PARENT_PAGE: u32 = u32::MAX;
/// Kind of parent an insertion is attached to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Zeroable, Pod)]
#[repr(transparent)]
pub struct InsertionParentKind(u32);
impl InsertionParentKind
{
/// The new page is a child of a resident cache page.
pub const INTERNAL: Self = Self(0);
/// The new page is the root of a structure owned by a structure table.
pub const EXTERNAL: Self = Self(1);
pub fn raw(self) -> u32
{
self.0
}
}
/// Identity and attachment point of the page being inserted.
///
/// This makes an insertion batch self-describing: the GPU can validate that the parent is still
/// the node the request was issued on, and link the new page without reading the request buffer.
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
#[repr(C)]
pub struct InsertionParent
{
/// [`InsertionParentKind`].
pub kind: u32,
/// Cache page of the parent. [`NO_PARENT_PAGE`] for external roots.
pub page_index: u32,
/// Child slot inside the parent. `0` for external roots.
pub children_index: u32,
/// Depth of the parent. [`NO_PARENT_PAGE`] for external roots.
pub depth: u32,
/// Locator of the parent inside the structure. `0` for external roots.
pub node_id: u32,
/// Producer that owns the parent.
pub producer_id: u32,
/// Opaque content identity of the structure the parent belongs to.
pub anchor: StructureAnchor,
/// Table slot of an external root; [`NO_TABLE_SLOT`] for internal
/// insertions.
pub table_slot: u32,
}
impl InsertionParent
{
/// Parent information for a child of a resident cache page.
pub fn internal(
meta: &RequestMeta,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor,
) -> Self
{
Self {
kind: InsertionParentKind::INTERNAL.raw(),
page_index: meta.page_index,
children_index: meta.children_index,
depth: meta.depth,
node_id,
producer_id,
anchor,
table_slot: NO_TABLE_SLOT,
}
}
/// Parent information for the root of an external structure.
pub fn external(producer_id: u32, anchor: StructureAnchor, table_slot: u32) -> Self
{
Self {
kind: InsertionParentKind::EXTERNAL.raw(),
page_index: NO_PARENT_PAGE,
children_index: 0,
depth: NO_PARENT_PAGE,
node_id: 0,
producer_id,
anchor,
table_slot,
}
}
pub fn is_external(&self) -> bool
{
self.kind == InsertionParentKind::EXTERNAL.raw()
}
pub fn is_internal(&self) -> bool
{
self.kind == InsertionParentKind::INTERNAL.raw()
}
}
/// Structure information about the children of a node.
/// Used when inserting data in the cache, to setup structure pointers
///
/// A specific child of a node being inserted can be in four state by
///
/// Whether it can be subdivided further or not
/// Whether it is considered occupied or not
/// 31st bit : subdivisable?
/// 30th bit : occupied?
#[derive(Clone, Copy, Debug, Zeroable, Pod)]
#[repr(transparent)]
pub struct ChildInformation(u32);
impl ChildInformation
{
pub const NONE: Self = Self(0);
pub const SUBDIVISABLE: Self = Self(1 << 31);
pub const OCCUPIED: Self = Self(1 << 30);
pub fn new(subdivisable: bool, occupied: bool) -> Self
{
let mut n = Self::NONE;
if subdivisable
{
n = n | Self::SUBDIVISABLE;
}
if occupied
{
n = n | Self::OCCUPIED;
}
n
}
}
impl BitOr for ChildInformation
{
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output
{
Self(self.0 | rhs.0)
}
}
/// Information given for an page insertion operation
#[derive(Debug, Clone, Copy, Zeroable)]
#[repr(C)]
pub struct InsertionInformation<const N: usize>
where
[(); N * N * N]:,
{
/// Information to setup structure pointers
pub children: [ChildInformation; N * N * N],
}
// SAFETY: Packed array of u32, no padding, all bit patterns allowed
unsafe impl<const N: usize> Pod for InsertionInformation<N> where [(); N * N * N]: {}
#[cfg(test)]
mod tests
{
use super::*;
#[test]
fn wire_layout_sizes_are_stable()
{
assert_eq!(size_of::<StructureAnchor>(), 16);
assert_eq!(size_of::<RequestInformation>(), 32);
assert_eq!(size_of::<LocationPage>(), 24);
assert_eq!(size_of::<InsertionParent>(), 44);
assert_eq!(size_of::<RequestMeta>(), 16);
}
#[test]
fn anchor_world_round_trips_negative_coordinates()
{
let anchor = StructureAnchor::from_world(-17, 42, -3, 7);
assert_eq!(anchor.world(), (-17, 42, -3, 7));
}
}
@@ -0,0 +1,23 @@
// For things that depend upon the cache layout/children count
struct PointerPage
{
occupancy_low: u32,
occupancy_high: u32,
pointers: array<u32, CHILDREN_COUNT>,
}
struct InsertionInformation
{
/// [`ChildInformation`] in schema.rs
children: array<u32, CHILDREN_COUNT>
}
// Takes index of pointer and gives cache index
fn pointer_index_to_cache_index(request_index: u32) -> CacheIndex
{
var cache_index: CacheIndex;
cache_index.page_index = request_index / CHILDREN_COUNT;
cache_index.children_index = request_index % CHILDREN_COUNT;
return cache_index;
}
@@ -0,0 +1,112 @@
enable wgpu_binding_array;
struct CacheIndex
{
page_index: u32,
children_index: u32,
}
const ANCHOR_WORDS: u32 = 4u;
struct StructureAnchor
{
words: array<u32, 4>
}
fn anchor_eq(a: StructureAnchor, b: StructureAnchor) -> bool
{
for(var i = 0u; i < ANCHOR_WORDS; i++)
{
if(a.words[i] != b.words[i])
{
return false;
}
}
return true;
}
struct RequestInformation
{
node_id: u32,
children_index: u32,
producer_id: u32,
demand: u32,
anchor: StructureAnchor
}
struct RequestMeta
{
page_index: u32,
children_index: u32,
depth: u32,
table_slot: u32
}
// No cache parent (external root insertion).
const NO_PARENT_PAGE: u32 = 0xFFFFFFFFu;
const INSERTION_PARENT_INTERNAL: u32 = 0u;
const INSERTION_PARENT_EXTERNAL: u32 = 1u;
// No structure-table slot (internal request/insertion).
const NO_TABLE_SLOT: u32 = 0xFFFFFFFFu;
struct InsertionParent
{
kind: u32,
page_index: u32,
children_index: u32,
depth: u32,
node_id: u32,
producer_id: u32,
anchor: StructureAnchor,
table_slot: u32
}
struct AttributeArray
{
values: array<u32>
}
struct LocationPage
{
node_id: u32,
producer_id: u32,
anchor: StructureAnchor
}
fn child_information_occupied(info: u32) -> bool
{
return ((info >> 30) & 1) != 0;
}
fn child_information_subdivided(info: u32) -> bool
{
return ((info >> 31) & 1) != 0;
}
// Makes an empty child pointer, which can be subdivisible or not
// but not available
fn child_pointer_empty(subdivisible: bool) -> u32
{
return select(u32(0), u32(1), subdivisible) << 31;
}
fn child_pointer_subdivided(pointer: u32) -> bool
{
return ((pointer >> 31) & 1) != 0;
}
fn child_pointer_available(pointer: u32) -> bool
{
// both bits set ?
return pointer >> 30 == u32(3);
}
fn child_pointer_pointer(pointer: u32) -> u32
{
return pointer & u32(0x3FFFFFFF);
}
fn child_pointer_make_available(pointer: u32) -> u32
{
return pointer | 0xC0000000;
}
@@ -0,0 +1,56 @@
/// Group 0: Lru list
@group(0) @binding(0) var<storage, read_write> timestamp_pages: array<u32>;
@group(0) @binding(1) var<storage, read_write> lru_list: array<u32>;
@group(0) @binding(2) var<storage, read_write> consumed_count: u32;
/// Group 1: Cache structure
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<u32>; // UNUSED
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 2: Scratch buffer
@group(2) @binding(0) var<storage, read_write> scratch_buffer: array<u32>;
/// Resets the lru list to identity order before the depth sort, and clears the
/// number of pages consumed by previous insertions.
@compute
@workgroup_size(256, 1, 1)
fn reset_lru_list(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
{
let index = global_invocation_id.x;
if(index >= arrayLength(&lru_list))
{
return;
}
// Indicies must be reset to id, so that the sort operation can use them as values,
// and the timestamps as keys
lru_list[index] = index;
consumed_count = 0;
}
/// Rearranges timestamps into depth order, in between the descending depth sort
/// and the stable timestamp sort.
///
/// `lru_list` currently holds page indices sorted deepest first. Writing each
/// page's timestamp to the same position gives the next (stable) radix sort an
/// input where equal timestamps preserve the deepest-first depth order.
@compute
@workgroup_size(256, 1, 1)
fn indirect_copy(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
{
let index = global_invocation_id.x;
if(index >= arrayLength(&lru_list))
{
return;
}
// Index sorted by depth
let gather_index = lru_list[index];
// Fetch corresponding timestamp
let ts = timestamp_pages[gather_index];
// Copy to corresponding locatoin
scratch_buffer[index] = ts;
}
@@ -0,0 +1,73 @@
// Group 0: Table pointers
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
// Group 2: Slot metadata
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
fn slot_matches(parent: InsertionParent) -> bool
{
let slot = parent.table_slot;
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
{
return false;
}
return anchor_eq(parent.anchor, fixed_table_anchors[slot]);
}
@compute
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
if(parent.kind != INSERTION_PARENT_EXTERNAL)
{
return;
}
let destination = insertion_data_destination_indices[index];
if(destination == DESTINATION_NONE)
{
return;
}
// Re-check identity and pointer state after allocation. A slot move between
// validation and insertion must not link the wrong tree.
if(!slot_matches(parent))
{
return;
}
let slot = parent.table_slot;
if(slot >= arrayLength(&fixed_table_pointers))
{
return;
}
// Re-check that the slot is still waiting for this root.
let pointer = fixed_table_pointers[slot];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
fixed_table_pointers[slot] = child_pointer_make_available(destination);
}
@@ -0,0 +1,42 @@
/// Group 0: Table pointers
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>; // Request count
// Group 1: Cache evictor
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
@group(1) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
@group(1) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
var<immediate> new_timestamp: u32;
@compute
@workgroup_size(256, 1, 1)
fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
let table_length = arrayLength(&fixed_table_pointers);
if(index >= table_length)
{
return;
}
let pointer = fixed_table_pointers[index];
if(pointer_invalid(pointer))
{
// Invalidate
fixed_table_pointers[index] = child_pointer_empty(child_pointer_subdivided(pointer));
}
}
fn pointer_invalid(pointer: u32) -> bool
{
if(child_pointer_available(pointer))
{
let pointer = child_pointer_pointer(pointer);
let pointed_timestamp = cache_evictor_timestamps[pointer];
// Is dirty marker ?
return pointed_timestamp == new_timestamp;
}
return false;
}
@@ -0,0 +1,79 @@
// Group 0: Table pointers
@group(0) @binding(0) var<storage, read_write> fixed_table_pointers: array<u32>;
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<u32>; // UNUSED
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
// Group 2: Slot metadata
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// The slot named by the parent still holds the same anchor. This is what makes
/// queue invalidation optional: a stale root response for a retired or reused
/// slot can no longer win.
fn slot_matches(parent: InsertionParent) -> bool
{
let slot = parent.table_slot;
if(slot == NO_TABLE_SLOT || slot >= arrayLength(&fixed_table_anchors))
{
return false;
}
return anchor_eq(parent.anchor, fixed_table_anchors[slot]);
}
/// Validates external root insertions against the structure table.
///
/// A root is still wanted while its table slot is subdivisible but not yet
/// available. Slots that were already satisfied (or whose structure was
/// invalidated before the request was dispatched) are dropped here, before the
/// cache allocates any page for them.
@compute
@workgroup_size(256, 1, 1)
fn validate_external(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
// Reset every destination; only validated entries that are allocated get a
// page written back by the cache insertion pass.
insertion_data_destination_indices[index] = DESTINATION_NONE;
if(parent.kind != INSERTION_PARENT_EXTERNAL)
{
return;
}
if(!slot_matches(parent))
{
return;
}
let slot = parent.table_slot;
if(slot >= arrayLength(&fixed_table_pointers))
{
return;
}
let pointer = fixed_table_pointers[slot];
if(!child_pointer_subdivided(pointer) || child_pointer_available(pointer))
{
return;
}
let valid_slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[valid_slot] = index;
}
@@ -0,0 +1,52 @@
/// Group 0: Cache request handler
@group(0) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@group(0) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
@group(0) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
/// Group 1: Request buffer
@group(1) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(1) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
/// Group 2: Slot metadata (current anchor assignment)
@group(2) @binding(0) var<storage, read_write> fixed_table_anchors: array<StructureAnchor>;
var<immediate> table_producer_id: u32;
@compute
@workgroup_size(256, 1, 1)
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
request_buffer_count = min(request_handler_count, arrayLength(&request_buffer_informations));
if(index >= request_handler_count)
{
return;
}
// The request handler emits a slot index; resolve its current assignment so
// the request carries stable identity plus the current placement.
let slot = request_handler_requests[index];
if(slot >= arrayLength(&fixed_table_anchors))
{
return;
}
var request_info: RequestInformation;
request_info.node_id = 0;
request_info.children_index = 0;
request_info.producer_id = table_producer_id;
request_info.demand = request_handler_counts[slot];
request_info.anchor = fixed_table_anchors[slot];
var request_meta: RequestMeta;
// External requests have no parent page.
request_meta.page_index = 0xFFFFFFFF;
request_meta.children_index = 0;
// u32s wrap arround
request_meta.depth = 0xFFFFFFFF;
request_meta.table_slot = slot;
request_buffer_informations[index] = request_info;
request_buffer_meta[index] = request_meta;
}
@@ -0,0 +1,25 @@
// Gathers the selected (count, index) pairs into contiguous buffers so they can
// be sorted by the radix sorter.
//
// `keys` receives the request counts and `values` receives the request indices.
@group(0) @binding(0) var<storage, read> requests: array<u32>;
@group(0) @binding(1) var<storage, read> selected_indices: array<u32>;
@group(0) @binding(2) var<storage, read> selected_count: u32;
@group(0) @binding(3) var<storage, read_write> keys: array<u32>;
@group(0) @binding(4) var<storage, read_write> values: array<u32>;
@compute
@workgroup_size(256, 1, 1)
fn gather_requests(@builtin(global_invocation_id) gid: vec3<u32>)
{
let i = gid.x;
if (i >= selected_count)
{
return;
}
let index = selected_indices[i];
keys[i] = requests[index];
values[i] = index;
}
@@ -0,0 +1,223 @@
// Group 0: cache_attributes
@group(0) @binding(0) var<storage, read_write> cache_attributes: binding_array<AttributeArray>;
/// Group 1: Cache structure
@group(1) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(1) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(1) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
// Group 2: Cache insertion data
@group(2) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(2) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(2) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(2) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(2) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(2) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(2) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
@group(2) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
// Group 3: Cache evictor
@group(3) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
@group(3) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
@group(3) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
// Group 4: Inserted count
@group(4) @binding(0) var<storage, read_write> pass_inserted_count: atomic<u32>;
var<immediate> new_timestamp: u32;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
fn insertion_entry_count() -> u32
{
return min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
}
/// Checks that the parent page still holds the node the request was issued on,
/// and that the requested child slot is still waiting for a page.
fn internal_parent_is_valid(parent: InsertionParent) -> bool
{
if(parent.page_index >= PAGE_COUNT)
{
return false;
}
let location = structure_location_pages[parent.page_index];
if(location.node_id != parent.node_id ||
location.producer_id != parent.producer_id ||
!anchor_eq(location.anchor, parent.anchor))
{
return false;
}
if(structure_depth_pages[parent.page_index] != parent.depth)
{
return false;
}
let pointer = structure_pointer_pages[parent.page_index].pointers[parent.children_index];
return child_pointer_subdivided(pointer) && !child_pointer_available(pointer);
}
/// Validates a batch of internal insertions and compacts the valid ones into
/// `insertion_data_valid_indices`.
///
/// This must run before page allocation so that stale insertions never consume
/// an evicted page. External roots are validated by the structure table that
/// requested them (see `fixed_table/validate_insertion.wgsl`).
@compute
@workgroup_size(256, 1, 1)
fn validate_internal(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= insertion_entry_count())
{
return;
}
let parent = insertion_data_parents[index];
// Reset the destination of every entry. Only entries compacted into
// `valid_indices` and actually allocated by the insertion pass get a page;
// this keeps invalid/stale insertions from reusing a previous batch's
// destination if the host did not pre-fill the buffer.
insertion_data_destination_indices[index] = DESTINATION_NONE;
if(parent.kind != INSERTION_PARENT_INTERNAL)
{
return;
}
if(internal_parent_is_valid(parent))
{
let slot = atomicAdd(&insertion_data_valid_count, 1u);
insertion_data_valid_indices[slot] = index;
}
}
fn available_amount(valid_count: u32) -> u32
{
let lru_remaining = arrayLength(&cache_evictor_timestamps) - cache_evictor_consumed_count;
return min(lru_remaining, valid_count);
}
@compute
@workgroup_size(1, 1, 1)
fn consume(@builtin(global_invocation_id) gid: vec3<u32>)
{
// Report consumed amount of LRU pages to cache evictor
// So that subsequent insertions can can continue to use new pages
cache_evictor_consumed_count += atomicLoad(&pass_inserted_count);
atomicStore(&pass_inserted_count, 0);
}
@compute
@workgroup_size(256, 1, 1)
fn insertion(@builtin(global_invocation_id) gid: vec3<u32>)
{
let slot = gid.x;
let entry_count = insertion_entry_count();
if(slot >= entry_count)
{
return;
}
let valid_count = atomicLoad(&insertion_data_valid_count);
if(slot >= valid_count)
{
return;
}
// Compacted entry index in the host-provided arrays.
let index = insertion_data_valid_indices[slot];
let insertion_count = available_amount(valid_count);
if(slot >= insertion_count)
{
// Report that page was not written. The host also pre-fills the whole
// destination array with DESTINATION_NONE, so this is defensive.
insertion_data_destination_indices[index] = DESTINATION_NONE;
return;
}
// Get a page to evict
let page_index = cache_evictor_lru_pages[slot + cache_evictor_consumed_count];
let page_timestamp = cache_evictor_timestamps[page_index];
if(page_timestamp >= new_timestamp - 1)
{
// Do not insert page
insertion_data_destination_indices[index] = DESTINATION_NONE;
return;
}
atomicAdd(&pass_inserted_count, 1);
insertion_data_destination_indices[index] = page_index;
// Copy new location
structure_location_pages[page_index] = insertion_data_location_pages[index];
// Copy new pointers
let new_pointers = insertion_info_to_pointer_page(insertion_data_information[index]);
structure_pointer_pages[page_index] = new_pointers;
// Mark page as dirty for invalidation
cache_evictor_timestamps[page_index] = new_timestamp;
// Set default depth. `write_pointers` refines it for internal insertions.
structure_depth_pages[page_index] = 0;
// Copy attributes
for(var attribute_index = u32(0); attribute_index < ATTRIBUTE_COUNT; attribute_index ++)
{
if(!ATTRIBUTE_COPY[attribute_index])
{
continue;
}
var page_stride = CHILDREN_COUNT * ATTRIBUTE_WORD_COUNTS[attribute_index];
var dest_offset = page_stride * page_index;
var src_offset = page_stride * index;
// Copy all words of the attribute page
for(var word = u32(0); word < page_stride; word ++)
{
cache_attributes[attribute_index].values[dest_offset + word] = insertion_data_attributes[attribute_index].values[src_offset + word];
}
}
}
fn insertion_info_to_pointer_page(info: InsertionInformation) -> PointerPage
{
var page: PointerPage;
var occupancy_low = u32(0);
var occupancy_high = u32(0);
for(var i = u32(0); i < CHILDREN_COUNT; i++)
{
let insert_info = info.children[i];
// Pointer
page.pointers[i] = child_pointer_empty(child_information_subdivided(insert_info));
// Occupancy
var bit = select(u32(0), u32(1), child_information_occupied(insert_info));
// Dispatch set bit on low or high word
bit = bit << (i % u32(32));
if(i < 32)
{
occupancy_low |= bit;
}
else
{
occupancy_high |= bit;
}
}
page.occupancy_low = occupancy_low;
page.occupancy_high = occupancy_high;
return page;
}
@@ -0,0 +1,51 @@
/// Group 0: Cache structure
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
// Group 1: Cache evictor
@group(1) @binding(0) var<storage, read_write> cache_evictor_timestamps: array<u32>;
@group(1) @binding(1) var<storage, read_write> cache_evictor_lru_pages: array<u32>;
@group(1) @binding(2) var<storage, read_write> cache_evictor_consumed_count: u32;
var<immediate> new_timestamp: u32;
@compute
@workgroup_size(256, 1, 1)
fn invalidation(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
if(index >= arrayLength(&structure_pointer_pages)) { return; }
for(var i = u32(0); i < CHILDREN_COUNT; i++)
{
let pointer = structure_pointer_pages[index].pointers[i];
if(child_pointer_available(pointer) && cache_evictor_timestamps[child_pointer_pointer(pointer)] == new_timestamp)
{
structure_pointer_pages[index].pointers[i] = child_pointer_empty(true);
}
}
}
fn pointer_invalid(pointer: u32) -> bool
{
if(child_pointer_available(pointer))
{
let pointer = child_pointer_pointer(pointer);
let pointed_timestamp = cache_evictor_timestamps[pointer];
// Is dirty marker ?
return pointed_timestamp == new_timestamp;
}
return false;
}
fn pointer_invalidate(page_index: u32, child_index: u32)
{
let pointer = structure_pointer_pages[page_index].pointers[child_index];
let pointed_page = child_pointer_pointer(pointer);
let new_pointer = child_pointer_empty(child_pointer_subdivided(pointer));
structure_pointer_pages[page_index].pointers[child_index] = new_pointer;
}
@@ -0,0 +1,15 @@
@group(0) @binding(0) var<storage, read_write> request_count_pages: array<u32>;
/// Resets the requests
@compute
@workgroup_size(256, 1, 1)
fn reset_requests(@builtin(global_invocation_id) global_invocation_id: vec3<u32>)
{
let index = global_invocation_id.x;
if(index >= arrayLength(&request_count_pages))
{
return;
}
request_count_pages[index] = 0;
}
@@ -0,0 +1,63 @@
/// Group 0: Cache structure
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
// Group 1: Cache insertion data
@group(1) @binding(0) var<storage, read_write> insertion_data_page_count_buffer: u32;
@group(1) @binding(1) var<storage, read_write> insertion_data_information: array<InsertionInformation>;
@group(1) @binding(2) var<storage, read_write> insertion_data_location_pages: array<LocationPage>;
@group(1) @binding(3) var<storage, read_write> insertion_data_destination_indices: array<u32>;
@group(1) @binding(4) var<storage, read_write> insertion_data_parents: array<InsertionParent>;
@group(1) @binding(5) var<storage, read_write> insertion_data_valid_indices: array<u32>;
@group(1) @binding(6) var<storage, read_write> insertion_data_valid_count: atomic<u32>;
@group(1) @binding(7) var<storage, read_write> insertion_data_attributes: binding_array<AttributeArray>;
const DESTINATION_NONE: u32 = 0xFFFFFFFFu;
/// Links inserted pages into their parent, using only the insertion batch's own
/// parent description. No request buffer is involved, so a batch may be
/// produced on a different frame than the one that emitted the requests.
@compute
@workgroup_size(256, 1, 1)
fn write_pointers(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
let entry_count = min(insertion_data_page_count_buffer, arrayLength(&insertion_data_parents));
if(index >= entry_count)
{
return;
}
let parent = insertion_data_parents[index];
if(parent.kind != INSERTION_PARENT_INTERNAL)
{
return;
}
let page_index = insertion_data_destination_indices[index];
if(page_index == DESTINATION_NONE)
{
return;
}
// The parent page may have been recycled while this insertion batch was in
// flight. Only link if it still describes the same node, and never link a
// page to itself.
if(parent.page_index >= PAGE_COUNT || parent.page_index == page_index)
{
return;
}
let location = structure_location_pages[parent.page_index];
if(location.node_id != parent.node_id ||
location.producer_id != parent.producer_id ||
!anchor_eq(location.anchor, parent.anchor))
{
return;
}
structure_pointer_pages[parent.page_index].pointers[parent.children_index]
= child_pointer_make_available(page_index);
structure_depth_pages[page_index] = parent.depth + 1;
}
@@ -0,0 +1,55 @@
/// Pipeline to write the requests out in to the request buffer
/// Group 0: Cache structure
@group(0) @binding(0) var<storage, read_write> structure_pointer_pages: array<PointerPage>;
@group(0) @binding(1) var<storage, read_write> structure_location_pages: array<LocationPage>;
@group(0) @binding(2) var<storage, read_write> structure_depth_pages: array<u32>;
/// Group 1: Cache request handler
@group(1) @binding(0) var<storage, read_write> request_handler_count: u32; // Request count
@group(1) @binding(1) var<storage, read_write> request_handler_requests: array<u32>;
@group(1) @binding(2) var<storage, read_write> request_handler_counts: array<u32>;
/// Group 3: Request buffer
@group(2) @binding(0) var<storage, read_write> request_buffer_count: u32; // Request count
@group(2) @binding(1) var<storage, read_write> request_buffer_informations: array<RequestInformation>;
@group(2) @binding(2) var<storage, read_write> request_buffer_meta: array<RequestMeta>;
@compute
@workgroup_size(256, 1, 1)
fn write_requests(@builtin(global_invocation_id) gid: vec3<u32>)
{
let index = gid.x;
// Max size of request buffer and request count
let max_requests =
min(arrayLength(&request_buffer_informations), request_handler_count);
if(index >= max_requests) { return; }
let request_index = request_handler_requests[index];
let request_location = pointer_index_to_cache_index(request_index);
let page_index = request_location.page_index;
// Fill out request information
var request_information: RequestInformation;
request_information.node_id = structure_location_pages[page_index].node_id;
request_information.children_index = request_location.children_index;
request_information.producer_id = structure_location_pages[page_index].producer_id;
request_information.demand = request_handler_counts[request_index];
request_information.anchor = structure_location_pages[page_index].anchor;
// Fill out request meta information
var request_meta: RequestMeta;
request_meta.page_index = page_index;
request_meta.children_index = request_location.children_index;
request_meta.depth = structure_depth_pages[page_index];
request_meta.table_slot = NO_TABLE_SLOT;
// Write them to request buffer
request_buffer_informations[index] = request_information;
request_buffer_meta[index] = request_meta;
// Write request count
request_buffer_count = max_requests;
}
+100
View File
@@ -0,0 +1,100 @@
use wgpu::BindGroup;
use wgpu::BindGroupLayout;
use wgpu::Buffer;
use wgpu::BufferUsages;
use vxls_gpu::create_multi_buffers_bind_group;
use vxls_gpu::create_multi_buffers_bind_group_layout;
use vxls_profiler::memory_profiler;
use crate::schema::DepthPage;
use crate::schema::StructurePage;
/// Contains the instanciated buffers relevant to the structure of the trees
pub struct CacheStructure<const N: usize>
where
[(); N * N * N]:,
{
pointer_pages: Buffer,
location_pages: Buffer,
depth_pages: Buffer,
bind_group_layout: BindGroupLayout,
bind_group: BindGroup,
}
impl<const N: usize> CacheStructure<N>
where
[(); N * N * N]:,
{
pub const POINTER_PAGES_BINDING: u32 = 0;
pub const LOCATION_PAGES_BINDING: u32 = 1;
pub const DEPTH_PAGES_BINDING: u32 = 2;
pub fn new(device: &mut memory_profiler::Device, page_count: usize) -> Self
{
let pointer_pages = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheStructure::pointer_pages"),
size: (size_of::<StructurePage<N>>() * page_count) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
let location_pages = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("CacheStructure::location_pages"),
size: (size_of::<StructurePage<N>>() * page_count) as u64,
usage: BufferUsages::STORAGE,
mapped_at_creation: false,
});
// Unused pages get the maximum depth so they lead the deepest-first
// depth sort used by the eviction pass. Combined with their initial
// timestamp of 0, this makes them the first pages reused.
let depth_pages = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("CacheStructure::depth_pages"),
usage: BufferUsages::STORAGE | BufferUsages::COPY_SRC,
contents: bytemuck::cast_slice(&vec![DepthPage::PAGE_UNUSED; page_count]),
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&pointer_pages, &location_pages, &depth_pages],
Some("CacheStructure::bind_group"),
);
CacheStructure {
pointer_pages,
location_pages,
depth_pages,
bind_group_layout,
bind_group,
}
}
pub fn create_bind_group_layout(device: &wgpu::Device) -> BindGroupLayout
{
create_multi_buffers_bind_group_layout(device, 3, Some("CacheStructure::bind_group_layout"))
}
pub fn bind_group_layout(&self) -> &BindGroupLayout
{
&self.bind_group_layout
}
pub fn bind_group(&self) -> &BindGroup
{
&self.bind_group
}
pub fn pointer_pages(&self) -> &Buffer
{
&self.pointer_pages
}
pub fn depth_pages(&self) -> &Buffer
{
&self.depth_pages
}
}
File diff suppressed because it is too large Load Diff
+33
View File
@@ -0,0 +1,33 @@
[package]
name = "vxls"
version = "0.1.0"
edition = "2024"
[dependencies]
vxls-bvh = { path = "../vxls-bvh" }
vxls-gpu = { path = "../vxls-gpu" }
vxls-production = { path = "../vxls-production" }
vxls-profiler = { path = "../vxls-profiler" }
vxls-terrain = { path = "../vxls-terrain" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
bytemuck.workspace = true
crevice.workspace = true
egui.workspace = true
egui-wgpu.workspace = true
egui-winit.workspace = true
egui_ltreeview.workspace = true
egui_plot.workspace = true
env_logger.workspace = true
fastapprox.workspace = true
glam.workspace = true
image.workspace = true
indicatif.workspace = true
itertools.workspace = true
noise.workspace = true
pollster.workspace = true
rand.workspace = true
rayon.workspace = true
tiff.workspace = true
wgpu.workspace = true
winit.workspace = true
+120
View File
@@ -0,0 +1,120 @@
use std::collections::HashSet;
use std::f32::consts::PI;
use glam::Mat4;
use glam::Vec2;
use glam::Vec3;
use winit::event::WindowEvent;
use winit::keyboard::KeyCode;
pub struct Camera
{
pub position: Vec3,
pitch: f32,
yaw: f32,
zfar: f32,
znear: f32,
fov: f32,
pub aspect: f32,
pub speed: f32,
pub pressed_keyset: HashSet<KeyCode>,
}
impl Default for Camera
{
fn default() -> Self
{
Self {
position: Vec3::new(0., 0., 0.),
pitch: Default::default(),
yaw: Default::default(),
speed: 0.1,
pressed_keyset: Default::default(),
znear: 0.01,
zfar: 100.,
fov: PI * 100.0f32 / 180.0f32,
aspect: 1.,
}
}
}
impl Camera
{
pub fn handle_input(&mut self, event: &WindowEvent)
{
if let WindowEvent::KeyboardInput { event, .. } = event
{
match (event.state, event.physical_key)
{
(winit::event::ElementState::Pressed, winit::keyboard::PhysicalKey::Code(c)) =>
{
self.pressed_keyset.insert(c);
}
(winit::event::ElementState::Released, winit::keyboard::PhysicalKey::Code(c)) =>
{
self.pressed_keyset.remove(&c);
}
_ =>
{}
}
}
}
pub fn update(&mut self)
{
let mut movement = Vec3::new(0., 0., 0.);
if self.pressed_keyset.contains(&KeyCode::KeyW)
{
movement.z += self.speed;
}
if self.pressed_keyset.contains(&KeyCode::KeyS)
{
movement.z -= self.speed;
}
// Left right
if self.pressed_keyset.contains(&KeyCode::KeyA)
{
movement.x += self.speed;
}
if self.pressed_keyset.contains(&KeyCode::KeyD)
{
movement.x -= self.speed;
}
let rot_movement = glam::Mat3::from_rotation_y(-self.yaw)
* glam::Mat3::from_rotation_x(-self.pitch)
* movement;
self.position -= rot_movement;
}
pub fn cursor_moved(&mut self, x: f32, y: f32)
{
const SENSITIVITY: f32 = 0.0004;
let position = Vec2::new(x, y);
let offset = position * SENSITIVITY;
self.yaw += offset.x;
self.pitch += offset.y;
}
pub fn view_proj(&self) -> Mat4
{
let view = glam::Mat4::from_translation(self.position)
* glam::Mat4::from_rotation_y(-self.yaw)
* glam::Mat4::from_rotation_x(-self.pitch);
let proj = glam::Mat4::perspective_rh(self.fov, self.aspect, self.znear, self.zfar);
OPENGL_TO_WGPU_MATRIX * proj * view.inverse()
}
}
#[rustfmt::skip]
pub const OPENGL_TO_WGPU_MATRIX: glam::Mat4 = glam::Mat4::from_cols(
glam::Vec4::new(1.0, 0.0, 0.0, 0.0),
glam::Vec4::new(0.0, 1.0, 0.0, 0.0),
glam::Vec4::new(0.0, 0.0, 0.5, 0.0),
glam::Vec4::new(0.0, 0.0, 0.5, 1.0),
);
+131
View File
@@ -0,0 +1,131 @@
use egui::Context;
use egui_wgpu::Renderer;
use egui_wgpu::RendererOptions;
use egui_wgpu::ScreenDescriptor;
use egui_winit::State;
use wgpu::CommandEncoder;
use wgpu::Device;
use wgpu::Queue;
use wgpu::RenderPassDescriptor;
use wgpu::TextureFormat;
use wgpu::TextureView;
use winit::event::WindowEvent;
use winit::window::Window;
pub struct EguiRenderer
{
state: State,
pub renderer: Renderer,
frame_started: bool,
}
impl EguiRenderer
{
pub fn context(&self) -> &Context
{
self.state.egui_ctx()
}
pub fn new(device: &Device, output_color_format: TextureFormat, window: &Window)
-> EguiRenderer
{
let egui_context = Context::default();
let egui_state = State::new(
egui_context,
egui::viewport::ViewportId::ROOT,
&window,
Some(window.scale_factor() as f32),
None,
Some(2 * 1024),
);
let egui_renderer = Renderer::new(device, output_color_format, RendererOptions::default());
EguiRenderer {
state: egui_state,
renderer: egui_renderer,
frame_started: false,
}
}
pub fn handle_input(&mut self, window: &Window, event: &WindowEvent)
{
let _ = self.state.on_window_event(window, event);
}
pub fn ppp(&mut self, v: f32)
{
self.context().set_pixels_per_point(v);
}
pub fn begin_frame(&mut self, window: &Window)
{
let raw_input = self.state.take_egui_input(window);
self.state.egui_ctx().begin_pass(raw_input);
self.frame_started = true;
}
pub fn end_frame_and_draw(
&mut self,
device: &Device,
queue: &Queue,
encoder: &mut CommandEncoder,
window: &Window,
window_surface_view: &TextureView,
screen_descriptor: ScreenDescriptor,
)
{
if !self.frame_started
{
panic!("begin_frame must be called before.");
}
self.ppp(screen_descriptor.pixels_per_point);
let mut full_output = self.state.egui_ctx().end_pass();
self.state
.handle_platform_output(window, full_output.platform_output);
let tris = self
.state
.egui_ctx()
.tessellate(full_output.shapes, self.state.egui_ctx().pixels_per_point());
for (id, image_delta) in &full_output.textures_delta.set
{
self.renderer
.update_texture(device, queue, *id, &image_delta[0]);
}
full_output.textures_delta.clear();
self.renderer
.update_buffers(device, queue, encoder, &tris, &screen_descriptor);
let rpass = encoder.begin_render_pass(&RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: window_surface_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations {
load: wgpu::LoadOp::Load,
store: wgpu::StoreOp::Store,
},
})],
multiview_mask: None,
depth_stencil_attachment: None,
timestamp_writes: None,
label: Some("egui main render pass"),
occlusion_query_set: None,
});
self.renderer
.render(&mut rpass.forget_lifetime(), &tris, &screen_descriptor);
for x in &full_output.textures_delta.free
{
self.renderer.free_texture(x);
}
self.frame_started = false;
}
}
+50
View File
@@ -0,0 +1,50 @@
use crate::gi_pipeline::sparse_set::GpuSparseSet;
use vxls_voxel_cache::VoxelCache;
use vxls_voxel_cache::{self};
mod sparse_set;
pub struct VoxelGiPipeline<const N: usize>
where
[(); N * N * N]:,
{
voxel_cache: VoxelCache<N>,
/// Keeps a set of the leaves present in the cache.
/// Kept in correspondancy with the leaf list attribute within the cache
leaf_list: GpuSparseSet,
leaf_list_attribute: usize,
}
impl<const N: usize> VoxelGiPipeline<N>
where
[(); N * N * N]:,
{
pub fn new(
device: &wgpu::Device,
cache_size: usize,
max_requests: usize,
cache_layout: &mut vxls_voxel_cache::CacheLayout,
) -> Self
{
let leaf_list_attribute = cache_layout.add_attribute(vxls_voxel_cache::CacheAttribute {
label: Some("VoxelGiPipeline::leaf_list_pointer"),
word_count: 1,
init: vxls_voxel_cache::CacheAttributeInit::External,
});
cache_layout.add_attribute(vxls_voxel_cache::CacheAttribute {
label: Some("VoxelGiPipeline::radiance"),
word_count: 3,
init: vxls_voxel_cache::CacheAttributeInit::DontTouch,
});
let voxel_cache = VoxelCache::new(device, cache_size, max_requests, cache_layout);
Self {
voxel_cache,
leaf_list: GpuSparseSet::new(device, cache_size),
leaf_list_attribute,
}
}
}
+57
View File
@@ -0,0 +1,57 @@
use wgpu::util::DeviceExt;
use vxls_gpu::create_multi_buffers_bind_group;
use vxls_gpu::create_multi_buffers_bind_group_layout;
/// To keep a set of voxel nodes in the cache
pub struct GpuSparseSet
{
/// Maximum size of the set
size: usize,
/// Contains pointers to nodes in the cache
pointers_buffer: wgpu::Buffer,
/// Amount of elements in the set
count_buffer: wgpu::Buffer,
bind_group: wgpu::BindGroup,
}
impl GpuSparseSet
{
pub fn new(device: &wgpu::Device, size: usize) -> Self
{
let pointers_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("GpuSparseSet::pointers_buffer"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::cast_slice(&vec![0u32; size]),
});
let count_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("GpuSparseSet::count_buffer"),
usage: wgpu::BufferUsages::STORAGE,
contents: bytemuck::bytes_of(&0u32),
});
let bind_group_layout = Self::create_bind_group_layout(device);
let bind_group = create_multi_buffers_bind_group(
device,
&bind_group_layout,
&[&pointers_buffer, &count_buffer],
Some("GpuSparseSet::bind_group"),
);
Self {
size,
pointers_buffer,
count_buffer,
bind_group,
}
}
pub fn create_bind_group_layout(device: &wgpu::Device) -> wgpu::BindGroupLayout
{
create_multi_buffers_bind_group_layout(device, 2, Some("GpuSparseSet::bind_group_layout"))
}
}
+15
View File
@@ -0,0 +1,15 @@
// Contains useful facilities to render data streamed in from the host
// Can produce a voxel given
// - Its depth
// - Its position within the chunk
// - The chunks position
pub trait ChunkVoxelProducer
{
fn produce_voxel(
&mut self,
depth: usize,
chunk_position: (usize, usize, usize),
voxel_position: (usize, usize, usize),
);
}
File diff suppressed because it is too large Load Diff
+683
View File
@@ -0,0 +1,683 @@
use std::fs::File;
use std::path::Path;
use glam::Vec3;
use itertools::Itertools;
use noise::Cylinders;
use noise::Fbm;
use noise::NoiseFn;
use noise::Simplex;
use rand::random;
use crate::sparse_tree::Color;
use vxls_voxel_cache::schema::ChildInformation;
pub struct BallGenerator<const N: usize>
{
chunk_power: usize,
}
pub fn map(x: f32, x_min: f32, x_max: f32, y_min: f32, y_max: f32) -> f32
{
//((x - x_min) / (x_max - x_min)) * (y_max - y_min) + y_min
let input_range = x_max.algebraic_sub(x_min);
let output_range = y_max.algebraic_sub(y_min);
(x.algebraic_sub(x_min).algebraic_div(input_range))
.algebraic_mul(output_range)
.algebraic_add(y_min)
}
pub trait Producer<const N: usize>
where
[(); N * N * N]:,
{
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>;
}
impl<const N: usize> BallGenerator<N>
where
[(); N * N * N]:,
{
pub fn new(chunk_power: usize) -> Self
{
BallGenerator { chunk_power }
}
}
impl<const N: usize> Producer<N> for BallGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(&self, depth: usize, nx: usize, ny: usize, nz: usize) -> ProducedChunk<N>
{
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![];
let mut children_color = vec![];
let mut children_normal = vec![];
let gnx = nx * node_size;
let gny = ny * node_size;
let gnz = nz * node_size;
// Iterate on children of this node
for ((cx, cy), cz) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
{
let gvx = gnx + cx * child_size + (child_size / 2);
let gvy = gny + cy * child_size + (child_size / 2);
let gvz = gnz + cz * child_size + (child_size / 2);
let dist = Vec3::new(
gvx as f32 - (global_size / 2) as f32,
gvy as f32 - (global_size / 2) as f32,
gvz as f32 - (global_size / 2) as f32,
)
.length();
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
let alpha;
let subdivided;
if (dist - (global_size as f32 / 2.)).abs() <= child_diagonal_length
{
//children.push(StructurePointer::new(depth <= 3, false, 0));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist > 128. { 0. } else { 1. };
}
else if dist > (global_size as f32 / 2.)
{
subdivided = false;
alpha = 0.;
}
else
{
subdivided = false;
alpha = 1.;
}
// let alpha = 1.;
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
children_normal.push((0., 0., 0.));
children_color.push(Color(
gvx as f32 / global_size as f32,
gvy as f32 / global_size as f32,
gvz as f32 / global_size as f32,
alpha,
));
}
ProducedChunk {
children: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
normals: std::array::from_fn(|i| children_normal[i].into()),
}
}
}
pub struct TerrainGenerator<const N: usize>
where
[(); N * N * N]:,
{
chunk_power: usize,
heightmap_width: usize,
heightmap_height: usize,
terrain_width: usize,
terrain_height: usize,
heightmap_min: f32,
heightmap_max: f32,
heightmap: Vec<f32>,
colormap: Vec<u8>,
heightmap_low_width: usize,
heightmap_low_height: usize,
heightmap_low: Vec<(f32, f32)>,
colormap_low_width: usize,
colormap_low_height: usize,
colormap_mip: Vec<u8>,
pub chunk_width: usize,
pub chunk_height: usize,
pub chunk_alt: usize,
}
impl<const N: usize> TerrainGenerator<N>
where
[(); N * N * N]:,
{
pub fn new<P: AsRef<Path>>(
chunk_power: usize,
height_path: P,
height_factor: f32,
color_path: P,
) -> Self
{
println!("Starting terrain producer");
println!("Loading height map.");
let mut tiff_dec = tiff::decoder::Decoder::new(File::open(height_path).unwrap()).unwrap();
let (heightmap_width, heightmap_height) = tiff_dec.dimensions().unwrap();
let (heightmap_width, heightmap_height) =
(heightmap_width as usize, heightmap_height as usize);
let mut heightmap = match tiff_dec.read_image().unwrap()
{
tiff::decoder::DecodingResult::F32(vec) => vec,
_ => panic!("Unsupported format"),
};
println!("Loading color map.");
let mut color = image::ImageReader::open(color_path).unwrap();
color.no_limits();
let color = color.decode().unwrap();
let mut colormap = color.as_rgb8().unwrap().to_vec();
println!("Converting color spaces");
colormap.iter_mut().for_each(|x| {
let normalized = map(*x as f32, 0., 255., 0., 1.);
let maped = normalized.powf(2.4);
*x = map(maped, 0., 1., 0., 255.) as u8;
});
let terrain_width = color.width() as usize;
let terrain_height = color.height() as usize;
println!("Computing heightmap min/max");
let heightmap_min = heightmap
.iter()
.copied()
.filter(|x| *x != -9999.)
.reduce(f32::min)
.unwrap();
let heightmap_max = heightmap.iter().copied().reduce(f32::max).unwrap();
heightmap
.iter_mut()
.filter(|x| **x == -9999.)
.for_each(|x| *x = heightmap_min);
// Decide size in chunks
let height_amplitude = heightmap_max - heightmap_min;
let chunk_size = N.pow(chunk_power as u32);
let chunk_width = terrain_width.div_ceil(chunk_size);
let chunk_height = terrain_height.div_ceil(chunk_size);
let chunk_alt = ((height_amplitude / height_factor) as usize).div_ceil(chunk_size);
// build the low heightmap
println!("Computing low res height/color maps");
let heightmap_low_width = heightmap_width / 8;
let heightmap_low_height = heightmap_height / 8;
let mut heightmap_low = vec![(0., 0.); heightmap_low_height * heightmap_low_width];
for y in 0..heightmap_low_height
{
for x in 0..heightmap_low_width
{
let mut min = heightmap_max;
let mut max = heightmap_min;
for sy in (y * 8)..(y * 8 + 8)
{
for sx in (x * 8)..(x * 8 + 8)
{
min = min.min(heightmap[sx + sy * heightmap_width]);
max = max.max(heightmap[sx + sy * heightmap_width]);
}
}
heightmap_low[x + y * heightmap_low_width] = (min, max);
}
}
// build the color map mip
let colormap_low_width = terrain_width / 8;
let colormap_low_height = terrain_height / 8;
let mut colormap_mip = vec![0u8; colormap_low_width * colormap_low_height * 3];
for y in 0..colormap_low_height
{
for x in 0..colormap_low_width
{
let mut r = 0u32;
let mut g = 0u32;
let mut b = 0u32;
for sy in (y * 8)..(y * 8 + 8)
{
for sx in (x * 8)..(x * 8 + 8)
{
r += colormap[(sx + sy * terrain_width) * 3] as u32;
g += colormap[(sx + sy * terrain_width) * 3 + 1] as u32;
b += colormap[(sx + sy * terrain_width) * 3 + 2] as u32;
}
}
colormap_mip[(x + y * colormap_low_width) * 3] =
((r as f32) / (8 * 8) as f32).clamp(0., 255.) as u8;
colormap_mip[(x + y * colormap_low_width) * 3 + 1] =
((g as f32) / (8 * 8) as f32).clamp(0., 255.) as u8;
colormap_mip[(x + y * colormap_low_width) * 3 + 2] =
((b as f32) / (8 * 8) as f32).clamp(0., 255.) as u8;
}
}
println!("Producer ready");
Self {
chunk_power,
heightmap_width,
heightmap_height,
heightmap_min,
heightmap_max,
terrain_width,
terrain_height,
heightmap,
colormap,
heightmap_low_width,
heightmap_low_height,
heightmap_low,
colormap_low_width,
colormap_low_height,
colormap_mip,
chunk_width,
chunk_height,
chunk_alt,
}
}
}
impl<const N: usize> ChunkedProducer<N> for TerrainGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![ChildInformation::NONE; N * N * N];
let mut children_color = vec![Color(0., 0., 0., 0.); N * N * N];
let mut children_normals = vec![(0., 0., 0.); N * N * N];
let gnx = chunk_pos.0 * global_size + nx * node_size;
let gny = chunk_pos.1 * global_size + ny * node_size;
let gnz = chunk_pos.2 * global_size + nz * node_size;
// Iterate on children of this node
for (cx, cz) in (0..N).cartesian_product(0..N)
{
let gcx = gnx + cx * child_size;
let gcz = gnz + cz * child_size;
// prepare 2d values
// Iterate on children
let mut sample_max = self.heightmap_min;
let mut sample_min = self.heightmap_max;
let mut color_avg = Color(0., 0., 0., 0.);
let mut count = 0;
if depth <= 2
{
for (z, x) in (0..(child_size / 8)).cartesian_product(0..(child_size / 8))
{
let gvx = (gcx + x * 8) / 8;
let gvz = (gcz + z * 8) / 8;
if gvx < self.colormap_low_width && gvz < self.colormap_low_height
{
// Height sample
let height_x = (gvx * self.heightmap_low_width) / self.colormap_low_width;
let height_z = (gvz * self.heightmap_low_height) / self.colormap_low_height;
let sample =
self.heightmap_low[height_x + height_z * self.heightmap_low_width];
sample_min = sample_min.min(sample.0);
sample_max = sample_max.max(sample.1);
let sample_color_r =
self.colormap_mip[(gvx + gvz * self.colormap_low_width) * 3];
let sample_color_g =
self.colormap_mip[(gvx + gvz * self.colormap_low_width) * 3 + 1];
let sample_color_b =
self.colormap_mip[(gvx + gvz * self.colormap_low_width) * 3 + 2];
color_avg.0 += map(sample_color_r as f32, 0., 256., 0., 1.);
color_avg.1 += map(sample_color_g as f32, 0., 256., 0., 1.);
color_avg.2 += map(sample_color_b as f32, 0., 256., 0., 1.);
count += 1;
}
//let gvy = gcy;
}
}
else
{
for (z, x) in (0..child_size).cartesian_product(0..child_size)
{
let gvx = gcx + x;
let gvz = gcz + z;
if gvx < self.terrain_width && gvz < self.terrain_height
{
// Height sample
let height_x = (gvx * self.heightmap_width) / self.terrain_width;
let height_z = (gvz * self.heightmap_height) / self.terrain_height;
let sample = self.heightmap[height_x + height_z * self.heightmap_width];
sample_max = sample_max.max(sample);
sample_min = sample_min.min(sample);
let sample_color_r = self.colormap[(gvx + gvz * self.terrain_width) * 3];
let sample_color_g =
self.colormap[(gvx + gvz * self.terrain_width) * 3 + 1];
let sample_color_b =
self.colormap[(gvx + gvz * self.terrain_width) * 3 + 2];
color_avg.0 += map(sample_color_r as f32, 0., 256., 0., 1.);
color_avg.1 += map(sample_color_g as f32, 0., 256., 0., 1.);
color_avg.2 += map(sample_color_b as f32, 0., 256., 0., 1.);
count += 1;
}
//let gvy = gcy;
}
}
color_avg.0 /= count as f32;
color_avg.1 /= count as f32;
color_avg.2 /= count as f32;
let sample_min = map(
sample_min,
self.heightmap_min,
self.heightmap_max,
0.,
(self.chunk_alt * global_size) as f32,
) as usize;
let sample_max = map(
sample_max,
self.heightmap_min,
self.heightmap_max,
0.,
(self.chunk_alt * global_size) as f32,
) as usize;
for cy in 0..N
{
let gcy = gny + cy * child_size;
let index = cz * N * N + cy * N + cx;
let alpha;
let subdivided;
if gcy > sample_max
{
subdivided = false;
alpha = 0.;
}
else if gcy + child_size < sample_min
{
subdivided = false;
alpha = 1.;
}
else
{
subdivided = depth < (self.chunk_power - 1);
//children.push(StructurePointer(0));
alpha = if (sample_max + sample_min / 2) > gcy + (child_size / 2)
{
1.
}
else
{
0.
};
}
children[index] = ChildInformation::new(subdivided, subdivided || alpha != 0.);
children_normals[index] = (0., 0., 0.);
children_color[index] = Color(color_avg.0, color_avg.1, color_avg.2, alpha);
//children_color[index] = Color(1., 1., 1., alpha);
}
}
ProducedChunk {
children: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
normals: std::array::from_fn(|i| children_normals[i].into()),
}
}
}
pub struct ProducedChunk<const N: usize>
where
[(); N * N * N]:,
{
pub children: [ChildInformation; N * N * N],
pub colors: [u32; N * N * N],
pub normals: [[f32; 3]; N * N * N],
}
pub trait ChunkedProducer<const N: usize>
where
[(); N * N * N]:,
{
fn produce_node(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>;
}
pub struct SdfGenerator<const N: usize>
{
chunk_power: usize,
perlin: Fbm<Simplex>,
//perlin: Cylinders,
}
impl<const N: usize> SdfGenerator<N>
{
pub fn new(chunk_power: usize) -> Self
{
Self {
chunk_power,
perlin: Fbm::new(67),
//perlin: Cylinders::new(),
}
}
}
impl<const N: usize> ChunkedProducer<N> for SdfGenerator<N>
where
[(); N * N * N]:,
{
fn produce_node(
&self,
depth: usize,
nx: usize,
ny: usize,
nz: usize,
chunk_pos: (usize, usize, usize),
) -> ProducedChunk<N>
{
fn hash(mut p: [f32; 3]) -> f32
{
p[0] = (p[0] * 127.1 + p[1] * 311.7 + p[2] * 74.7).sin() * 43758.5453123;
p[0].fract()
}
// let sdf = |x: f32, y: f32, z: f32| {
// Vec3::new((x % 1024.) - 512., (y % 1024.) - 512., (z % 1024.) - 512.).length() - 512.
// };
// let sdf = |mut x: f32, mut y: f32, mut z: f32| {
// // x = -5000. * 1024.;
// // z = -5000. * 1024.;
// y -= 1024.;
// let scale = 2048.;
// let tx = x / scale;
// let ty = y / scale;
// let tz = z / scale;
//
// let val = (self.perlin.get([tx as f64, tz as f64, ty as f64]) + 0.5) * 0.23;
// let dist = val * scale as f64;
// return (dist as f32).max(ty);
// };
// let sdf = |x: f32, y: f32, z: f32| {
// let scale = 1024. * 10.;
// let domain = 1.;
// let tx = map(x, 0., scale, -domain, domain);
// let ty = map(y, 0., scale, -domain, domain);
// let tz = map(z, 0., scale, -domain, domain);
// nebula_sdf(tx, ty, tz) * 0.2 * scale / domain
// };
let sdf = |x: f32, y: f32, z: f32| {
let scale = 10. * 1024.;
let height = 5000.;
let tx = x / scale;
let tz = z / scale;
let ty = y;
let val = map(
self.perlin.get([tx as f64, tz as f64]) as f32,
-1.,
1.,
1.,
height,
);
// Trees
let tree_space = 10.;
let mx = x.rem_euclid(tree_space);
let mz = z.rem_euclid(tree_space);
let tree_x = x.div_euclid(tree_space);
let tree_z = z.div_euclid(tree_space);
let h1 = hash([tree_x, tree_z, 1.]);
let h2 = hash([tree_z, tree_x, 1.]);
let h3 = hash([tree_z, tree_x, tree_z]);
let d = Vec3::new(
mx + h1 * 3. - tree_space * 0.5,
(ty - val) * 0.2,
mz + h2 * 3. - tree_space * 0.5,
)
.length()
- 4. * map(h3, 0., 1., 0.8, 1.2);
let bound = 1. / scale * height;
((ty - val) / (1. + bound.powf(2.)).sqrt()).min(d)
};
let node_size = N.pow((self.chunk_power - depth) as u32);
let child_size = node_size / N;
let global_size = N.pow(self.chunk_power as u32);
let mut children = vec![];
let mut children_color = vec![];
let mut children_normals = vec![];
let cx = chunk_pos.0 * global_size;
let cy = chunk_pos.1 * global_size;
let cz = chunk_pos.2 * global_size;
let gnx = nx * node_size + cx;
let gny = ny * node_size + cy;
let gnz = nz * node_size + cz;
// Iterate on children of this node
for ((cz, cy), cx) in (0..N).cartesian_product(0..N).cartesian_product(0..N)
{
let gvx = gnx + cx * child_size + (child_size / 2);
let gvy = gny + cy * child_size + (child_size / 2);
let gvz = gnz + cz * child_size + (child_size / 2);
let dist = sdf(gvx as f32, gvy as f32, gvz as f32);
let child_diagonal_length = (child_size as f32 / 2.) * f32::sqrt(3.);
let alpha;
let subdivided;
if dist.abs() < child_diagonal_length
{
//children.push(StructurePointer::new(depth <= 3, false, 0));
subdivided = depth < (self.chunk_power - 1);
alpha = if dist >= 0. { 0. } else { 1. };
//alpha = 0.;
}
else if dist >= 0.
{
subdivided = false;
alpha = 0.;
}
else
{
subdivided = false;
alpha = 1.;
}
let offset = 1. * (child_size as f32 / 2.);
let a = sdf(
gvx as f32 + offset,
gvy as f32 - offset,
gvz as f32 - offset,
);
let b = sdf(
gvx as f32 - offset,
gvy as f32 - offset,
gvz as f32 + offset,
);
let c = sdf(
gvx as f32 - offset,
gvy as f32 + offset,
gvz as f32 - offset,
);
let d = sdf(
gvx as f32 + offset,
gvy as f32 + offset,
gvz as f32 + offset,
);
let normal = Vec3::new(a - b - c + d, -a - b + c + d, -a + b - c + d);
let normal = if normal.length() <= f32::EPSILON
{
Vec3::new(1., 0., 0.)
}
else
{
normal.normalize()
};
let color = (normal.dot(Vec3::new(0., 1., 0.)) + 1.) * 0.5;
// let alpha = 1.;
// children_color.push(Color(
// (gvx - cx) as f32 / global_size as f32,
// (gvy - cy) as f32 / global_size as f32,
// (gvz - cz) as f32 / global_size as f32,
// alpha,
// ));
children.push(ChildInformation::new(subdivided, subdivided || alpha != 0.));
children_color.push(Color(color + random::<f32>() * 0.02, color, color, alpha));
children_normals.push((normal.x, normal.y, normal.z));
//children_color.push(Color(normal.x, normal.y, normal.z, alpha));
}
ProducedChunk {
children: std::array::from_fn(|i| children[i]),
colors: std::array::from_fn(|i| children_color[i].as_packed_u32()),
normals: std::array::from_fn(|i| children_normals[i].into()),
//normals: std::array::from_fn(|i| (1., 0., 0.)),
}
}
}
+464
View File
@@ -0,0 +1,464 @@
use std::collections::HashMap;
use std::collections::VecDeque;
use bytemuck::Pod;
use bytemuck::Zeroable;
use itertools::Itertools;
use noise::Terrace;
use vxls_production::tree_locator::TreeLocator;
#[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<I: Iterator<Item = Color>>(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
}
pub fn as_packed_u32(&self) -> u32
{
let mapped_r = (self.0 * 255.0).clamp(0., 255.0) as u32;
let mapped_g = (self.1 * 255.0).clamp(0., 255.0) as u32;
let mapped_b = (self.2 * 255.0).clamp(0., 255.0) as u32;
let mapped_a = (self.3 * 255.0).clamp(0., 255.0) as u32;
mapped_r | (mapped_g << 8) | (mapped_b << 16) | (mapped_a << 24)
}
}
#[derive(Debug, Clone)]
pub struct NTree<const N: usize>
{
map: HashMap<TreeLocator<N>, 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<N>,
dfs_stack: Vec<TreeLocator<N>>,
}
#[derive(Debug, Clone, Copy)]
pub struct NTreeNode
{
pub color: Color,
pub subdivided: bool,
}
impl<const N: usize> NTree<N>
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(TreeLocator::<N>::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 = TreeLocator::<N>::root();
let mut current_node_size = N.pow(self.depth as u32);
let mut current_node = self.map.get(&current_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 as u32, child_y as u32, child_z as u32);
current_node = self.map.get(&current_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 = TreeLocator::<N>::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(&current_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().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 as u32, child_y as u32, child_z as u32);
current_node = self.map.get_mut(&current_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()
.map(|child_loc| self.map.get(&child_loc).unwrap().color)
// AGGREGATE AND AVERAGE HERE !!
.next()
.unwrap();
current_node = self.map.get_mut(&current_node_loc).unwrap();
current_node.color = children_color_avg;
if current_depth == 0
{
break;
}
}
}
fn make_constant(&mut self, locator: TreeLocator<N>, 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(&current);
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 (z, y) in (0..width).cartesian_product(0..width)
{
let mut x = 0;
while x < 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
x += merged_size[x + y * width + z * width * width];
continue;
}
// Check smallest depth aligned with current position
let x_trailing = base_trailing_zeroes::<N>(x).unwrap_or(depth as u32);
let y_trailing = base_trailing_zeroes::<N>(y).unwrap_or(depth as u32);
let z_trailing = base_trailing_zeroes::<N>(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 =
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
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
{
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_z, merge_y), merge_x) 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);
x += 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 = TreeLocator::<N>::from_node_coords(
(depth - current_power) as u32,
block_x as u32,
block_y as u32,
block_z as u32,
);
// Get average color of children
let color = Color::average(
locator
.children()
.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 get_by_loc(&self, locator: TreeLocator<N>) -> Option<NTreeNode>
{
self.map.get(&locator).copied()
}
}
fn base_trailing_zeroes<const N: usize>(mut number: usize) -> Option<u32>
{
if number == 0
{
return None;
}
let mut trailing_zeroes = 0;
while number % N == 0
{
number /= N;
trailing_zeroes += 1;
}
Some(trailing_zeroes)
}
pub fn load_ply<P: AsRef<std::path::Path>, const N: usize>(path: P) -> NTree<N>
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];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
NTree::from_array(&colors, 4)
}
mod test
{
use glam::Vec3;
use rand::random;
use vxls_production::tree_locator::TreeLocator;
use crate::sparse_tree::Color;
use crate::sparse_tree::NTree;
#[test]
fn constant_set()
{
let mut tree = NTree::<4>::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.));
}
#[test]
fn load_read_same()
{
let file = std::fs::read_to_string(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../dragon.txt"
))
.unwrap();
let mut colors = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
for line in file.lines()
{
let coords = line
.split(',')
.take(3)
.map(|s| s.trim_end().trim_start().parse::<u32>().unwrap())
.collect::<Vec<_>>();
let (x, y, z) = (coords[0], coords[1], coords[2]);
let index = x + z * 256 + y * 256 * 256;
colors[index as usize] = Color(1., 1., 1., 1.);
}
println!("building tree");
let tree = NTree::<4>::from_array(&colors, 4);
println!("ok");
for x in 0..256
{
for y in 0..256
{
for z in 0..256
{
let index = x + y * 256 + z * 256 * 256;
let color = colors[index];
let t = tree.get(x, y, z);
assert!(t == color);
}
}
}
}
}