1use crate::*;
3use alloc::vec::Vec;
4use core::{fmt, mem::size_of};
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq)]
8#[non_exhaustive]
9pub enum ProcessStage {
10 Validate,
12 Sanitize,
14 Weld,
16 Orient,
18 SplitVertices,
20 StitchCracks,
22 FillHoles,
24 Lod,
26 Cache,
28 Overdraw,
30 Fetch,
32 Quality,
34 Meshlets,
36 Clusters,
38 Encode,
40}
41#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43#[non_exhaustive]
44pub struct ProcessError {
45 pub stage: ProcessStage,
47 pub level: Option<usize>,
49 pub error: Error,
51}
52impl fmt::Display for ProcessError {
53 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
54 write!(f, "{:?} level {:?}: {}", self.stage, self.level, self.error)
55 }
56}
57#[cfg(feature = "std")]
58impl std::error::Error for ProcessError {
59 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
60 Some(&self.error)
61 }
62}
63#[derive(Clone, Debug)]
65#[non_exhaustive]
66pub struct ProcessStageReport {
67 pub stage: ProcessStage,
69 pub level: Option<usize>,
71 pub input: [usize; 2],
73 pub output: [usize; 2],
75 pub elapsed_ns: Option<u128>,
78 pub work: u64,
80}
81#[derive(Debug)]
83#[non_exhaustive]
84pub struct ProcessReport {
85 pub stages: Vec<ProcessStageReport>,
87 pub usage: Usage,
89 pub quality: Vec<Option<LodQuality>>,
91}
92#[derive(Clone, Copy, Debug)]
94#[non_exhaustive]
95pub struct ProcessSkin<'a> {
96 pub joints_offset: usize,
98 pub weights_offset: usize,
100 pub influences: usize,
102 pub importance: &'a [f32],
104 pub options: CharacterOptions,
106}
107impl<'a> ProcessSkin<'a> {
108 pub fn new(
110 joints_offset: usize,
111 weights_offset: usize,
112 influences: usize,
113 importance: &'a [f32],
114 ) -> Self {
115 Self {
116 joints_offset,
117 weights_offset,
118 influences,
119 importance,
120 options: CharacterOptions::default(),
121 }
122 }
123}
124#[derive(Clone, Debug)]
129#[non_exhaustive]
130pub struct ProcessOptions<'a> {
131 pub sanitize: Option<SanitizeOptions>,
133 pub weld: bool,
135 pub orient: bool,
137 pub split_non_manifold_vertices: bool,
139 pub stitch_cracks: Option<Option<f32>>,
141 pub fill_holes: Option<usize>,
143 pub lod: Option<LodChainOptions<'a>>,
145 pub attributes: Option<(usize, &'a [f32])>,
147 pub skin: Option<ProcessSkin<'a>>,
149 pub cache: bool,
151 pub overdraw: Option<f32>,
153 pub fetch: bool,
155 pub quality: LodQualityOptions,
157 pub meshlets: Option<(MeshletSettings, f32)>,
159 #[cfg(feature = "clusterlod")]
161 pub clusters: Option<clusterlod::Config>,
162 pub index_encoding: Option<codec::IndexEncoding>,
164 pub vertex_encoding: Option<codec::VertexEncoding>,
166}
167impl Default for ProcessOptions<'_> {
168 fn default() -> Self {
169 Self {
170 sanitize: Some(SanitizeOptions::default()),
171 weld: true,
172 orient: false,
173 split_non_manifold_vertices: false,
174 stitch_cracks: None,
175 fill_holes: None,
176 lod: Some(LodChainOptions::new(
177 LodTargets::Ratios(&[0.5, 0.25]),
178 LodErrors::Uniform(0.01),
179 )),
180 attributes: None,
181 skin: None,
182 cache: true,
183 overdraw: Some(1.05),
184 fetch: true,
185 quality: LodQualityOptions::default(),
186 meshlets: None,
187 #[cfg(feature = "clusterlod")]
188 clusters: None,
189 index_encoding: None,
190 vertex_encoding: None,
191 }
192 }
193}
194#[cfg(feature = "clusterlod")]
198#[derive(Debug)]
199#[non_exhaustive]
200pub struct ProcessClusters {
201 pub positions: Vec<[f32; 3]>,
203 pub groups: Vec<clusterlod::GroupOutput>,
205}
206#[derive(Debug)]
208#[non_exhaustive]
209pub struct ProcessLevel {
210 pub indices: Vec<u32>,
212 pub vertices: Vec<u8>,
214 pub meshlets: Option<Meshlets>,
216 #[cfg(feature = "clusterlod")]
218 pub clusters: Option<ProcessClusters>,
219 pub encoded_indices: Option<Vec<u8>>,
221 pub encoded_vertices: Option<Vec<u8>>,
223}
224#[derive(Debug)]
226#[non_exhaustive]
227pub struct ProcessedMesh {
228 pub levels: Vec<ProcessLevel>,
230 pub report: ProcessReport,
232}
233
234struct Meter {
235 limits: Limits,
236 held: usize,
237 peak: usize,
238 work: u64,
239 stages: Vec<ProcessStageReport>,
240 stage: ProcessStage,
241 level: Option<usize>,
242}
243impl Meter {
244 fn hold<T>(&mut self, v: &Vec<T>) -> Result<(), Error> {
245 self.held = self
246 .held
247 .checked_add(
248 v.capacity()
249 .checked_mul(size_of::<T>())
250 .ok_or(Error::SizeOverflow)?,
251 )
252 .ok_or(Error::SizeOverflow)?;
253 if self.held > self.limits.max_bytes {
254 return Err(Error::LimitExceeded);
255 }
256 Ok(())
257 }
258 fn call<T>(
259 &mut self,
260 stage: ProcessStage,
261 level: Option<usize>,
262 input: [usize; 2],
263 ws: &mut Workspace,
264 f: impl FnOnce(&mut Workspace) -> Result<T, Error>,
265 ) -> Result<T, Error> {
266 self.stage = stage;
267 self.level = level;
268 ws.set_lod_limits(Limits {
269 max_bytes: self
270 .limits
271 .max_bytes
272 .checked_sub(self.held)
273 .ok_or(Error::LimitExceeded)?,
274 max_work: self
275 .limits
276 .max_work
277 .checked_sub(self.work)
278 .ok_or(Error::LimitExceeded)?,
279 });
280 #[cfg(all(
281 feature = "std",
282 not(all(target_arch = "wasm32", target_os = "unknown"))
283 ))]
284 let start = std::time::Instant::now();
285 let work = ws.begin();
287 ws.finish(&work);
288 let r = f(ws);
289 let usage = ws.usage();
290 self.work = self
291 .work
292 .checked_add(usage.work)
293 .ok_or(Error::SizeOverflow)?;
294 self.peak = self.peak.max(
295 self.held
296 .checked_add(usage.bytes)
297 .ok_or(Error::SizeOverflow)?,
298 );
299 #[cfg(all(
300 feature = "std",
301 not(all(target_arch = "wasm32", target_os = "unknown"))
302 ))]
303 let elapsed_ns = Some(start.elapsed().as_nanos());
304 #[cfg(any(
305 not(feature = "std"),
306 all(target_arch = "wasm32", target_os = "unknown")
307 ))]
308 let elapsed_ns = None;
309 if self.stages.len() == self.stages.capacity() {
310 return Err(Error::LimitExceeded);
311 }
312 self.stages.push(ProcessStageReport {
313 stage,
314 level,
315 input,
316 output: input,
317 elapsed_ns,
318 work: usage.work,
319 });
320 r
321 }
322 fn counts(&mut self, output: [usize; 2]) {
323 if let Some(s) = self.stages.last_mut() {
324 s.output = output;
325 }
326 }
327}
328fn positions(bytes: &[u8], stride: usize, offset: usize) -> Result<Positions<'_>, Error> {
329 let max_offset = stride.checked_sub(12).ok_or(Error::InvalidLayout)?;
330 if offset > max_offset {
331 return Err(Error::InvalidLayout);
332 }
333 let offset = if bytes.is_empty() { 0 } else { offset };
335 Positions::from_bytes(
336 bytes,
337 bytes.len() / stride,
338 stride,
339 offset,
340 ByteOrder::LittleEndian,
341 )
342}
343fn copied<T: Copy>(source: &[T], ws: &mut Workspace) -> Result<Vec<T>, Error> {
344 let mut work = ws.begin();
345 let r = (|| {
346 work.add(source.len())?;
347 crate::budget::Budget::new(ws).copied(source)
348 })();
349 ws.finish(&work);
350 r
351}
352pub fn process_mesh(
367 indices: &[u32],
368 vertices: &[u8],
369 stride: usize,
370 position_offset: usize,
371 options: &ProcessOptions<'_>,
372 ws: &mut Workspace,
373) -> Result<ProcessedMesh, ProcessError> {
374 let limits = ws.limits();
375 let mut m = Meter {
376 limits,
377 held: 0,
378 peak: 0,
379 work: 0,
380 stages: Vec::new(),
381 stage: ProcessStage::Validate,
382 level: None,
383 };
384 let result = process(
385 indices,
386 vertices,
387 stride,
388 position_offset,
389 options,
390 ws,
391 &mut m,
392 );
393 ws.set_lod_limits(limits);
394 ws.set_lod_usage(Usage {
395 bytes: m.peak.max(m.held),
396 work: m.work,
397 });
398 result.map_err(|error| ProcessError {
399 stage: m.stage,
400 level: m.level,
401 error,
402 })
403}
404fn process(
405 indices: &[u32],
406 input: &[u8],
407 stride: usize,
408 offset: usize,
409 o: &ProcessOptions<'_>,
410 ws: &mut Workspace,
411 m: &mut Meter,
412) -> Result<ProcessedMesh, Error> {
413 let initial_work = ws.begin();
414 m.peak = ws.retained_bytes()?;
415 if !(12..=256).contains(&stride) || !input.len().is_multiple_of(stride) {
416 return Err(Error::InvalidLayout);
417 }
418 let source_positions = positions(input, stride, offset)?;
419 if o.lod
420 .is_some_and(|l| l.attributes.is_some() || l.vertex_flags.is_some())
421 {
422 return Err(Error::InvalidParameter);
423 }
424 let targets = o.lod.map_or(0, |l| match l.targets {
425 LodTargets::Counts(v) => v.len(),
426 LodTargets::Ratios(v) => v.len(),
427 });
428 let levels_count = targets.checked_add(1).ok_or(Error::SizeOverflow)?;
429 let records = levels_count
430 .checked_mul(12)
431 .and_then(|n| n.checked_add(20))
432 .ok_or(Error::SizeOverflow)?;
433 m.stages = crate::budget::Budget::new(ws).reserved(records)?;
434 let stage_bytes = m
435 .stages
436 .capacity()
437 .checked_mul(size_of::<ProcessStageReport>())
438 .ok_or(Error::SizeOverflow)?;
439 m.held = stage_bytes;
440 ws.finish(&initial_work);
441 m.peak = m.peak.max(
442 m.held
443 .checked_add(ws.retained_bytes()?)
444 .ok_or(Error::SizeOverflow)?,
445 );
446 let mut indices = if let Some(s) = o.sanitize {
447 let r = m.call(
448 ProcessStage::Sanitize,
449 None,
450 [indices.len(), source_positions.len()],
451 ws,
452 |ws| sanitize(indices, source_positions, s, ws),
453 )?;
454 m.counts([r.indices.len(), source_positions.len()]);
455 r.indices
456 } else {
457 m.call(
458 ProcessStage::Validate,
459 None,
460 [indices.len(), source_positions.len()],
461 ws,
462 |ws| {
463 let mut work = ws.begin();
464 let r = (|| {
465 crate::workspace::topology(indices, source_positions.len(), &mut work)?;
466 for &i in indices {
467 work.add(1)?;
468 let p = source_positions
469 .get(usize::try_from(i).map_err(|_| Error::SizeOverflow)?)
470 .ok_or(Error::IndexOutOfBounds)?;
471 if p.iter().any(|x| !x.is_finite()) {
472 return Err(Error::NumericalFailure);
473 }
474 }
475 work.add(indices.len())?;
476 crate::budget::Budget::new(ws).copied(indices)
477 })();
478 ws.finish(&work);
479 r
480 },
481 )?
482 };
483 m.hold(&indices)?;
484 let mut vertices = if o.weld {
485 let remap = m.call(
486 ProcessStage::Weld,
487 None,
488 [indices.len(), source_positions.len()],
489 ws,
490 |ws| generate_vertex_remap(Some(&indices), VertexStream::packed(input, stride)?, ws),
491 )?;
492 m.hold(&remap.remap)?;
493 indices = m.call(
494 ProcessStage::Weld,
495 None,
496 [indices.len(), source_positions.len()],
497 ws,
498 |ws| remap_index_buffer(Some(&indices), &remap.remap, ws),
499 )?;
500 m.hold(&indices)?;
501 let v = m.call(
502 ProcessStage::Weld,
503 None,
504 [indices.len(), source_positions.len()],
505 ws,
506 |ws| remap_vertex_buffer(VertexStream::packed(input, stride)?, &remap.remap, ws),
507 )?;
508 m.counts([indices.len(), v.len() / stride]);
509 v
510 } else {
511 m.call(
512 ProcessStage::Validate,
513 None,
514 [indices.len(), source_positions.len()],
515 ws,
516 |ws| copied(input, ws),
517 )?
518 };
519 m.hold(&vertices)?;
520 if o.orient {
521 indices = m.call(
522 ProcessStage::Orient,
523 None,
524 [indices.len(), vertices.len() / stride],
525 ws,
526 |ws| orient_faces(&indices, vertices.len() / stride, ws).map(|r| r.indices),
527 )?;
528 m.hold(&indices)?;
529 }
530 if let Some(tolerance) = o.stitch_cracks {
531 let r = m.call(
532 ProcessStage::StitchCracks,
533 None,
534 [indices.len(), vertices.len() / stride],
535 ws,
536 |ws| {
537 stitch_cracks(
538 &indices,
539 VertexStream::packed(&vertices, stride)?,
540 positions(&vertices, stride, offset)?,
541 tolerance,
542 ws,
543 )
544 },
545 )?;
546 indices = r.indices;
547 vertices = r.vertices;
548 m.counts([indices.len(), vertices.len() / stride]);
549 m.hold(&indices)?;
550 m.hold(&vertices)?;
551 }
552 if o.split_non_manifold_vertices {
553 let r = m.call(
554 ProcessStage::SplitVertices,
555 None,
556 [indices.len(), vertices.len() / stride],
557 ws,
558 |ws| {
559 split_non_manifold_vertices(&indices, VertexStream::packed(&vertices, stride)?, ws)
560 },
561 )?;
562 indices = r.indices;
563 vertices = r.vertices;
564 m.counts([indices.len(), vertices.len() / stride]);
565 m.hold(&indices)?;
566 m.hold(&vertices)?;
567 }
568 if let Some(max_edges) = o.fill_holes {
569 indices = m.call(
570 ProcessStage::FillHoles,
571 None,
572 [indices.len(), vertices.len() / stride],
573 ws,
574 |ws| {
575 fill_holes(
576 &indices,
577 positions(&vertices, stride, offset)?,
578 max_edges,
579 ws,
580 )
581 .map(|r| r.indices)
582 },
583 )?;
584 m.counts([indices.len(), vertices.len() / stride]);
585 m.hold(&indices)?;
586 }
587 let mut chain = if let Some(mut settings) = o.lod {
588 m.stage = ProcessStage::Lod;
589 m.level = None;
590 let p = positions(&vertices, stride, offset)?;
591 if let Some((a, weights)) = o.attributes {
592 settings.attributes = Some(LodChainAttributes::new(
593 Attributes::from_bytes(
594 &vertices,
595 p.len(),
596 weights.len(),
597 stride,
598 a,
599 ByteOrder::LittleEndian,
600 )?,
601 weights,
602 ));
603 }
604 if let Some(skin) = o.skin {
605 let (joints, weights) = m.call(
606 ProcessStage::Lod,
607 None,
608 [indices.len(), p.len()],
609 ws,
610 |ws| {
611 if skin.influences != 4 && skin.influences != 8 {
612 return Err(Error::InvalidParameter);
613 }
614 let width = skin.influences.checked_mul(4).ok_or(Error::SizeOverflow)?;
615 if skin
616 .joints_offset
617 .checked_add(width)
618 .ok_or(Error::SizeOverflow)?
619 > stride
620 || skin
621 .weights_offset
622 .checked_add(width)
623 .ok_or(Error::SizeOverflow)?
624 > stride
625 {
626 return Err(Error::InvalidLayout);
627 }
628 let mut work = ws.begin();
629 let r = (|| {
630 let n = p
631 .len()
632 .checked_mul(skin.influences)
633 .ok_or(Error::SizeOverflow)?;
634 let mut b = crate::budget::Budget::new(ws);
635 let mut j = b.reserved(n)?;
636 let mut w = b.reserved(n)?;
637 for record in vertices.chunks_exact(stride) {
638 for k in 0..skin.influences {
639 work.add(1)?;
640 let a = skin.joints_offset + k * 4;
641 let c = skin.weights_offset + k * 4;
642 j.push(u32::from_le_bytes(
643 record[a..a + 4]
644 .try_into()
645 .map_err(|_| Error::InvalidLayout)?,
646 ));
647 w.push(f32::from_le_bytes(
648 record[c..c + 4]
649 .try_into()
650 .map_err(|_| Error::InvalidLayout)?,
651 ));
652 }
653 }
654 Ok((j, w))
655 })();
656 ws.finish(&work);
657 r
658 },
659 )?;
660 m.hold(&joints)?;
661 m.hold(&weights)?;
662 let mut data = CharacterInputs::new();
663 data.skin = Some(CharacterSkin::new(
664 &joints,
665 &weights,
666 skin.influences,
667 skin.importance,
668 ));
669 m.call(
670 ProcessStage::Lod,
671 None,
672 [indices.len(), p.len()],
673 ws,
674 |ws| {
675 build_character_lod_chain(
676 &indices,
677 p,
678 &data,
679 &skin.options,
680 &settings,
681 &o.quality,
682 ws,
683 )
684 .map(|r| r.chain)
685 },
686 )?
687 } else {
688 m.call(
689 ProcessStage::Lod,
690 None,
691 [indices.len(), p.len()],
692 ws,
693 |ws| build_lod_chain(&indices, p, &settings, ws).map_err(|e| e.error),
694 )?
695 }
696 } else {
697 LodChain { levels: Vec::new() }
698 };
699 if o.lod.is_some() {
700 let total = chain.levels.iter().try_fold(0usize, |n, l| {
701 n.checked_add(l.indices.len()).ok_or(Error::SizeOverflow)
702 })?;
703 m.counts([total, vertices.len() / stride]);
704 }
705 m.hold(&chain.levels)?;
706 for level in &chain.levels {
707 m.hold(&level.indices)?;
708 }
709 let (mut levels, mut quality) = m.call(
710 ProcessStage::Validate,
711 None,
712 [indices.len(), vertices.len() / stride],
713 ws,
714 |ws| {
715 let mut b = crate::budget::Budget::new(ws);
716 Ok((b.reserved(levels_count)?, b.reserved(levels_count)?))
717 },
718 )?;
719 m.hold(&levels)?;
720 m.hold(&quality)?;
721 let source_indices = m.call(
723 ProcessStage::Validate,
724 None,
725 [indices.len(), vertices.len() / stride],
726 ws,
727 |ws| copied(&indices, ws),
728 )?;
729 m.hold(&source_indices)?;
730 let source_vertices = m.call(
731 ProcessStage::Validate,
732 None,
733 [indices.len(), vertices.len() / stride],
734 ws,
735 |ws| copied(&vertices, ws),
736 )?;
737 m.hold(&source_vertices)?;
738 for level in 0..levels_count {
739 if level > 0 {
740 indices = core::mem::take(&mut chain.levels[level - 1].indices);
741 vertices = m.call(
742 ProcessStage::Validate,
743 Some(level),
744 [indices.len(), source_vertices.len() / stride],
745 ws,
746 |ws| copied(&source_vertices, ws),
747 )?;
748 m.hold(&vertices)?;
749 }
750 if o.cache {
751 indices = m.call(
752 ProcessStage::Cache,
753 Some(level),
754 [indices.len(), vertices.len() / stride],
755 ws,
756 |ws| optimize_vertex_cache(&indices, vertices.len() / stride, ws),
757 )?;
758 m.hold(&indices)?;
759 }
760 if let Some(t) = o.overdraw {
761 indices = m.call(
762 ProcessStage::Overdraw,
763 Some(level),
764 [indices.len(), vertices.len() / stride],
765 ws,
766 |ws| optimize_overdraw(&indices, positions(&vertices, stride, offset)?, t, ws),
767 )?;
768 m.hold(&indices)?;
769 }
770 if o.fetch {
771 let fetched = m.call(
772 ProcessStage::Fetch,
773 Some(level),
774 [indices.len(), vertices.len() / stride],
775 ws,
776 |ws| optimize_vertex_fetch(&indices, VertexStream::packed(&vertices, stride)?, ws),
777 )?;
778 indices = fetched.indices;
779 vertices = fetched.vertices;
780 m.counts([indices.len(), vertices.len() / stride]);
781 m.hold(&indices)?;
782 m.hold(&vertices)?;
783 }
784 let p = positions(&vertices, stride, offset)?;
785 quality.push(if indices.is_empty() || source_indices.is_empty() {
786 None
787 } else {
788 Some(m.call(
789 ProcessStage::Quality,
790 Some(level),
791 [indices.len(), p.len()],
792 ws,
793 |ws| {
794 measure_lod_quality(
795 LodQualityMesh::new(
796 &source_indices,
797 positions(&source_vertices, stride, offset)?,
798 ),
799 LodQualityMesh::new(&indices, p),
800 &o.quality,
801 ws,
802 )
803 },
804 )?)
805 });
806 let meshlets = if let Some((settings, cone)) = o.meshlets {
807 let r = m.call(
808 ProcessStage::Meshlets,
809 Some(level),
810 [indices.len(), p.len()],
811 ws,
812 |ws| build_meshlets(&indices, p, settings, cone, ws),
813 )?;
814 m.hold(&r.meshlets)?;
815 m.hold(&r.vertices)?;
816 m.hold(&r.triangles)?;
817 Some(r)
818 } else {
819 None
820 };
821 #[cfg(feature = "clusterlod")]
822 let clusters = if let Some(config) = o.clusters {
823 let mut packed = m.call(
824 ProcessStage::Clusters,
825 Some(level),
826 [indices.len(), p.len()],
827 ws,
828 |ws| {
829 let mut work = ws.begin();
830 let r = (|| {
831 let mut b = crate::budget::Budget::new(ws);
832 let mut v = b.reserved(p.len())?;
833 for i in 0..p.len() {
834 work.add(1)?;
835 v.push(p.get(i).ok_or(Error::IndexOutOfBounds)?);
836 }
837 Ok(v)
838 })();
839 ws.finish(&work);
840 r
841 },
842 )?;
843 m.hold(&packed)?;
844 let r = m.call(
845 ProcessStage::Clusters,
846 Some(level),
847 [indices.len(), p.len()],
848 ws,
849 |ws| {
850 let attributes = o
851 .attributes
852 .map(|(offset, weights)| {
853 Attributes::from_bytes(
854 &vertices,
855 p.len(),
856 weights.len(),
857 stride,
858 offset,
859 ByteOrder::LittleEndian,
860 )
861 })
862 .transpose()?;
863 clusterlod::build(
864 config,
865 clusterlod::Mesh {
866 indices: &indices,
867 positions: &mut packed,
868 attributes,
869 vertex_lock: None,
870 attribute_weights: o.attributes.map_or(&[], |(_, weights)| weights),
871 attribute_protect_mask: 0,
872 },
873 ws,
874 )
875 },
876 )?;
877 m.hold(&r)?;
878 for g in &r {
879 m.hold(&g.clusters)?;
880 for c in &g.clusters {
881 m.hold(&c.indices)?;
882 }
883 }
884 Some(ProcessClusters {
885 positions: packed,
886 groups: r,
887 })
888 } else {
889 None
890 };
891 let encoded_indices = if let Some(e) = o.index_encoding {
892 let r = m.call(
893 ProcessStage::Encode,
894 Some(level),
895 [indices.len(), p.len()],
896 ws,
897 |ws| codec::encode_index_buffer(&indices, e, ws),
898 )?;
899 m.hold(&r)?;
900 Some(r)
901 } else {
902 None
903 };
904 let encoded_vertices = if let Some(e) = o.vertex_encoding {
905 let r = m.call(
906 ProcessStage::Encode,
907 Some(level),
908 [indices.len(), p.len()],
909 ws,
910 |ws| codec::encode_vertex_buffer(&vertices, p.len(), stride, e, ws),
911 )?;
912 m.hold(&r)?;
913 Some(r)
914 } else {
915 None
916 };
917 levels.push(ProcessLevel {
918 indices: core::mem::take(&mut indices),
919 vertices: core::mem::take(&mut vertices),
920 meshlets,
921 #[cfg(feature = "clusterlod")]
922 clusters,
923 encoded_indices,
924 encoded_vertices,
925 });
926 }
927 let usage = Usage {
928 bytes: m.peak.max(m.held),
929 work: m.work,
930 };
931 Ok(ProcessedMesh {
932 levels,
933 report: ProcessReport {
934 stages: core::mem::take(&mut m.stages),
935 usage,
936 quality,
937 },
938 })
939}
940
941#[cfg(test)]
942mod tests {
943 use super::*;
944
945 #[test]
946 fn failed_validation_reports_retained_storage() -> Result<(), Error> {
947 let mut indices = [0u32; 300];
948 for (i, value) in indices.iter_mut().enumerate() {
949 *value = u32::try_from(i).map_err(|_| Error::SizeOverflow)?;
950 }
951 let mut ws = Workspace::default();
952 let _ = optimize_vertex_cache(&indices, 300, &mut ws)?;
953 let retained = ws.retained_bytes()?;
954 assert!(retained > 0);
955 let limits = ws.limits();
956 let error = match process_mesh(&[], &[], 0, 0, &ProcessOptions::default(), &mut ws) {
957 Err(error) => error,
958 Ok(_) => return Err(Error::InvalidParameter),
959 };
960 assert_eq!(error.stage, ProcessStage::Validate);
961 assert_eq!(
962 ws.usage(),
963 Usage {
964 bytes: retained,
965 work: 0
966 }
967 );
968 assert_eq!(ws.limits(), limits);
969 Ok(())
970 }
971}