refactor: cleaner request path + raytracing code
This commit is contained in:
@@ -81,9 +81,10 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
|
||||
6. **`N` is overloaded:** Rust `VoxelCache<N>` / `VoxelCacheInsertion<N>` use `N`
|
||||
as the branching factor; Slang `VoxelCacheParameters<N>` uses `N` as the
|
||||
attribute count. Read the surrounding type before assuming.
|
||||
7. **Depth assumptions:** `VoxelTraceStack` holds 5 entries and indexes
|
||||
`stack[10 - scale_exp/2]`, assuming branching 4 and `chunk_power = 5`.
|
||||
Changing either breaks tracing silently.
|
||||
7. **Depth assumptions:** the caller-owned trace stack (`LocalTraceStack`)
|
||||
holds 5 entries and indexes `entries[10 - scale_exp/2]`, assuming branching
|
||||
4 and `chunk_power = 5`. Changing either breaks tracing silently. The stack
|
||||
is caller-owned; the tracer must not depend on where the front-end stores it.
|
||||
8. **Generated WGSL constants:** `CHILDREN_COUNT`, `PAGE_COUNT`, and attribute
|
||||
metadata are injected at runtime by `pipelines.rs`. Edit the Rust generator,
|
||||
not a generated copy.
|
||||
@@ -116,7 +117,8 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
|
||||
| Add/change slot allocation or table growth | `crates/vxls-voxel-cache/src/tables.rs` (`DynamicStructureTable`, `SlotAllocator`, `StructureTableCore`) |
|
||||
| Change structure identity / anchors | `crates/vxls-voxel-cache/src/schema.rs` (`StructureAnchor`, wire structs), `crates/vxls-production/src/request_queue.rs`, `crates/vxls-voxel-cache/src/tables.rs`, `crates/vxls-voxel-cache/src/shaders/common.wgsl`, fixed-table shaders |
|
||||
| Change ray marching/LOD | `shaders/voxel.slang`, `shaders/voxel_cache.slang`, `shaders/lod_policies.slang` |
|
||||
| Add a producer | `crates/vxls/src/producers.rs` (interface), `crates/vxls/src/main.rs` (`fullfill_request`), [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) |
|
||||
| Add a producer | `crates/vxls/src/producers.rs` (`TreeProducer`), `crates/vxls-production/src/producer.rs` (`Producer`/`ProducedNode`), `crates/vxls-production/src/request_queue.rs`, [`docs/pipeline-and-producers.md`](./docs/pipeline-and-producers.md) |
|
||||
| Add/change a secondary-ray pass | `shaders/gi.slang` (AO), `shaders/voxel_tracing.slang` (`TraceSettings`, `ITraceStack`), `shaders/bvh.slang` (`max_t`), [`docs/shaders.md`](./docs/shaders.md#81-ao-pass-gislang) |
|
||||
|
||||
## Current demo configuration
|
||||
|
||||
@@ -125,7 +127,7 @@ VoxelCache<4> branching 64
|
||||
150_000 pages
|
||||
1_024 max requests
|
||||
attributes: color (1 word), normal (3 words), both External
|
||||
SdfGenerator<4>::new(5) chunk_power 5 => 4^5 = 1024 voxels/axis per chunk cell
|
||||
TreeProducer<4> source: dragon.txt sparse tree (SdfGenerator is an unused fixture)
|
||||
20 x 20 x 20 toroidal chunk extent
|
||||
request buffers: 1024 (cache), 128 (structure table)
|
||||
```
|
||||
@@ -145,11 +147,12 @@ The full tables live in the docs. The most important ones:
|
||||
fulfilment blocks the render thread.
|
||||
- **Insertion can silently drop pages** (`destination_indices == 0xFFFFFFFF`)
|
||||
with no signal to the producer.
|
||||
- **Several modules are not wired in:** `crates/vxls-production/src/*`,
|
||||
`crates/vxls/src/host_production.rs`, and `VoxelGiPipeline`. Mark them as inactive rather
|
||||
than treating them as current behaviour.
|
||||
- **`gi.slang` is a stub** with legacy bindings that do not match the Rust GI
|
||||
bind group.
|
||||
- **Several modules are not wired in:** the terrain/ball fixtures and
|
||||
`VoxelGiPipeline`. Mark them as inactive rather than treating them as current
|
||||
behaviour. The production request queue and durable producer types are on the
|
||||
demo's live path.
|
||||
- **`gi.slang` is a simple AO pass**, not full GI: a few short hemisphere rays
|
||||
per pixel, no denoiser. It is a secondary-ray smoke test.
|
||||
- **`fixed_structure_table.slang` is imported but unused**; the active path is
|
||||
the toroidal wrapper around Rust's `FixedStructureTable`.
|
||||
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
+20
-17
@@ -93,11 +93,12 @@ Implemented and wired into the running demo:
|
||||
- WGSL cache-management shaders, specialised at runtime with generated
|
||||
constants.
|
||||
- Procedural fixtures (`SdfGenerator`, `TerrainGenerator`, `BallGenerator`) and
|
||||
a blocking host request-fulfilment loop in `main.rs`.
|
||||
a blocking host request-fulfilment loop in `main.rs` built on `RequestQueue`,
|
||||
`Producer`/`ProducedNode`, and `CacheInsertionData::upload`.
|
||||
|
||||
Not wired in: the `production/` subsystem, `tree.rs`, the older
|
||||
`host_production.rs` trait, and `VoxelGiPipeline` (module compiles but is never
|
||||
instantiated). See the module map below.
|
||||
Not wired in: the terrain/ball fixtures, `tree.rs`, and `VoxelGiPipeline`
|
||||
(module compiles but is never instantiated). The demo uses `TreeProducer` and
|
||||
the production subsystem's queue. See the module map below.
|
||||
|
||||
---
|
||||
|
||||
@@ -147,7 +148,9 @@ Both loops share the same request-buffer implementation and host download path.
|
||||
- write position/albedo/normal G-buffers;
|
||||
- update per-page usage timestamps;
|
||||
- increment request counters for missing children.
|
||||
3. **GI pass** (`gi.slang`) — currently a stub that copies albedo.
|
||||
3. **GI / AO pass** (`gi.slang`) — reads the world-space G-buffer, traces a few
|
||||
short hemisphere rays per pixel with `any_hit` and a finite `t_max`, and
|
||||
multiplies albedo by the AO term.
|
||||
4. **Blit / UI** — copy the selected debug texture, draw egui, download a usage
|
||||
histogram for the plot.
|
||||
5. **Encode request gathering** for both the cache and the structure table
|
||||
@@ -202,10 +205,8 @@ Consequences agents should keep in mind:
|
||||
| `crates/vxls-profiler/src/` | Timestamp profiling and memory accounting wrappers | Active infrastructure |
|
||||
| `crates/vxls/src/gi_pipeline.rs` (+ `sparse_set.rs`) | Planned GI pipeline using cache attribute sets | **Compiled but never instantiated** |
|
||||
| `crates/vxls-production/src/lib.rs` | Producer ID, `StructureAnchor` re-export, `Producer`/`ProducedNode` | Compiled; durable contract |
|
||||
| `crates/vxls-production/src/host_production.rs` | Rayon-based `HostRequestHandler` | Compiled; `fullfill` still a stub |
|
||||
| `crates/vxls-production/src/tree_locator.rs` | Compact N-tree locator encoding | Compiled; inactive |
|
||||
| `crates/vxls-production/src/request_queue.rs` | Bounded, deduplicating, priority-ordered request queue | Compiled, unit-tested; not yet on the live async path |
|
||||
| `crates/vxls/src/host_production.rs` | Legacy `ChunkVoxelProducer` trait | **Inactive** |
|
||||
| `crates/vxls-production/src/tree_locator.rs` | Compact N-tree locator encoding | Active via `RequestKey::node_locator` and `TreeProducer` |
|
||||
| `crates/vxls-production/src/request_queue.rs` | Bounded, deduplicating, priority-ordered request queue | Active in the demo driver, unit-tested |
|
||||
| `crates/vxls/src/sparse_tree.rs` | CPU `NTree` prototype, packed color helper and node locator used by producers | Active via `main.rs`/`producers.rs` |
|
||||
|
||||
The workspace uses edition 2024. Crates that use const-generic expressions enable
|
||||
@@ -232,10 +233,12 @@ mantissas to derive tree levels.
|
||||
`scale_exp`, so the tree is effectively spatially indexed by float bit
|
||||
patterns. This is why the tracer can descend without explicit bounding boxes.
|
||||
|
||||
`VoxelTraceStack` in `voxel_cache.slang` is a 5-entry stack indexed by
|
||||
`10 - scale_exp/2`. That hardcodes the maximum supported depth and the
|
||||
branching factor. It also assumes `chunk_power = 5`; changing chunk depth without
|
||||
updating the stack breaks tracing.
|
||||
The trace stack is caller-owned through `ITraceStack`. The local
|
||||
implementation (`LocalTraceStack` in `voxel_tracing.slang`) is a 5-entry stack
|
||||
indexed by `10 - scale_exp/2`. That hardcodes the maximum supported depth and
|
||||
the branching factor. It also assumes `chunk_power = 5`; changing chunk depth
|
||||
without updating the stack breaks tracing. A groupshared-backed implementation
|
||||
is a front-end change and needs no trace-core edits.
|
||||
|
||||
The toroidal table is a dense 3D grid of chunk root pointers. It wraps with
|
||||
`imod`, so moving the camera across a chunk boundary invalidates the departing
|
||||
@@ -300,9 +303,9 @@ demo; the UI plots both a frame timer and a ray-march timer.
|
||||
|---|---|---|---|
|
||||
| Location pages are sized with `size_of::<StructurePage<N>>()` (264 B at N=4) instead of `LocationPage` (28 B). | `crates/vxls-voxel-cache/src/structure.rs:44` | ~39.6 MB allocated where ~4.2 MB is needed. | High — direct code read. |
|
||||
| The host request path busy-waits on `device.poll`, making a callback design behave synchronously. | `crates/vxls/src/main.rs` around the `loop { ... poll ... }` after request downloads | Stalls the CPU on the render thread; prevents real pipelining/streaming. | High. |
|
||||
| `VoxelTraceStack` is 5 entries and indexes `stack[10 - scale_exp/2]`, assuming `N = 4` and `chunk_power = 5`. | `shaders/voxel_cache.slang:93-96,177,189,257` | Changing branching or chunk depth silently corrupts tracing. | High. |
|
||||
| The caller-owned trace stack (`LocalTraceStack`, or a groupshared-backed `ITraceStack`) is 5 entries and indexes `entries[10 - scale_exp/2]`, assuming `N = 4` and `chunk_power = 5`. | `shaders/voxel_tracing.slang`, `shaders/voxel_cache.slang` | Changing branching or chunk depth silently corrupts tracing. | High. |
|
||||
| Slang hardcodes `64` children per node and attribute meanings (0 = packed color, 1 = 3-word normal). | `shaders/voxel_cache.slang`, `shaders/voxel.slang` | Any cache layout change must be mirrored in Slang; mismatches are not caught at compile time. | High. |
|
||||
| `gi.slang` is a stub that copies albedo and declares legacy bindings that do not match the Rust GI bind group. | `shaders/gi.slang`, `crates/vxls/src/main.rs` | Works only because the declared bindings are unused; misleading as an example. | High. |
|
||||
| `gi.slang` is a simple AO pass (4 fixed hemisphere rays, no denoiser), not a full GI solution. | `shaders/gi.slang` | Noisy, view-dependent AO; it exists as a secondary-ray smoke test. | High. |
|
||||
| `FixedStructureTable` / `ToroidalStructureTable` naming: the toroidal wrapper delegates to the fixed table, and `fixed_structure_table.slang` is imported but unused by `voxel.slang`. | `crates/vxls-terrain/src/lib.rs`, `shaders/fixed_structure_table.slang`, `shaders/voxel.slang:3` | Readers may look for toroidal logic in the wrong shader/module. | High. |
|
||||
| Several subsystems are present but not wired into the binary (see module map). | `crates/vxls-production/src/*`, `crates/vxls/src/host_production.rs`, `crates/vxls/src/gi_pipeline.rs` | Dead code can be mistaken for current architecture; it does not compile into the binary unless declared. | High. |
|
||||
| `fullfill_request` hardcodes `NTreeNodeLocator<4>` and a `+5000` chunk offset. | `crates/vxls/src/main.rs:1762-1838` | Not generic over the cache branching factor; offsets are demo-specific. | High. |
|
||||
| Several subsystems are present but not wired into the binary (see module map). | `crates/vxls/src/gi_pipeline.rs`, terrain/ball fixtures | Dead code can be mistaken for current architecture; it does not compile into the binary unless declared. | High. |
|
||||
| The demo worker thread still lives in `main.rs`, so scheduling and producer ownership are not reusable. | `crates/vxls/src/main.rs` | Production types are durable; the host service around them is playground code. | Medium. |
|
||||
|
||||
+128
-136
@@ -144,101 +144,95 @@ corrupting the tree.
|
||||
|
||||
## 3. The durable producer shape
|
||||
|
||||
`crates/vxls/src/producers.rs` defines:
|
||||
The durable interface is `vxls-production::Producer`, and the demo driver uses
|
||||
it through `TreeProducer` in `crates/vxls/src/producers.rs`:
|
||||
|
||||
```rust
|
||||
pub trait ChunkedProducer<const N: usize>
|
||||
pub trait Producer<const N: usize, A: Attributes>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
fn produce_node(
|
||||
fn produce(
|
||||
&self,
|
||||
depth: usize,
|
||||
nx: usize,
|
||||
ny: usize,
|
||||
nz: usize,
|
||||
chunk_pos: (usize, usize, usize),
|
||||
) -> ProducedChunk<N>;
|
||||
anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> ProducedNode<N, A>;
|
||||
}
|
||||
|
||||
pub struct ProducedChunk<const N: usize> {
|
||||
pub children: [ChildInformation; N * N * N],
|
||||
pub colors: [u32; N * N * N], // packed RGBA
|
||||
pub normals: [[f32; 3]; N * N * N],
|
||||
pub struct ProducedNode<const N: usize, A: Attributes>
|
||||
where [(); N * N * N]:,
|
||||
{
|
||||
pub insertion: InsertionInformation<N>,
|
||||
pub attributes: [A; N * N * N],
|
||||
}
|
||||
```
|
||||
|
||||
`locator` is the content-local path of the node to produce, obtained from the
|
||||
request with `RequestKey::node_locator::<N>()`. The producer does not need to
|
||||
know whether the request was a structure root or an internal child: the locator
|
||||
already names the node, and the cache derives the matching `LocationPage` from
|
||||
the same key.
|
||||
|
||||
The cache owns identity, so `ProducedNode` deliberately carries no producer id,
|
||||
anchor, table slot, or location. The host/queue adds those when it builds an
|
||||
`InsertionEntry`.
|
||||
|
||||
The older `ChunkedProducer` / `ProducedChunk` shape in
|
||||
`crates/vxls/src/producers.rs` is retained only for the unused terrain/ball
|
||||
fixtures. It is not the interface new producers should implement.
|
||||
|
||||
Interpretation:
|
||||
|
||||
- `depth` is the node depth inside a chunk (root = 0).
|
||||
- `(nx, ny, nz)` is the node's position in the depth-specific coordinate space
|
||||
(`0 .. N^depth`), i.e. the node's grid coordinate at that depth, not a voxel
|
||||
coordinate.
|
||||
- `chunk_pos` is the chunk's grid position in the world.
|
||||
- The producer must fill one entry per child. Each child says whether it can be
|
||||
subdivided further and whether it is occupied, and supplies its attribute
|
||||
words.
|
||||
- A leaf is `subdividable = false`. A node that should be refined later is
|
||||
`subdividable = true`. Occupancy controls hit testing and coarse skipping.
|
||||
|
||||
This shape is independent of the cache layout only up to the attribute buffers:
|
||||
the demo's `colors` / `normals` arrays correspond exactly to the two configured
|
||||
attributes. A general design should produce `word_count` words per attribute per
|
||||
child instead of hardcoding color/normal.
|
||||
- The producer fills one entry per child of the requested node, plus the
|
||||
attributes for those children.
|
||||
- `anchor` is the content identity. A producer must derive world position from
|
||||
it and never from a table slot.
|
||||
|
||||
### 3.1 Fulfilling a request
|
||||
|
||||
The demo's `fullfill_request` (`crates/vxls/src/main.rs`) does:
|
||||
`TreeProducer` (`crates/vxls/src/producers.rs`) does:
|
||||
|
||||
1. Decode the table-defined anchor with
|
||||
`ToroidalStructureTable::position_for_anchor` to get an absolute chunk
|
||||
coordinate.
|
||||
2. Add the playground offset `+5000` to x and z and take `abs()` of y.
|
||||
3. If `request_meta.page_index == 0xFFFFFFFF` (an external table request),
|
||||
produce the chunk root at depth 0, emit the root locator, and emit
|
||||
`InsertionParent::external(producer_id, anchor, table_slot)`.
|
||||
4. Otherwise (an internal child request):
|
||||
- decode the parent `NTreeNodeLocator<4>` from `node_id`;
|
||||
- decode `children_index` into `(child_x, child_y, child_z)` with x fastest;
|
||||
- compute the child locator;
|
||||
- produce the child node at `parent_depth + 1` with the child's node
|
||||
coordinates;
|
||||
- emit the child locator as the new `LocationPage.node_id`;
|
||||
- emit `InsertionParent::internal(meta, node_id, producer_id, anchor)`.
|
||||
1. Decode `locator` with `TreeLocator::<N>::from`.
|
||||
2. If the node is not subdivided, emit a constant page: every child has the
|
||||
node's attribute and `ChildInformation::new(false, occupied)`.
|
||||
3. Otherwise iterate `locator.children()` and emit each child's
|
||||
`ChildInformation` and `VoxelAttributes`.
|
||||
4. Return a `ProducedNode`; no location or parent is produced here.
|
||||
|
||||
The root/child test must use `RequestMeta.page_index`, not `node_id`: child 0
|
||||
of the root also has `node_id = 0`.
|
||||
The request path is:
|
||||
|
||||
The `+5000` offset and the hardcoded `<4>` are playground artifacts. They assume
|
||||
chunk dimensions of 20×20×20 and a 4-ary tree.
|
||||
1. `RequestQueue` yields a `WorkItem` with a `RequestKey`.
|
||||
2. The worker calls `producer.produce(key.anchor, key.node_locator::<4>())`.
|
||||
3. On drain, `ReadyItem::insertion_entry()` combines the payload with
|
||||
`ReadyItem::insertion_parent()` and `ReadyItem::location_page()`.
|
||||
4. `CacheInsertionData::upload` writes the batch.
|
||||
|
||||
### 3.2 Locators
|
||||
|
||||
Two locator implementations exist:
|
||||
`TreeLocator<N>` (`crates/vxls-production/src/tree_locator.rs`) is the locator
|
||||
used by the request queue and the demo producer. Three base-N accumulators
|
||||
(`x`, `y`, `z`) with a leading `1` digit; root is `(1,1,1)`; `depth =
|
||||
ilog_N(x)`; `parent` divides each coordinate by `N`; `child` multiplies by `N`
|
||||
and adds the child digit. `StructureLocator` is a flat interleaved form.
|
||||
|
||||
- **`NTreeNodeLocator<N>`** (`crates/vxls/src/sparse_tree.rs`) — used by the demo. A packed
|
||||
`usize`; supports `root`, `from_usize`, `depth`, `child`, `node_location`,
|
||||
`as_usize`, `parent`, `children`.
|
||||
- **`TreeLocator<N>`** (`crates/vxls-production/src/tree_locator.rs`) — the unwired
|
||||
production subsystem's version. Three base-N accumulators (`x`, `y`, `z`) with
|
||||
a leading `1` digit; root is `(1,1,1)`; `depth = ilog_N(x)`; `parent` divides
|
||||
each coordinate by `N`; `child` multiplies by `N` and adds the child digit.
|
||||
`StructureLocator` is a flat interleaved form.
|
||||
|
||||
Both encode "path from root" and can be converted to/from application-level
|
||||
coordinates. Whichever is used, it must round-trip through the 32-bit
|
||||
`node_id`.
|
||||
`NTree<N>` in `crates/vxls/src/sparse_tree.rs` is keyed by the same locator, so
|
||||
a `RequestKey` can name a produced node directly. Locators must round-trip
|
||||
through the 32-bit `node_id`.
|
||||
|
||||
---
|
||||
|
||||
## 4. The current driver, step by step
|
||||
|
||||
Relevant code: `State::render` and `fullfill_request` in `crates/vxls/src/main.rs`.
|
||||
Relevant code: `State::render` and `TreeProducer` in `crates/vxls/src/main.rs` /
|
||||
`crates/vxls/src/producers.rs`.
|
||||
|
||||
1. **Render** writes G-buffers and request counters.
|
||||
2. **Gather** encodes both request pipelines (cache + table) into the same
|
||||
command buffer, then submits and presents.
|
||||
3. **Download** starts three asynchronous reads per request buffer (count,
|
||||
informations, meta).
|
||||
informations, meta). Each callback only ingests the wire requests into the
|
||||
shared `RequestQueue`; it does not drain or upload.
|
||||
4. **Busy-wait**:
|
||||
|
||||
```rust
|
||||
@@ -249,19 +243,26 @@ Relevant code: `State::render` and `fullfill_request` in `crates/vxls/src/main.r
|
||||
```
|
||||
|
||||
`finished` counts completed callbacks (one cache, one table), so completion
|
||||
does not require all six reads to land independently.
|
||||
5. **Produce** on the CPU with rayon: one `fullfill_request` per
|
||||
`(RequestInformation, RequestMeta)` pair. The results are copied into dense
|
||||
vectors, then uploaded with `queue.write_buffer` into:
|
||||
- `insertion_information_buffer()`
|
||||
- `location_pages_buffer()`
|
||||
- `insertion_parents_buffer()`
|
||||
- `attributes_buffers()[0]` (color)
|
||||
- `attributes_buffers()[1]` (normal)
|
||||
- `destination_indices_buffer()` (pre-filled with `0xFFFFFFFF`)
|
||||
- `valid_count_buffer()` (`0`)
|
||||
- `page_count_buffer()`
|
||||
6. **Insert** encodes:
|
||||
does not require all six reads to land independently. Each callback
|
||||
increments it only after ingesting.
|
||||
5. **Drain** the queue once both downloads have landed:
|
||||
|
||||
```rust
|
||||
let children = queue.drain_ready_matching(
|
||||
frame_id, cache_insertion.capacity(), |key| !key.is_root());
|
||||
let roots = queue.drain_ready_matching(
|
||||
frame_id, structure_table_insertion.capacity(), |key| key.is_root());
|
||||
```
|
||||
|
||||
`frame_id` is a host-owned monotonic counter, not the cache timestamp word.
|
||||
6. **Produce** on the worker thread with rayon, one `Producer::produce` call per
|
||||
`WorkItem`. Each result is a `ProducedNode<N, A>` keyed by
|
||||
`RequestKey::node_locator::<N>()`. On drain,
|
||||
`ReadyItem::insertion_entry()` attaches the parent and location, and
|
||||
`CacheInsertionData::upload` writes the whole batch (structure, location,
|
||||
parent, attributes, `valid_count`, `page_count`). `destination_indices` is
|
||||
reset by the validation shaders, not by the host.
|
||||
7. **Insert** encodes:
|
||||
|
||||
```rust
|
||||
cache.insert(&device, &mut encoder, &mut [
|
||||
@@ -277,7 +278,7 @@ Relevant code: `State::render` and `fullfill_request` in `crates/vxls/src/main.r
|
||||
preparation is shared by both page allocations. It orders pages by timestamp
|
||||
first (least recently used first) and depth second (deepest first among equal
|
||||
timestamps).
|
||||
7. **Submit** and read back the insertion profile.
|
||||
8. **Submit** and read back the insertion profile.
|
||||
|
||||
Because the external insertion is processed first, newly produced chunk roots
|
||||
are resident before the internal child insertion links them. The table insertion
|
||||
@@ -285,14 +286,16 @@ then points the slot at the root page.
|
||||
|
||||
### 4.1 Problems this creates
|
||||
|
||||
- The render thread blocks on the CPU producer; there is no overlap between
|
||||
production and rendering.
|
||||
- The render thread blocks waiting for downloads before it can drain results, so
|
||||
production does not overlap with rendering.
|
||||
- Request buffers are read back every frame even when empty.
|
||||
- `finished >= 2` is a coarse synchronization; it assumes exactly two buffers
|
||||
and no retries.
|
||||
- The producer runs on the same thread that owns the event loop, so a slow
|
||||
producer directly reduces frame rate.
|
||||
- The worker thread is spawned from the playground, so scheduling and producer
|
||||
ownership are not reusable outside `main.rs`.
|
||||
- No backpressure or prioritisation beyond the top-K request cap.
|
||||
- Rejected insertions (`destination_indices == 0xFFFFFFFF`) are still not
|
||||
reported back to the producer.
|
||||
|
||||
These are acceptable for a playground and are the first things to redesign for a
|
||||
real engine.
|
||||
@@ -306,9 +309,10 @@ stable.
|
||||
|
||||
| Generator | Status | What it does |
|
||||
|---|---|---|
|
||||
| `SdfGenerator<N>` | Used by the demo | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. |
|
||||
| `TerrainGenerator<N>` | Supported but commented out | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. |
|
||||
| `BallGenerator<N>` | Unused | Implements the older `Producer<N>` trait (not `ChunkedProducer`), draws a sphere; useful as a minimal example. |
|
||||
| `TreeProducer<N>` | Used by the demo | Implements the durable `vxls_production::Producer` over an in-memory `NTree`; the request's `node_locator` selects the node. |
|
||||
| `SdfGenerator<N>` | Fixture, unused | Signed-distance field from FBM simplex noise plus procedural "trees"; derives normal by finite differences; packs color from normal. |
|
||||
| `TerrainGenerator<N>` | Fixture, unused | Loads a TIFF heightmap and a JPEG/PNG colormap; builds low-resolution mips; produces nodes from min/max height spans. |
|
||||
| `BallGenerator<N>` | Fixture, unused | Implements the local playground `producers::Producer<N>` trait, not the durable one. |
|
||||
|
||||
`TerrainGenerator` is the closest thing to a realistic producer, but it is
|
||||
single-threaded at load time and uses hardcoded mip factors (8×). It also has
|
||||
@@ -325,9 +329,10 @@ branching logic based on `depth <= 2`.
|
||||
|
||||
## 6. The production subsystem
|
||||
|
||||
`crates/vxls-production/src/lib.rs` and its children are compiled (`mod production;`), but the
|
||||
demo driver in `main.rs` still uses its synchronous `fullfill_request` path. The
|
||||
production types are the durable contract; the driver is still the playground.
|
||||
`crates/vxls-production/src/lib.rs` and its children are compiled, and the demo
|
||||
driver now uses its durable `Producer` / `ProducedNode` / `RequestQueue` types.
|
||||
The `main.rs` producer remains a playground fixture, but it implements the
|
||||
durable interface.
|
||||
|
||||
### 6.1 `crates/vxls-production/src/lib.rs`
|
||||
|
||||
@@ -362,16 +367,18 @@ The cache-facing side is:
|
||||
```rust
|
||||
let layout = CacheLayout::from_attributes(&A::LAYOUT, &[]);
|
||||
let insertion = CacheInsertionData::new(&device, max_entries, &layout);
|
||||
let entry_count = insertion.write_attributes(&queue, node.attributes())?;
|
||||
let entries: Vec<InsertionEntry<N>> = ...;
|
||||
insertion.upload(&queue, &entries, &voxels)?;
|
||||
```
|
||||
|
||||
Differences from the demo interface:
|
||||
Differences from the legacy `ChunkedProducer` fixture interface:
|
||||
|
||||
- A node carries a `producer_id`, so one cache can mix multiple producers.
|
||||
- Attributes are abstracted behind `Attributes`, avoiding hardcoded
|
||||
color/normal buffers.
|
||||
- The producer receives a `StructureLocator` rather than depth + coordinates,
|
||||
pushing locator arithmetic into the producer.
|
||||
- `ProducedNode` carries no identity: the request key supplies producer, anchor,
|
||||
parent, and `LocationPage` when the entry is staged.
|
||||
- `anchor` is the content identity. A producer must derive world position from
|
||||
it and never from a table slot.
|
||||
|
||||
@@ -389,12 +396,11 @@ table keeps an anchor's identity while it stays in view and retires anchors that
|
||||
leave. An anchor must keep naming the same content if it later re-enters; bump
|
||||
its version word when content generation changes for the same coordinates.
|
||||
|
||||
### 6.2 `crates/vxls-production/src/host_production.rs`
|
||||
### 6.2 Host production helper (not present)
|
||||
|
||||
`HostRequestHandler<N, P: VoxelProducer<N>>` owns a rayon `ThreadPool` and a
|
||||
producer, and is intended to fulfil requests on the CPU. Note that its
|
||||
`fullfill` method is a stub: it downloads the request buffer with an empty
|
||||
callback. `produce_requests` does the real parallel mapping.
|
||||
There is no `crates/vxls-production/src/host_production.rs` in this tree. The
|
||||
worker thread and `RequestQueue` in `crates/vxls/src/main.rs` are the current
|
||||
host-side implementation.
|
||||
|
||||
### 6.3 `crates/vxls-production/src/tree_locator.rs`
|
||||
|
||||
@@ -440,32 +446,25 @@ Properties:
|
||||
queued/in-flight/ready jobs. Invalidation is a cancellation/cleanup hint,
|
||||
**not** a correctness mechanism: the GPU rejects stale insertions by checking
|
||||
the current anchor/slot.
|
||||
- `RequestKey::node_locator::<N>()` derives the locator of the requested node
|
||||
(root or child) from the key, so producers and `LocationPage` agree.
|
||||
- `ReadyItem::insertion_parent()` builds the `InsertionParent` for the insertion
|
||||
batch from the key and the latest `RequestMeta` (which carries `table_slot`).
|
||||
- `ReadyItem::location_page::<N>()` builds the `LocationPage` from the key, not
|
||||
from the producer payload or the table slot.
|
||||
- `ReadyItem::insertion_entry()` combines the payload's `InsertionInformation`
|
||||
with those two into a cache-facing `InsertionEntry`.
|
||||
|
||||
The queue is unit-tested without a GPU (`cargo test -p vxls-production request_queue`).
|
||||
|
||||
### 6.5 `crates/vxls/src/host_production.rs`
|
||||
|
||||
An older, simpler trait:
|
||||
|
||||
```rust
|
||||
pub trait ChunkVoxelProducer {
|
||||
fn produce_voxel(&mut self, depth, chunk_position, voxel_position);
|
||||
}
|
||||
```
|
||||
|
||||
It has no return value and no cache insertion types; it predates the current
|
||||
request/response pipeline.
|
||||
|
||||
### 6.6 `crates/vxls/src/sparse_tree.rs`
|
||||
### 6.5 `crates/vxls/src/sparse_tree.rs`
|
||||
|
||||
A CPU `NTree<N>` prototype backed by a `HashMap<TreeLocator<N>, NTreeNode>`,
|
||||
with `constant`, `get`, `set`, array conversion, and explicit-structure export.
|
||||
It also provides the packed `Color` helper and PLY loading. Useful for
|
||||
understanding the tree and used by the playground producers, not by the renderer.
|
||||
|
||||
### 6.7 `crates/vxls/src/gi_pipeline.rs` + `sparse_set.rs`
|
||||
### 6.6 `crates/vxls/src/gi_pipeline.rs` + `sparse_set.rs`
|
||||
|
||||
Compiles (declared in `main.rs`) but `VoxelGiPipeline` is never instantiated. It
|
||||
adds `DontTouch` attributes for a leaf list and radiance, and a `GpuSparseSet`
|
||||
@@ -478,36 +477,34 @@ code.
|
||||
|
||||
Minimum viable path with the current demo interface:
|
||||
|
||||
1. Implement `ChunkedProducer<N>`:
|
||||
1. Implement the durable `vxls_production::Producer<N, A>`:
|
||||
|
||||
```rust
|
||||
impl ChunkedProducer<4> for MyProducer {
|
||||
fn produce_node(&self, depth, nx, ny, nz, chunk_pos) -> ProducedChunk<4> { ... }
|
||||
impl Producer<4, MyAttributes> for MyProducer {
|
||||
fn produce(
|
||||
&self,
|
||||
anchor: StructureAnchor,
|
||||
locator: StructureLocator,
|
||||
) -> ProducedNode<4, MyAttributes> { ... }
|
||||
}
|
||||
```
|
||||
|
||||
2. For each child, compute:
|
||||
2. Decode `locator` with `TreeLocator::<N>::from` if the producer needs node
|
||||
coordinates.
|
||||
3. For each child of the requested node, compute:
|
||||
- `subdividable`: can this child be refined?
|
||||
- `occupied`: can it produce a hit?
|
||||
- attribute words in the cache layout order.
|
||||
3. Wire the producer into `fullfill_request` (or replace that function).
|
||||
Request → coordinates:
|
||||
- external (`RequestMeta.page_index == 0xFFFFFFFF`), produce chunk root;
|
||||
- internal: decode `node_id`, decode `children_index`, produce child at
|
||||
`depth + 1`.
|
||||
4. Emit a `LocationPage` matching the produced node. For internal requests,
|
||||
it must be `parent.child(child_x, child_y, child_z)`.
|
||||
5. Emit an `InsertionParent`:
|
||||
- external: `InsertionParent::external(producer_id, anchor, table_slot)`;
|
||||
- internal: `InsertionParent::internal(meta, node_id, producer_id, anchor)`.
|
||||
6. Set `page_count_buffer` to the number of entries. Order does not matter, but
|
||||
every entry must have matching information, location, parent, and attributes.
|
||||
7. Update the size passed to `CacheInsertionData::new` if the maximum batch can
|
||||
exceed `max_requests`.
|
||||
4. Return a `ProducedNode` with `InsertionInformation` and the attribute array.
|
||||
Do not emit a `LocationPage` or `InsertionParent`; those are derived from the
|
||||
`RequestKey` when the result is drained.
|
||||
5. Replace `TreeProducer` in `crates/vxls/src/main.rs` with the new producer.
|
||||
6. Keep `CacheInsertionData::new` capacity at least as large as the maximum
|
||||
number of entries the queue can drain in one frame.
|
||||
|
||||
A production-ready producer should additionally:
|
||||
|
||||
- use the `Producer`/`Attributes` abstraction so attributes are not hardcoded;
|
||||
- use the `Attributes` abstraction so attributes are not hardcoded;
|
||||
- run through `RequestQueue` on a worker thread and stream results across frames
|
||||
without blocking the render loop;
|
||||
- handle `destination_indices == 0xFFFFFFFF` by retrying the request;
|
||||
@@ -522,14 +519,9 @@ A production-ready producer should additionally:
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| The host request path busy-waits on `device.poll`; production blocks the render thread. | `crates/vxls/src/main.rs` (`loop { ... poll ... }` in `render`) | No overlap, frame stalls, no streaming. | High |
|
||||
| `fullfill_request` hardcodes `NTreeNodeLocator<4>`, x/y/z child unpacking with `4` and `16`, and a `+5000` chunk offset. | `crates/vxls/src/main.rs:1814-1905` | Not generic; offsets only make sense for the demo terrain. | High |
|
||||
| The demo driver is still synchronous: it downloads, produces, and inserts in one frame. The queue exists but `main.rs` does not schedule through it yet. | `crates/vxls/src/main.rs` (`render`), `crates/vxls-production/src/request_queue.rs` | No overlap between production and rendering in the demo. The durable contract is ready for an async scheduler. | High |
|
||||
| `page_count_buffer` is set to `request_informations.len()`, which may exceed `CacheInsertionData`'s `max_page_count` (1024) if `max_requests` is raised without resizing. | `crates/vxls/src/main.rs` (write of `page_count_buffer`), `CacheInsertionData::new` | Buffer overrun / truncated production. | High |
|
||||
| The demo driver is still synchronous: it downloads, produces, and inserts in one frame. | `crates/vxls/src/main.rs` (`render`), `crates/vxls-production/src/request_queue.rs` | No overlap between production and rendering in the demo. The queue is on the live path but the scheduler is still frame-blocking. | High |
|
||||
| If `destination_indices[i] == 0xFFFFFFFF`, the producer is not told; the cache will re-request the node later. | `insertion.wgsl`, host callback | Wasted work and repeated requests; no metric for dropped pages. | High |
|
||||
| The external table insertion consumes the same eviction list as the cache insertion; if it inserts fewer roots than requested, the table has missing entries with no host-visible signal. | `VoxelCache::insert`, `fixed_table/insertion.wgsl` | Silent holes in the world. | Medium |
|
||||
| `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `crates/vxls/src/producers.rs:207-263,330` | Not robust to different chunk resolutions. | High |
|
||||
| `BallGenerator` implements the old `Producer` trait, not `ChunkedProducer`. | `crates/vxls/src/producers.rs:31-116` | Copying it as a template will not work with the current driver. | High |
|
||||
| The `production/` subsystem is compiled but not used by the demo driver. | `crates/vxls-production/src/lib.rs`, `crates/vxls-production/src/*` | Agents may assume the queue is on the live path; it is the durable target, while `fullfill_request` is still the active playground path. | High |
|
||||
| `crates/vxls-production/src/request_queue.rs` is new. | same | Its API may still change; `main.rs` does not depend on it yet. | Medium |
|
||||
| The demo uploads all attribute payloads with `bytemuck::cast_slice` of Rust arrays, so layout mismatches (padding, alignment) are not checked. | `crates/vxls/src/main.rs` upload section | Silent corruption if the Rust struct layout diverges from the WGSL/Slang layout. | Medium |
|
||||
| The `+5000` offset plus `chunk_y.abs()` means negative chunk coordinates fold onto positive ones. | `crates/vxls/src/main.rs:1785-1789` | Duplicate chunks / visual artifacts at negative y. | Medium |
|
||||
| `TerrainGenerator` uses hardcoded mip factor 8 and `depth <= 2` special cases. | `crates/vxls/src/producers.rs` | Not robust to different chunk resolutions. | High |
|
||||
| `BallGenerator` implements the local playground `producers::Producer<N>` trait, not the durable `vxls_production::Producer`. | `crates/vxls/src/producers.rs` | Copying it as a template will not work with the current driver. | High |
|
||||
| The worker thread is owned by `main.rs` rather than `vxls-production`, so queue scheduling and producers are not reusable yet. | `crates/vxls/src/main.rs` | Durable producer types exist, but the host service around them does not. | Medium |
|
||||
|
||||
+141
-37
@@ -64,23 +64,31 @@ module creation fails.
|
||||
flowchart TD
|
||||
V[voxel.slang<br/>ray_march_compute] --> VC[voxel_cache.slang<br/>VoxelCacheTracer]
|
||||
V --> VT[voxel_tracing.slang<br/>Tracer / interfaces]
|
||||
V --> BVH[bvh.slang<br/>Bvh]
|
||||
V --> TST[toroidal_structure_table.slang<br/>ToroidalStructureTableTracer]
|
||||
V --> LOD[lod_policies.slang<br/>PixelFootprintLod]
|
||||
V -. unused import .-> FST[fixed_structure_table.slang]
|
||||
G[gi.slang<br/>AO pass] --> VC
|
||||
G --> VT
|
||||
G --> BVH
|
||||
G --> LOD
|
||||
VC --> VT
|
||||
TST --> VT
|
||||
TST --> VC
|
||||
BVH --> VT
|
||||
BVH --> VC
|
||||
```
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `voxel_tracing.slang` | `Ray`, `Span`, `Cell`, `Hit`; `IStructure`, `IVoxelCache`, `ILodPolicy`; generic `Tracer`. |
|
||||
| `voxel_cache.slang` | `StructurePointer`, `StructureElement`, `VoxelCacheParameters`, `VoxelTraceStack`, `VoxelCacheTracer`, attribute helpers. |
|
||||
| `voxel_tracing.slang` | `Ray`, `Cell`, `Hit`, `TraceSettings`, `ITraceStack`/`LocalTraceStack`; `IStructure`, `IVoxelCache`, `ILodPolicy`; generic `Tracer`. |
|
||||
| `voxel_cache.slang` | `StructurePointer`, `StructureElement`, `VoxelCacheParameters`, `VoxelCacheTracer`, `ColorHit`, attribute helpers. |
|
||||
| `bvh.slang` | `Bvh` structure: restart-trail traversal, object transforms, bounded distance (`max_t`) for secondary rays. |
|
||||
| `toroidal_structure_table.slang` | Dense wrapped chunk grid; produces cache entry cells. |
|
||||
| `lod_policies.slang` | `PixelFootprintLod`. |
|
||||
| `fixed_structure_table.slang` | Non-wrapping chunk grid; imported by `voxel.slang` but not used. |
|
||||
| `voxel.slang` | Push constants, G-buffer bindings, `ColorHit`, `ray_march_compute`. |
|
||||
| `gi.slang` | Stub GI pass (copies albedo). |
|
||||
| `voxel.slang` | Push constants, G-buffer bindings, `ray_march_compute`. |
|
||||
| `gi.slang` | Screen-space AO: reads the world-space G-buffer and traces short hemisphere rays with the shared tracer. |
|
||||
| `compaction.slang`, `radix_sort.slang`, `radix_reduce.slang` | GPU utility kernels. |
|
||||
|
||||
---
|
||||
@@ -118,8 +126,11 @@ ParameterBlock<ToroidalStructureTable> table_parameters; // group 1
|
||||
|
||||
### Group 2 — G-buffers
|
||||
|
||||
Three `rgba32f` storage textures written by the main pass; `gi.slang` binds
|
||||
target + position + albedo + normal instead.
|
||||
Three `rgba32f` storage textures written by the main pass. Position and normal
|
||||
are **world space**: the tracer maps the cache's unit-cube hit through
|
||||
`Cell::cube_to_world` / `Cell::world_origin`, and rotates local attribute
|
||||
normals with `Hit::normal_to_world`. `gi.slang` binds target + position +
|
||||
albedo + normal and uses the world-space position/normal as AO ray origins.
|
||||
|
||||
### Push constants / immediates
|
||||
|
||||
@@ -155,14 +166,14 @@ pages were touched this frame.
|
||||
```slang
|
||||
public interface IStructure {
|
||||
associatedtype Cursor;
|
||||
Cursor begin(Ray worldRay, Span s);
|
||||
Cursor begin(Ray worldRay);
|
||||
bool next(inout Cursor c, out Cell cell);
|
||||
}
|
||||
|
||||
public interface IVoxelCache {
|
||||
associatedtype GroupSharedData;
|
||||
bool trace<L : ILodPolicy>(
|
||||
uint32_t root, inout GroupSharedData data, Ray r, L lod, float offset_t, out Hit v);
|
||||
bool trace<L : ILodPolicy, St : ITraceStack>(
|
||||
uint32_t root, Ray r, L lod, TraceSettings settings,
|
||||
float offset_t, inout St stack, out Hit v);
|
||||
}
|
||||
|
||||
public interface ILodPolicy {
|
||||
@@ -171,7 +182,8 @@ public interface ILodPolicy {
|
||||
|
||||
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
|
||||
S structure; C cache; L lod;
|
||||
bool trace(inout C.GroupSharedData gsData, out Hit h, Ray r, Span s);
|
||||
bool trace<St : ITraceStack>(
|
||||
out Hit h, Ray r, TraceSettings settings, inout St stack);
|
||||
}
|
||||
```
|
||||
|
||||
@@ -179,6 +191,24 @@ public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy> {
|
||||
interface can be replaced without touching the others; this is the main
|
||||
extensibility point on the render side.
|
||||
|
||||
`TraceSettings` is the per-ray policy shared by primary and secondary rays:
|
||||
|
||||
```slang
|
||||
public struct TraceSettings {
|
||||
float t_min; // start of the search interval
|
||||
float t_max; // end (exclusive); FLT_MAX for unbounded
|
||||
uint32_t max_cells; // structure cells visited
|
||||
uint32_t max_steps; // DDA iterations inside one cache cell
|
||||
bool any_hit; // first acceptable hit instead of nearest
|
||||
bool report_usage; // refresh LRU timestamps
|
||||
bool report_requests; // emit cache detail requests
|
||||
}
|
||||
```
|
||||
|
||||
The same tracer therefore serves the primary pass (closest hit, camera LOD,
|
||||
usage + requests) and shadow/visibility rays (`any_hit`, a finite `t_max`,
|
||||
requests off) without a separate code path.
|
||||
|
||||
---
|
||||
|
||||
## 5. `VoxelCacheTracer` algorithm
|
||||
@@ -216,18 +246,20 @@ world-space node size from the exponent/mantissa.
|
||||
|
||||
### 5.3 Main loop
|
||||
|
||||
Per iteration (max 500):
|
||||
Per iteration (`settings.max_steps`, 500 for primary rays):
|
||||
|
||||
1. Read the current child pointer.
|
||||
2. **Descend** while the pointer is `subdivided_valid()` (bits 31 and 30 set)
|
||||
1. If `offset_t + t >= settings.t_max`, stop: the rest of the ray is outside the
|
||||
requested interval.
|
||||
2. Read the current child pointer.
|
||||
3. **Descend** while the pointer is `subdivided_valid()` (bits 31 and 30 set)
|
||||
and the LOD policy says the node is still too large:
|
||||
- `scale_exp -= 2`, `current_node_index = pointer()`, push onto the
|
||||
`VoxelTraceStack`, report usage.
|
||||
3. **Request** if the LOD still wants detail, the pointer is subdividable, and
|
||||
it is not resident:
|
||||
trace stack, report usage when `settings.report_usage`.
|
||||
4. **Request** if `settings.report_requests`, the LOD still wants detail, the
|
||||
pointer is subdividable, and it is not resident:
|
||||
`requests[current_node_index][child_index] += 1`.
|
||||
4. **Hit test** using the occupancy mask and `IVoxelHit::shouldHit`.
|
||||
5. **DDA step**:
|
||||
5. **Hit test** using the occupancy mask and `IVoxelHit::shouldHit`.
|
||||
6. **DDA step**:
|
||||
- If the coarser 2×2×2 neighbourhood is empty
|
||||
(`(occupancy >> (child_index & 0b101010)) & 0x00330033 == 0`), advance one
|
||||
extra level (`adv_scale_exp++`) to skip empty space.
|
||||
@@ -236,26 +268,60 @@ Per iteration (max 500):
|
||||
- Find the most common ancestor of old and new positions via XOR and
|
||||
`firstbithigh`, then restore `scale_exp` and pop the stack to that level.
|
||||
|
||||
`Tracer::trace` bounds the structure walk with `settings.max_cells`. It skips
|
||||
cells that start at or beyond `t_max` or (for closest-hit traces) the best hit
|
||||
so far. Structure cells are not distance ordered, so it never breaks on those
|
||||
conditions.
|
||||
|
||||
### 5.4 Stack
|
||||
|
||||
```slang
|
||||
public struct VoxelTraceStack { public uint32_t stack[5]; }
|
||||
public interface ITraceStack {
|
||||
uint32_t get(uint32_t depth);
|
||||
[mutating] void set(uint32_t depth, uint32_t node);
|
||||
}
|
||||
|
||||
public struct LocalTraceStack : ITraceStack {
|
||||
public uint32_t entries[5];
|
||||
// get/set index entries[depth]
|
||||
}
|
||||
```
|
||||
|
||||
`voxel.slang` allocates one per thread in groupshared memory:
|
||||
The stack is **caller-owned**, so the tracer has no module-scope storage and no
|
||||
dependency on the dispatch shape. `voxel.slang` keeps one per thread as a local
|
||||
(`LocalTraceStack stack;`), which the driver can promote to registers or spill
|
||||
to per-thread scratch. If the primary pass regresses, the front-end can switch
|
||||
to groupshared storage without touching the trace core: implement `ITraceStack`
|
||||
over a module-scope groupshared array plus a per-thread base slot, and pass that
|
||||
handle instead.
|
||||
|
||||
```slang
|
||||
groupshared VoxelTraceStack stacks[256]; // 16x16 workgroup
|
||||
groupshared uint32_t trace_stacks[5 * 256];
|
||||
|
||||
public struct GroupsharedTraceStack : ITraceStack {
|
||||
public uint32_t base; // slot * 5
|
||||
|
||||
public uint32_t get(uint32_t depth) { return trace_stacks[base + depth]; }
|
||||
[mutating]
|
||||
public void set(uint32_t depth, uint32_t node) { trace_stacks[base + depth] = node; }
|
||||
}
|
||||
|
||||
// entry point
|
||||
GroupsharedTraceStack stack;
|
||||
stack.base = (local_location.x + local_location.y * 16) * 5;
|
||||
```
|
||||
|
||||
The index `stack[10 - scale_exp / 2]` hardcodes the supported depth. With
|
||||
Both variants compile from the same primary entry point; only the implementation
|
||||
type and its construction change.
|
||||
|
||||
The index `depth = 10 - scale_exp / 2` hardcodes the supported trace depth. With
|
||||
`N = 4` and `chunk_power = 5`, the deepest level used is 5, so the stack must
|
||||
hold entries for levels 1..5. Changing the branching factor or chunk depth
|
||||
requires changing both the stack size and this index formula.
|
||||
|
||||
### 5.5 Hit test
|
||||
|
||||
`voxel.slang` defines `ColorHit<2>`:
|
||||
`voxel_cache.slang` defines `ColorHit<2>` (shared by the primary and AO passes):
|
||||
|
||||
```slang
|
||||
bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index) {
|
||||
@@ -301,6 +367,23 @@ A non-wrapping version of the same idea. It is imported by `voxel.slang` but not
|
||||
instantiated; the Rust `FixedStructureTable` is used through the toroidal
|
||||
wrapper instead.
|
||||
|
||||
### 6.3 `bvh.slang` (active demo path)
|
||||
|
||||
`Bvh` walks a top-level BVH of transformed unit-cube objects and emits a `Cell`
|
||||
for each object the ray can enter. Traversal uses a restart trail instead of a
|
||||
stack, so the cells are **not** distance ordered (the tracer accumulates the
|
||||
nearest hit and skips rather than breaks).
|
||||
|
||||
`Bvh::max_t` bounds the traversal: nodes and objects whose entry distance is
|
||||
beyond it are culled. Primary rays set `FLT_MAX`; secondary passes (the AO pass)
|
||||
set their ray length, which avoids walking the infinite ray through every object
|
||||
behind the surface. The field assumes rigid rotation/translation transforms, so
|
||||
local and world distances match.
|
||||
|
||||
Each emitted cell carries `world_origin` and `cube_to_world`; `Tracer::trace`
|
||||
uses them to turn the cache's unit-cube hit into a world-space `Hit` and to
|
||||
rotate local attribute normals.
|
||||
|
||||
---
|
||||
|
||||
## 7. LOD
|
||||
@@ -344,18 +427,16 @@ Interpretation:
|
||||
```slang
|
||||
[shader("compute")]
|
||||
[numthreads(16,16,1)]
|
||||
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID,
|
||||
uint32_t3 local_location : SV_GroupThreadID)
|
||||
void ray_march_compute(uint32_t3 location : SV_DispatchThreadID)
|
||||
```
|
||||
|
||||
1. Bounds-check against `constants.width/height`.
|
||||
2. Build a `VoxelCacheTracer<2, ColorHit<2>>` with usage + request reporting and
|
||||
the frame timestamp.
|
||||
3. Build a `ToroidalStructureTableTracer` with
|
||||
`extent = (chunk_width, chunk_alt, chunk_width)`.
|
||||
4. Build a `Tracer` and call `trace` with the per-thread stack.
|
||||
5. On hit, fetch normal and color from attribute pools and store position,
|
||||
normal, and albedo G-buffers.
|
||||
2. Build a `VoxelCacheTracer<2, ColorHit<2>>` with the frame timestamp.
|
||||
3. Fill in `TraceSettings` (unbounded closest-hit, 500 DDA steps, usage and
|
||||
requests on) and declare the per-ray `LocalTraceStack`.
|
||||
4. Build a `Tracer` (currently over `Bvh`) and call `trace` with the stack.
|
||||
5. On hit, store the world-space hit position, the world-space normal
|
||||
(`Hit::normal_to_world` rotates the local attribute normal), and albedo.
|
||||
6. On miss, store zero albedo.
|
||||
|
||||
`fetch_color` and `fetch_normal` hardcode the demo layout:
|
||||
@@ -368,6 +449,29 @@ attributes_pool[1][node * 64*3 + child*3 + 0..2] // normal
|
||||
This is the most important cross-language contract in the repo. If you reorder
|
||||
or resize attributes in `CacheLayout`, update these functions and `ColorHit`.
|
||||
|
||||
### 8.1 AO pass (`gi.slang`)
|
||||
|
||||
The AO pass is the secondary-ray smoke test. It reuses the same tracer, hit
|
||||
predicate, structure (`Bvh`) and LOD policy as the primary pass:
|
||||
|
||||
```slang
|
||||
TraceSettings settings;
|
||||
settings.t_min = 0.01; // skip the surface itself
|
||||
settings.t_max = 0.25; // short, local occlusion
|
||||
settings.max_cells = 64;
|
||||
settings.max_steps = 64;
|
||||
settings.any_hit = true; // visibility, not nearest
|
||||
settings.report_usage = true;
|
||||
settings.report_requests = false; // secondaries do not drive detail
|
||||
```
|
||||
|
||||
Per pixel it reconstructs a world-space origin/normal from the G-buffer, then
|
||||
traces four cosine-weighted hemisphere samples rotated by a per-pixel hash. The
|
||||
AO term is `1 - occluded / 4`, softened before multiplying albedo. The pass is
|
||||
incoherent by nature; the caller-owned `LocalTraceStack` is reused sequentially
|
||||
across the four rays, which is exactly why the stack is not tied to the
|
||||
workgroup shape.
|
||||
|
||||
---
|
||||
|
||||
## 9. WGSL cache shaders
|
||||
@@ -494,7 +598,7 @@ Do not do this casually. Required changes include:
|
||||
|
||||
- `VoxelCache<N>` / producer `N` and all 64-element assumptions;
|
||||
- `get_children_index` (`*4`, `*16`) and the child-mirror shifts;
|
||||
- `VoxelTraceStack` size and `10 - scale_exp/2` indexing;
|
||||
- `LocalTraceStack` size and `10 - scale_exp/2` indexing;
|
||||
- `StructureElement.pointers[64]`;
|
||||
- `fetch_color`/`fetch_normal` strides (`*64`, `*64*3`);
|
||||
- generated WGSL `CHILDREN_COUNT`;
|
||||
@@ -518,12 +622,12 @@ Makefile before building.
|
||||
| Symptom | Location | Impact | Confidence |
|
||||
|---|---|---|---|
|
||||
| `voxel.slang` imports `fixed_structure_table` but never uses it. | `shaders/voxel.slang:3` | Misleads readers; increases compile surface. | High |
|
||||
| `gi.slang` declares legacy bindings (`structure_pool`, `attributes_pool`, request/usage buffers, table buffers) that do not match the GI bind group Rust actually creates. | `shaders/gi.slang:17-45`, `crates/vxls/src/main.rs:563-611` | Works only because the mismatched bindings are unused. Any real GI work will hit validation errors. | High |
|
||||
| `gi.slang` is a simple AO pass, not a full GI solution (no bounces, no denoiser, 4 fixed hemisphere samples). | `shaders/gi.slang` | AO is noisy and view-dependent; it is a secondary-ray smoke test, not production lighting. | High. |
|
||||
| `PixelFootprintLod` demo parameters are hardcoded (100° FOV, 1080 px, threshold 2). | `shaders/voxel.slang:149` | LOD does not follow the window/FOV; resizing the window changes effective LOD. | High |
|
||||
| `VoxelTraceStack` size and indexing assume `N = 4` and `chunk_power = 5`. | `shaders/voxel_cache.slang:93-96,177,189,257` | Branching/depth changes silently break tracing. | High |
|
||||
| `LocalTraceStack` size and indexing assume `N = 4` and `chunk_power = 5`. | `shaders/voxel_tracing.slang` (`ITraceStack`/`LocalTraceStack`), `shaders/voxel_cache.slang` | Branching/depth changes silently break tracing. | High |
|
||||
| `fetch_color` / `fetch_normal` hardcode stride 64 and attribute indices 0/1. | `shaders/voxel.slang:68-79` | Cache layout changes break rendering with no compile-time error. | High |
|
||||
| The child-index and child-mirror arithmetic hardcodes `4` and `16`. | `shaders/voxel_cache.slang:103-108,154-165` | Not generic over branching factor. | High |
|
||||
| The toroidal tracer walks one unit cell per axis crossing with no empty-chunk skip. | `shaders/toroidal_structure_table.slang:62-101` | Cost scales with traversed grid cells, not just occupied chunks. | Medium |
|
||||
| `chunk_*` immediate field naming/order differs between Rust (`width, height, alt`) and the table extent (`width, alt, height`). | `crates/vxls/src/main.rs:1049-1062`, `shaders/voxel.slang:140` | Hidden because the demo uses 20×20×20; non-cubic extents would mismatch. | Medium |
|
||||
| `radix_reduce.spv` is built and checked in but unused. | `shaders/Makefile:1` | Confusing build artifact. | High |
|
||||
| `voxel.slang` uses `groupshared VoxelTraceStack stacks[256]` but `create_shader_module_passthrough` bypasses wgpu validation. | `shaders/voxel.slang:118`, `crates/vxls/src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |
|
||||
| `voxel.slang` uses `create_shader_module_passthrough`, so wgpu validation is bypassed for the render pipeline. | `crates/vxls/src/main.rs:477-498` | Layout/limit errors appear as driver errors, not friendly validation messages. | Medium |
|
||||
|
||||
+36
-19
@@ -75,11 +75,12 @@ struct LocationPage {
|
||||
```
|
||||
|
||||
The cache never interprets these values; they are copied from insertion data and
|
||||
returned in requests so the producer knows which node is missing. In the demo,
|
||||
`node_id` is an `NTreeNodeLocator` and `anchor` is the toroidal table's world
|
||||
position plus a version word. The anchor is the structure identity, so child
|
||||
requests inherit it from their parent page and producers never need a host-side
|
||||
identity directory. `LocationPage` is 24 bytes.
|
||||
returned in requests so the producer knows which node is missing. On the Rust
|
||||
side, `node_id` is a `StructureLocator` encoded through `TreeLocator<N>`. In the
|
||||
demo the active BVH table uses zeroed anchors; the toroidal table variant uses
|
||||
world position plus a version word. The anchor is the structure identity, so
|
||||
child requests inherit it from their parent page and producers never need a
|
||||
host-side identity directory. `LocationPage` is 24 bytes.
|
||||
|
||||
On the Rust side, `node_id` and `producer_id` are the typed
|
||||
`StructureLocator` and `ProducerId` newtypes (both `#[repr(transparent)]`
|
||||
@@ -294,7 +295,7 @@ correctness requirement.
|
||||
| `insertion_parents` | dense `InsertionParent` per entry |
|
||||
| `destination_indices` | reset to `0xFFFFFFFF` by the validation pass; the insertion pass writes the destination page for accepted entries |
|
||||
| `valid_indices` | filled by the validation pass: compacted indices of valid entries |
|
||||
| `valid_count` | host writes `0`; the validation pass fills the amount of valid entries |
|
||||
| `valid_count` | `CacheInsertionData::upload` writes `0`; the validation pass fills the amount of valid entries |
|
||||
| attribute buffers | dense per-entry attribute payloads |
|
||||
|
||||
Build the layout from a producer payload with
|
||||
@@ -302,12 +303,24 @@ Build the layout from a producer payload with
|
||||
`CacheAttributeInit::External` and come first, `extras` are appended for
|
||||
GPU-only data.
|
||||
|
||||
Upload producer voxels with `CacheInsertionData::write_attributes(&queue, voxels)`.
|
||||
It accepts a slice in `[entry][child]` order (the child order is
|
||||
`x + 4*y + 16*z`), validates that `A::LAYOUT` is an `External` prefix of the
|
||||
cache layout with matching word counts and labels, and writes one buffer per
|
||||
attribute. It returns the entry count to write to `page_count_buffer`. The
|
||||
`DontTouch` attributes after the producer prefix are left untouched.
|
||||
Upload a complete batch with
|
||||
|
||||
```rust
|
||||
let entries: Vec<InsertionEntry<N>> = ...;
|
||||
insertion.upload(&queue, &entries, &voxels)?;
|
||||
```
|
||||
|
||||
`InsertionEntry` bundles the produced page's `InsertionInformation`, its
|
||||
`InsertionParent`, and its `LocationPage`. `voxels` is a slice in
|
||||
`[entry][child]` order (child order is `x + 4*y + 16*z`) and must contain
|
||||
exactly `entries.len() * N^3` elements. `upload` writes the structure, location,
|
||||
and parent arrays, resets `valid_count`, sets `page_count`, and delegates the
|
||||
attribute payloads to `write_attributes`. It does not pre-fill
|
||||
`destination_indices`; both validation shaders reset every entry they process.
|
||||
|
||||
`write_attributes` validates that `A::LAYOUT` matches the cache layout and writes
|
||||
one buffer per attribute. The `DontTouch` attributes after the producer prefix
|
||||
are left untouched.
|
||||
|
||||
`InsertionInformation<N>` is just `children: [ChildInformation; 64]`, where each
|
||||
`ChildInformation` uses the four-state encoding below.
|
||||
@@ -441,7 +454,10 @@ collapse them.
|
||||
`&request_informations[0..count]` and `&request_meta[0..count]`.
|
||||
|
||||
The callback is asynchronous by API, but the demo blocks on it with a
|
||||
`device.poll` loop. See [`pipeline-and-producers.md`](./pipeline-and-producers.md).
|
||||
`device.poll` loop. The callback only ingests the wire requests into the
|
||||
`RequestQueue`; the demo drains produced results and uploads the insertion batch
|
||||
after both request buffers have landed. See
|
||||
[`pipeline-and-producers.md`](./pipeline-and-producers.md).
|
||||
|
||||
### 5.4 What a producer receives
|
||||
|
||||
@@ -449,10 +465,10 @@ For an **internal** request:
|
||||
|
||||
- `node_id` and `anchor` identify the **parent** node.
|
||||
- `children_index` identifies which child is missing.
|
||||
- The producer must generate that child node and emit a `LocationPage` for the
|
||||
child (typically `parent_locator.child(x, y, z)`) with the same anchor.
|
||||
- It must also emit an internal `InsertionParent` carrying the parent page,
|
||||
child index, depth, parent identity, and anchor.
|
||||
- The producer generates that child node as a `ProducedNode`. It does not emit a
|
||||
`LocationPage` or `InsertionParent`: `RequestKey::node_locator::<N>()` names
|
||||
the produced node, and `ReadyItem::insertion_entry()` derives both from the
|
||||
request key.
|
||||
|
||||
For an **external** (structure-table) request:
|
||||
|
||||
@@ -460,8 +476,9 @@ For an **external** (structure-table) request:
|
||||
table currently points.
|
||||
- `node_id` and `children_index` are 0, and `RequestMeta.page_index` is
|
||||
`0xFFFFFFFF`.
|
||||
- The producer must generate a chunk root and emit its `LocationPage` plus an
|
||||
external `InsertionParent` with `producer_id`, `anchor`, and `table_slot`.
|
||||
- The producer generates a chunk root as a `ProducedNode`; the queue derives the
|
||||
root `LocationPage` and an external `InsertionParent` with `producer_id`,
|
||||
`anchor`, and `table_slot`.
|
||||
|
||||
There is no output-order requirement. Each insertion is attached to its parent
|
||||
by its own `InsertionParent`.
|
||||
|
||||
BIN
Binary file not shown.
+17
-8
@@ -84,9 +84,11 @@ public struct Bvh : IStructure
|
||||
typedef BvhCursor Cursor;
|
||||
public BvhParameters parameters;
|
||||
|
||||
/// Kept for compatibility with the existing call sites. The restart
|
||||
/// traversal does not need per-thread storage, so this is unused.
|
||||
public uint32_t thread_index;
|
||||
/// Reject nodes/objects whose entry distance is beyond this value.
|
||||
/// Set to FLT_MAX for unbounded primary rays. Distances are in the
|
||||
/// object's local units, which equal world units for the rigid
|
||||
/// rotation/translation transforms used here.
|
||||
public float max_t;
|
||||
|
||||
public BvhCursor begin(Ray world_ray)
|
||||
{
|
||||
@@ -100,14 +102,15 @@ public struct Bvh : IStructure
|
||||
c.leaf_depth = 0;
|
||||
c.have_leaf = false;
|
||||
|
||||
// Early out when the ray misses the whole scene.
|
||||
// Early out when the ray misses the whole scene or the root is beyond
|
||||
// the requested range.
|
||||
let root = this.parameters.nodes[0];
|
||||
let root_t = intersect_aabb(
|
||||
world_ray.origin,
|
||||
c.inv_direction,
|
||||
root.aabb.min,
|
||||
root.aabb.max);
|
||||
c.done = !(root_t.y >= max(root_t.x, 0.));
|
||||
c.done = !(root_t.y >= max(root_t.x, 0.) && root_t.x <= this.max_t);
|
||||
|
||||
return c;
|
||||
}
|
||||
@@ -121,6 +124,8 @@ public struct Bvh : IStructure
|
||||
cell.local_ray.origin = float3(0.);
|
||||
cell.local_ray.direction = float3(0.);
|
||||
cell.t = 0.;
|
||||
cell.cube_to_world = mat3_identity();
|
||||
cell.world_origin = float3(0.);
|
||||
|
||||
if (c.done)
|
||||
{
|
||||
@@ -189,8 +194,8 @@ public struct Bvh : IStructure
|
||||
this.parameters.nodes[right].aabb.min,
|
||||
this.parameters.nodes[right].aabb.max);
|
||||
|
||||
let hit_left = t_left.y >= max(t_left.x, 0.);
|
||||
let hit_right = t_right.y >= max(t_right.x, 0.);
|
||||
let hit_left = t_left.y >= max(t_left.x, 0.) && t_left.x <= this.max_t;
|
||||
let hit_right = t_right.y >= max(t_right.x, 0.) && t_right.x <= this.max_t;
|
||||
|
||||
if (hit_left && hit_right)
|
||||
{
|
||||
@@ -258,6 +263,8 @@ public struct Bvh : IStructure
|
||||
cell.local_ray.origin = float3(0.);
|
||||
cell.local_ray.direction = float3(0.);
|
||||
cell.t = 0.;
|
||||
cell.cube_to_world = mat3_identity();
|
||||
cell.world_origin = float3(0.);
|
||||
|
||||
let object = this.parameters.objects[object_index];
|
||||
|
||||
@@ -272,7 +279,7 @@ public struct Bvh : IStructure
|
||||
float3(0.),
|
||||
float3(1.));
|
||||
|
||||
if (t.y < max(t.x, 0.))
|
||||
if (t.y < max(t.x, 0.) || t.x > this.max_t)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
@@ -285,6 +292,8 @@ public struct Bvh : IStructure
|
||||
cell.local_ray.origin = local_origin + local_direction * entry_t;
|
||||
cell.local_ray.direction = local_direction;
|
||||
cell.t = entry_t;
|
||||
cell.cube_to_world = float3x3(object.local_to_world);
|
||||
cell.world_origin = mul(object.local_to_world, float4(0., 0., 0., 1.)).xyz;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
+120
-29
@@ -1,3 +1,13 @@
|
||||
import voxel_cache;
|
||||
import bvh;
|
||||
import voxel_tracing;
|
||||
import lod_policies;
|
||||
|
||||
// Simple screen-space AO: reconstruct the world-space surface from the primary
|
||||
// G-buffer and trace a few short, incoherent hemisphere rays per pixel through
|
||||
// the same tracer the primary pass uses. This is the secondary-ray smoke test:
|
||||
// short `t_max`, any-hit, usage feedback only, no detail requests.
|
||||
|
||||
struct PushConstants
|
||||
{
|
||||
float4x4 view_proj;
|
||||
@@ -10,6 +20,7 @@ struct PushConstants
|
||||
uint32_t chunk_height;
|
||||
uint32_t chunk_alt;
|
||||
|
||||
// Canonical table slot of the visible block's minimum corner.
|
||||
uint32_t table_base_slot_x;
|
||||
uint32_t table_base_slot_y;
|
||||
uint32_t table_base_slot_z;
|
||||
@@ -18,19 +29,8 @@ struct PushConstants
|
||||
[[vk::push_constant]]
|
||||
uniform PushConstants constants;
|
||||
|
||||
[[vk::binding(0, 0)]]
|
||||
RWStructuredBuffer<uint32_t> structure_pool;
|
||||
[[vk::binding(1, 0)]]
|
||||
RWStructuredBuffer<uint32_t> attributes_pool[2];
|
||||
[[vk::binding(2, 0)]]
|
||||
RWStructuredBuffer<uint32_t> request_buffer;
|
||||
[[vk::binding(3, 0)]]
|
||||
RWStructuredBuffer<uint32_t> usage_buffer;
|
||||
|
||||
[[vk::binding(0, 1)]]
|
||||
RWStructuredBuffer<uint32_t> structure_table_pointer;
|
||||
[[vk::binding(1, 1)]]
|
||||
RWStructuredBuffer<Atomic<uint32_t>> structure_table_request_buffer;
|
||||
ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
|
||||
ParameterBlock<BvhParameters> table_parameters;
|
||||
|
||||
[[vk::binding(0, 2)]]
|
||||
[[format("rgba32f")]]
|
||||
@@ -48,38 +48,129 @@ RWTexture2D<float4> gbuffer_albedo;
|
||||
[[format("rgba32f")]]
|
||||
RWTexture2D<float4> gbuffer_normal;
|
||||
|
||||
float3 get_ray_direction(uint32_t2 pixel_loc)
|
||||
static const uint32_t AO_SAMPLE_COUNT = 4;
|
||||
static const float AO_RADIUS = 0.25;
|
||||
static const float AO_EPSILON = 0.01;
|
||||
|
||||
float hash12(float2 p)
|
||||
{
|
||||
let ndc_loc_x = (float)pixel_loc.x / (float)constants.width * 2. - 1.;
|
||||
let ndc_loc_y = 1. - (float)pixel_loc.y / (float)constants.height * 2.;
|
||||
var world_loc = mul(constants.view_proj, float4(ndc_loc_x, ndc_loc_y, 1., 1.));
|
||||
world_loc /= world_loc.w;
|
||||
return normalize(world_loc.xyz - constants.cam_pos);
|
||||
var p3 = frac(float3(p.xyx) * 0.1031);
|
||||
p3 += dot(p3, p3.yzx + 33.33);
|
||||
return frac((p3.x + p3.y) * p3.z);
|
||||
}
|
||||
|
||||
float3 fetch_normal(uint32_t index, uint32_t child_index)
|
||||
{
|
||||
let a = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3]);
|
||||
let b = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 1]);
|
||||
let c = asfloat(cache_parameters.attributes_pool[1][index * 64 * 3 + child_index * 3 + 2]);
|
||||
return float3(a, b, c);
|
||||
}
|
||||
|
||||
/// Cosine-weighted hemisphere sample around `n`, rotated per pixel so the
|
||||
/// fixed sample count does not band.
|
||||
float3 hemisphere_sample(float3 n, uint32_t sample_index, float rotation)
|
||||
{
|
||||
let up = select(abs(n.z) < 0.999, float3(1., 0., 0.), float3(0., 0., 1.));
|
||||
let tangent = normalize(cross(up, n));
|
||||
let bitangent = cross(n, tangent);
|
||||
|
||||
let r = sqrt((float(sample_index) + 0.5) / float(AO_SAMPLE_COUNT));
|
||||
let phi = 6.28318530718 * frac(rotation + float(sample_index) * 0.61803398875);
|
||||
let disk = r * float2(cos(phi), sin(phi));
|
||||
|
||||
return normalize(tangent * disk.x + bitangent * disk.y + n * sqrt(max(0., 1. - r * r)));
|
||||
}
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void gi(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
void gi(uint32_t3 location: SV_DispatchThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (gbuffer_albedo.Load(location.xy).w == 0.)
|
||||
let albedo = gbuffer_albedo.Load(location.xy);
|
||||
// Shunt albedo
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
|
||||
// AO Example
|
||||
|
||||
if (albedo.w == 0.)
|
||||
{
|
||||
target_texture.Store(location.xy, float4(0.));
|
||||
return;
|
||||
}
|
||||
|
||||
let pos = gbuffer_position.Load(location.xy);
|
||||
let normal = gbuffer_normal.Load(location.xy);
|
||||
let albedo = gbuffer_albedo.Load(location.xy);
|
||||
let position = gbuffer_position.Load(location.xy).xyz;
|
||||
let normal_raw = gbuffer_normal.Load(location.xy).xyz;
|
||||
let normal_length = length(normal_raw);
|
||||
if (normal_length < 1e-6)
|
||||
{
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
}
|
||||
let normal = -normal_raw / normal_length;
|
||||
|
||||
// let floored_pos = floor(pos);
|
||||
// let c = (floored_pos.x + floored_pos.y + floored_pos.z) % 2;
|
||||
// target_texture.Store(location.xy, albedo * select(c == 0, 0.5, 1.));
|
||||
target_texture.Store(location.xy, albedo);
|
||||
return;
|
||||
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
|
||||
cache_tracer.parameters = cache_parameters;
|
||||
cache_tracer.frame_timestamp = constants.frame_timestamp;
|
||||
cache_tracer.voxel_hit = ColorHit<2>();
|
||||
|
||||
Bvh bvh;
|
||||
bvh.parameters = table_parameters;
|
||||
bvh.max_t = AO_RADIUS;
|
||||
|
||||
// Coarse LOD: AO does not need primary-ray detail.
|
||||
// PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f, 0.05f);
|
||||
PixelFootprintLod lod = PixelFootprintLod.create((100.f * 3.14f) / 180.f, 1080.f, 2.f);
|
||||
|
||||
Tracer<Bvh, VoxelCacheTracer<2, ColorHit<2>>, PixelFootprintLod> tracer;
|
||||
tracer.structure = bvh;
|
||||
tracer.cache = cache_tracer;
|
||||
tracer.lod = lod;
|
||||
|
||||
TraceSettings settings;
|
||||
settings.t_min = AO_EPSILON;
|
||||
settings.t_max = 100.;
|
||||
settings.max_cells = 64;
|
||||
settings.max_steps = 64;
|
||||
settings.any_hit = false;
|
||||
settings.report_usage = true;
|
||||
settings.report_requests = false;
|
||||
|
||||
LocalTraceStack stack;
|
||||
|
||||
let rotation = hash12(float2(location.xy));
|
||||
uint32_t occluded = 0;
|
||||
|
||||
// [loop]
|
||||
// for (uint32_t sample_index = 0; sample_index < AO_SAMPLE_COUNT; sample_index++)
|
||||
// {
|
||||
Ray r;
|
||||
r.origin = position + normal * (AO_EPSILON + 0.1);
|
||||
r.direction = reflect(normalize(position - constants.cam_pos), normal);
|
||||
// r.direction = hemisphere_sample(normal, sample_index, rotation);
|
||||
|
||||
Hit h;
|
||||
if (tracer.trace(h, r, settings, stack))
|
||||
{
|
||||
occluded += 1;
|
||||
let hit_normal = fetch_normal(h.node_index, h.child_index);
|
||||
let shade = max(dot(hit_normal, float3(0., 1., 0.)), 0.1);
|
||||
target_texture.Store(location.xy, float4(shade));
|
||||
}
|
||||
else
|
||||
{
|
||||
target_texture.Store(location.xy, float4(0.));
|
||||
}
|
||||
//}
|
||||
|
||||
// let ao = 1. - float(occluded) / float(AO_SAMPLE_COUNT);
|
||||
// Soften the effect: a fully black crevice reads as a hole in this demo.
|
||||
// let lit = lerp(1., ao, 0.7);
|
||||
// target_texture.Store(location.xy, float4(albedo.rgb * lit, albedo.a));
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -97,6 +97,8 @@ public struct ToroidalStructureTableTracer : IStructure
|
||||
cell.local_ray.origin = position - float3(c.current_voxel);
|
||||
cell.local_ray.direction = c.r.direction;
|
||||
cell.t = t_adv;
|
||||
cell.cube_to_world = mat3_identity();
|
||||
cell.world_origin = float3(c.current_voxel);
|
||||
hit = true;
|
||||
}
|
||||
else if (this.structure_table.structure_table_pointer[chunk_index].subdivided())
|
||||
|
||||
+25
-20
@@ -46,15 +46,8 @@ ParameterBlock<VoxelCacheParameters<2>> cache_parameters;
|
||||
// ParameterBlock<ToroidalStructureTable> table_parameters;
|
||||
ParameterBlock<BvhParameters> table_parameters;
|
||||
|
||||
public struct ColorHit<let N : uint32_t> : IVoxelHit<N>
|
||||
{
|
||||
public __init() {};
|
||||
|
||||
public bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
|
||||
}
|
||||
}
|
||||
// ColorHit<2> (the demo hit predicate) lives in voxel_cache.slang so the
|
||||
// primary and secondary front-ends share one definition.
|
||||
|
||||
// [[vk::binding(0, 0)]]
|
||||
// RWStructuredBuffer<StructurePoolElement> structure_pool;
|
||||
@@ -122,22 +115,32 @@ void gi_march(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location:
|
||||
|
||||
[shader("compute")]
|
||||
[numthreads(16, 16, 1)]
|
||||
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_location: SV_GroupThreadID)
|
||||
void ray_march_compute(uint32_t3 location: SV_DispatchThreadID)
|
||||
{
|
||||
if (location.x >= constants.width || location.y >= constants.height)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let stack_index = local_location.x + local_location.y * 16;
|
||||
|
||||
VoxelCacheTracer<2, ColorHit<2>> cache_tracer;
|
||||
cache_tracer.parameters = cache_parameters;
|
||||
cache_tracer.report_usage = true;
|
||||
cache_tracer.report_requests = true;
|
||||
cache_tracer.frame_timestamp = constants.frame_timestamp;
|
||||
cache_tracer.voxel_hit = ColorHit<2>();
|
||||
|
||||
// Per-ray trace state. Local storage keeps the tracer independent of the
|
||||
// workgroup shape; swap this for a groupshared-backed ITraceStack if the
|
||||
// primary pass needs groupshared memory back.
|
||||
LocalTraceStack stack;
|
||||
|
||||
TraceSettings settings;
|
||||
settings.t_min = 0.;
|
||||
settings.t_max = asfloat(0x7f7fffff); // FLT_MAX
|
||||
settings.max_cells = 0xFFFFFFFF;
|
||||
settings.max_steps = 500;
|
||||
settings.any_hit = false;
|
||||
settings.report_usage = true;
|
||||
settings.report_requests = true;
|
||||
|
||||
let ray_direction = get_ray_direction(location.xy);
|
||||
|
||||
Ray r;
|
||||
@@ -146,7 +149,7 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_
|
||||
|
||||
Bvh bvh;
|
||||
bvh.parameters = table_parameters;
|
||||
bvh.thread_index = stack_index;
|
||||
bvh.max_t = asfloat(0x7f7fffff); // FLT_MAX: unbounded primary rays
|
||||
// BvhCursor c = bvh.begin(r);
|
||||
Cell cell;
|
||||
|
||||
@@ -176,19 +179,21 @@ void ray_march_compute(uint32_t3 location: SV_DispatchThreadID, uint32_t3 local_
|
||||
|
||||
Hit h;
|
||||
// Closest hit at or past tMin. Re-trace past a hit with:
|
||||
// t_min = h.t + 1e-4;
|
||||
// hit = tracer.trace(stack_index, t_min, h, r);
|
||||
bool hit = tracer.trace(stack_index, 0., h, r);
|
||||
// settings.t_min = h.t + 1e-4;
|
||||
// hit = tracer.trace(h, r, settings, stack);
|
||||
bool hit = tracer.trace(h, r, settings, stack);
|
||||
|
||||
// ToroidalStructureTableTracer.Cursor cursor = table_tracer.begin(r);
|
||||
// Cell cell;
|
||||
|
||||
if (hit)
|
||||
{
|
||||
// Gather
|
||||
// `Hit` is already in world space; only the local attribute normal
|
||||
// still needs rotating into world space.
|
||||
let hit_pos = h.hit_location;
|
||||
|
||||
let hit_normal = fetch_normal(h.node_index, h.child_index);
|
||||
let local_normal = mul(h.normal_to_world, fetch_normal(h.node_index, h.child_index));
|
||||
let hit_normal = local_normal / max(length(local_normal), 1e-6);
|
||||
var hit_albedo = float4(0.);
|
||||
hit_albedo = fetch_color(h.node_index, h.child_index).float_color;
|
||||
// let hit_albedo = hit.color;
|
||||
|
||||
+30
-12
@@ -129,18 +129,31 @@ public interface IVoxelHit<let N : uint32_t>
|
||||
public bool shouldHit(VoxelCacheParameters<N> parameters, uint32_t node_index, uint32_t child_index);
|
||||
}
|
||||
|
||||
static const uint32_t WG_COUNT = 256;
|
||||
groupshared uint32_t stack[5 * WG_COUNT];
|
||||
/// Default hit test for the demo layout: alpha != 0 means solid.
|
||||
public struct ColorHit<let N : uint32_t> : IVoxelHit<N>
|
||||
{
|
||||
public __init() {};
|
||||
|
||||
public bool shouldHit(VoxelCacheParameters<N> cache, uint32_t node_index, uint32_t child_index)
|
||||
{
|
||||
return ByteColor(cache.attributes_pool[0][node_index * 64 + child_index]).byte_a != 0;
|
||||
}
|
||||
}
|
||||
|
||||
public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
|
||||
{
|
||||
public bool report_usage;
|
||||
public bool report_requests;
|
||||
public uint32_t frame_timestamp;
|
||||
public H voxel_hit;
|
||||
public VoxelCacheParameters<N> parameters;
|
||||
|
||||
public bool trace<L : ILodPolicy>(uint32_t root, uint32_t thread_id, Ray r, L lod, float offset_t, out Hit v)
|
||||
public bool trace<L : ILodPolicy, St : ITraceStack>(
|
||||
uint32_t root,
|
||||
Ray r,
|
||||
L lod,
|
||||
TraceSettings settings,
|
||||
float offset_t,
|
||||
inout St stack,
|
||||
out Hit v)
|
||||
{
|
||||
v.t = 0.;
|
||||
|
||||
@@ -168,15 +181,20 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
|
||||
float3 pos = r.origin;
|
||||
uint32_t scale_exp = 23 - 2;
|
||||
uint32_t current_node_index = root;
|
||||
if (this.report_usage)
|
||||
if (settings.report_usage)
|
||||
{
|
||||
this.parameters.usage_buffer[current_node_index] = this.frame_timestamp;
|
||||
}
|
||||
stack[thread_id + WG_COUNT * (10 - scale_exp / 2)] = current_node_index;
|
||||
stack.set(10 - scale_exp / 2, current_node_index);
|
||||
|
||||
[loop]
|
||||
for (uint32_t iter = 0; iter < 500; iter++)
|
||||
for (uint32_t iter = 0; iter < settings.max_steps; iter++)
|
||||
{
|
||||
if (offset_t + t >= settings.t_max)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
uint32_t child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
StructurePointer current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
|
||||
|
||||
@@ -184,18 +202,18 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
|
||||
{
|
||||
scale_exp -= 2;
|
||||
current_node_index = current_node.pointer();
|
||||
stack[thread_id + WG_COUNT * (10 - scale_exp / 2)] = current_node_index;
|
||||
stack.set(10 - scale_exp / 2, current_node_index);
|
||||
child_index = get_children_index(pos, scale_exp) ^ child_mirror;
|
||||
current_node = this.parameters.structure_pool[current_node_index].pointers[child_index];
|
||||
// Write usage
|
||||
if (this.report_usage)
|
||||
if (settings.report_usage)
|
||||
{
|
||||
this.parameters.usage_buffer[current_node_index] = frame_timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
// Request subdiv
|
||||
if (this.report_requests && !lod.shouldStop(t + offset_t, node_size(scale_exp)) && current_node.subdivided() && !current_node.pointer_valid())
|
||||
if (settings.report_requests && !lod.shouldStop(t + offset_t, node_size(scale_exp)) && current_node.subdivided() && !current_node.pointer_valid())
|
||||
{
|
||||
this.parameters.request_buffer[current_node_index].requests[child_index].add(1);
|
||||
}
|
||||
@@ -253,7 +271,7 @@ public struct VoxelCacheTracer<let N : int, H : IVoxelHit<N>> : IVoxelCache
|
||||
}
|
||||
|
||||
scale_exp = 23 - common_depth;
|
||||
current_node_index = stack[thread_id + WG_COUNT * (10 - scale_exp / 2)];
|
||||
current_node_index = stack.get(10 - scale_exp / 2);
|
||||
}
|
||||
|
||||
v.hit = false;
|
||||
|
||||
+139
-13
@@ -16,6 +16,13 @@ public struct Cell
|
||||
|
||||
/// How much distance from the camera
|
||||
public float t;
|
||||
|
||||
/// Rotation/scale from the cell's unit-cube space to world space.
|
||||
/// Identity for axis-aligned chunks.
|
||||
public float3x3 cube_to_world;
|
||||
|
||||
/// World-space position of the cell's unit-cube origin.
|
||||
public float3 world_origin;
|
||||
}
|
||||
|
||||
public interface IStructure
|
||||
@@ -43,18 +50,99 @@ public struct Hit
|
||||
// Cache location
|
||||
public uint32_t node_index;
|
||||
public uint32_t child_index;
|
||||
public float3 hit_location;
|
||||
public float3 hit_location; // world space
|
||||
|
||||
/// Rotation applied to the hit's local attribute normals.
|
||||
public float3x3 normal_to_world;
|
||||
|
||||
/// Distance of the hit from the ray origin, in the units of the ray
|
||||
/// direction. Used to order hits and to restart the traversal past a hit.
|
||||
public float t;
|
||||
}
|
||||
|
||||
/// Identity matrix helper (scalar-to-matrix casts splat instead of making an
|
||||
/// identity in Slang).
|
||||
public float3x3 mat3_identity()
|
||||
{
|
||||
return float3x3(
|
||||
1., 0., 0.,
|
||||
0., 1., 0.,
|
||||
0., 0., 1.);
|
||||
}
|
||||
|
||||
/// Per-ray parameters for a trace call.
|
||||
///
|
||||
/// Primary and secondary rays use the same tracer; only these values differ.
|
||||
/// `t_min`/`t_max` are world-space distances along the (normalised) ray
|
||||
/// direction. A hit at exactly `t_max` is excluded, so `t_max` is an open
|
||||
/// interval end.
|
||||
public struct TraceSettings
|
||||
{
|
||||
/// Start of the search interval. Re-traces set this just past the
|
||||
/// previous hit.
|
||||
public float t_min;
|
||||
|
||||
/// End of the search interval. Use FLT_MAX for unbounded traces.
|
||||
public float t_max;
|
||||
|
||||
/// Maximum number of structure cells to visit.
|
||||
public uint32_t max_cells;
|
||||
|
||||
/// Maximum number of DDA iterations inside one cache cell.
|
||||
public uint32_t max_steps;
|
||||
|
||||
/// Stop at the first acceptable hit instead of accumulating the nearest
|
||||
/// one. Meant for shadow/visibility rays.
|
||||
public bool any_hit;
|
||||
|
||||
/// Refresh the LRU timestamp of every node the ray touches.
|
||||
public bool report_usage;
|
||||
|
||||
/// Emit cache detail requests for nodes the ray reaches at the LOD.
|
||||
public bool report_requests;
|
||||
}
|
||||
|
||||
/// Per-ray stack access owned by the caller.
|
||||
///
|
||||
/// The trace core never stores the stack itself, so a front-end chooses where
|
||||
/// it lives. [`LocalTraceStack`] keeps it in per-thread storage. A primary pass
|
||||
/// that wants groupshared memory implements this interface over a module-scope
|
||||
/// `groupshared` array plus a thread slot instead; no trace-core code changes.
|
||||
///
|
||||
/// The depth index (`10 - scale_exp / 2`) assumes branching 4 and
|
||||
/// `chunk_power = 5`, so implementations store five entries.
|
||||
public interface ITraceStack
|
||||
{
|
||||
public uint32_t get(uint32_t depth);
|
||||
[mutating] public void set(uint32_t depth, uint32_t node);
|
||||
}
|
||||
|
||||
public struct LocalTraceStack : ITraceStack
|
||||
{
|
||||
public uint32_t entries[5];
|
||||
|
||||
public uint32_t get(uint32_t depth)
|
||||
{
|
||||
return this.entries[depth];
|
||||
}
|
||||
|
||||
[mutating]
|
||||
public void set(uint32_t depth, uint32_t node)
|
||||
{
|
||||
this.entries[depth] = node;
|
||||
}
|
||||
}
|
||||
|
||||
public interface IVoxelCache
|
||||
{
|
||||
// The voxel cache tracer needs to store a small stack.
|
||||
// Keeping it in registers is wastefull thus using groupshared memory is the best option
|
||||
public bool trace<L : ILodPolicy>(uint32_t root, uint32_t thread_id, Ray r, L lod, float offset_t, out Hit v);
|
||||
public bool trace<L : ILodPolicy, St : ITraceStack>(
|
||||
uint32_t root,
|
||||
Ray r,
|
||||
L lod,
|
||||
TraceSettings settings,
|
||||
float offset_t,
|
||||
inout St stack,
|
||||
out Hit v);
|
||||
}
|
||||
|
||||
public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
|
||||
@@ -64,40 +152,56 @@ public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
|
||||
public C cache;
|
||||
public L lod;
|
||||
|
||||
/// Traces the closest hit at or past `t_min`.
|
||||
/// Traces the closest hit (or the first acceptable hit when
|
||||
/// `settings.any_hit`) at or past `settings.t_min`.
|
||||
///
|
||||
/// The structure may return cells in any order (the BVH restart trail is
|
||||
/// not distance ordered). Instead of returning on the first cache hit, we
|
||||
/// keep the closest hit found so far and skip cells that start beyond it:
|
||||
/// every hit inside a cell is at least `cell.t` away, so a cell with
|
||||
/// `entry >= best_t` cannot improve the result.
|
||||
public bool trace(uint32_t thread_id, float t_min, out Hit h, Ray r)
|
||||
/// `entry >= best_t` cannot improve the result. Because the cells are not
|
||||
/// ordered, such cells are skipped and never used to break the loop.
|
||||
///
|
||||
/// `stack` is caller-owned trace state. Keeping it out of the cache tracer
|
||||
/// lets primary and secondary front-ends choose their own storage.
|
||||
public bool trace<St : ITraceStack>(
|
||||
out Hit h,
|
||||
Ray r,
|
||||
TraceSettings settings,
|
||||
inout St stack)
|
||||
{
|
||||
h.hit = false;
|
||||
h.hit_location = float3(0.f);
|
||||
h.child_index = 0;
|
||||
h.node_index = 0;
|
||||
h.normal_to_world = mat3_identity();
|
||||
h.t = 0.f;
|
||||
|
||||
// Start just past the previous hit.
|
||||
Ray adjusted = r;
|
||||
adjusted.origin += r.direction * t_min;
|
||||
adjusted.origin += r.direction * settings.t_min;
|
||||
|
||||
float best_t = asfloat(0x7f7fffff); // FLT_MAX
|
||||
float best_t = settings.t_max;
|
||||
Hit best_hit = h;
|
||||
bool found = false;
|
||||
|
||||
S.Cursor cursor = this.structure.begin(adjusted);
|
||||
Cell cell;
|
||||
uint32_t visited = 0;
|
||||
|
||||
[loop]
|
||||
while (this.structure.next(cursor, cell))
|
||||
while (visited++ < settings.max_cells && this.structure.next(cursor, cell))
|
||||
{
|
||||
// `cell.t` is relative to the advanced origin, `best_t` is not.
|
||||
float cell_t = t_min + cell.t;
|
||||
float cell_t = settings.t_min + cell.t;
|
||||
|
||||
// No hit inside this cell can be closer than the current best.
|
||||
if (cell_t >= best_t)
|
||||
// Cells are not ordered, so skip instead of breaking.
|
||||
if (cell_t >= settings.t_max)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (!settings.any_hit && cell_t >= best_t)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
@@ -105,12 +209,34 @@ public struct Tracer<S : IStructure, C : IVoxelCache, L : ILodPolicy>
|
||||
Hit candidate = h;
|
||||
if (cache.trace(
|
||||
cell.cache_pointer,
|
||||
thread_id,
|
||||
cell.local_ray,
|
||||
lod,
|
||||
settings,
|
||||
cell_t,
|
||||
stack,
|
||||
candidate))
|
||||
{
|
||||
// The cache enforces `t_max`; the guard keeps a misbehaving
|
||||
// implementation from accepting an out-of-range hit.
|
||||
if (candidate.t >= settings.t_max)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// The cache reports hits in its unit-cube space. Bring the
|
||||
// position and the local attribute normal into world space so
|
||||
// front-ends can use the hit directly, including as the origin
|
||||
// of secondary rays.
|
||||
candidate.hit_location =
|
||||
cell.world_origin + mul(cell.cube_to_world, candidate.hit_location);
|
||||
candidate.normal_to_world = cell.cube_to_world;
|
||||
|
||||
if (settings.any_hit)
|
||||
{
|
||||
h = candidate;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (candidate.t < best_t)
|
||||
{
|
||||
best_t = candidate.t;
|
||||
|
||||
Reference in New Issue
Block a user