refactor: Factoring out attribtues
This commit is contained in:
@@ -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" }
|
||||
@@ -0,0 +1,426 @@
|
||||
//! Voxel attribute traits and layouts.
|
||||
//!
|
||||
//! An [`Attribute`] is one datum stored per voxel. An [`Attributes`] struct
|
||||
//! bundles several of them into a payload: each field becomes one cache
|
||||
//! attribute with its own GPU buffer.
|
||||
//!
|
||||
//! The layout is part of the Rust/WGSL/Slang contract: attribute order must
|
||||
//! 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;
|
||||
|
||||
/// A single voxel attribute.
|
||||
///
|
||||
/// Attributes are plain bits that can be moved between the CPU producer, the
|
||||
/// insertion buffers and the GPU. Equality is `PartialEq` rather than `Eq`
|
||||
/// because payloads commonly contain `f32` (for example `[f32; 3]` normals),
|
||||
/// and `Eq` cannot be implemented for foreign float arrays.
|
||||
pub trait Attribute:
|
||||
// An attribute can be turned into predictable, safe, raw bytes
|
||||
Pod +
|
||||
Zeroable +
|
||||
|
||||
// It can be compared with itself, equal attributes mean they can be merged in a sparse structure
|
||||
PartialEq +
|
||||
|
||||
// It can be created by anybody, without knowing what is inside
|
||||
Default +
|
||||
|
||||
// It can be moved around without problems, and does not depend on anything
|
||||
Clone +
|
||||
Copy +
|
||||
Send +
|
||||
Sync +
|
||||
'static
|
||||
{
|
||||
/// Many attributes can be averaged together.
|
||||
///
|
||||
/// Implementations must return `Self::default()` for an empty slice.
|
||||
fn average(attributes: &[Self]) -> Self;
|
||||
}
|
||||
|
||||
/// A bundle of attributes making up one voxel.
|
||||
///
|
||||
/// The layout of a structure is part of the cache contract: the order of the
|
||||
/// attributes must match the order the shaders read, and every attribute size
|
||||
/// must be a whole number of `u32` words.
|
||||
pub trait Attributes: Attribute
|
||||
{
|
||||
/// The attributes layout for this struct.
|
||||
///
|
||||
/// Built by `#[derive(Attributes)]`, but it can also be written by hand.
|
||||
const LAYOUT: AttributesLayout;
|
||||
|
||||
/// Gets the nth attribute's bytes in the struct.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `index` is not a valid attribute index.
|
||||
fn get_attr(&self, index: usize) -> &[u8];
|
||||
|
||||
/// Gets the nth attribute's bytes in the struct mutably.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `index` is not a valid attribute index.
|
||||
fn get_attr_mut(&mut self, index: usize) -> &mut [u8];
|
||||
|
||||
/// Gets the nth attribute's bytes, or [`None`] if the index is out of range.
|
||||
fn try_get_attr(&self, index: usize) -> Option<&[u8]>
|
||||
{
|
||||
(index < Self::LAYOUT.len()).then(|| self.get_attr(index))
|
||||
}
|
||||
|
||||
/// Gets the nth attribute's bytes mutably, or [`None`] if the index is out of range.
|
||||
fn try_get_attr_mut(&mut self, index: usize) -> Option<&mut [u8]>
|
||||
{
|
||||
(index < Self::LAYOUT.len()).then(|| self.get_attr_mut(index))
|
||||
}
|
||||
}
|
||||
|
||||
/// Describes one attribute of a voxel
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AttributeDescriptor
|
||||
{
|
||||
/// A name for the attribute, used as the GPU buffer label
|
||||
pub label: &'static str,
|
||||
|
||||
/// The size, in 32-bit words, of the attribute
|
||||
pub word_count: u32,
|
||||
|
||||
/// Optional shader-facing role ("color", "normal", ...).
|
||||
///
|
||||
/// The cache still indexes attributes by position; this field only exists
|
||||
/// so a host can detect that the Rust side and the shaders drifted apart.
|
||||
pub semantic: Option<&'static str>,
|
||||
}
|
||||
|
||||
impl AttributeDescriptor
|
||||
{
|
||||
/// Creates a descriptor without a semantic role
|
||||
pub const fn new(label: &'static str, word_count: u32) -> Self
|
||||
{
|
||||
Self {
|
||||
label,
|
||||
word_count,
|
||||
semantic: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a semantic role to this descriptor
|
||||
pub const fn with_semantic(mut self, semantic: &'static str) -> Self
|
||||
{
|
||||
self.semantic = Some(semantic);
|
||||
self
|
||||
}
|
||||
|
||||
/// The size of this attribute in bytes
|
||||
pub const fn size_bytes(&self) -> u32
|
||||
{
|
||||
self.word_count * size_of::<u32>() as u32
|
||||
}
|
||||
}
|
||||
|
||||
/// An attribute layout, for voxels
|
||||
///
|
||||
/// The layout is stored as a `'static` slice so it can live in an associated
|
||||
/// constant. Runtime-built layouts can copy it into a `Vec`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct AttributesLayout
|
||||
{
|
||||
/// The attributes, in binding order
|
||||
pub attributes: &'static [AttributeDescriptor],
|
||||
}
|
||||
|
||||
impl AttributesLayout
|
||||
{
|
||||
/// A layout with no attributes
|
||||
pub const EMPTY: Self = Self { attributes: &[] };
|
||||
|
||||
/// Creates a layout from a static descriptor slice
|
||||
pub const fn new(attributes: &'static [AttributeDescriptor]) -> Self
|
||||
{
|
||||
Self { attributes }
|
||||
}
|
||||
|
||||
/// Number of attributes
|
||||
pub const fn len(&self) -> usize
|
||||
{
|
||||
self.attributes.len()
|
||||
}
|
||||
|
||||
/// Whether the layout has no attributes
|
||||
pub const fn is_empty(&self) -> bool
|
||||
{
|
||||
self.attributes.is_empty()
|
||||
}
|
||||
|
||||
/// Gets the descriptor at `index`
|
||||
pub fn get(&self, index: usize) -> Option<&AttributeDescriptor>
|
||||
{
|
||||
self.attributes.get(index)
|
||||
}
|
||||
|
||||
/// Iterates over `(index, descriptor)` pairs
|
||||
pub fn iter(&self) -> impl Iterator<Item = (usize, &AttributeDescriptor)> + '_
|
||||
{
|
||||
self.attributes.iter().enumerate()
|
||||
}
|
||||
|
||||
/// Sum of every attribute's word count, i.e. the words used by one voxel
|
||||
pub fn total_word_count(&self) -> u32
|
||||
{
|
||||
self.attributes
|
||||
.iter()
|
||||
.map(|attribute| attribute.word_count)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Finds an attribute by label
|
||||
pub fn by_label(&self, label: &str) -> Option<(usize, &AttributeDescriptor)>
|
||||
{
|
||||
self.iter().find(|(_, attribute)| attribute.label == label)
|
||||
}
|
||||
|
||||
/// Finds an attribute by semantic role
|
||||
pub fn by_semantic(&self, semantic: &str) -> Option<(usize, &AttributeDescriptor)>
|
||||
{
|
||||
self.iter()
|
||||
.find(|(_, attribute)| attribute.semantic == Some(semantic))
|
||||
}
|
||||
|
||||
/// Checks that the layout can be used as a cache layout
|
||||
pub fn validate(&self) -> Result<(), LayoutError>
|
||||
{
|
||||
if self.attributes.is_empty()
|
||||
{
|
||||
return Err(LayoutError::Empty);
|
||||
}
|
||||
|
||||
for (index, attribute) in self.attributes.iter().enumerate()
|
||||
{
|
||||
if attribute.label.is_empty()
|
||||
{
|
||||
return Err(LayoutError::EmptyLabel { index });
|
||||
}
|
||||
|
||||
if attribute.word_count == 0
|
||||
{
|
||||
return Err(LayoutError::ZeroWordCount { index });
|
||||
}
|
||||
|
||||
if let Some((first, _)) = self
|
||||
.attributes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(index)
|
||||
.find(|(_, other)| other.label == attribute.label)
|
||||
{
|
||||
return Err(LayoutError::DuplicateLabel {
|
||||
first,
|
||||
second: index,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(semantic) = attribute.semantic
|
||||
&& let Some((first, _)) = self
|
||||
.attributes
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(index)
|
||||
.find(|(_, other)| other.semantic == Some(semantic))
|
||||
{
|
||||
return Err(LayoutError::DuplicateSemantic {
|
||||
first,
|
||||
second: index,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A stable fingerprint of the layout, used to check that a producer, a
|
||||
/// cache instance and a shader build agree on the attribute layout.
|
||||
pub fn fingerprint(&self) -> u64
|
||||
{
|
||||
let mut hash = 0xcbf2_9ce4_8422_2325u64;
|
||||
|
||||
for attribute in self.attributes
|
||||
{
|
||||
fnv1a(&mut hash, attribute.label.as_bytes());
|
||||
fnv1a(&mut hash, &attribute.word_count.to_le_bytes());
|
||||
|
||||
match attribute.semantic
|
||||
{
|
||||
Some(semantic) =>
|
||||
{
|
||||
fnv1a(&mut hash, &[1]);
|
||||
fnv1a(&mut hash, semantic.as_bytes());
|
||||
}
|
||||
None => fnv1a(&mut hash, &[0]),
|
||||
}
|
||||
}
|
||||
|
||||
hash
|
||||
}
|
||||
}
|
||||
|
||||
fn fnv1a(hash: &mut u64, bytes: &[u8])
|
||||
{
|
||||
for byte in bytes
|
||||
{
|
||||
*hash ^= *byte as u64;
|
||||
*hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
|
||||
}
|
||||
}
|
||||
|
||||
/// Errors reported by [`AttributesLayout::validate`]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum LayoutError
|
||||
{
|
||||
/// The layout has no attributes, which a cache cannot represent
|
||||
Empty,
|
||||
/// An attribute has an empty label
|
||||
EmptyLabel
|
||||
{
|
||||
/// Index of the offending attribute
|
||||
index: usize,
|
||||
},
|
||||
/// An attribute has a zero word count
|
||||
ZeroWordCount
|
||||
{
|
||||
/// Index of the offending attribute
|
||||
index: usize,
|
||||
},
|
||||
/// Two attributes share a label
|
||||
DuplicateLabel
|
||||
{
|
||||
/// Index of the first attribute
|
||||
first: usize,
|
||||
/// Index of the duplicate attribute
|
||||
second: usize,
|
||||
},
|
||||
/// Two attributes share a semantic role
|
||||
DuplicateSemantic
|
||||
{
|
||||
/// Index of the first attribute
|
||||
first: usize,
|
||||
/// Index of the duplicate attribute
|
||||
second: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl std::fmt::Display for LayoutError
|
||||
{
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result
|
||||
{
|
||||
match self
|
||||
{
|
||||
Self::Empty => write!(formatter, "attribute layout has no attributes"),
|
||||
Self::EmptyLabel { index } =>
|
||||
{
|
||||
write!(formatter, "attribute {index} has an empty label")
|
||||
}
|
||||
Self::ZeroWordCount { index } =>
|
||||
{
|
||||
write!(formatter, "attribute {index} has a zero word count")
|
||||
}
|
||||
Self::DuplicateLabel { first, second } =>
|
||||
{
|
||||
write!(
|
||||
formatter,
|
||||
"attributes {first} and {second} share the same label"
|
||||
)
|
||||
}
|
||||
Self::DuplicateSemantic { first, second } =>
|
||||
{
|
||||
write!(
|
||||
formatter,
|
||||
"attributes {first} and {second} share the same semantic role"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for LayoutError {}
|
||||
|
||||
// Primitive attributes
|
||||
|
||||
impl Attribute for u32
|
||||
{
|
||||
fn average(attributes: &[Self]) -> Self
|
||||
{
|
||||
if attributes.is_empty()
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
(attributes.iter().map(|value| *value as u64).sum::<u64>() / attributes.len() as u64) as u32
|
||||
}
|
||||
}
|
||||
|
||||
impl Attribute for i32
|
||||
{
|
||||
fn average(attributes: &[Self]) -> Self
|
||||
{
|
||||
if attributes.is_empty()
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
(attributes.iter().map(|value| *value as i64).sum::<i64>() / attributes.len() as i64) as i32
|
||||
}
|
||||
}
|
||||
|
||||
impl Attribute for f32
|
||||
{
|
||||
fn average(attributes: &[Self]) -> Self
|
||||
{
|
||||
if attributes.is_empty()
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
attributes.iter().sum::<f32>() / attributes.len() as f32
|
||||
}
|
||||
}
|
||||
|
||||
macro_rules! impl_array_attribute {
|
||||
($($count:literal),* $(,)?) => {
|
||||
$(
|
||||
impl<T: Attribute> Attribute for [T; $count]
|
||||
{
|
||||
fn average(attributes: &[Self]) -> Self
|
||||
{
|
||||
if attributes.is_empty()
|
||||
{
|
||||
return Self::default();
|
||||
}
|
||||
|
||||
::core::array::from_fn(|index| {
|
||||
T::average(
|
||||
&attributes
|
||||
.iter()
|
||||
.map(|value| value[index])
|
||||
.collect::<Vec<_>>(),
|
||||
)
|
||||
})
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
|
||||
impl_array_attribute!(
|
||||
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26,
|
||||
27, 28, 29, 30, 31, 32,
|
||||
);
|
||||
@@ -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()
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user