meshoptimizer_rs/vertex_layout.rs
1//! Typed vertex layouts, an opt-in extension not in C++ meshoptimizer.
2//!
3//! Struct padding cannot safely be borrowed as initialized bytes. These helpers
4//! copy only the selected float field into a zero-filled byte buffer, preserving
5//! the struct's byte stride and field offset. Construction allocates and copies;
6//! the returned existing views borrow that snapshot, not the original vertices.
7
8use alloc::vec::Vec;
9use core::mem::{align_of, size_of};
10
11use crate::{Attributes, ByteOrder, Positions};
12
13/// A construction failure for a typed vertex layout or snapshot.
14///
15/// New variants may be added in a minor release.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17#[non_exhaustive]
18pub enum VertexLayoutError {
19 /// The struct stride is not a multiple of four in the range 4..=256.
20 InvalidStride,
21 /// The struct alignment or field offset is unsuitable for `f32`.
22 MisalignedField,
23 /// The field has zero or more than 32 components, or extends past the record.
24 InvalidFieldSize,
25 /// A position field does not contain exactly three components.
26 InvalidPositionSize,
27 /// The selector returned a field at a different address from the given offset.
28 FieldOffsetMismatch,
29 /// The snapshot length overflowed the platform allocation range.
30 SizeOverflow,
31 /// The snapshot could not be allocated.
32 AllocationFailed,
33}
34
35impl core::fmt::Display for VertexLayoutError {
36 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
37 f.write_str(match self {
38 Self::InvalidStride => "unsupported vertex stride",
39 Self::MisalignedField => "misaligned float field",
40 Self::InvalidFieldSize => "unsupported field size",
41 Self::InvalidPositionSize => "positions require three float components",
42 Self::FieldOffsetMismatch => "field selector does not match offset",
43 Self::SizeOverflow => "vertex snapshot size overflow",
44 Self::AllocationFailed => "vertex snapshot allocation failed",
45 })
46 }
47}
48
49#[cfg(feature = "std")]
50impl std::error::Error for VertexLayoutError {}
51
52/// Checked float-array field layout, not in C++ meshoptimizer.
53///
54/// `V` need not be plain old data: padding and other fields are never read.
55/// Use `#[repr(C)]` for a stable layout. The selector enforces the `f32` element
56/// type and array size at compile time. Its address is checked against `offset`
57/// for every vertex when copying; an empty slice has no field address to check.
58///
59/// ```
60/// use core::mem::{offset_of, size_of};
61/// use meshoptimizer_rs::{VertexFieldSnapshot, VertexLayout};
62///
63/// #[repr(C)]
64/// struct Vertex {
65/// position: [f32; 3],
66/// normal: [f32; 3],
67/// uv: [f32; 2],
68/// }
69/// let vertices = [Vertex {
70/// position: [1.0, 2.0, 3.0], normal: [0.0, 0.0, 1.0], uv: [0.5, 0.5],
71/// }];
72/// let layout = VertexLayout::new(offset_of!(Vertex, position), |v: &Vertex| &v.position)?;
73/// assert_eq!(layout.stride(), size_of::<Vertex>());
74/// let positions = layout.copy_from(&vertices)?;
75/// assert_eq!(positions.positions()?.get(0), Some([1.0, 2.0, 3.0]));
76/// let normals = VertexFieldSnapshot::from_vertices(
77/// &vertices, offset_of!(Vertex, normal), |v| &v.normal,
78/// )?;
79/// assert_eq!(normals.attributes()?.components(), 3);
80/// let uv = VertexFieldSnapshot::from_vertices(&vertices, offset_of!(Vertex, uv), |v| &v.uv)?;
81/// assert_eq!(uv.attributes()?.components(), 2);
82/// # Ok::<(), meshoptimizer_rs::VertexLayoutError>(())
83/// ```
84///
85/// Non-float fields cannot be selected:
86///
87/// ```compile_fail
88/// use meshoptimizer_rs::VertexLayout;
89/// #[repr(C)]
90/// struct Vertex { position: [u32; 3] }
91/// let layout = VertexLayout::new(0, |v: &Vertex| &v.position);
92/// ```
93///
94/// The selector may be any `Fn(&V) -> &[f32; N]`, including a capturing closure;
95/// the layout is `Clone`/`Copy` when the selector is.
96pub struct VertexLayout<V, const N: usize, F> {
97 offset: usize,
98 field: F,
99 marker: core::marker::PhantomData<fn(&V) -> &[f32; N]>,
100}
101
102// Manual impls: derives would needlessly require `V: Clone`/`V: Debug`.
103impl<V, const N: usize, F: Clone> Clone for VertexLayout<V, N, F> {
104 fn clone(&self) -> Self {
105 Self {
106 offset: self.offset,
107 field: self.field.clone(),
108 marker: core::marker::PhantomData,
109 }
110 }
111}
112
113impl<V, const N: usize, F: Copy> Copy for VertexLayout<V, N, F> {}
114
115impl<V, const N: usize, F> core::fmt::Debug for VertexLayout<V, N, F> {
116 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
117 f.debug_struct("VertexLayout")
118 .field("stride", &self.stride())
119 .field("offset", &self.offset)
120 .field("components", &N)
121 .finish()
122 }
123}
124
125impl<V, const N: usize, F> VertexLayout<V, N, F> {
126 /// Byte stride, equal to `size_of::<V>()`.
127 pub const fn stride(&self) -> usize {
128 size_of::<V>()
129 }
130
131 /// Byte offset of the selected field.
132 pub const fn offset(&self) -> usize {
133 self.offset
134 }
135}
136
137impl<V, const N: usize, F: Fn(&V) -> &[f32; N]> VertexLayout<V, N, F> {
138 /// Check a byte offset and typed field selector using `V`'s size/alignment.
139 ///
140 /// # Errors
141 /// Returns `InvalidStride`, `MisalignedField` or `InvalidFieldSize` for an
142 /// unsupported layout. A selector/offset mismatch is checked by `copy_from`.
143 pub fn new(offset: usize, field: F) -> Result<Self, VertexLayoutError> {
144 let stride = size_of::<V>();
145 if stride == 0 || stride > 256 || !stride.is_multiple_of(4) {
146 return Err(VertexLayoutError::InvalidStride);
147 }
148 if align_of::<V>() < align_of::<f32>() || !offset.is_multiple_of(align_of::<f32>()) {
149 return Err(VertexLayoutError::MisalignedField);
150 }
151 if N == 0 || N > 32 || offset.checked_add(N * 4).is_none_or(|end| end > stride) {
152 return Err(VertexLayoutError::InvalidFieldSize);
153 }
154 Ok(Self {
155 offset,
156 field,
157 marker: core::marker::PhantomData,
158 })
159 }
160
161 /// Copy the selected field into an initialized snapshot with the same layout.
162 ///
163 /// Unselected bytes are zero, including padding. Float bit patterns are
164 /// preserved, including non-finite values; geometric operations validate them.
165 /// Allocation is caller-owned and outside `Workspace` limits.
166 ///
167 /// # Errors
168 /// Returns `SizeOverflow` or `AllocationFailed` if the snapshot cannot be
169 /// allocated; `FieldOffsetMismatch` if any selector result differs from the
170 /// declared field address. Selector panics propagate to the caller.
171 pub fn copy_from(&self, vertices: &[V]) -> Result<VertexFieldSnapshot<N>, VertexLayoutError> {
172 let len = vertices
173 .len()
174 .checked_mul(self.stride())
175 .filter(|&len| len <= isize::MAX as usize)
176 .ok_or(VertexLayoutError::SizeOverflow)?;
177 let mut bytes = Vec::new();
178 bytes
179 .try_reserve_exact(len)
180 .map_err(|_| VertexLayoutError::AllocationFailed)?;
181 bytes.resize(len, 0);
182 for (vertex, record) in vertices.iter().zip(bytes.chunks_exact_mut(self.stride())) {
183 let field = (self.field)(vertex);
184 if (field.as_ptr() as usize).checked_sub(vertex as *const V as usize)
185 != Some(self.offset)
186 {
187 return Err(VertexLayoutError::FieldOffsetMismatch);
188 }
189 for (component, value) in field.iter().enumerate() {
190 let start = self.offset + component * 4;
191 record[start..start + 4].copy_from_slice(&value.to_le_bytes());
192 }
193 }
194 Ok(VertexFieldSnapshot {
195 bytes,
196 count: vertices.len(),
197 stride: self.stride(),
198 offset: self.offset,
199 })
200 }
201}
202
203/// Owned field snapshot exposing existing views, not in C++ meshoptimizer.
204///
205/// Stores `vertex_count * size_of::<V>()` bytes. Only the selected field is
206/// copied; remaining bytes are zero. This is not a serialization of the struct.
207#[derive(Debug)]
208pub struct VertexFieldSnapshot<const N: usize> {
209 bytes: Vec<u8>,
210 count: usize,
211 stride: usize,
212 offset: usize,
213}
214
215impl<const N: usize> VertexFieldSnapshot<N> {
216 /// Check and copy a typed field directly from a vertex slice and byte offset.
217 ///
218 /// # Errors
219 /// Returns the layout and snapshot errors described by `VertexLayout::new`
220 /// and `VertexLayout::copy_from`.
221 pub fn from_vertices<V>(
222 vertices: &[V],
223 offset: usize,
224 field: impl Fn(&V) -> &[f32; N],
225 ) -> Result<Self, VertexLayoutError> {
226 VertexLayout::new(offset, field)?.copy_from(vertices)
227 }
228
229 /// Borrow XYZ from this snapshot.
230 ///
231 /// # Errors
232 /// Returns `InvalidPositionSize` unless the selected field has three floats.
233 pub fn positions(&self) -> Result<Positions<'_>, VertexLayoutError> {
234 if N != 3 {
235 return Err(VertexLayoutError::InvalidPositionSize);
236 }
237 // Empty byte views require offset <= buffer length.
238 Positions::from_bytes(
239 &self.bytes,
240 self.count,
241 self.stride,
242 if self.count == 0 { 0 } else { self.offset },
243 ByteOrder::LittleEndian,
244 )
245 .map_err(|_| VertexLayoutError::InvalidFieldSize)
246 }
247
248 /// Borrow the selected float components as attributes.
249 ///
250 /// # Errors
251 /// Returns `InvalidFieldSize` if the underlying view rejects the layout.
252 pub fn attributes(&self) -> Result<Attributes<'_>, VertexLayoutError> {
253 Attributes::from_bytes(
254 &self.bytes,
255 self.count,
256 N,
257 self.stride,
258 if self.count == 0 { 0 } else { self.offset },
259 ByteOrder::LittleEndian,
260 )
261 .map_err(|_| VertexLayoutError::InvalidFieldSize)
262 }
263
264 /// Initialized little-endian bytes, including zero-filled unselected bytes.
265 pub fn as_bytes(&self) -> &[u8] {
266 &self.bytes
267 }
268
269 /// Byte stride of each original vertex.
270 pub const fn stride(&self) -> usize {
271 self.stride
272 }
273
274 /// Byte offset of the selected field in each original vertex.
275 pub const fn offset(&self) -> usize {
276 self.offset
277 }
278}