From 42f85757d553e64cbb7d4bf58e48b7ca91b2805f Mon Sep 17 00:00:00 2001 From: Albin Chaboissier Date: Sun, 22 Nov 2026 16:28:52 +0100 Subject: [PATCH] refactor: Factoring out attribtues --- AGENTS.md | 9 +- crates/vxls-attributes-derive/src/lib.rs | 22 +- crates/vxls-attributes/Cargo.toml | 8 + .../src/attributes.rs | 41 +- crates/vxls-attributes/src/lib.rs | 29 ++ crates/vxls-attributes/tests/attributes.rs | 141 ++++++ crates/vxls-production/Cargo.toml | 2 +- crates/vxls-production/src/io/read.rs | 2 +- crates/vxls-production/src/io/write.rs | 2 +- crates/vxls-production/src/lib.rs | 7 +- crates/vxls-production/src/producer.rs | 17 +- crates/vxls-production/tests/attributes.rs | 21 +- crates/vxls-voxel-cache/Cargo.toml | 1 + crates/vxls-voxel-cache/src/insertion.rs | 456 ++++++++++++++++++ crates/vxls-voxel-cache/src/layout.rs | 28 ++ crates/vxls/Cargo.toml | 1 + crates/vxls/src/main.rs | 4 +- docs/architecture.md | 6 +- docs/pipeline-and-producers.md | 43 +- docs/voxel-cache.md | 12 + 20 files changed, 767 insertions(+), 85 deletions(-) create mode 100644 crates/vxls-attributes/Cargo.toml rename crates/{vxls-production => vxls-attributes}/src/attributes.rs (90%) create mode 100644 crates/vxls-attributes/src/lib.rs create mode 100644 crates/vxls-attributes/tests/attributes.rs diff --git a/AGENTS.md b/AGENTS.md index 086e249..a511b95 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 ` 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 ` 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` | diff --git a/crates/vxls-attributes-derive/src/lib.rs b/crates/vxls-attributes-derive/src/lib.rs index f4087c1..154983e 100644 --- a/crates/vxls-attributes-derive/src/lib.rs +++ b/crates/vxls-attributes-derive/src/lib.rs @@ -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 }; 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 }); 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 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 } #[automatically_derived] - impl ::vxls_production::Attribute for #ident + impl ::vxls_attributes::Attribute for #ident { fn average(items: &[Self]) -> Self { diff --git a/crates/vxls-attributes/Cargo.toml b/crates/vxls-attributes/Cargo.toml new file mode 100644 index 0000000..6f0b03c --- /dev/null +++ b/crates/vxls-attributes/Cargo.toml @@ -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" } diff --git a/crates/vxls-production/src/attributes.rs b/crates/vxls-attributes/src/attributes.rs similarity index 90% rename from crates/vxls-production/src/attributes.rs rename to crates/vxls-attributes/src/attributes.rs index 3a203d0..399e482 100644 --- a/crates/vxls-production/src/attributes.rs +++ b/crates/vxls-attributes/src/attributes.rs @@ -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]) diff --git a/crates/vxls-attributes/src/lib.rs b/crates/vxls-attributes/src/lib.rs new file mode 100644 index 0000000..d7fc8d4 --- /dev/null +++ b/crates/vxls-attributes/src/lib.rs @@ -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::*; diff --git a/crates/vxls-attributes/tests/attributes.rs b/crates/vxls-attributes/tests/attributes.rs new file mode 100644 index 0000000..9fb9ddc --- /dev/null +++ b/crates/vxls-attributes/tests/attributes.rs @@ -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() + ); +} diff --git a/crates/vxls-production/Cargo.toml b/crates/vxls-production/Cargo.toml index b26650e..1aa2421 100644 --- a/crates/vxls-production/Cargo.toml +++ b/crates/vxls-production/Cargo.toml @@ -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" diff --git a/crates/vxls-production/src/io/read.rs b/crates/vxls-production/src/io/read.rs index c0e801e..16b7ba3 100644 --- a/crates/vxls-production/src/io/read.rs +++ b/crates/vxls-production/src/io/read.rs @@ -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; diff --git a/crates/vxls-production/src/io/write.rs b/crates/vxls-production/src/io/write.rs index 8f0f0e2..dc5168d 100644 --- a/crates/vxls-production/src/io/write.rs +++ b/crates/vxls-production/src/io/write.rs @@ -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; diff --git a/crates/vxls-production/src/lib.rs b/crates/vxls-production/src/lib.rs index b3187fd..72f65fb 100644 --- a/crates/vxls-production/src/lib.rs +++ b/crates/vxls-production/src/lib.rs @@ -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 diff --git a/crates/vxls-production/src/producer.rs b/crates/vxls-production/src/producer.rs index d6809bc..aa994f8 100644 --- a/crates/vxls-production/src/producer.rs +++ b/crates/vxls-production/src/producer.rs @@ -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, + ) -> Result + { + 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. /// diff --git a/crates/vxls-production/tests/attributes.rs b/crates/vxls-production/tests/attributes.rs index e19092e..912f6c5 100644 --- a/crates/vxls-production/tests/attributes.rs +++ b/crates/vxls-production/tests/attributes.rs @@ -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] diff --git a/crates/vxls-voxel-cache/Cargo.toml b/crates/vxls-voxel-cache/Cargo.toml index 5bbe2fa..6e8772e 100644 --- a/crates/vxls-voxel-cache/Cargo.toml +++ b/crates/vxls-voxel-cache/Cargo.toml @@ -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" } diff --git a/crates/vxls-voxel-cache/src/insertion.rs b/crates/vxls-voxel-cache/src/insertion.rs index 5982732..e821a61 100644 --- a/crates/vxls-voxel-cache/src/insertion.rs +++ b/crates/vxls-voxel-cache/src/insertion.rs @@ -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, + /// 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( + 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( + voxels: &[A], + index: usize, +) -> Result, AttributeUploadError> +{ + let Some(descriptor) = A::LAYOUT.attributes.get(index) else + { + return Err(AttributeUploadError::AttributeIndexOutOfBounds { index }); + }; + + let expected = descriptor.word_count as usize * size_of::(); + 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 CacheInsertionData 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( + &self, + queue: &wgpu::Queue, + voxels: &[A], + ) -> Result + { + validate_attribute_layout::(&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::() + / attributes.len() as u64) as u32, + normal: std::array::from_fn(|index| { + attributes + .iter() + .map(|value| value.normal[index]) + .sum::() + / 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::(&[1, 2])); + + let normals = collect_attribute_bytes(&voxels, 1).unwrap(); + assert_eq!( + normals, + bytemuck::cast_slice::(&[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::(&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::(&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::(&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::(&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::(&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, + }) + ); + } } diff --git a/crates/vxls-voxel-cache/src/layout.rs b/crates/vxls-voxel-cache/src/layout.rs index 3585513..bedfd33 100644 --- a/crates/vxls-voxel-cache/src/layout.rs +++ b/crates/vxls-voxel-cache/src/layout.rs @@ -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] { diff --git a/crates/vxls/Cargo.toml b/crates/vxls/Cargo.toml index 6a85a6b..eab6932 100644 --- a/crates/vxls/Cargo.toml +++ b/crates/vxls/Cargo.toml @@ -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" } diff --git a/crates/vxls/src/main.rs b/crates/vxls/src/main.rs index bd95c4b..a7decfe 100644 --- a/crates/vxls/src/main.rs +++ b/crates/vxls/src/main.rs @@ -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 = diff --git a/docs/architecture.md b/docs/architecture.md index 85ab625..8584eac 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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 | diff --git a/docs/pipeline-and-producers.md b/docs/pipeline-and-producers.md index f730241..7acc317 100644 --- a/docs/pipeline-and-producers.md +++ b/docs/pipeline-and-producers.md @@ -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 { - 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 { - type Output: VoxelAttributes; - fn produce( - &self, - producer_id: ProducerId, - anchor: StructureAnchor, - locator: StructureLocator, - ) -> (InsertionInformation, [Self::Output; N * N * N]); +pub trait Producer { + fn produce(&self, anchor: StructureAnchor, locator: StructureLocator) + -> ProducedNode; } + +pub struct ProducedNode { + pub insertion: InsertionInformation, + 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; diff --git a/docs/voxel-cache.md b/docs/voxel-cache.md index 8a228dd..638c5bb 100644 --- a/docs/voxel-cache.md +++ b/docs/voxel-cache.md @@ -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` is just `children: [ChildInformation; 64]`, where each `ChildInformation` uses the four-state encoding below.