refactor: Factoring out attribtues
This commit is contained in:
@@ -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
|
||||
{
|
||||
|
||||
@@ -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" }
|
||||
+4
-37
@@ -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])
|
||||
@@ -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::*;
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
@@ -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"
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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.
|
||||
///
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
{
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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 =
|
||||
|
||||
Reference in New Issue
Block a user