refactor: Factoring out attribtues

This commit is contained in:
2026-11-22 16:28:52 +01:00
parent bbf9c4d0a8
commit 42f85757d5
20 changed files with 767 additions and 85 deletions
+5 -4
View File
@@ -15,6 +15,7 @@ The durable system is:
- `crates/vxls-voxel-cache/src/lib.rs` and `crates/vxls-voxel-cache/src/*` — cache API and GPU passes.
- `crates/vxls-voxel-cache/src/shaders/*.wgsl` — runtime-specialised cache shaders.
- `crates/vxls-attributes/src/*` — producer-facing attribute traits, payload layouts, and the `Attributes` derive.
- `crates/vxls-gpu/src/*` — radix sort, top-K, indirect dispatch, compaction.
- `shaders/*.slang` — render-side ray marching, compiled ahead of time.
- `crates/vxls-voxel-cache/src/tables.rs` + `crates/vxls-terrain/src/lib.rs` — structure tables
@@ -40,9 +41,9 @@ cargo test --workspace # unit tests (GPU tests need an adapter)
```
The repository is a virtual Cargo workspace: the binary lives in `crates/vxls`,
the durable engine is split across `crates/vxls-voxel-cache`, `crates/vxls-gpu`,
`crates/vxls-profiler`, `crates/vxls-production`, `crates/vxls-bvh`, and
`crates/vxls-terrain`. Use `cargo check -p <crate>` for a single crate.
the durable engine is split across `crates/vxls-voxel-cache`, `crates/vxls-attributes`,
`crates/vxls-gpu`, `crates/vxls-profiler`, `crates/vxls-production`, `crates/vxls-bvh`,
and `crates/vxls-terrain`. Use `cargo check -p <crate>` for a single crate.
SPIR-V files are embedded with `include_spirv_source!` / `include_spirv!` at
Rust compile time, so after rebuilding shaders you must also rebuild Rust.
@@ -107,7 +108,7 @@ Do not change these casually; they are contracts between Rust, WGSL, and Slang.
| Task | Start at |
|---|---|
| Change page/pointer layout | `crates/vxls-voxel-cache/src/schema.rs`, `crates/vxls-voxel-cache/src/shaders/cache_common.wgsl`, `crates/vxls-voxel-cache/src/shaders/common.wgsl` |
| Add/change a cache attribute | `crates/vxls-voxel-cache/src/layout.rs`, `crates/vxls-voxel-cache/src/attributes.rs`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl`, Slang `fetch_*` in `shaders/voxel.slang` |
| Add/change a cache attribute | `crates/vxls-attributes/src/attributes.rs`, `crates/vxls-voxel-cache/src/layout.rs`, `crates/vxls-voxel-cache/src/insertion.rs` (`write_attributes`), `crates/vxls-voxel-cache/src/attributes.rs`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl`, Slang `fetch_*` in `shaders/voxel.slang` |
| Change request prioritisation | `crates/vxls-voxel-cache/src/requests.rs`, `crates/vxls-gpu/src/top_k.rs`, `crates/vxls-gpu/src/radix_sort.rs` |
| Change eviction | `crates/vxls-voxel-cache/src/eviction.rs`, `crates/vxls-voxel-cache/src/shaders/eviction.wgsl`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl` |
| Change insertion semantics | `crates/vxls-voxel-cache/src/lib.rs` (`insert`), `crates/vxls-voxel-cache/src/pipelines.rs`, `crates/vxls-voxel-cache/src/shaders/insertion.wgsl`, `write_pointers.wgsl` |
+11 -11
View File
@@ -1,10 +1,10 @@
//! Derive macro for the `vxls_production::Attributes` trait.
//! Derive macro for the `vxls_attributes::Attributes` trait.
//!
//! # Example
//!
//! ```ignore
//! use bytemuck::{Pod, Zeroable};
//! use vxls_production::Attributes;
//! use vxls_attributes::Attributes;
//!
//! #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes)]
//! #[repr(C)]
@@ -19,7 +19,7 @@
//! ```
//!
//! Each non-skipped field becomes one cache attribute, in declaration order.
//! The derive also implements `vxls_production::Attribute` for the struct by
//! The derive also implements `vxls_attributes::Attribute` for the struct by
//! averaging every field independently.
//!
//! Field options:
@@ -168,7 +168,7 @@ fn expand(input: DeriveInput) -> Result<TokenStream2>
};
descriptors.push(quote! {
::vxls_production::AttributeDescriptor {
::vxls_attributes::AttributeDescriptor {
label: #label,
word_count: (::core::mem::size_of::<#ty>() / 4) as u32,
semantic: #semantic,
@@ -176,15 +176,15 @@ fn expand(input: DeriveInput) -> Result<TokenStream2>
});
getters.push(quote! {
#index => ::vxls_production::bytemuck::bytes_of(&self.#name),
#index => ::vxls_attributes::bytemuck::bytes_of(&self.#name),
});
getters_mut.push(quote! {
#index => ::vxls_production::bytemuck::bytes_of_mut(&mut self.#name),
#index => ::vxls_attributes::bytemuck::bytes_of_mut(&mut self.#name),
});
averages.push(quote! {
#name: <#ty as ::vxls_production::Attribute>::average(
#name: <#ty as ::vxls_attributes::Attribute>::average(
&items
.iter()
.map(|item| item.#name)
@@ -201,10 +201,10 @@ fn expand(input: DeriveInput) -> Result<TokenStream2>
Ok(quote! {
#[automatically_derived]
impl ::vxls_production::Attributes for #ident
impl ::vxls_attributes::Attributes for #ident
{
const LAYOUT: ::vxls_production::AttributesLayout =
::vxls_production::AttributesLayout {
const LAYOUT: ::vxls_attributes::AttributesLayout =
::vxls_attributes::AttributesLayout {
attributes: &[ #(#descriptors),* ],
};
@@ -238,7 +238,7 @@ fn expand(input: DeriveInput) -> Result<TokenStream2>
}
#[automatically_derived]
impl ::vxls_production::Attribute for #ident
impl ::vxls_attributes::Attribute for #ident
{
fn average(items: &[Self]) -> Self
{
+8
View File
@@ -0,0 +1,8 @@
[package]
name = "vxls-attributes"
version = "0.1.0"
edition = "2024"
[dependencies]
bytemuck.workspace = true
vxls-attributes-derive = { path = "../vxls-attributes-derive" }
@@ -8,12 +8,13 @@
//! match the order the shaders read, and each field must be a whole number of
//! `u32` words. `#[derive(Attributes)]` (re-exported at the crate root) builds
//! the layout from the field order and checks both properties at compile time.
//!
//! This crate is deliberately free of GPU and producer dependencies. The cache
//! consumes [`AttributesLayout`] to build its own `CacheLayout`, and producers
//! implement [`Attributes`] for the payloads they generate.
use bytemuck::Pod;
use bytemuck::Zeroable;
use vxls_voxel_cache::CacheAttribute;
use vxls_voxel_cache::CacheAttributeInit;
use vxls_voxel_cache::CacheLayout;
/// A single voxel attribute.
///
@@ -270,40 +271,6 @@ impl AttributesLayout
hash
}
/// Converts this layout to the GPU-facing [`CacheLayout`].
///
/// Every attribute of this layout is inserted from the producer and is
/// therefore [`CacheAttributeInit::External`]. `extra` attributes are
/// appended after them and are meant for GPU-only data
/// ([`CacheAttributeInit::DontTouch`]), which producers never fill.
pub fn to_cache_layout(&self, extra: &[CacheAttribute]) -> CacheLayout
{
let mut layout = CacheLayout::default();
for attribute in self.attributes
{
layout.add_attribute(CacheAttribute {
label: Some(attribute.label),
word_count: attribute.word_count,
init: CacheAttributeInit::External,
});
}
for attribute in extra
{
layout.add_attribute(*attribute);
}
layout
}
/// Converts this layout to the GPU-facing [`CacheLayout`] without extra
/// GPU-only attributes.
pub fn to_cache_layout_only(&self) -> CacheLayout
{
self.to_cache_layout(&[])
}
}
fn fnv1a(hash: &mut u64, bytes: &[u8])
+29
View File
@@ -0,0 +1,29 @@
//! Voxel attribute vocabulary shared by the cache and its producers.
//!
//! A payload struct implements [`Attributes`]. Each non-skipped field becomes
//! one cache attribute, stored in its own GPU buffer (`word_count` 32-bit words
//! per voxel). The order of the fields is the order of the attribute bindings,
//! so it is the same order the shaders index.
//!
//! ```ignore
//! #[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes)]
//! #[repr(C)]
//! struct MyAttributes
//! {
//! #[attribute(label = "color", semantic = "color")]
//! color: u32,
//! #[attribute(label = "normal", semantic = "normal")]
//! normal: [f32; 3],
//! }
//! ```
//!
//! This crate only describes attribute data. Building a GPU-facing cache
//! layout and uploading a slice of attributes to a
//! `vxls_voxel_cache::CacheInsertionData` live in `vxls-voxel-cache`.
pub use bytemuck;
pub use vxls_attributes_derive::Attributes;
mod attributes;
pub use attributes::*;
+141
View File
@@ -0,0 +1,141 @@
use bytemuck::Pod;
use bytemuck::Zeroable;
use vxls_attributes::Attribute;
use vxls_attributes::AttributeDescriptor;
use vxls_attributes::Attributes;
use vxls_attributes::AttributesLayout;
use vxls_attributes::LayoutError;
#[derive(Clone, Copy, PartialEq, Default, Pod, Zeroable, Attributes, Debug)]
#[repr(C)]
struct TestAttributes
{
#[attribute(label = "color", semantic = "color")]
color: u32,
#[attribute(label = "normal", semantic = "normal")]
normal: [f32; 3],
#[attribute(skip)]
reserved: u32,
}
fn sample(color: u32, normal: [f32; 3]) -> TestAttributes
{
TestAttributes {
color,
normal,
reserved: 0,
}
}
#[test]
fn layout_matches_the_declared_fields()
{
let layout = TestAttributes::LAYOUT;
assert_eq!(layout.len(), 2);
assert!(!layout.is_empty());
assert_eq!(layout.attributes[0].label, "color");
assert_eq!(layout.attributes[0].semantic, Some("color"));
assert_eq!(layout.attributes[0].word_count, 1);
assert_eq!(layout.attributes[1].label, "normal");
assert_eq!(layout.attributes[1].semantic, Some("normal"));
assert_eq!(layout.attributes[1].word_count, 3);
assert_eq!(layout.total_word_count(), 4);
assert!(layout.validate().is_ok());
assert_eq!(layout.by_label("normal").map(|(index, _)| index), Some(1));
assert_eq!(layout.by_semantic("color").map(|(index, _)| index), Some(0));
assert!(layout.by_label("reserved").is_none());
}
#[test]
fn get_attr_returns_the_field_bytes()
{
let value = sample(0x1122_3344, [1.0, 2.0, 3.0]);
assert_eq!(value.get_attr(0), bytemuck::bytes_of(&value.color));
assert_eq!(value.get_attr(1), bytemuck::bytes_of(&value.normal));
assert!(value.try_get_attr(2).is_none());
let mut value = value;
value.get_attr_mut(0).copy_from_slice(&0xAABB_CCDDu32.to_ne_bytes());
assert_eq!(value.color, 0xAABB_CCDD);
assert!(value.try_get_attr_mut(2).is_none());
}
#[test]
fn average_is_component_wise_and_skips_the_reserved_field()
{
let first = TestAttributes {
color: 2,
normal: [1.0, 2.0, 3.0],
reserved: 7,
};
let second = TestAttributes {
color: 4,
normal: [3.0, 4.0, 5.0],
reserved: 9,
};
let average = TestAttributes::average(&[first, second]);
assert_eq!(average.color, 3);
assert_eq!(average.normal, [2.0, 3.0, 4.0]);
assert_eq!(average.reserved, 0);
assert_eq!(TestAttributes::average(&[]), TestAttributes::default());
}
#[test]
fn validate_rejects_duplicate_labels_and_semantics()
{
const DUPLICATE_LABELS: AttributesLayout = AttributesLayout {
attributes: &[
AttributeDescriptor {
label: "a",
word_count: 1,
semantic: None,
},
AttributeDescriptor {
label: "a",
word_count: 1,
semantic: None,
},
],
};
assert_eq!(
DUPLICATE_LABELS.validate(),
Err(LayoutError::DuplicateLabel {
first: 0,
second: 1
})
);
const DUPLICATE_SEMANTICS: AttributesLayout = AttributesLayout {
attributes: &[
AttributeDescriptor::new("a", 1).with_semantic("color"),
AttributeDescriptor::new("b", 1).with_semantic("color"),
],
};
assert_eq!(
DUPLICATE_SEMANTICS.validate(),
Err(LayoutError::DuplicateSemantic {
first: 0,
second: 1
})
);
assert_eq!(AttributesLayout::EMPTY.validate(), Err(LayoutError::Empty));
assert_ne!(
TestAttributes::LAYOUT.fingerprint(),
DUPLICATE_LABELS.fingerprint()
);
}
+1 -1
View File
@@ -8,7 +8,7 @@ bytemuck.workspace = true
itertools.workspace = true
rayon.workspace = true
wgpu.workspace = true
vxls-attributes-derive = { path = "../vxls-attributes-derive" }
vxls-attributes = { path = "../vxls-attributes" }
vxls-voxel-cache = { path = "../vxls-voxel-cache" }
binrw = "0.15.2"
crc32fast = "1.5.1"
+1 -1
View File
@@ -15,7 +15,7 @@ use super::format::{
HEADER_SIZE, Header, LevelArgs, LevelBody, MAGIC, OFFSET_ENTRY_SIZE, OffsetEntry, PREAMBLE_SIZE,
Preamble, TAG_ATTRIBUTES, level_of, mask_words,
};
use crate::attributes::{Attribute, AttributesLayout};
use crate::{Attribute, AttributesLayout};
use crate::sparse_tree::{NTree, NTreeNode};
use crate::tree_locator::TreeLocator;
+1 -1
View File
@@ -14,7 +14,7 @@ use super::format::{
HEADER_SIZE, Header, LevelBody, MAGIC, OFFSET_ENTRY_SIZE, OffsetEntry, PREAMBLE_SIZE, Preamble,
TAG_ATTRIBUTES, level_tag, mask_words,
};
use crate::attributes::{Attribute, AttributesLayout};
use crate::{Attribute, AttributesLayout};
use crate::sparse_tree::NTree;
use crate::tree_locator::TreeLocator;
+3 -4
View File
@@ -1,7 +1,8 @@
#![allow(incomplete_features)]
#![feature(generic_const_exprs)]
//! Producer-side API: attributes, produced nodes and cache layout bridging.
//! Producer-side API: produced nodes, producers, and the attribute vocabulary
//! re-exported from `vxls-attributes`.
//!
//! A voxel payload is described by a type implementing [`Attributes`]. Each
//! non-skipped field of that type becomes one cache attribute, stored in its
@@ -26,13 +27,11 @@
//! ```
pub use bytemuck;
pub use vxls_attributes_derive::Attributes;
pub use vxls_attributes::*;
pub use vxls_voxel_cache::schema::StructureAnchor;
mod attributes;
mod producer;
pub use attributes::*;
pub use producer::*;
/// A structure locator format to locate node within an ntree
+16 -1
View File
@@ -1,12 +1,14 @@
//! Producers and the nodes they produce.
use vxls_voxel_cache::insertion::CacheInsertionData;
use vxls_voxel_cache::schema::InsertionInformation;
pub use vxls_voxel_cache::insertion::AttributeUploadError;
pub use vxls_voxel_cache::schema::ProducerId;
pub use vxls_voxel_cache::schema::StructureLocator;
use crate::Attributes;
use crate::StructureAnchor;
use crate::attributes::Attributes;
/// A node produced by a [`Producer`], ready to be inserted into the cache.
///
@@ -49,6 +51,19 @@ where
&mut self.attributes
}
/// Uploads this node's voxels into an insertion batch.
///
/// Returns the number of entries the batch now describes, which is `1`
/// for a single produced node.
pub fn write_attributes_into(
&self,
queue: &wgpu::Queue,
insertion: &CacheInsertionData<N>,
) -> Result<usize, AttributeUploadError>
{
insertion.write_attributes(queue, &self.attributes)
}
/// Writes attribute `index` of every child to `out`, in the
/// `[child][word]` order expected by the cache insertion buffer.
///
+15 -6
View File
@@ -11,6 +11,7 @@ use vxls_production::LayoutError;
use vxls_production::ProducedNode;
use vxls_voxel_cache::CacheAttribute;
use vxls_voxel_cache::CacheAttributeInit;
use vxls_voxel_cache::CacheLayout;
use vxls_voxel_cache::schema::ChildInformation;
use vxls_voxel_cache::schema::InsertionInformation;
@@ -102,11 +103,14 @@ fn average_is_component_wise_and_skips_the_reserved_field()
#[test]
fn cache_layout_starts_with_external_attributes_then_extras()
{
let layout = TestAttributes::LAYOUT.to_cache_layout(&[CacheAttribute {
label: Some("gi"),
word_count: 2,
init: CacheAttributeInit::DontTouch,
}]);
let layout = CacheLayout::from_attributes(
&TestAttributes::LAYOUT,
&[CacheAttribute {
label: Some("gi"),
word_count: 2,
init: CacheAttributeInit::DontTouch,
}],
);
let attributes = layout.attributes();
@@ -120,7 +124,12 @@ fn cache_layout_starts_with_external_attributes_then_extras()
assert_eq!(attributes[2].word_count, 2);
assert_eq!(attributes[2].init, CacheAttributeInit::DontTouch);
assert_eq!(TestAttributes::LAYOUT.to_cache_layout_only().attributes().len(), 2);
assert_eq!(
CacheLayout::from_attributes(&TestAttributes::LAYOUT, &[])
.attributes()
.len(),
2
);
}
#[test]
+1
View File
@@ -6,5 +6,6 @@ edition = "2024"
[dependencies]
bytemuck.workspace = true
wgpu.workspace = true
vxls-attributes = { path = "../vxls-attributes" }
vxls-gpu = { path = "../vxls-gpu" }
vxls-profiler = { path = "../vxls-profiler" }
+456
View File
@@ -4,6 +4,9 @@ use wgpu::BindGroupLayout;
use wgpu::BufferUsages;
use wgpu::ShaderStages;
use vxls_attributes::Attributes;
use crate::layout::CacheAttributeInit;
use crate::layout::CacheLayout;
use crate::schema::InsertionInformation;
use crate::schema::InsertionParent;
@@ -29,6 +32,10 @@ where
/// Contains the attributes to import in the cache.
attributes: Vec<wgpu::Buffer>,
/// Layout the attribute buffers were created from. Kept so attribute
/// uploads can validate producer layouts against the cache layout.
layout: CacheLayout,
/// Contains the indicies of the page in which the data was written
destination_indices: wgpu::Buffer,
@@ -46,6 +53,176 @@ where
bind_group_no_attributes: wgpu::BindGroup,
}
/// Errors reported while uploading a producer attribute slice into
/// [`CacheInsertionData`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum AttributeUploadError
{
/// The slice is not a whole number of pages.
NotWholePages
{
voxel_count: usize,
children: usize,
},
/// The slice does not fit in this insertion batch.
TooManyVoxels
{
voxel_count: usize,
capacity: usize,
},
/// The producer declares more attributes than the cache layout has.
MissingCacheAttribute
{
index: usize,
},
/// The producer attribute index is out of bounds.
AttributeIndexOutOfBounds
{
index: usize,
},
/// The cache attribute is not `External`, so insertion will not copy it.
NotExternal
{
index: usize,
},
/// Declared word counts disagree.
WordCountMismatch
{
index: usize,
producer: u32,
cache: u32,
},
/// Declared labels disagree (only checked when the cache label is present).
LabelMismatch
{
index: usize,
producer: &'static str,
cache: Option<&'static str>,
},
/// A `get_attr` implementation returned the wrong number of bytes.
BadAttributeBytes
{
index: usize,
expected: usize,
actual: usize,
},
}
/// Checks that `A::LAYOUT` is a valid prefix of `layout`.
///
/// Every producer attribute must map to an `External` cache attribute with the
/// same word count and (when present) the same label. Extra attributes after
/// the producer prefix are allowed; they are meant for GPU-only data.
pub fn validate_attribute_layout<A: Attributes>(
layout: &CacheLayout,
) -> Result<(), AttributeUploadError>
{
let producer_layout = &A::LAYOUT;
for (index, descriptor) in producer_layout.attributes.iter().enumerate()
{
let Some(cache_attribute) = layout.attributes().get(index) else
{
return Err(AttributeUploadError::MissingCacheAttribute { index });
};
if cache_attribute.init != CacheAttributeInit::External
{
return Err(AttributeUploadError::NotExternal { index });
}
if cache_attribute.word_count != descriptor.word_count
{
return Err(AttributeUploadError::WordCountMismatch {
index,
producer: descriptor.word_count,
cache: cache_attribute.word_count,
});
}
if let Some(cache_label) = cache_attribute.label
&& cache_label != descriptor.label
{
return Err(AttributeUploadError::LabelMismatch {
index,
producer: descriptor.label,
cache: Some(cache_label),
});
}
}
Ok(())
}
/// Checks that a voxel slice is a whole number of pages and fits the batch.
pub fn validate_voxel_count(
voxel_count: usize,
children: usize,
capacity: usize,
) -> Result<(), AttributeUploadError>
{
if voxel_count % children != 0
{
return Err(AttributeUploadError::NotWholePages {
voxel_count,
children,
});
}
if voxel_count > capacity
{
return Err(AttributeUploadError::TooManyVoxels {
voxel_count,
capacity,
});
}
Ok(())
}
/// Collects attribute `index` of every voxel into `[voxel][word]` bytes.
///
/// The resulting byte slice is exactly what the insertion attribute buffer
/// expects for one entry-major attribute page.
pub fn collect_attribute_bytes<A: Attributes>(
voxels: &[A],
index: usize,
) -> Result<Vec<u8>, AttributeUploadError>
{
let Some(descriptor) = A::LAYOUT.attributes.get(index) else
{
return Err(AttributeUploadError::AttributeIndexOutOfBounds { index });
};
let expected = descriptor.word_count as usize * size_of::<u32>();
let mut bytes = Vec::with_capacity(voxels.len() * expected);
for voxel in voxels
{
let attribute = voxel.get_attr(index);
if attribute.len() != expected
{
return Err(AttributeUploadError::BadAttributeBytes {
index,
expected,
actual: attribute.len(),
});
}
bytes.extend_from_slice(attribute);
}
Ok(bytes)
}
impl<const N: usize> CacheInsertionData<N>
where
[(); N * N * N]:,
@@ -178,6 +355,7 @@ where
valid_indices,
valid_count,
attributes,
layout: layout.clone(),
bind_group_layout,
bind_group,
@@ -296,4 +474,282 @@ where
{
&self.attributes
}
/// The layout this insertion data was created from.
pub fn layout(&self) -> &CacheLayout
{
&self.layout
}
/// Number of attribute buffers in this insertion batch.
pub fn attribute_count(&self) -> usize
{
self.attributes.len()
}
/// The attribute buffer for `index`, if it exists.
pub fn attribute_buffer(&self, index: usize) -> Option<&wgpu::Buffer>
{
self.attributes.get(index)
}
/// Maximum number of voxels this insertion batch can hold.
pub fn attribute_capacity(&self) -> usize
{
self.max_page_count * N * N * N
}
/// Uploads `[entry][child]` voxel attributes into the insertion buffers.
///
/// `voxels` must contain `entry_count * N^3` elements in child-major order
/// (`x + 4*y + 16*z`). Returns `entry_count`, which the caller should write
/// to [`Self::page_count_buffer`] before insertion.
///
/// Only the producer attributes (`A::LAYOUT`) are written. `DontTouch`
/// attributes appended to the cache layout are left untouched.
pub fn write_attributes<A: Attributes>(
&self,
queue: &wgpu::Queue,
voxels: &[A],
) -> Result<usize, AttributeUploadError>
{
validate_attribute_layout::<A>(&self.layout)?;
validate_voxel_count(voxels.len(), N * N * N, self.attribute_capacity())?;
if voxels.is_empty()
{
return Ok(0);
}
for index in 0..A::LAYOUT.len()
{
let bytes = collect_attribute_bytes(voxels, index)?;
queue.write_buffer(&self.attributes[index], 0, &bytes);
}
Ok(voxels.len() / (N * N * N))
}
}
#[cfg(test)]
mod tests
{
use super::*;
use vxls_attributes::Attribute;
use vxls_attributes::AttributeDescriptor;
use vxls_attributes::AttributesLayout;
use crate::layout::CacheAttribute;
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
#[repr(C)]
struct TestAttributes
{
color: u32,
normal: [f32; 3],
}
impl Attribute for TestAttributes
{
fn average(attributes: &[Self]) -> Self
{
if attributes.is_empty()
{
return Self::default();
}
let count = attributes.len() as f32;
Self {
color: (attributes.iter().map(|value| value.color as u64).sum::<u64>()
/ attributes.len() as u64) as u32,
normal: std::array::from_fn(|index| {
attributes
.iter()
.map(|value| value.normal[index])
.sum::<f32>()
/ count
}),
}
}
}
impl Attributes for TestAttributes
{
const LAYOUT: AttributesLayout = AttributesLayout::new(&[
AttributeDescriptor::new("color", 1),
AttributeDescriptor::new("normal", 3),
]);
fn get_attr(&self, index: usize) -> &[u8]
{
match index
{
0 => bytemuck::bytes_of(&self.color),
1 => bytemuck::bytes_of(&self.normal),
_ => panic!("attribute index out of bounds"),
}
}
fn get_attr_mut(&mut self, index: usize) -> &mut [u8]
{
match index
{
0 => bytemuck::bytes_of_mut(&mut self.color),
1 => bytemuck::bytes_of_mut(&mut self.normal),
_ => panic!("attribute index out of bounds"),
}
}
}
fn cache_layout() -> CacheLayout
{
CacheLayout::from_attributes(&TestAttributes::LAYOUT, &[])
}
#[test]
fn collect_attribute_bytes_orders_by_voxel()
{
let voxels = [
TestAttributes {
color: 1,
normal: [1., 2., 3.],
},
TestAttributes {
color: 2,
normal: [4., 5., 6.],
},
];
let colors = collect_attribute_bytes(&voxels, 0).unwrap();
assert_eq!(colors, bytemuck::cast_slice::<u32, u8>(&[1, 2]));
let normals = collect_attribute_bytes(&voxels, 1).unwrap();
assert_eq!(
normals,
bytemuck::cast_slice::<f32, u8>(&[1., 2., 3., 4., 5., 6.])
);
assert_eq!(
collect_attribute_bytes(&voxels, 2).unwrap_err(),
AttributeUploadError::AttributeIndexOutOfBounds { index: 2 }
);
}
#[test]
fn matching_layout_passes_validation()
{
assert_eq!(
validate_attribute_layout::<TestAttributes>(&cache_layout()),
Ok(())
);
}
#[test]
fn validation_rejects_word_count_mismatch()
{
let mut layout = CacheLayout::default();
layout.add_attribute(CacheAttribute {
label: Some("color"),
word_count: 2,
init: CacheAttributeInit::External,
});
layout.add_attribute(CacheAttribute {
label: Some("normal"),
word_count: 3,
init: CacheAttributeInit::External,
});
assert_eq!(
validate_attribute_layout::<TestAttributes>(&layout),
Err(AttributeUploadError::WordCountMismatch {
index: 0,
producer: 1,
cache: 2,
})
);
}
#[test]
fn validation_rejects_non_external_attributes()
{
let mut layout = CacheLayout::default();
layout.add_attribute(CacheAttribute {
label: Some("color"),
word_count: 1,
init: CacheAttributeInit::DontTouch,
});
layout.add_attribute(CacheAttribute {
label: Some("normal"),
word_count: 3,
init: CacheAttributeInit::External,
});
assert_eq!(
validate_attribute_layout::<TestAttributes>(&layout),
Err(AttributeUploadError::NotExternal { index: 0 })
);
}
#[test]
fn validation_rejects_missing_attributes()
{
let mut layout = CacheLayout::default();
layout.add_attribute(CacheAttribute {
label: Some("color"),
word_count: 1,
init: CacheAttributeInit::External,
});
assert_eq!(
validate_attribute_layout::<TestAttributes>(&layout),
Err(AttributeUploadError::MissingCacheAttribute { index: 1 })
);
}
#[test]
fn validation_rejects_label_mismatch()
{
let mut layout = CacheLayout::default();
layout.add_attribute(CacheAttribute {
label: Some("not-color"),
word_count: 1,
init: CacheAttributeInit::External,
});
layout.add_attribute(CacheAttribute {
label: Some("normal"),
word_count: 3,
init: CacheAttributeInit::External,
});
assert_eq!(
validate_attribute_layout::<TestAttributes>(&layout),
Err(AttributeUploadError::LabelMismatch {
index: 0,
producer: "color",
cache: Some("not-color"),
})
);
}
#[test]
fn voxel_counts_must_be_whole_pages_within_capacity()
{
assert_eq!(validate_voxel_count(64, 64, 128), Ok(()));
assert_eq!(
validate_voxel_count(65, 64, 128),
Err(AttributeUploadError::NotWholePages {
voxel_count: 65,
children: 64,
})
);
assert_eq!(
validate_voxel_count(128, 64, 64),
Err(AttributeUploadError::TooManyVoxels {
voxel_count: 128,
capacity: 64,
})
);
}
}
+28
View File
@@ -1,5 +1,6 @@
use wgpu::BufferUsages;
use vxls_attributes::AttributesLayout;
use vxls_profiler::memory_profiler;
/// Defines how a [`VoxelCache`]'s attribute is populated upon populating a page
@@ -96,6 +97,33 @@ impl CacheLayout
index
}
/// Builds a cache layout from producer attributes followed by `extra`.
///
/// Every attribute of `layout` is inserted from the producer and is
/// therefore [`CacheAttributeInit::External`]. `extra` attributes are
/// appended after them and are meant for GPU-only data
/// ([`CacheAttributeInit::DontTouch`]), which producers never fill.
pub fn from_attributes(layout: &AttributesLayout, extra: &[CacheAttribute]) -> Self
{
let mut cache_layout = Self::default();
for attribute in layout.attributes
{
cache_layout.add_attribute(CacheAttribute {
label: Some(attribute.label),
word_count: attribute.word_count,
init: CacheAttributeInit::External,
});
}
for attribute in extra
{
cache_layout.add_attribute(*attribute);
}
cache_layout
}
/// The attributes of this layout, in binding order
pub fn attributes(&self) -> &[CacheAttribute]
{
+1
View File
@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
vxls-attributes = { path = "../vxls-attributes" }
vxls-bvh = { path = "../vxls-bvh" }
vxls-gpu = { path = "../vxls-gpu" }
vxls-production = { path = "../vxls-production" }
+3 -1
View File
@@ -83,6 +83,7 @@ use vxls_profiler::Frame;
use vxls_profiler::Profile;
use vxls_profiler::ProfilingEncoder;
use vxls_terrain::ToroidalStructureTable;
use vxls_voxel_cache::CacheLayout;
use vxls_voxel_cache::VoxelCache;
use vxls_voxel_cache::VoxelCacheInsertion;
use vxls_voxel_cache::insertion::CacheInsertionData;
@@ -396,7 +397,8 @@ impl State
let egui_renderer = EguiRenderer::new(&device, surface_format, &window);
let layout = crate::producers::VoxelAttributes::LAYOUT.to_cache_layout_only();
let layout =
CacheLayout::from_attributes(&crate::producers::VoxelAttributes::LAYOUT, &[]);
let request_buffer = CacheRequestBuffer::new(&device, 1024);
let voxel_cache =
+4 -2
View File
@@ -186,7 +186,9 @@ Consequences agents should keep in mind:
| `crates/vxls/src/producers.rs` | `ChunkedProducer` + procedural fixtures | **Temporary playground** (trait is the useful part) |
| `crates/vxls-voxel-cache/src/lib.rs` | `VoxelCache` orchestrator, public API, raytrace bind group | Active, durable |
| `crates/vxls-voxel-cache/src/schema.rs` | Pointer bits, page structs, request structs | Active, durable |
| `crates/vxls-voxel-cache/src/layout.rs` | Attribute descriptors and generated WGSL constants | Active, durable |
| `crates/vxls-attributes/src/attributes.rs` | Producer-facing `Attribute`/`Attributes` traits and static attribute layouts | Active, durable |
| `crates/vxls-attributes-derive/src/lib.rs` | `#[derive(Attributes)]` layout generator | Active, durable |
| `crates/vxls-voxel-cache/src/layout.rs` | `CacheAttribute`/`CacheLayout`, bridge from `AttributesLayout`, generated WGSL constants | Active, durable |
| `crates/vxls-voxel-cache/src/attributes.rs` | Attribute page buffers and bind group | Active, durable |
| `crates/vxls-voxel-cache/src/structure.rs` | Pointer/location/depth page buffers | Active, durable |
| `crates/vxls-voxel-cache/src/requests.rs` | Request counters, request buffer, top-K/sort, host download | Active, durable |
@@ -199,7 +201,7 @@ Consequences agents should keep in mind:
| `crates/vxls-gpu/src/` | Radix sort, top-K, indirect dispatch, compaction helpers | Active infrastructure |
| `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, `VoxelProducer` trait | Compiled; durable contract |
| `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 |
+27 -16
View File
@@ -331,32 +331,44 @@ production types are the durable contract; the driver is still the playground.
### 6.1 `crates/vxls-production/src/lib.rs`
Defines a more ambitious interface:
Defines the producer-facing attribute vocabulary and the production interface.
The attribute traits and layouts live in `vxls-attributes` and are re-exported
here:
```rust
// Identity types live in vxls-voxel-cache::schema and are re-exported here.
pub use voxel_cache::schema::{ProducerId, StructureAnchor, StructureLocator};
pub use vxls_attributes::{Attribute, AttributeDescriptor, Attributes, AttributesLayout};
pub use vxls_voxel_cache::schema::{ProducerId, StructureAnchor, StructureLocator};
pub trait VoxelAttributes<const N: usize> {
fn attribute_count() -> usize;
fn attribute(&self, attribute_index: usize) -> &[u32];
pub trait Attributes: Attribute {
const LAYOUT: AttributesLayout;
fn get_attr(&self, index: usize) -> &[u8];
fn get_attr_mut(&mut self, index: usize) -> &mut [u8];
}
pub trait VoxelProducer<const N: usize> {
type Output: VoxelAttributes<N>;
fn produce(
&self,
producer_id: ProducerId,
anchor: StructureAnchor,
locator: StructureLocator,
) -> (InsertionInformation<N>, [Self::Output; N * N * N]);
pub trait Producer<const N: usize, A: Attributes> {
fn produce(&self, anchor: StructureAnchor, locator: StructureLocator)
-> ProducedNode<N, A>;
}
pub struct ProducedNode<const N: usize, A: Attributes> {
pub insertion: InsertionInformation<N>,
pub attributes: [A; N * N * N],
}
```
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())?;
```
Differences from the demo interface:
- A node carries a `producer_id`, so one cache can mix multiple producers.
- Attributes are abstracted behind `VoxelAttributes`, avoiding hardcoded
- 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.
@@ -495,8 +507,7 @@ Minimum viable path with the current demo interface:
A production-ready producer should additionally:
- use the `VoxelProducer`/`VoxelAttributes` abstraction (or an equivalent) so
attributes are not hardcoded;
- use the `Producer`/`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;
+12
View File
@@ -297,6 +297,18 @@ correctness requirement.
| `valid_count` | host 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
`CacheLayout::from_attributes(&A::LAYOUT, &extras)`: producer attributes become
`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.
`InsertionInformation<N>` is just `children: [ChildInformation; 64]`, where each
`ChildInformation` uses the four-state encoding below.