Skip to main content

meshoptimizer_rs/
input.rs

1use crate::Error;
2use core::ops::{BitAnd, BitAndAssign, BitOr, BitOrAssign};
3
4#[derive(Debug)]
5enum MutableStorage<'a> {
6    Packed(&'a mut [[f32; 3]]),
7    Floats(&'a mut [f32]),
8    Bytes(&'a mut [u8], ByteOrder),
9}
10/// Checked mutable positions for destructive update simplification.
11#[derive(Debug)]
12pub struct PositionsMut<'a> {
13    storage: MutableStorage<'a>,
14    count: usize,
15    stride: usize,
16    offset: usize,
17}
18impl<'a> PositionsMut<'a> {
19    /// Borrow tightly packed positions.
20    pub fn from_packed(data: &'a mut [[f32; 3]]) -> Self {
21        let count = data.len();
22        Self {
23            storage: MutableStorage::Packed(data),
24            count,
25            stride: 3,
26            offset: 0,
27        }
28    }
29    /// Borrow interleaved floats with a stride and offset in float components.
30    ///
31    /// # Errors
32    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
33    /// `SizeOverflow` if view size arithmetic overflows.
34    pub fn from_interleaved(
35        data: &'a mut [f32],
36        count: usize,
37        stride: usize,
38        offset: usize,
39    ) -> Result<Self, Error> {
40        layout(data.len(), count, 3, stride, offset)?;
41        Ok(Self {
42            storage: MutableStorage::Floats(data),
43            count,
44            stride,
45            offset,
46        })
47    }
48    /// Borrow initialized byte positions with explicit byte order and byte addresses.
49    ///
50    /// # Errors
51    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
52    /// `SizeOverflow` if view size arithmetic overflows.
53    pub fn from_bytes(
54        data: &'a mut [u8],
55        count: usize,
56        stride: usize,
57        offset: usize,
58        order: ByteOrder,
59    ) -> Result<Self, Error> {
60        View::bytes(data, count, 3, stride, offset, order)?;
61        Ok(Self {
62            storage: MutableStorage::Bytes(data, order),
63            count,
64            stride,
65            offset,
66        })
67    }
68    /// Number of positions.
69    pub const fn len(&self) -> usize {
70        self.count
71    }
72    /// Whether the view is empty.
73    pub const fn is_empty(&self) -> bool {
74        self.count == 0
75    }
76    /// Borrow the same positions read-only.
77    #[inline]
78    pub fn as_view(&self) -> Positions<'_> {
79        match &self.storage {
80            MutableStorage::Packed(p) => Positions::from_packed(p),
81            MutableStorage::Floats(p) => {
82                Positions::from_interleaved(p, self.count, self.stride, self.offset)
83                    .expect("validated layout")
84            }
85            MutableStorage::Bytes(p, o) => {
86                Positions::from_bytes(p, self.count, self.stride, self.offset, *o)
87                    .expect("validated layout")
88            }
89        }
90    }
91    pub(crate) fn set(&mut self, i: usize, value: [f32; 3]) {
92        match &mut self.storage {
93            MutableStorage::Packed(p) => p[i] = value,
94            MutableStorage::Floats(p) => {
95                let start = self.offset + i * self.stride;
96                p[start..start + 3].copy_from_slice(&value);
97            }
98            MutableStorage::Bytes(p, o) => {
99                let start = self.offset + i * self.stride;
100                for (k, v) in value.into_iter().enumerate() {
101                    let b = match o {
102                        ByteOrder::LittleEndian => v.to_bits().to_le_bytes(),
103                        ByteOrder::BigEndian => v.to_bits().to_be_bytes(),
104                    };
105                    p[start + k * 4..start + k * 4 + 4].copy_from_slice(&b);
106                }
107            }
108        }
109    }
110}
111/// Checked mutable attribute components for destructive update simplification.
112#[derive(Debug)]
113pub struct AttributesMut<'a> {
114    storage: MutableStorage<'a>,
115    count: usize,
116    width: usize,
117    stride: usize,
118    offset: usize,
119}
120impl<'a> AttributesMut<'a> {
121    /// Borrow up to 32 components per interleaved float record.
122    ///
123    /// # Errors
124    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
125    /// `SizeOverflow` if view size arithmetic overflows.
126    pub fn from_interleaved(
127        data: &'a mut [f32],
128        count: usize,
129        width: usize,
130        stride: usize,
131        offset: usize,
132    ) -> Result<Self, Error> {
133        Attributes::from_interleaved(data, count, width, stride, offset)?;
134        Ok(Self {
135            storage: MutableStorage::Floats(data),
136            count,
137            width,
138            stride,
139            offset,
140        })
141    }
142    /// Borrow initialized byte attributes with explicit byte order.
143    ///
144    /// # Errors
145    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
146    /// `SizeOverflow` if view size arithmetic overflows.
147    pub fn from_bytes(
148        data: &'a mut [u8],
149        count: usize,
150        width: usize,
151        stride: usize,
152        offset: usize,
153        order: ByteOrder,
154    ) -> Result<Self, Error> {
155        Attributes::from_bytes(data, count, width, stride, offset, order)?;
156        Ok(Self {
157            storage: MutableStorage::Bytes(data, order),
158            count,
159            width,
160            stride,
161            offset,
162        })
163    }
164    /// Number of attribute records.
165    pub const fn len(&self) -> usize {
166        self.count
167    }
168    /// Whether the view is empty.
169    pub const fn is_empty(&self) -> bool {
170        self.count == 0
171    }
172    /// Number of components per record.
173    pub const fn components(&self) -> usize {
174        self.width
175    }
176    /// Borrow the same attributes read-only.
177    #[inline]
178    pub fn as_view(&self) -> Attributes<'_> {
179        match &self.storage {
180            MutableStorage::Floats(p) => {
181                Attributes::from_interleaved(p, self.count, self.width, self.stride, self.offset)
182                    .expect("validated layout")
183            }
184            MutableStorage::Bytes(p, o) => {
185                Attributes::from_bytes(p, self.count, self.width, self.stride, self.offset, *o)
186                    .expect("validated layout")
187            }
188            MutableStorage::Packed(_) => unreachable!("attributes are interleaved"),
189        }
190    }
191    pub(crate) fn set(&mut self, i: usize, k: usize, value: f32) {
192        match &mut self.storage {
193            MutableStorage::Floats(p) => p[self.offset + i * self.stride + k] = value,
194            MutableStorage::Bytes(p, o) => {
195                let start = self.offset + i * self.stride + k * 4;
196                let b = match o {
197                    ByteOrder::LittleEndian => value.to_bits().to_le_bytes(),
198                    ByteOrder::BigEndian => value.to_bits().to_be_bytes(),
199                };
200                p[start..start + 4].copy_from_slice(&b);
201            }
202            MutableStorage::Packed(_) => unreachable!("attributes are interleaved"),
203        }
204    }
205}
206
207/// Explicit byte order of floating-point components in byte-backed views.
208#[derive(Clone, Copy, Debug, PartialEq, Eq)]
209pub enum ByteOrder {
210    /// Least significant byte first.
211    LittleEndian,
212    /// Most significant byte first.
213    BigEndian,
214}
215
216/// Independent upstream simplification vertex flags; unknown bits are rejected.
217#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
218pub struct VertexFlags(u8);
219
220impl VertexFlags {
221    /// No vertex preferences or restrictions.
222    pub const EMPTY: Self = Self(0);
223    /// Prevent removal of this vertex in simplification.
224    pub const LOCK: Self = Self(1);
225    /// Protect an attribute discontinuity in permissive simplification.
226    pub const PROTECT: Self = Self(2);
227    /// Prefer this vertex; this is not a preservation guarantee.
228    pub const PRIORITY: Self = Self(4);
229
230    /// Construct a flag combination, rejecting all unknown bits.
231    ///
232    /// # Errors
233    /// `UnknownFlags` if any flag bit is unsupported.
234    pub const fn from_bits(bits: u8) -> Result<Self, Error> {
235        if bits & !7 != 0 {
236            Err(Error::UnknownFlags)
237        } else {
238            Ok(Self(bits))
239        }
240    }
241    /// Return the upstream bit representation.
242    pub const fn bits(self) -> u8 {
243        self.0
244    }
245    /// Test whether every bit in `other` is set.
246    pub const fn contains(self, other: Self) -> bool {
247        self.0 & other.0 == other.0
248    }
249}
250
251impl BitOr for VertexFlags {
252    type Output = Self;
253    fn bitor(self, rhs: Self) -> Self {
254        Self(self.0 | rhs.0)
255    }
256}
257impl BitAnd for VertexFlags {
258    type Output = Self;
259    fn bitand(self, rhs: Self) -> Self {
260        Self(self.0 & rhs.0)
261    }
262}
263impl BitOrAssign for VertexFlags {
264    fn bitor_assign(&mut self, rhs: Self) {
265        self.0 |= rhs.0;
266    }
267}
268impl BitAndAssign for VertexFlags {
269    fn bitand_assign(&mut self, rhs: Self) {
270        self.0 &= rhs.0;
271    }
272}
273
274/// Validate that optional vertex flags have exactly one entry per vertex.
275///
276/// Function-specific flag restrictions belong to the consuming operation;
277/// the sloppy simplifier must not treat `PROTECT` or `PRIORITY` as locks.
278///
279/// # Errors
280/// `InvalidLayout` if the supplied flag count differs from the vertex count.
281pub fn validate_vertex_flags(flags: Option<&[VertexFlags]>, count: usize) -> Result<(), Error> {
282    if flags.is_some_and(|f| f.len() != count) {
283        Err(Error::InvalidLayout)
284    } else {
285        Ok(())
286    }
287}
288
289#[derive(Clone, Copy, Debug)]
290enum Storage<'a> {
291    Floats(&'a [f32]),
292    Bytes(&'a [u8], ByteOrder),
293}
294
295#[derive(Clone, Copy, Debug)]
296struct View<'a> {
297    storage: Storage<'a>,
298    count: usize,
299    width: usize,
300    stride: usize,
301    offset: usize,
302}
303
304#[inline(always)]
305fn position_bytes<const BIG_ENDIAN: bool>(b: &[u8; 12]) -> [f32; 3] {
306    [
307        [b[0], b[1], b[2], b[3]],
308        [b[4], b[5], b[6], b[7]],
309        [b[8], b[9], b[10], b[11]],
310    ]
311    .map(|word| {
312        f32::from_bits(if BIG_ENDIAN {
313            u32::from_be_bytes(word)
314        } else {
315            u32::from_le_bytes(word)
316        })
317    })
318}
319
320fn layout(
321    len: usize,
322    count: usize,
323    width: usize,
324    stride: usize,
325    offset: usize,
326) -> Result<(), Error> {
327    if stride < width || stride > 64 {
328        return Err(Error::InvalidLayout);
329    }
330    let end = if count == 0 {
331        offset
332    } else {
333        (count - 1)
334            .checked_mul(stride)
335            .and_then(|n| n.checked_add(offset))
336            .and_then(|n| n.checked_add(width))
337            .ok_or(Error::SizeOverflow)?
338    };
339    if end > len {
340        return Err(Error::InvalidLayout);
341    }
342    Ok(())
343}
344
345impl<'a> View<'a> {
346    fn floats(
347        data: &'a [f32],
348        count: usize,
349        width: usize,
350        stride: usize,
351        offset: usize,
352    ) -> Result<Self, Error> {
353        layout(data.len(), count, width, stride, offset)?;
354        Ok(Self {
355            storage: Storage::Floats(data),
356            count,
357            width,
358            stride,
359            offset,
360        })
361    }
362    fn bytes(
363        data: &'a [u8],
364        count: usize,
365        width: usize,
366        stride: usize,
367        offset: usize,
368        order: ByteOrder,
369    ) -> Result<Self, Error> {
370        if !stride.is_multiple_of(4) {
371            return Err(Error::InvalidLayout);
372        }
373        let width_bytes = width.checked_mul(4).ok_or(Error::SizeOverflow)?;
374        // Check byte addresses directly: byte offsets need not be aligned.
375        if stride < width_bytes || stride > 256 {
376            return Err(Error::InvalidLayout);
377        }
378        let end = if count == 0 {
379            offset
380        } else {
381            (count - 1)
382                .checked_mul(stride)
383                .and_then(|n| n.checked_add(offset))
384                .and_then(|n| n.checked_add(width_bytes))
385                .ok_or(Error::SizeOverflow)?
386        };
387        if end > data.len() {
388            return Err(Error::InvalidLayout);
389        }
390        Ok(Self {
391            storage: Storage::Bytes(data, order),
392            count,
393            width,
394            stride,
395            offset,
396        })
397    }
398    #[inline(always)]
399    fn position(self, vertex: usize) -> Option<[f32; 3]> {
400        if vertex >= self.count {
401            return None;
402        }
403        // Position views always have width three. Check the whole XYZ record
404        // once, preserving support for unaligned byte offsets and either order.
405        match self.storage {
406            Storage::Floats(data) => {
407                let start = self.offset + vertex * self.stride;
408                Some(*data.get(start..)?.first_chunk::<3>()?)
409            }
410            Storage::Bytes(data, order) => {
411                let start = self.offset + vertex * self.stride;
412                let b = data.get(start..)?.first_chunk::<12>()?;
413                Some(match order {
414                    ByteOrder::LittleEndian => position_bytes::<false>(b),
415                    ByteOrder::BigEndian => position_bytes::<true>(b),
416                })
417            }
418        }
419    }
420    #[inline(always)]
421    fn get(self, vertex: usize, component: usize) -> Option<f32> {
422        if vertex >= self.count || component >= self.width {
423            return None;
424        }
425        match self.storage {
426            Storage::Floats(data) => data
427                .get(self.offset + vertex * self.stride + component)
428                .copied(),
429            Storage::Bytes(data, order) => {
430                let p = self.offset + vertex * self.stride + component * 4;
431                let b = [
432                    *data.get(p)?,
433                    *data.get(p + 1)?,
434                    *data.get(p + 2)?,
435                    *data.get(p + 3)?,
436                ];
437                Some(f32::from_bits(match order {
438                    ByteOrder::LittleEndian => u32::from_le_bytes(b),
439                    ByteOrder::BigEndian => u32::from_be_bytes(b),
440                }))
441            }
442        }
443    }
444}
445
446#[derive(Clone, Copy, Debug)]
447enum PositionStorage<'a> {
448    Packed(&'a [[f32; 3]]),
449    View(View<'a>),
450}
451
452type PackedPositionSource<'a> = (&'a [[f32; 3]], Option<&'a [u32]>);
453
454/// Checked borrowed XYZ view, preserving all supplied vertices, including unused ones.
455///
456/// Layout constructors do not scan values. Geometric operations reject
457/// non-finite components before changing destinations.
458#[derive(Clone, Copy, Debug)]
459pub struct Positions<'a>(PositionStorage<'a>, Option<&'a [u32]>);
460
461/// Monomorphized reads for the 0.5 generators: packed input dispatches once.
462pub(crate) trait PositionReader: Copy {
463    fn len(self) -> usize;
464    fn read(self, index: usize) -> [f32; 3];
465    #[cfg(feature = "experimental")]
466    fn for_each_counted(
467        self,
468        work: &mut crate::workspace::Work,
469        visit: impl FnMut([f32; 3]) -> Result<(), Error>,
470    ) -> Result<(), Error>;
471}
472
473impl PositionReader for &[[f32; 3]] {
474    #[inline(always)]
475    fn len(self) -> usize {
476        <[[f32; 3]]>::len(self)
477    }
478    #[inline(always)]
479    fn read(self, index: usize) -> [f32; 3] {
480        self[index]
481    }
482    #[cfg(feature = "experimental")]
483    fn for_each_counted(
484        self,
485        work: &mut crate::workspace::Work,
486        visit: impl FnMut([f32; 3]) -> Result<(), Error>,
487    ) -> Result<(), Error> {
488        work.scan(self.iter().copied(), visit)
489    }
490}
491
492impl PositionReader for Positions<'_> {
493    #[inline(always)]
494    fn len(self) -> usize {
495        Positions::len(self)
496    }
497    #[inline(always)]
498    fn read(self, index: usize) -> [f32; 3] {
499        self.get(index).expect("validated index")
500    }
501    #[cfg(feature = "experimental")]
502    fn for_each_counted(
503        self,
504        work: &mut crate::workspace::Work,
505        visit: impl FnMut([f32; 3]) -> Result<(), Error>,
506    ) -> Result<(), Error> {
507        Positions::for_each_counted(self, work, visit)
508    }
509}
510
511impl<'a> Positions<'a> {
512    pub(crate) fn packed(self) -> Option<&'a [[f32; 3]]> {
513        match self.0 {
514            PositionStorage::Packed(values) => Some(values),
515            PositionStorage::View(_) => None,
516        }
517    }
518    /// Borrow tightly packed XYZ components without allocation.
519    pub const fn from_packed(data: &'a [[f32; 3]]) -> Self {
520        Self(PositionStorage::Packed(data), None)
521    }
522    /// Borrow interleaved floats; `stride` and `offset` are in f32 elements.
523    /// The stride must be between 3 and 64 elements.
524    ///
525    /// # Errors
526    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
527    /// `SizeOverflow` if view size arithmetic overflows.
528    pub fn from_interleaved(
529        data: &'a [f32],
530        count: usize,
531        stride: usize,
532        offset: usize,
533    ) -> Result<Self, Error> {
534        let view = View::floats(data, count, 3, stride, offset)?;
535        let storage = if stride == 3 {
536            let components = count.checked_mul(3).ok_or(Error::SizeOverflow)?;
537            PositionStorage::Packed(data[offset..][..components].as_chunks::<3>().0)
538        } else {
539            PositionStorage::View(view)
540        };
541        Ok(Self(storage, None))
542    }
543    /// Borrow initialized bytes; stride and offset are in bytes, with an explicit byte order.
544    /// Stride must be a multiple of four between 12 and 256 bytes.
545    ///
546    /// # Errors
547    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
548    /// `SizeOverflow` if view size arithmetic overflows.
549    pub fn from_bytes(
550        data: &'a [u8],
551        count: usize,
552        stride: usize,
553        offset: usize,
554        order: ByteOrder,
555    ) -> Result<Self, Error> {
556        Ok(Self(
557            PositionStorage::View(View::bytes(data, count, 3, stride, offset, order)?),
558            None,
559        ))
560    }
561    /// Number of supplied vertices.
562    pub const fn len(self) -> usize {
563        if let Some(remap) = self.1 {
564            return remap.len();
565        }
566        match self.0 {
567            PositionStorage::Packed(p) => p.len(),
568            PositionStorage::View(v) => v.count,
569        }
570    }
571    /// Whether there are no supplied vertices.
572    pub const fn is_empty(self) -> bool {
573        self.len() == 0
574    }
575    /// Read XYZ for a vertex, or `None` if its index is outside this view.
576    #[inline(always)]
577    pub fn get(self, index: usize) -> Option<[f32; 3]> {
578        let index = if let Some(remap) = self.1 {
579            *remap.get(index)? as usize
580        } else {
581            index
582        };
583        match self.0 {
584            PositionStorage::Packed(p) => p.get(index).copied(),
585            PositionStorage::View(v) => v.position(index),
586        }
587    }
588    pub(crate) fn packed_values(self) -> Option<&'a [[f32; 3]]> {
589        if self.1.is_none() {
590            if let PositionStorage::Packed(values) = self.0 {
591                return Some(values);
592            }
593        }
594        None
595    }
596    /// Fixed-stride cooker records for scale's independent validation/reduction.
597    /// Keep every other layout on its existing reader, including mapped views.
598    pub(crate) fn scale_records(self) -> Option<impl Iterator<Item = [f32; 3]> + Clone + 'a> {
599        if self.1.is_some() {
600            return None;
601        }
602        let PositionStorage::View(View {
603            storage: Storage::Bytes(data, ByteOrder::LittleEndian),
604            count,
605            stride: 64,
606            offset,
607            ..
608        }) = self.0
609        else {
610            return None;
611        };
612        Some(data[offset..].chunks(64).take(count).map(|record| {
613            position_bytes::<false>(record.first_chunk().expect("validated position record"))
614        }))
615    }
616    /// Fully padded cooker records for a bounds-check-free inner iterator.
617    /// Keep the original reader for short records to preserve validation order.
618    pub(crate) fn scale_full_records(
619        self,
620    ) -> Option<impl ExactSizeIterator<Item = [f32; 3]> + Clone + 'a> {
621        if self.1.is_some() {
622            return None;
623        }
624        let PositionStorage::View(View {
625            storage: Storage::Bytes(data, ByteOrder::LittleEndian),
626            count,
627            stride: 64,
628            offset,
629            ..
630        }) = self.0
631        else {
632            return None;
633        };
634        // Full records prove all XYZ reads once. A legal final record without
635        // trailing padding keeps the general reader, avoiding an iterator state
636        // transition in the hot bounds-reduction loop.
637        let records = data[offset..]
638            .get(..count.checked_mul(64)?)?
639            .as_chunks::<64>()
640            .0;
641        Some(
642            records
643                .iter()
644                .map(|record| position_bytes::<false>(record.first_chunk().unwrap())),
645        )
646    }
647    /// Original packed coordinates and an optional sparse source mapping.
648    pub(crate) fn packed_source(self) -> Option<PackedPositionSource<'a>> {
649        match self.0 {
650            PositionStorage::Packed(values) => Some((values, self.1)),
651            PositionStorage::View(_) => None,
652        }
653    }
654    pub(crate) fn mapped(self, remap: &'a [u32]) -> Self {
655        debug_assert!(self.1.is_none());
656        Self(self.0, Some(remap))
657    }
658    /// Dispatch the storage layout once for sequential scans.
659    #[inline(always)]
660    pub(crate) fn for_each(
661        self,
662        mut visit: impl FnMut([f32; 3]) -> Result<(), Error>,
663    ) -> Result<(), Error> {
664        if self.1.is_some() {
665            for i in 0..self.len() {
666                visit(self.at(i)?)?;
667            }
668            return Ok(());
669        }
670        match self.0 {
671            PositionStorage::Packed(values) => {
672                for &value in values {
673                    visit(value)?;
674                }
675            }
676            PositionStorage::View(v) => match v.storage {
677                Storage::Floats(data) => {
678                    for record in data[v.offset..].chunks(v.stride).take(v.count) {
679                        visit(
680                            *record
681                                .first_chunk::<3>()
682                                .expect("validated position record"),
683                        )?;
684                    }
685                }
686                Storage::Bytes(data, ByteOrder::LittleEndian) => {
687                    for record in data[v.offset..].chunks(v.stride).take(v.count) {
688                        visit(position_bytes::<false>(
689                            record.first_chunk().expect("validated position record"),
690                        ))?;
691                    }
692                }
693                Storage::Bytes(data, ByteOrder::BigEndian) => {
694                    for record in data[v.offset..].chunks(v.stride).take(v.count) {
695                        visit(position_bytes::<true>(
696                            record.first_chunk().expect("validated position record"),
697                        ))?;
698                    }
699                }
700            },
701        }
702        Ok(())
703    }
704    #[inline(always)]
705    pub(crate) fn for_each_counted(
706        self,
707        work: &mut crate::workspace::Work,
708        mut visit: impl FnMut([f32; 3]) -> Result<(), Error>,
709    ) -> Result<(), Error> {
710        if self.1.is_some() {
711            return work.scan(0..self.len(), |i| visit(self.at(i)?));
712        }
713        match self.0 {
714            PositionStorage::Packed(values) => work.scan(values.iter().copied(), visit),
715            // Constructors validate every record boundary. Dispatch layout and
716            // byte order once, while Work::scan retains exact failure-prefix
717            // accounting and the original callback/coordinate order.
718            PositionStorage::View(v) => match v.storage {
719                Storage::Floats(data) => {
720                    work.scan(data[v.offset..].chunks(v.stride).take(v.count), |record| {
721                        visit(
722                            *record
723                                .first_chunk::<3>()
724                                .expect("validated position record"),
725                        )
726                    })
727                }
728                Storage::Bytes(data, ByteOrder::LittleEndian) => {
729                    work.scan(data[v.offset..].chunks(v.stride).take(v.count), |record| {
730                        visit(position_bytes::<false>(
731                            record.first_chunk().expect("validated position record"),
732                        ))
733                    })
734                }
735                Storage::Bytes(data, ByteOrder::BigEndian) => {
736                    work.scan(data[v.offset..].chunks(v.stride).take(v.count), |record| {
737                        visit(position_bytes::<true>(
738                            record.first_chunk().expect("validated position record"),
739                        ))
740                    })
741                }
742            },
743        }
744    }
745    /// Dispatch indexed triangle reads once, preserving checked reads and the
746    /// exact per-triangle work/failure prefix through Work::scan.
747    #[inline(always)]
748    pub(crate) fn for_each_triangle_counted(
749        self,
750        triangles: &[[u32; 3]],
751        work: &mut crate::workspace::Work,
752        visit: impl FnMut([[f32; 3]; 3]) -> Result<(), Error>,
753    ) -> Result<(), Error> {
754        #[inline(always)]
755        fn scan(
756            triangles: &[[u32; 3]],
757            work: &mut crate::workspace::Work,
758            read: impl Fn(usize) -> Result<[f32; 3], Error>,
759            mut visit: impl FnMut([[f32; 3]; 3]) -> Result<(), Error>,
760        ) -> Result<(), Error> {
761            work.scan(triangles.iter(), |tri| {
762                visit([
763                    read(tri[0] as usize)?,
764                    read(tri[1] as usize)?,
765                    read(tri[2] as usize)?,
766                ])
767            })
768        }
769        // Full 64-byte records let a single checked record lookup prove all
770        // twelve XYZ byte reads. Keep the general reader for mapped views or
771        // a legal final record whose trailing padding is absent.
772        if self.1.is_none() {
773            if let PositionStorage::View(View {
774                storage: Storage::Bytes(data, order),
775                count,
776                stride: 64,
777                offset,
778                ..
779            }) = self.0
780            {
781                if let Some(records) = count
782                    .checked_mul(64)
783                    .and_then(|size| data[offset..].get(..size))
784                    .map(|data| data.as_chunks::<64>().0)
785                {
786                    return match order {
787                        ByteOrder::LittleEndian => scan(
788                            triangles,
789                            work,
790                            |i| {
791                                records
792                                    .get(i)
793                                    .map(|record| {
794                                        position_bytes::<false>(record.first_chunk().unwrap())
795                                    })
796                                    .ok_or(Error::IndexOutOfBounds)
797                            },
798                            visit,
799                        ),
800                        ByteOrder::BigEndian => scan(
801                            triangles,
802                            work,
803                            |i| {
804                                records
805                                    .get(i)
806                                    .map(|record| {
807                                        position_bytes::<true>(record.first_chunk().unwrap())
808                                    })
809                                    .ok_or(Error::IndexOutOfBounds)
810                            },
811                            visit,
812                        ),
813                    };
814                }
815            }
816        }
817        if self.1.is_some() {
818            return scan(triangles, work, |i| self.at(i), visit);
819        }
820        match self.0 {
821            PositionStorage::Packed(values) => scan(
822                triangles,
823                work,
824                |i| values.get(i).copied().ok_or(Error::IndexOutOfBounds),
825                visit,
826            ),
827            PositionStorage::View(v) => {
828                // Layout constructors have checked every XYZ record boundary.
829                // Keep the view count check even if the backing slice is longer.
830                match v.storage {
831                    Storage::Floats(data) => scan(
832                        triangles,
833                        work,
834                        |i| {
835                            if i >= v.count {
836                                return Err(Error::IndexOutOfBounds);
837                            }
838                            let start = v.offset + i * v.stride;
839                            Ok(*data[start..]
840                                .first_chunk::<3>()
841                                .expect("validated position record"))
842                        },
843                        visit,
844                    ),
845                    Storage::Bytes(data, ByteOrder::LittleEndian) => scan(
846                        triangles,
847                        work,
848                        |i| {
849                            if i >= v.count {
850                                return Err(Error::IndexOutOfBounds);
851                            }
852                            let start = v.offset + i * v.stride;
853                            Ok(position_bytes::<false>(
854                                data[start..]
855                                    .first_chunk()
856                                    .expect("validated position record"),
857                            ))
858                        },
859                        visit,
860                    ),
861                    Storage::Bytes(data, ByteOrder::BigEndian) => scan(
862                        triangles,
863                        work,
864                        |i| {
865                            if i >= v.count {
866                                return Err(Error::IndexOutOfBounds);
867                            }
868                            let start = v.offset + i * v.stride;
869                            Ok(position_bytes::<true>(
870                                data[start..]
871                                    .first_chunk()
872                                    .expect("validated position record"),
873                            ))
874                        },
875                        visit,
876                    ),
877                }
878            }
879        }
880    }
881    #[inline(always)]
882    pub(crate) fn at(self, index: usize) -> Result<[f32; 3], Error> {
883        self.get(index).ok_or(Error::IndexOutOfBounds)
884    }
885}
886
887/// Checked borrowed attribute view with at most 32 components per vertex.
888#[derive(Clone, Copy, Debug)]
889pub struct Attributes<'a>(View<'a>, Option<&'a [u32]>);
890
891impl<'a> Attributes<'a> {
892    // Character preparation owns and meters this packed buffer. Public attribute
893    // constructors retain their upstream-compatible width and stride limits.
894    pub(crate) fn from_character_packed(
895        data: &'a [f32],
896        count: usize,
897        components: usize,
898    ) -> Result<Self, Error> {
899        if count.checked_mul(components).ok_or(Error::SizeOverflow)? != data.len() {
900            return Err(Error::InvalidLayout);
901        }
902        Ok(Self(
903            View {
904                storage: Storage::Floats(data),
905                count,
906                width: components,
907                stride: components,
908                offset: 0,
909            },
910            None,
911        ))
912    }
913    /// Borrow interleaved attributes; stride and offset are in f32 elements.
914    /// Zero components are supported; stride is at most 64 elements.
915    ///
916    /// # Errors
917    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
918    /// `SizeOverflow` if view size arithmetic overflows.
919    pub fn from_interleaved(
920        data: &'a [f32],
921        count: usize,
922        components: usize,
923        stride: usize,
924        offset: usize,
925    ) -> Result<Self, Error> {
926        if components > 32 {
927            return Err(Error::InvalidLayout);
928        }
929        Ok(Self(
930            View::floats(data, count, components, stride, offset)?,
931            None,
932        ))
933    }
934    /// Borrow initialized attribute bytes with an explicit byte order.
935    /// Byte stride is a multiple of four and at most 256 bytes.
936    ///
937    /// # Errors
938    /// `InvalidLayout` for an unsupported width, stride, offset or buffer length;
939    /// `SizeOverflow` if view size arithmetic overflows.
940    pub fn from_bytes(
941        data: &'a [u8],
942        count: usize,
943        components: usize,
944        stride: usize,
945        offset: usize,
946        order: ByteOrder,
947    ) -> Result<Self, Error> {
948        if components > 32 {
949            return Err(Error::InvalidLayout);
950        }
951        Ok(Self(
952            View::bytes(data, count, components, stride, offset, order)?,
953            None,
954        ))
955    }
956    /// Number of supplied vertices.
957    pub const fn len(self) -> usize {
958        if let Some(remap) = self.1 {
959            remap.len()
960        } else {
961            self.0.count
962        }
963    }
964    /// Whether this view has no vertices.
965    pub const fn is_empty(self) -> bool {
966        self.len() == 0
967    }
968    /// Components per vertex.
969    pub const fn components(self) -> usize {
970        self.0.width
971    }
972    /// Read a component, or `None` for an out-of-range vertex or component.
973    #[inline(always)]
974    pub fn get(self, vertex: usize, component: usize) -> Option<f32> {
975        let vertex = if let Some(remap) = self.1 {
976            *remap.get(vertex)? as usize
977        } else {
978            vertex
979        };
980        self.0.get(vertex, component)
981    }
982    #[inline(always)]
983    pub(crate) fn float_record(self, vertex: usize) -> Option<&'a [f32]> {
984        let vertex = if let Some(remap) = self.1 {
985            *remap.get(vertex)? as usize
986        } else {
987            vertex
988        };
989        if vertex >= self.0.count {
990            return None;
991        }
992        let Storage::Floats(values) = self.0.storage else {
993            return None;
994        };
995        let start = self.0.offset + vertex * self.0.stride;
996        values.get(start..start + self.0.width)
997    }
998    /// All components of an unmapped float view whose stride equals its
999    /// width: vertex `i` is `[i * width..(i + 1) * width]`, the same slice
1000    /// `float_record(i)` returns.
1001    pub(crate) fn contiguous_floats(self) -> Option<&'a [f32]> {
1002        if self.1.is_some() || self.0.stride != self.0.width {
1003            return None;
1004        }
1005        let Storage::Floats(values) = self.0.storage else {
1006            return None;
1007        };
1008        values
1009            .get(self.0.offset..)?
1010            .get(..self.0.count.checked_mul(self.0.width)?)
1011    }
1012    pub(crate) fn mapped(self, remap: &'a [u32]) -> Self {
1013        debug_assert!(self.1.is_none());
1014        Self(self.0, Some(remap))
1015    }
1016}
1017
1018#[cfg(test)]
1019mod triangle_tests {
1020    use super::*;
1021    use crate::{Limits, Workspace};
1022    use alloc::{vec, vec::Vec};
1023
1024    #[test]
1025    fn specialized_triangle_reads_keep_bits_errors_and_work_prefixes() {
1026        let points = [[-0.0f32, 1.0, 2.0], [3.0, 4.0, 5.0], [6.0, 7.0, 8.0]];
1027        let mut floats = vec![99.0; 12];
1028        let mut little = vec![99; 49];
1029        let mut big = little.clone();
1030        for (i, point) in points.iter().enumerate() {
1031            floats[i * 4 + 1..i * 4 + 4].copy_from_slice(point);
1032            for (j, value) in point.iter().enumerate() {
1033                let start = 1 + i * 16 + j * 4;
1034                little[start..start + 4].copy_from_slice(&value.to_le_bytes());
1035                big[start..start + 4].copy_from_slice(&value.to_be_bytes());
1036            }
1037        }
1038        // Include backing storage beyond count and a last record without
1039        // padding: neither may change the checked view's index domain.
1040        let mut little64 = vec![99; 1 + 4 * 64];
1041        let mut big64 = little64.clone();
1042        for (i, point) in points.iter().enumerate() {
1043            for (j, value) in point.iter().enumerate() {
1044                let start = 1 + i * 64 + j * 4;
1045                little64[start..start + 4].copy_from_slice(&value.to_le_bytes());
1046                big64[start..start + 4].copy_from_slice(&value.to_be_bytes());
1047            }
1048        }
1049        let views = [
1050            Positions::from_packed(&points),
1051            Positions::from_interleaved(&floats, 3, 4, 1).unwrap(),
1052            Positions::from_bytes(&little, 3, 16, 1, ByteOrder::LittleEndian).unwrap(),
1053            Positions::from_bytes(&big, 3, 16, 1, ByteOrder::BigEndian).unwrap(),
1054            Positions::from_bytes(&little64, 3, 64, 1, ByteOrder::LittleEndian).unwrap(),
1055            Positions::from_bytes(&big64, 3, 64, 1, ByteOrder::BigEndian).unwrap(),
1056            Positions::from_bytes(&little64[..141], 3, 64, 1, ByteOrder::LittleEndian).unwrap(),
1057            Positions::from_bytes(&big64[..141], 3, 64, 1, ByteOrder::BigEndian).unwrap(),
1058        ];
1059        let remap = [2, 0, 1];
1060        let triangles = [[0, 1, 2], [2, 1, 0], [0, 3, 1]];
1061        for view in views.into_iter().flat_map(|v| [v, v.mapped(&remap)]) {
1062            for max_work in 0..=4 {
1063                let mut a = Workspace::new(Limits {
1064                    max_work,
1065                    ..Limits::default()
1066                });
1067                let mut b = Workspace::new(Limits {
1068                    max_work,
1069                    ..Limits::default()
1070                });
1071                let mut old = Vec::new();
1072                let mut new = Vec::new();
1073                let mut aw = a.begin();
1074                let expected = aw.scan(triangles.iter(), |t| {
1075                    old.push(
1076                        [
1077                            view.at(t[0] as usize)?,
1078                            view.at(t[1] as usize)?,
1079                            view.at(t[2] as usize)?,
1080                        ]
1081                        .map(|p| p.map(f32::to_bits)),
1082                    );
1083                    Ok(())
1084                });
1085                a.finish(&aw);
1086                let mut bw = b.begin();
1087                let observed = view.for_each_triangle_counted(&triangles, &mut bw, |p| {
1088                    new.push(p.map(|p| p.map(f32::to_bits)));
1089                    Ok(())
1090                });
1091                b.finish(&bw);
1092                assert_eq!((observed, new, b.usage()), (expected, old, a.usage()));
1093            }
1094        }
1095    }
1096}