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
+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]
{