refactor: cleaner request path + raytracing code

This commit is contained in:
2026-11-23 11:32:16 +01:00
parent dd0e102348
commit dd5fdc13b8
20 changed files with 1427 additions and 618 deletions
+291 -16
View File
@@ -2,29 +2,304 @@
#![feature(generic_const_exprs)]
use std::fs::File;
use vxls_production::AttributeDescriptor;
use vxls_production::AttributesLayout;
use bytemuck::Zeroable;
use vxls_attributes::Attributes;
use vxls_production::io::write_tree;
use vxls_production::sparse_tree::Color;
use vxls_production::sparse_tree::ColorByte;
use vxls_production::sparse_tree::NTree;
use vxls_production::sparse_tree::load_ply;
/// Side length of the dense voxel grid.
const GRID: usize = 256;
const GRID_SQ: usize = GRID * GRID;
const VOXEL_COUNT: usize = GRID * GRID * GRID;
/// Number of smoothing passes. Each pass applies a 3D Gaussian approximation
/// with a support of 5 voxels, so two passes give a smooth normal field.
const BLUR_PASSES: usize = 2;
/// Voxel coordinates are stored as `x + z * GRID + y * GRID^2`, matching the
/// order used by `dragon.txt`.
#[inline]
fn voxel_index(x: usize, y: usize, z: usize) -> usize {
x + z * GRID + y * GRID_SQ
}
/// Pushes `(x, y, z)` onto the flood fill stack if it is empty and not yet
/// marked as exterior.
#[inline]
fn seed_exterior(
exterior: &mut [bool],
stack: &mut Vec<u32>,
occupied: &[bool],
x: usize,
y: usize,
z: usize,
) {
let index = voxel_index(x, y, z);
if !occupied[index] && !exterior[index] {
exterior[index] = true;
stack.push(index as u32);
}
}
/// Marks every empty voxel reachable from the grid border.
fn exterior_mask(occupied: &[bool]) -> Vec<bool> {
let mut exterior = vec![false; VOXEL_COUNT];
let mut stack = Vec::new();
// Seed from the six grid faces. Every air region connected to the outside
// is reachable from one of them.
for z in 0..GRID {
for y in 0..GRID {
seed_exterior(&mut exterior, &mut stack, occupied, 0, y, z);
seed_exterior(&mut exterior, &mut stack, occupied, GRID - 1, y, z);
}
}
for z in 0..GRID {
for x in 0..GRID {
seed_exterior(&mut exterior, &mut stack, occupied, x, 0, z);
seed_exterior(&mut exterior, &mut stack, occupied, x, GRID - 1, z);
}
}
for y in 0..GRID {
for x in 0..GRID {
seed_exterior(&mut exterior, &mut stack, occupied, x, y, 0);
seed_exterior(&mut exterior, &mut stack, occupied, x, y, GRID - 1);
}
}
while let Some(index) = stack.pop() {
let index = index as usize;
let x = index % GRID;
let z = (index / GRID) % GRID;
let y = index / GRID_SQ;
if x > 0 {
seed_exterior(&mut exterior, &mut stack, occupied, x - 1, y, z);
}
if x + 1 < GRID {
seed_exterior(&mut exterior, &mut stack, occupied, x + 1, y, z);
}
if y > 0 {
seed_exterior(&mut exterior, &mut stack, occupied, x, y - 1, z);
}
if y + 1 < GRID {
seed_exterior(&mut exterior, &mut stack, occupied, x, y + 1, z);
}
if z > 0 {
seed_exterior(&mut exterior, &mut stack, occupied, x, y, z - 1);
}
if z + 1 < GRID {
seed_exterior(&mut exterior, &mut stack, occupied, x, y, z + 1);
}
}
exterior
}
/// Builds a smoothable field that is `1` inside the dragon and `0` outside.
///
/// `dragon.txt` only samples the surface, so the occupied voxels form a thin
/// shell. Blurring that shell directly produces a density that peaks on the
/// shell, where the gradient is close to zero. Filling the enclosed volume
/// first makes the blurred field ramp across the surface, so its gradient is
/// well defined there.
fn solid_field(occupied: &[bool]) -> Vec<f32> {
let exterior = exterior_mask(occupied);
(0..VOXEL_COUNT)
.map(|index| {
// Anything occupied, or empty but not connected to the outside,
// belongs to the solid.
if occupied[index] || !exterior[index] {
1.0
} else {
0.0
}
})
.collect()
}
/// Separable [`1, 4, 6, 4, 1`] / 16 blur along `x` (clamped at the borders).
fn blur_x(src: &[f32], dst: &mut [f32]) {
for y in 0..GRID {
for z in 0..GRID {
let base = z * GRID + y * GRID_SQ;
for x in 0..GRID {
let xm2 = x.saturating_sub(2);
let xm1 = x.saturating_sub(1);
let xp1 = (x + 1).min(GRID - 1);
let xp2 = (x + 2).min(GRID - 1);
dst[base + x] = (src[base + xm2]
+ 4.0 * src[base + xm1]
+ 6.0 * src[base + x]
+ 4.0 * src[base + xp1]
+ src[base + xp2])
* (1.0 / 16.0);
}
}
}
}
/// Separable [`1, 4, 6, 4, 1`] / 16 blur along `y` (clamped at the borders).
fn blur_y(src: &[f32], dst: &mut [f32]) {
for z in 0..GRID {
for x in 0..GRID {
let base = z * GRID + x;
for y in 0..GRID {
let ym2 = y.saturating_sub(2);
let ym1 = y.saturating_sub(1);
let yp1 = (y + 1).min(GRID - 1);
let yp2 = (y + 2).min(GRID - 1);
dst[base + y * GRID_SQ] = (src[base + ym2 * GRID_SQ]
+ 4.0 * src[base + ym1 * GRID_SQ]
+ 6.0 * src[base + y * GRID_SQ]
+ 4.0 * src[base + yp1 * GRID_SQ]
+ src[base + yp2 * GRID_SQ])
* (1.0 / 16.0);
}
}
}
}
/// Separable [`1, 4, 6, 4, 1`] / 16 blur along `z` (clamped at the borders).
fn blur_z(src: &[f32], dst: &mut [f32]) {
for y in 0..GRID {
for x in 0..GRID {
let base = y * GRID_SQ + x;
for z in 0..GRID {
let zm2 = z.saturating_sub(2);
let zm1 = z.saturating_sub(1);
let zp1 = (z + 1).min(GRID - 1);
let zp2 = (z + 2).min(GRID - 1);
dst[base + z * GRID] = (src[base + zm2 * GRID]
+ 4.0 * src[base + zm1 * GRID]
+ 6.0 * src[base + z * GRID]
+ 4.0 * src[base + zp1 * GRID]
+ src[base + zp2 * GRID])
* (1.0 / 16.0);
}
}
}
}
/// Computes an outward unit normal for every occupied voxel from the smoothed
/// solid field.
///
/// The field is `1` inside and `0` outside, so its gradient points inwards;
/// the outward normal is the negated, normalised gradient.
fn compute_normals(occupied: &[bool], field: &[f32], normals: &mut [[f32; 3]]) {
for z in 0..GRID {
for y in 0..GRID {
for x in 0..GRID {
let index = voxel_index(x, y, z);
if !occupied[index] {
continue;
}
let xm = voxel_index(x.saturating_sub(1), y, z);
let xp = voxel_index((x + 1).min(GRID - 1), y, z);
let ym = voxel_index(x, y.saturating_sub(1), z);
let yp = voxel_index(x, (y + 1).min(GRID - 1), z);
let zm = voxel_index(x, y, z.saturating_sub(1));
let zp = voxel_index(x, y, (z + 1).min(GRID - 1));
let gx = field[xp] - field[xm];
let gy = field[yp] - field[ym];
let gz = field[zp] - field[zm];
let (nx, ny, nz) = (-gx, -gy, -gz);
let length = (nx * nx + ny * ny + nz * nz).sqrt();
normals[index] = if length > 1e-6 {
[nx / length, ny / length, nz / length]
} else {
// Degenerate gradient (for example a voxel fully enclosed
// by the solid): keep a sane unit normal.
[0.0, 1.0, 0.0]
};
}
}
}
}
#[derive(Attributes, PartialEq, Clone, Copy, Default, bytemuck::Pod, Zeroable)]
#[repr(C)]
struct VoxelPayload {
#[attribute(label = "color", semantic = "color")]
color_byte: ColorByte,
#[attribute(label = "normal", semantic = "normal")]
normal: [f32; 3],
}
// impl Attribute for VoxelPayload
// {
// fn average(attributes: &[Self]) -> Self {
// let colors: Vec<ColorByte> = attributes.iter().map(|a| a.color_byte).collect();
// let normals: Vec<[f32; 3]> = attributes.iter().map(|a| a.normal).collect();
//
// Self
// {
// color_byte: ColorByte::average(&colors),
// normal: <[f32; 3] as Attribute>::average(&normals),
// }
// }
// }
fn main() {
let dragon: NTree<4, Color> = load_ply("../../dragon.txt");
let mut file = File::create("../../dragon.vxls").unwrap();
let file = std::fs::read_to_string("../../dragon.txt").unwrap();
let dragon_u32 = dragon.mapped(|v| v.as_color_byte());
let mut colors = vec![Color::default(); VOXEL_COUNT];
let mut normals = vec![[0.0f32; 3]; VOXEL_COUNT];
// Load file
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] as usize, coords[1] as usize, coords[2] as usize);
let index = voxel_index(x, y, z);
colors[index] = Color(1., 1., 1., 1.);
}
// Occupancy comes straight from the loaded colors (alpha > 0).
let occupied: Vec<bool> = colors.iter().map(|color| color.3 != 0.0).collect();
// Smooth a solid version of the occupancy, then read the surface normal
// from the gradient of the smoothed field.
let mut field = solid_field(&occupied);
let mut scratch = vec![0.0f32; VOXEL_COUNT];
for _ in 0..BLUR_PASSES {
blur_x(&field, &mut scratch);
blur_y(&scratch, &mut field);
blur_z(&field, &mut scratch);
std::mem::swap(&mut field, &mut scratch);
}
compute_normals(&occupied, &field, &mut normals);
let bundled: Vec<_> = colors
.iter()
.zip(normals.iter())
.map(|(color, normal)| VoxelPayload {
color_byte: color.as_color_byte(),
normal: *normal,
})
.collect();
let tree: NTree<4, _> = NTree::from_array(&bundled, 4);
write_tree(
&mut file,
&dragon_u32,
AttributesLayout {
attributes: &[AttributeDescriptor {
label: "color",
word_count: 1,
semantic: None,
}],
},
&mut File::create("../../dragon.vxls").unwrap(),
&tree,
VoxelPayload::LAYOUT,
)
.unwrap();
println!("Wrote file")
}
+155
View File
@@ -4,7 +4,12 @@ use std::collections::HashMap;
use crate::ProducerId;
use crate::StructureLocator;
use crate::producer::ProducedNode;
use crate::tree_locator::TreeLocator;
use vxls_attributes::Attributes;
use vxls_voxel_cache::insertion::InsertionEntry;
use vxls_voxel_cache::schema::InsertionParent;
use vxls_voxel_cache::schema::LocationPage;
use vxls_voxel_cache::schema::NO_PARENT_PAGE;
use vxls_voxel_cache::schema::RequestInformation;
use vxls_voxel_cache::schema::RequestMeta;
@@ -71,6 +76,28 @@ impl RequestKey {
pub fn is_root(&self) -> bool {
matches!(self.target, RequestTarget::Root)
}
/// The content-local locator of the node this request asks for.
///
/// This is the locator a producer must pass to the sparse tree, and the
/// locator that goes into the produced page's `LocationPage`. Deriving it
/// from the key keeps production and insertion identity in sync.
pub fn node_locator<const N: usize>(&self) -> StructureLocator {
match self.target {
RequestTarget::Root => TreeLocator::<N>::root().into(),
RequestTarget::Child {
parent,
children_index,
} => {
let n = N as u32;
let x = children_index % n;
let y = (children_index / n) % n;
let z = children_index / (n * n);
TreeLocator::<N>::from(parent).child(x, y, z).into()
}
}
}
}
/// Scheduling priority. Higher is more urgent.
@@ -211,6 +238,32 @@ impl<T> ReadyItem<T> {
}
}
}
/// Identity recorded for the produced page.
///
/// Page identity comes from the request key (producer, anchor and target),
/// never from the producer payload. The table slot is deliberately absent.
pub fn location_page<const N: usize>(&self) -> LocationPage {
LocationPage {
node_id: self.key.node_locator::<N>(),
producer_id: self.key.producer_id,
anchor: self.key.anchor,
}
}
}
impl<const N: usize, A: Attributes> ReadyItem<ProducedNode<N, A>>
where
[(); N * N * N]:,
{
/// Builds the complete cache-facing entry for this produced node.
pub fn insertion_entry(&self) -> InsertionEntry<N> {
InsertionEntry {
information: self.payload.insertion,
parent: self.insertion_parent(),
location: self.location_page::<N>(),
}
}
}
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
@@ -706,6 +759,8 @@ impl<T> RequestQueue<T> {
mod tests {
use super::*;
use vxls_voxel_cache::schema::ChildInformation;
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::NO_TABLE_SLOT;
const PRODUCER: ProducerId = ProducerId(0);
@@ -1318,4 +1373,104 @@ mod tests {
assert!(q.contains(&b));
assert!(!q.contains(&a));
}
#[test]
fn root_key_locator_is_root() {
let key = RequestKey::root(PRODUCER, ANCHOR);
let expected: StructureLocator = TreeLocator::<4>::root().into();
assert_eq!(key.node_locator::<4>(), expected);
}
#[test]
fn child_key_locator_is_child_of_parent() {
let parent: StructureLocator = TreeLocator::<4>::root().into();
// children_index = x + 4*y + 16*z = 2 + 12 + 16.
let key = RequestKey::child(PRODUCER, ANCHOR, parent, 30);
let expected: StructureLocator = TreeLocator::<4>::from(parent).child(2, 3, 1).into();
assert_eq!(key.node_locator::<4>(), expected);
}
#[test]
fn ready_item_location_page_uses_key_identity() {
let mut q = queue(8, 1, 8);
let parent: StructureLocator = TreeLocator::<4>::root().into();
let key = RequestKey::child(PRODUCER, ANCHOR, parent, 5);
q.ingest(
0,
[IncomingRequest {
key,
priority: RequestPriority::child(1, 3),
meta: meta(7, 5, 3),
}],
);
let item = q.pop().unwrap();
q.complete(item, 1);
let ready = q.drain_ready_matching(0, 8, |_| true);
let location = ready[0].location_page::<4>();
assert_eq!(location.node_id, key.node_locator::<4>());
assert_eq!(location.producer_id, PRODUCER);
assert_eq!(location.anchor, ANCHOR);
}
#[derive(
Clone,
Copy,
PartialEq,
Default,
bytemuck::Pod,
bytemuck::Zeroable,
vxls_attributes::Attributes,
Debug,
)]
#[repr(C)]
struct TestVoxel {
#[attribute(label = "color", semantic = "color")]
color: u32,
}
#[test]
fn ready_item_builds_a_complete_insertion_entry() {
let mut q: RequestQueue<ProducedNode<4, TestVoxel>> = RequestQueue::new(QueueConfig {
max_queued: 8,
max_in_flight: 1,
max_ready: 8,
stale_after: 4,
max_attempts: 3,
});
let parent: StructureLocator = TreeLocator::<4>::root().into();
let key = RequestKey::child(PRODUCER, ANCHOR, parent, 5);
q.ingest(
0,
[IncomingRequest {
key,
priority: RequestPriority::child(1, 3),
meta: meta(7, 5, 3),
}],
);
let node = ProducedNode::new(
InsertionInformation::<4> {
children: [ChildInformation::NONE; 4 * 4 * 4],
},
[TestVoxel { color: 9 }; 4 * 4 * 4],
);
let item = q.pop().unwrap();
q.complete(item, node);
let ready = q.drain_ready_matching(0, 8, |_| true);
let entry = ready[0].insertion_entry();
assert_eq!(entry.location.node_id, key.node_locator::<4>());
assert_eq!(entry.location.producer_id, PRODUCER);
assert_eq!(entry.location.anchor, ANCHOR);
assert_eq!(entry.parent.page_index, 7);
assert_eq!(entry.parent.children_index, 5);
assert_eq!(entry.parent.depth, 3);
}
}
+4 -2
View File
@@ -34,7 +34,8 @@ impl Attribute for Color {
c.3 += color.3;
}
let count = attributes.len() as f32;
//let count = attributes.len() as f32;
let count = c.3;
c.0 /= count;
c.1 /= count;
c.2 /= count;
@@ -58,7 +59,8 @@ impl Attribute for ColorByte {
c.3 += color.3;
}
let count = attributes.len() as f32;
//let count = attributes.len() as f32;
let count = c.3;
c.0 /= count;
c.1 /= count;
c.2 /= count;
+145
View File
@@ -53,6 +53,74 @@ where
bind_group_no_attributes: wgpu::BindGroup,
}
/// One entry of an insertion batch.
///
/// The cache owns page identity, so the host supplies the structure of the
/// produced page together with the parent it attaches to and the location it
/// should be recorded at. The cache does not depend on the producer crate, so
/// this is the primitive form produced by `ReadyItem::insertion_entry`.
#[derive(Clone, Copy, Debug)]
pub struct InsertionEntry<const N: usize>
where
[(); N * N * N]:,
{
/// Structure of the produced page.
pub information: InsertionInformation<N>,
/// Attachment point of the produced page.
pub parent: InsertionParent,
/// Identity recorded for the produced page.
pub location: LocationPage,
}
/// Errors reported while uploading a full insertion batch.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InsertionUploadError {
/// The batch has more entries than the insertion data can hold.
TooManyEntries { provided: usize, capacity: usize },
/// The voxel slice does not contain exactly one page per entry.
VoxelCountMismatch { provided: usize, expected: usize },
/// The producer attribute layout does not match the cache layout.
LayoutMismatch {
producer: AttributesLayout,
cache: AttributesLayout,
},
/// The attribute payload was rejected by [`CacheInsertionData::write_attributes`].
Attributes(AttributeUploadError),
}
impl From<AttributeUploadError> for InsertionUploadError {
fn from(error: AttributeUploadError) -> Self {
Self::Attributes(error)
}
}
impl std::fmt::Display for InsertionUploadError {
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::TooManyEntries { provided, capacity } => write!(
formatter,
"insertion batch has {provided} entries but capacity is {capacity}"
),
Self::VoxelCountMismatch { provided, expected } => write!(
formatter,
"insertion batch has {provided} voxels but expected {expected}"
),
Self::LayoutMismatch { producer, cache } => write!(
formatter,
"producer attribute layout {producer:?} does not match cache layout {cache:?}"
),
Self::Attributes(error) => write!(formatter, "attribute upload failed: {error:?}"),
}
}
}
impl std::error::Error for InsertionUploadError {}
/// Errors reported while uploading a producer attribute slice into
/// [`CacheInsertionData`].
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -355,6 +423,11 @@ where
self.max_page_count
}
/// Maximum number of entries a batch can hold.
pub fn capacity(&self) -> usize {
self.max_page_count
}
pub fn page_count_buffer(&self) -> &wgpu::Buffer {
&self.page_count_buffer
}
@@ -440,6 +513,78 @@ where
Ok(voxels.len() / (N * N * N))
}
/// Uploads a complete insertion batch.
///
/// `entries` and `voxels` must agree: `voxels` contains one page of
/// [`Attributes`] per entry, in entry-major order. This writes the
/// structure, location and parent arrays, resets `valid_count`, sets
/// `page_count` to the number of entries, and uploads the attributes.
///
/// `destination_indices` is intentionally not written here: the internal
/// and external validation passes reset every entry they process, so a
/// stale destination can never survive a batch.
///
/// Returns the number of entries written.
pub fn upload<A: Attributes>(
&self,
queue: &wgpu::Queue,
entries: &[InsertionEntry<N>],
voxels: &[A],
) -> Result<usize, InsertionUploadError> {
if A::LAYOUT != self.layout {
return Err(InsertionUploadError::LayoutMismatch {
producer: A::LAYOUT,
cache: self.layout,
});
}
if entries.len() > self.capacity() {
return Err(InsertionUploadError::TooManyEntries {
provided: entries.len(),
capacity: self.capacity(),
});
}
let expected_voxels = entries.len() * N * N * N;
if voxels.len() != expected_voxels {
return Err(InsertionUploadError::VoxelCountMismatch {
provided: voxels.len(),
expected: expected_voxels,
});
}
// Disable the batch until every buffer has been written successfully.
// This prevents a partially-uploaded batch from being encoded if an
// attribute upload fails after the structure buffers were written.
queue.write_buffer(&self.page_count_buffer, 0, bytemuck::bytes_of(&0u32));
queue.write_buffer(&self.valid_count, 0, bytemuck::bytes_of(&0u32));
if entries.is_empty() {
return Ok(0);
}
let informations: Vec<InsertionInformation<N>> =
entries.iter().map(|entry| entry.information).collect();
let locations: Vec<LocationPage> = entries.iter().map(|entry| entry.location).collect();
let parents: Vec<InsertionParent> = entries.iter().map(|entry| entry.parent).collect();
queue.write_buffer(
&self.insertion_information,
0,
bytemuck::cast_slice(&informations),
);
queue.write_buffer(&self.location_pages, 0, bytemuck::cast_slice(&locations));
queue.write_buffer(&self.insertion_parents, 0, bytemuck::cast_slice(&parents));
self.write_attributes(queue, voxels)?;
// Only now is the batch complete and safe to process.
let entry_count = entries.len() as u32;
queue.write_buffer(&self.page_count_buffer, 0, bytemuck::bytes_of(&entry_count));
Ok(entries.len())
}
}
#[cfg(test)]
+81 -299
View File
@@ -2,6 +2,7 @@
#![feature(generic_const_exprs)]
#![feature(float_algebraic)]
use std::fs::File;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::AtomicU32;
@@ -23,6 +24,7 @@ use itertools::Itertools;
use rand::random_range;
use rayon::iter::IntoParallelRefIterator;
use rayon::iter::ParallelIterator;
use vxls_production::io::read_tree;
use vxls_production::sparse_tree::Color;
use vxls_production::sparse_tree::NTree;
use vxls_production::sparse_tree::load_ply;
@@ -56,32 +58,31 @@ use winit::window::WindowId;
use crate::camera::Camera;
use crate::egui_renderer::EguiRenderer;
use crate::producers::SdfGenerator;
use crate::producers::TreeProducer;
use crate::producers::VoxelAttributes;
use vxls_bvh::BvhHandle;
use vxls_bvh::BvhObject;
use vxls_bvh::BvhStructureTable;
use vxls_bvh::aabb::Aabb;
use vxls_bvh::debug::BvhDebugPipeline;
use vxls_production::Attributes;
use vxls_production::ProducedNode;
use vxls_production::Producer;
use vxls_production::ProducerId;
use vxls_production::StructureAnchor;
use vxls_production::StructureLocator;
use vxls_production::request_queue::FrameId;
use vxls_production::request_queue::IncomingRequest;
use vxls_production::request_queue::QueueConfig;
use vxls_production::request_queue::RequestKey;
use vxls_production::request_queue::ReadyItem;
use vxls_production::request_queue::RequestQueue;
use vxls_production::request_queue::RequestTarget;
use vxls_production::tree_locator::TreeLocator;
use vxls_profiler::Frame;
use vxls_profiler::Profile;
use vxls_profiler::ProfilingEncoder;
use vxls_voxel_cache::VoxelCache;
use vxls_voxel_cache::VoxelCacheInsertion;
use vxls_voxel_cache::insertion::CacheInsertionData;
use vxls_voxel_cache::insertion::InsertionUploadError;
use vxls_voxel_cache::requests::CacheRequestBuffer;
use vxls_voxel_cache::schema::ChildInformation;
use vxls_voxel_cache::schema::InsertionInformation;
use vxls_voxel_cache::schema::LocationPage;
mod camera;
mod egui_renderer;
@@ -94,16 +95,6 @@ enum DisplayTexture {
Albedo,
}
struct VoxelPayload<const N: usize>
where
[(); N * N * N]:,
{
color: [u32; N * N * N],
normal: [[f32; 3]; N * N * N],
insertion_information: InsertionInformation<N>,
location_page: LocationPage,
}
struct State {
instance: wgpu::Instance,
window: Arc<Window>,
@@ -128,9 +119,10 @@ struct State {
gi_bg_layout: BindGroupLayout,
voxel_cache: Arc<Mutex<VoxelCache<4>>>,
request_queue: Arc<Mutex<RequestQueue<VoxelPayload<4>>>>,
request_queue: Arc<Mutex<RequestQueue<ProducedNode<4, VoxelAttributes>>>>,
request_buffer: Arc<CacheRequestBuffer>,
cache_insertion: Arc<CacheInsertionData<4>>,
frame_id: FrameId,
structure_table: Arc<Mutex<BvhStructureTable>>,
//structure_table: Arc<Mutex<FixedStructureTable>>,
@@ -358,7 +350,9 @@ impl State {
*/
// Load dragon ply
let tree: NTree<4, Color> = load_ply("../../dragon.txt");
//let tree: NTree<4, Color> = load_ply("../../dragon.txt");
let mut file = File::open("../../dragon.vxls").unwrap();
let tree: NTree<4, VoxelAttributes> = read_tree(&mut file, None).unwrap().tree;
// let mut arrays = vec![Color(0., 0., 0., 0.); 256 * 256 * 256];
// for ((x, y), z) in (0..256).cartesian_product(0..256).cartesian_product(0..256)
// {
@@ -420,12 +414,13 @@ impl State {
let mut bvh_objs = Vec::new();
for _ in 0..1000 {
let transform = Mat4::from_rotation_translation(
Quat::from_euler(
glam::EulerRot::XYZ,
random_range(-3.1..3.1),
random_range(-3.1..3.1),
random_range(-3.1..3.1),
),
// Quat::from_euler(
// glam::EulerRot::XYZ,
// random_range(-3.1..3.1),
// random_range(-3.1..3.1),
// random_range(-3.1..3.1),
// ),
Quat::IDENTITY,
Vec3::new(
random_range(extent.min().x..extent.max().x),
random_range(extent.min().y..extent.max().y),
@@ -729,10 +724,10 @@ impl State {
});
let structure_table = Arc::new(Mutex::new(structure_table));
let structure_table_1 = structure_table.clone();
let request_queue = Arc::new(Mutex::new(RequestQueue::new(QueueConfig::default())));
let request_queue_1 = request_queue.clone();
let (wakeup_tx, wakeup_rx) = std::sync::mpsc::channel();
let producer = TreeProducer::new(tree);
std::thread::spawn(move || {
loop {
if !wakeup_rx.recv().is_ok() {
@@ -755,30 +750,18 @@ impl State {
break;
}
let finshed = work
let finished = work
.par_iter()
.map(|work_item| {
// let d = fullfill_request(
// &terrain_generator,
// &work_item.key,
// &structure_table_1,
// );
let d = fullfill_request_tree(&tree, &work_item.key);
(
work_item,
VoxelPayload {
color: d.0,
normal: d.1,
insertion_information: d.2,
location_page: d.3,
},
)
let payload = producer
.produce(work_item.key.anchor, work_item.key.node_locator::<4>());
(work_item, payload)
})
.collect::<Vec<_>>();
{
let mut locked = request_queue_1.lock();
finshed.into_iter().for_each(|(work_item, payload)| {
finished.into_iter().for_each(|(work_item, payload)| {
locked.complete(*work_item, payload);
});
}
@@ -827,6 +810,7 @@ impl State {
request_queue,
request_buffer: Arc::new(request_buffer),
cache_insertion: Arc::new(insertion_data),
frame_id: 0,
structure_table,
structure_table_cache_insertion: Arc::new(structure_table_insertion_data),
@@ -1034,6 +1018,7 @@ impl State {
fn render(&mut self) {
self.camera.update();
/*
let mut locked_table = self.structure_table.lock();
for (hndl, dir) in self.bvh_objs.iter_mut() {
let obj = locked_table.get_mut(hndl);
@@ -1053,6 +1038,7 @@ impl State {
locked_table.mark_dirty();
locked_table.rebuild_if_dirty(&self.device, &self.queue);
drop(locked_table);
*/
// Create texture view.
// NOTE: We must handle Timeout because the surface may be unavailable
@@ -1422,25 +1408,22 @@ impl State {
.contains(&winit::keyboard::KeyCode::KeyF)
{
self.insertion_debounce = true;
let frame_id: FrameId = self.voxel_cache.lock().current_timestamp().into();
let cloned_queue = self.queue.clone();
self.frame_id = self.frame_id.wrapping_add(1);
let frame_id = self.frame_id;
let finished = Arc::new(AtomicU32::new(0));
// Cache requests
let cloned_insertion_data = self.cache_insertion.clone();
// Cache requests. The callback only ingests; production and
// uploads happen after both downloads have landed, so the main
// thread can never encode an insertion from a half-updated batch.
let request_buffer_done = Arc::new(AtomicBool::new(false));
let request_buffer_done_1 = request_buffer_done.clone();
let finshed_1 = finished.clone();
let finished_1 = finished.clone();
let request_queue_1 = self.request_queue.clone();
self.request_buffer.host_download_requests(
&self.device,
&self.queue,
move |request_informations, request_metas| {
let done = request_buffer_done_1.load(std::sync::atomic::Ordering::Relaxed);
if !done {
request_buffer_done_1.store(true, std::sync::atomic::Ordering::Relaxed);
finshed_1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
} else {
if request_buffer_done_1.swap(true, std::sync::atomic::Ordering::Relaxed) {
return;
}
@@ -1451,99 +1434,23 @@ impl State {
.zip(request_metas.iter())
.map(|(info, meta)| IncomingRequest::from_wire(info, meta)),
);
//println!("Structure table: {} requests", request_informations.len());
let drained =
request_queue_1
.lock()
.drain_ready_matching(frame_id, 1024, |key| !key.is_root());
let mut insertion_infos = vec![];
let mut color_attributes = vec![];
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
let mut insertion_parents = vec![];
drained.into_iter().for_each(|payload| {
insertion_infos.push(payload.payload.insertion_information);
color_attributes.push(payload.payload.color);
normal_attributes.push(payload.payload.normal);
location_pages.push(payload.payload.location_page);
insertion_parents.push(payload.insertion_parent());
});
let request_count = request_informations.len() as u32;
cloned_queue.write_buffer(
cloned_insertion_data.insertion_information_buffer(),
0,
bytemuck::cast_slice(&insertion_infos),
);
cloned_queue.write_buffer(
cloned_insertion_data.location_pages_buffer(),
0,
bytemuck::cast_slice(&location_pages),
);
cloned_queue.write_buffer(
cloned_insertion_data.insertion_parents_buffer(),
0,
bytemuck::cast_slice(&insertion_parents),
);
cloned_queue.write_buffer(
&cloned_insertion_data.attributes_buffers()[0],
0,
bytemuck::cast_slice(&color_attributes),
);
cloned_queue.write_buffer(
&cloned_insertion_data.attributes_buffers()[1],
0,
bytemuck::cast_slice(&normal_attributes),
);
cloned_queue.write_buffer(
cloned_insertion_data.destination_indices_buffer(),
0,
bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]),
);
cloned_queue.write_buffer(
cloned_insertion_data.valid_count_buffer(),
0,
bytemuck::bytes_of(&0u32),
);
cloned_queue.write_buffer(
cloned_insertion_data.page_count_buffer(),
0,
bytemuck::bytes_of(&request_count),
);
finished_1.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
},
);
let cloned_queue = self.queue.clone();
// Structure table requests
let cloned_st_insertion_data = self.structure_table_cache_insertion.clone();
// Structure table requests.
let structure_table_request_buffer_done = Arc::new(AtomicBool::new(false));
let structure_table_request_buffer_done_1 = structure_table_request_buffer_done.clone();
let finshed_2 = finished.clone();
let cloned_table_2 = self.structure_table.clone();
let finished_2 = finished.clone();
let request_queue_2 = self.request_queue.clone();
self.structure_table_request_buffer.host_download_requests(
&self.device,
&self.queue,
move |request_informations, request_metas| {
let done = structure_table_request_buffer_done_1
.load(std::sync::atomic::Ordering::Relaxed);
if !done {
structure_table_request_buffer_done_1
.store(true, std::sync::atomic::Ordering::Relaxed);
finshed_2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
} else {
if structure_table_request_buffer_done_1
.swap(true, std::sync::atomic::Ordering::Relaxed)
{
return;
}
@@ -1555,76 +1462,7 @@ impl State {
.map(|(info, meta)| IncomingRequest::from_wire(info, meta)),
);
let drained =
request_queue_2
.lock()
.drain_ready_matching(frame_id, 128, |key| key.is_root());
//println!("Structure table: {} requests", request_informations.len());
let mut insertion_infos = vec![];
let mut color_attributes = vec![];
let mut normal_attributes: Vec<[[f32; 3]; 64]> = vec![];
let mut location_pages = vec![];
let mut insertion_parents = vec![];
drained.into_iter().for_each(|payload| {
insertion_infos.push(payload.payload.insertion_information);
color_attributes.push(payload.payload.color);
normal_attributes.push(payload.payload.normal);
location_pages.push(payload.payload.location_page);
insertion_parents.push(payload.insertion_parent());
});
let request_count = request_informations.len() as u32;
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_information_buffer(),
0,
bytemuck::cast_slice(&insertion_infos),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.location_pages_buffer(),
0,
bytemuck::cast_slice(&location_pages),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.insertion_parents_buffer(),
0,
bytemuck::cast_slice(&insertion_parents),
);
cloned_queue.write_buffer(
&cloned_st_insertion_data.attributes_buffers()[0],
0,
bytemuck::cast_slice(&color_attributes),
);
cloned_queue.write_buffer(
&cloned_st_insertion_data.attributes_buffers()[1],
0,
bytemuck::cast_slice(&normal_attributes),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.destination_indices_buffer(),
0,
bytemuck::cast_slice(&vec![u32::MAX; request_count as usize]),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.valid_count_buffer(),
0,
bytemuck::bytes_of(&0u32),
);
cloned_queue.write_buffer(
cloned_st_insertion_data.page_count_buffer(),
0,
bytemuck::bytes_of(&request_count),
);
finished_2.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
},
);
@@ -1637,6 +1475,26 @@ impl State {
let _ = self.device.poll(wgpu::wgt::PollType::Poll);
}
let children = self.request_queue.lock().drain_ready_matching(
frame_id,
self.cache_insertion.capacity(),
|key| !key.is_root(),
);
let roots = self.request_queue.lock().drain_ready_matching(
frame_id,
self.structure_table_cache_insertion.capacity(),
|key| key.is_root(),
);
if let Err(error) = upload_ready(&self.queue, &self.cache_insertion, children) {
eprintln!("cache insertion upload failed: {error}");
}
if let Err(error) =
upload_ready(&self.queue, &self.structure_table_cache_insertion, roots)
{
eprintln!("structure table insertion upload failed: {error}");
}
let mut encoder = self.device.create_command_encoder(&Default::default());
let mut scoped_encoder = ProfilingEncoder::new(&self.device, &mut encoder);
@@ -1780,100 +1638,6 @@ pub struct ChunkImmediate {
frame_timestamp: u32,
}
fn fullfill_request_tree<const N: usize>(
tree: &NTree<N, Color>,
request: &RequestKey,
) -> (
[u32; N * N * N],
[[f32; 3]; N * N * N],
InsertionInformation<N>,
LocationPage,
) {
match request.target {
RequestTarget::Root => {
let root = tree
.get_by_loc(TreeLocator::root())
.expect("Root must exist");
if !root.subdivided {
// Produce little node of constant
(
[root.attribute.as_packed_u32(); N * N * N],
//[sparse_tree::Color(1., 1., 1., 1.).as_packed_u32(); N * N * N],
[Default::default(); N * N * N],
InsertionInformation {
children: [ChildInformation::new(false, root.attribute.3 != 0.); N * N * N],
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()),
producer_id: ProducerId(0),
anchor: StructureAnchor::zeroed(),
},
)
} else {
let mut colors = vec![];
let mut children = vec![];
TreeLocator::root().children().for_each(|loc| {
let node = tree.get_by_loc(loc).unwrap();
colors.push(node.attribute.as_packed_u32());
children.push(ChildInformation::new(
node.subdivided,
node.subdivided || node.attribute.3 != 0.,
));
});
(
std::array::from_fn(|i| colors[i]),
[Default::default(); N * N * N],
InsertionInformation {
children: std::array::from_fn(|i| children[i]),
},
LocationPage {
node_id: StructureLocator::from(TreeLocator::<N>::root()),
producer_id: ProducerId(0),
anchor: StructureAnchor::zeroed(),
},
)
}
}
RequestTarget::Child {
parent,
children_index,
} => {
let child_z = children_index / (4 * 4);
let child_y = (children_index % (4 * 4)) / 4;
let child_x = children_index % 4;
let loc: TreeLocator<N> = parent.into();
let loc = loc.child(child_x, child_y, child_z);
let mut colors = vec![];
let mut children = vec![];
loc.children().for_each(|child_loc| {
let node = tree.get_by_loc(child_loc).unwrap();
colors.push(node.attribute.as_packed_u32());
children.push(ChildInformation::new(
node.subdivided,
node.subdivided || node.attribute.3 != 0.,
));
});
(
std::array::from_fn(|i| colors[i]),
[Default::default(); N * N * N],
InsertionInformation {
children: std::array::from_fn(|i| children[i]),
},
LocationPage {
node_id: StructureLocator::from(loc),
producer_id: ProducerId(0),
anchor: StructureAnchor::zeroed(),
},
)
}
}
}
/*
fn fullfill_request<const N: usize>(
generator: &dyn ChunkedProducer<N>,
@@ -1973,3 +1737,21 @@ where
)
}
*/
/// Stages produced nodes into one insertion batch and uploads it.
fn upload_ready<const N: usize>(
queue: &wgpu::Queue,
insertion: &CacheInsertionData<N>,
ready: Vec<ReadyItem<ProducedNode<N, VoxelAttributes>>>,
) -> Result<usize, InsertionUploadError>
where
[(); N * N * N]:,
{
let entries: Vec<_> = ready.iter().map(|item| item.insertion_entry()).collect();
let voxels: Vec<VoxelAttributes> = ready
.iter()
.flat_map(|item| item.payload.attributes.iter().copied())
.collect();
insertion.upload(queue, &entries, &voxels)
}
+80
View File
@@ -11,8 +11,16 @@ use noise::NoiseFn;
use noise::Simplex;
use rand::random;
use vxls_production::ProducedNode;
use vxls_production::Producer as VoxelProducer;
use vxls_production::StructureAnchor;
use vxls_production::StructureLocator;
use vxls_production::sparse_tree::Color;
use vxls_production::sparse_tree::ColorByte;
use vxls_production::sparse_tree::NTree;
use vxls_production::tree_locator::TreeLocator;
use vxls_voxel_cache::schema::ChildInformation;
use vxls_voxel_cache::schema::InsertionInformation;
/// The voxel attributes used by the demo cache.
///
@@ -646,3 +654,75 @@ where
}
}
}
/// Produces cache pages from an in-memory sparse tree.
///
/// The node to produce is named by the request's `node_locator`, so the
/// producer never needs to know whether the cache asked for a structure root
/// or an internal child.
pub struct TreeProducer<const N: usize>
where
[(); N * N * N]:,
{
tree: NTree<N, VoxelAttributes>,
}
impl<const N: usize> TreeProducer<N>
where
[(); N * N * N]:,
{
pub fn new(tree: NTree<N, VoxelAttributes>) -> Self {
Self { tree }
}
}
impl<const N: usize> VoxelProducer<N, VoxelAttributes> for TreeProducer<N>
where
[(); N * N * N]:,
{
fn produce(
&self,
_anchor: StructureAnchor,
locator: StructureLocator,
) -> ProducedNode<N, VoxelAttributes> {
let locator = TreeLocator::<N>::from(locator);
let node = self
.tree
.get_by_loc(locator)
.expect("requested node is not in the source tree");
let mut children = [ChildInformation::NONE; N * N * N];
let mut attributes = [VoxelAttributes::default(); N * N * N];
if node.subdivided {
for (index, child_locator) in locator.children().enumerate() {
let child = self
.tree
.get_by_loc(child_locator)
.expect("subdivided node is missing a child");
children[index] = ChildInformation::new(
child.subdivided,
child.subdivided || ColorByte(child.attribute.color).as_color().3 != 0.,
);
attributes[index] = VoxelAttributes {
color: child.attribute.color,
normal: child.attribute.normal,
};
}
} else {
let color = node.attribute.color;
let occupied = ColorByte(node.attribute.color).as_color().3 != 0.;
for index in 0..N * N * N {
children[index] = ChildInformation::new(false, occupied);
attributes[index] = VoxelAttributes {
color,
normal: node.attribute.normal,
};
}
}
ProducedNode::new(InsertionInformation { children }, attributes)
}
}