1use super::{
4 Arc, Color, Error, Fog3d, Lighting3d, Mesh3d, MeshStyle3d, NEXT_SCENE3D_ID, Ordering,
5 RetainedMesh3d, Texture3dError, TextureMaterial3d, Transform3d, WireframeStyle3d, fmt, texture,
6 validate_mesh_source_style, validate_mesh_style, validate_scene3d_transform,
7};
8
9#[cfg(test)]
10mod tests;
11#[cfg(test)]
12pub(super) use tests::verify_scene_accounting;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16pub struct Object3dId {
17 pub(super) scene_id: u64,
18 pub(super) object_id: u64,
19 slot: usize,
20}
21
22impl Object3dId {
23 pub const fn get(self) -> u64 {
28 self.object_id
29 }
30}
31
32#[derive(Clone)]
34pub struct Mesh3dInstance {
35 pub(super) id: Object3dId,
36 pub(super) mesh: RetainedMesh3d,
37 pub(super) transform: Transform3d,
38 pub(super) style: MeshStyle3d,
39 pub(super) visible: bool,
40}
41
42impl Mesh3dInstance {
43 fn new(
44 id: Object3dId,
45 mesh: &RetainedMesh3d,
46 transform: Transform3d,
47 style: MeshStyle3d,
48 ) -> Self {
49 Self {
50 id,
51 mesh: mesh.clone(),
52 transform,
53 style,
54 visible: true,
55 }
56 }
57
58 pub const fn id(&self) -> Object3dId {
60 self.id
61 }
62
63 pub const fn mesh(&self) -> &RetainedMesh3d {
65 &self.mesh
66 }
67
68 pub const fn transform(&self) -> Transform3d {
70 self.transform
71 }
72
73 pub const fn style(&self) -> MeshStyle3d {
75 self.style
76 }
77
78 pub const fn is_visible(&self) -> bool {
80 self.visible
81 }
82
83 pub const fn wireframe(&self) -> Option<WireframeStyle3d> {
85 self.style.wireframe_style()
86 }
87}
88
89pub struct Scene3d {
91 pub(super) scene_id: u64,
92 pub(super) background: Color,
93 pub(super) lighting: Lighting3d,
94 pub(super) fog: Option<Fog3d>,
95 pub(super) instances: Vec<Mesh3dInstance>,
96 pub(super) next_object_id: u64,
97 pub(super) renderer_identity: Option<Arc<()>>,
98 slots: Vec<ObjectSlot>,
99 free_slot: Option<usize>,
100 resources: Vec<ResourceUsage>,
101 resource_totals: ResourceTotals,
102 visible_count: usize,
103 budget: Scene3dBudget,
104}
105
106#[derive(Clone)]
107struct ObjectSlot {
108 dense_index: Option<usize>,
109 next_free: Option<usize>,
110}
111
112#[derive(Clone, Copy)]
113struct ResourceUsage {
114 key: (u8, usize),
115 references: usize,
116 bytes: usize,
117}
118
119#[derive(Default)]
120struct ResourceTotals {
121 bytes: [usize; 4],
122 counts: [usize; 4],
123}
124
125pub(super) struct DynamicSceneMeshChange {
126 index: usize,
127 outgoing: [ResourceUsage; 4],
128 resources: Option<Vec<ResourceUsage>>,
129}
130
131impl DynamicSceneMeshChange {
132 pub(super) fn object_index(&self) -> usize {
133 self.index
134 }
135}
136
137#[derive(Debug, Clone, Copy, PartialEq, Eq)]
143pub struct Scene3dBudget {
144 max_objects: usize,
145 max_storage_bytes: usize,
146 max_mesh_cpu_bytes: usize,
147 max_mesh_gpu_bytes: usize,
148 max_texture_cpu_bytes: usize,
149 max_texture_gpu_bytes: usize,
150}
151
152impl Scene3dBudget {
153 pub fn new(
155 max_objects: usize,
156 max_storage_bytes: usize,
157 max_mesh_cpu_bytes: usize,
158 max_mesh_gpu_bytes: usize,
159 ) -> Result<Self, Scene3dError> {
160 if [
161 max_objects,
162 max_storage_bytes,
163 max_mesh_cpu_bytes,
164 max_mesh_gpu_bytes,
165 ]
166 .contains(&0)
167 {
168 return Err(Scene3dError::InvalidBudget);
169 }
170 Ok(Self {
171 max_objects,
172 max_storage_bytes,
173 max_mesh_cpu_bytes,
174 max_mesh_gpu_bytes,
175 max_texture_cpu_bytes: 64 * 1024 * 1024,
176 max_texture_gpu_bytes: 64 * 1024 * 1024,
177 })
178 }
179 pub const fn max_objects(self) -> usize {
181 self.max_objects
182 }
183 pub const fn max_storage_bytes(self) -> usize {
185 self.max_storage_bytes
186 }
187 pub const fn max_mesh_cpu_bytes(self) -> usize {
189 self.max_mesh_cpu_bytes
190 }
191 pub const fn max_mesh_gpu_bytes(self) -> usize {
193 self.max_mesh_gpu_bytes
194 }
195 pub const fn with_texture_limits(mut self, cpu_bytes: usize, gpu_bytes: usize) -> Self {
198 self.max_texture_cpu_bytes = cpu_bytes;
199 self.max_texture_gpu_bytes = gpu_bytes;
200 self
201 }
202 pub const fn max_texture_cpu_bytes(self) -> usize {
204 self.max_texture_cpu_bytes
205 }
206 pub const fn max_texture_gpu_bytes(self) -> usize {
208 self.max_texture_gpu_bytes
209 }
210}
211
212impl Default for Scene3dBudget {
213 fn default() -> Self {
214 Self {
215 max_objects: 65_536,
216 max_storage_bytes: 64 * 1024 * 1024,
217 max_mesh_cpu_bytes: 256 * 1024 * 1024,
218 max_mesh_gpu_bytes: 256 * 1024 * 1024,
219 max_texture_cpu_bytes: 64 * 1024 * 1024,
220 max_texture_gpu_bytes: 64 * 1024 * 1024,
221 }
222 }
223}
224
225#[derive(Debug, Clone, Copy, PartialEq, Eq)]
227pub enum Scene3dBudgetResource {
228 TextureCpuBytes,
230 TextureGpuBytes,
232 Objects,
234 StorageBytes,
236 MeshCpuBytes,
238 MeshGpuBytes,
240}
241
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub struct Scene3dStatistics {
245 object_count: usize,
246 slot_capacity: usize,
247 storage_bytes: usize,
248 mesh_count: usize,
249 mesh_cpu_bytes: usize,
250 mesh_gpu_bytes: usize,
251 texture_count: usize,
252 texture_cpu_bytes: usize,
253 texture_gpu_bytes: usize,
254}
255
256impl Scene3dStatistics {
257 pub const fn texture_count(self) -> usize {
259 self.texture_count
260 }
261 pub const fn texture_cpu_bytes(self) -> usize {
263 self.texture_cpu_bytes
264 }
265 pub const fn texture_gpu_bytes(self) -> usize {
267 self.texture_gpu_bytes
268 }
269 pub const fn object_count(self) -> usize {
271 self.object_count
272 }
273 pub const fn slot_capacity(self) -> usize {
275 self.slot_capacity
276 }
277 pub const fn storage_bytes(self) -> usize {
279 self.storage_bytes
280 }
281 pub const fn mesh_count(self) -> usize {
283 self.mesh_count
284 }
285 pub const fn mesh_cpu_bytes(self) -> usize {
287 self.mesh_cpu_bytes
288 }
289 pub const fn mesh_gpu_bytes(self) -> usize {
291 self.mesh_gpu_bytes
292 }
293}
294
295#[derive(Debug, Clone, Copy, PartialEq, Eq)]
297pub struct Scene3dMeshUpdateReport {
298 statistics: Scene3dStatistics,
299 peak_mesh_cpu_bytes: usize,
300 peak_mesh_gpu_bytes: usize,
301 peak_texture_cpu_bytes: usize,
302 peak_texture_gpu_bytes: usize,
303}
304
305impl Scene3dMeshUpdateReport {
306 pub const fn peak_texture_cpu_bytes(self) -> usize {
308 self.peak_texture_cpu_bytes
309 }
310 pub const fn peak_texture_gpu_bytes(self) -> usize {
312 self.peak_texture_gpu_bytes
313 }
314 pub const fn statistics(self) -> Scene3dStatistics {
316 self.statistics
317 }
318 pub const fn peak_mesh_cpu_bytes(self) -> usize {
320 self.peak_mesh_cpu_bytes
321 }
322 pub const fn peak_mesh_gpu_bytes(self) -> usize {
324 self.peak_mesh_gpu_bytes
325 }
326}
327
328impl Scene3d {
329 pub fn new(background: Color) -> Result<Self, Scene3dError> {
331 Self::with_budget(background, Scene3dBudget::default())
332 }
333
334 pub fn with_budget(background: Color, budget: Scene3dBudget) -> Result<Self, Scene3dError> {
336 if !background.is_normalized() || background.alpha() != 1.0 {
337 return Err(Scene3dError::InvalidBackground);
338 }
339 Self::with_alpha_background_and_budget(background, budget)
340 }
341
342 pub fn with_alpha_background(background: Color) -> Result<Self, Scene3dError> {
346 Self::with_alpha_background_and_budget(background, Scene3dBudget::default())
347 }
348
349 pub fn with_alpha_background_and_budget(
351 background: Color,
352 budget: Scene3dBudget,
353 ) -> Result<Self, Scene3dError> {
354 if !background.is_normalized() {
355 return Err(Scene3dError::InvalidBackground);
356 }
357 let scene_id = NEXT_SCENE3D_ID
358 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
359 current.checked_add(1)
360 })
361 .map_err(|_| Scene3dError::SceneIdExhausted)?;
362 Ok(Self {
363 scene_id,
364 background,
365 lighting: Lighting3d::default(),
366 fog: None,
367 instances: Vec::new(),
368 next_object_id: 0,
369 renderer_identity: None,
370 slots: Vec::new(),
371 free_slot: None,
372 resources: Vec::new(),
373 resource_totals: ResourceTotals::default(),
374 visible_count: 0,
375 budget,
376 })
377 }
378
379 pub fn set_lighting(&mut self, lighting: Lighting3d) {
381 self.lighting = lighting;
382 }
383 pub const fn lighting(&self) -> Lighting3d {
385 self.lighting
386 }
387 pub fn set_fog(&mut self, fog: Option<Fog3d>) {
389 self.fog = fog;
390 }
391 pub const fn fog(&self) -> Option<Fog3d> {
393 self.fog
394 }
395
396 pub fn try_push(
398 &mut self,
399 mesh: &RetainedMesh3d,
400 transform: Transform3d,
401 style: MeshStyle3d,
402 ) -> Result<Object3dId, Scene3dError> {
403 validate_mesh_style(mesh, style)?;
404 validate_scene3d_transform(transform)?;
405 self.validate_mesh_owner(mesh)?;
406 check_scene_limit(
407 Scene3dBudgetResource::Objects,
408 self.budget.max_objects,
409 self.instances.len().saturating_add(1),
410 )?;
411 let next_object_id = self
412 .next_object_id
413 .checked_add(1)
414 .ok_or(Scene3dError::ObjectIdExhausted)?;
415 let keys = mesh_resources(mesh);
416 self.validate_resource_change(&keys, None)?;
417 self.reserve_storage(
418 1,
419 usize::from(self.free_slot.is_none()),
420 self.missing_resources(&keys),
421 )?;
422 let slot = self.free_slot.unwrap_or(self.slots.len());
423 let id = Object3dId {
424 scene_id: self.scene_id,
425 object_id: self.next_object_id,
426 slot,
427 };
428 if let Some(free) = self.free_slot {
429 self.free_slot = self.slots[free].next_free;
430 self.slots[free] = ObjectSlot {
431 dense_index: Some(self.instances.len()),
432 next_free: None,
433 };
434 } else {
435 self.slots.push(ObjectSlot {
436 dense_index: Some(self.instances.len()),
437 next_free: None,
438 });
439 }
440 for resource in keys {
441 self.add_resource(resource);
442 }
443 self.renderer_identity = Some(Arc::clone(&mesh.renderer_identity));
444 self.instances
445 .push(Mesh3dInstance::new(id, mesh, transform, style));
446 self.visible_count += 1;
447 self.next_object_id = next_object_id;
448 Ok(id)
449 }
450
451 pub const fn background(&self) -> Color {
453 self.background
454 }
455
456 pub fn set_background(&mut self, background: Color) -> Result<(), Scene3dError> {
464 if !background.is_normalized() {
465 return Err(Scene3dError::InvalidBackground);
466 }
467 self.background = background;
468 Ok(())
469 }
470
471 pub fn instances(&self) -> &[Mesh3dInstance] {
473 &self.instances
474 }
475
476 pub fn object_count(&self) -> usize {
478 self.instances.len()
479 }
480
481 pub const fn budget(&self) -> Scene3dBudget {
483 self.budget
484 }
485
486 pub fn statistics(&self) -> Scene3dStatistics {
489 Scene3dStatistics {
490 texture_count: self.resource_totals.counts[3],
491 texture_cpu_bytes: self.resource_totals.bytes[2],
492 texture_gpu_bytes: self.resource_totals.bytes[3],
493 object_count: self.instances.len(),
494 slot_capacity: self.slots.capacity(),
495 storage_bytes: storage_bytes(
496 self.instances.capacity(),
497 self.slots.capacity(),
498 self.resources.capacity(),
499 ),
500 mesh_count: self.resource_totals.counts[1],
501 mesh_cpu_bytes: self.resource_totals.bytes[0],
502 mesh_gpu_bytes: self.resource_totals.bytes[1],
503 }
504 }
505
506 pub fn instance(&self, object_id: Object3dId) -> Result<&Mesh3dInstance, Scene3dError> {
508 let index = self.instance_index(object_id)?;
509 Ok(&self.instances[index])
510 }
511
512 pub fn remove(&mut self, object_id: Object3dId) -> Result<Mesh3dInstance, Scene3dError> {
519 let index = self.instance_index(object_id)?;
520 let removed = self.instances.remove(index);
521 for instance in &self.instances[index..] {
522 if let Some(dense) = &mut self.slots[instance.id.slot].dense_index {
523 *dense -= 1;
524 }
525 }
526 self.slots[object_id.slot] = ObjectSlot {
527 dense_index: None,
528 next_free: self.free_slot,
529 };
530 self.free_slot = Some(object_id.slot);
531 for resource in mesh_resources(&removed.mesh) {
532 self.remove_resource(resource.key);
533 }
534 if removed.visible {
535 self.visible_count -= 1;
536 }
537 Ok(removed)
538 }
539
540 pub fn set_texture_material(
553 &mut self,
554 object_id: Object3dId,
555 material: Option<&TextureMaterial3d>,
556 ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
557 let mesh = self.instance(object_id)?.mesh();
558 let replacement = match material {
559 Some(material) => texture::attach_material(&mesh.renderer_identity, mesh, material)
560 .map_err(Scene3dError::Texture)?,
561 None => mesh.without_material(),
562 };
563 self.set_mesh(object_id, &replacement)
564 }
565
566 pub fn set_mesh(
574 &mut self,
575 object_id: Object3dId,
576 mesh: &RetainedMesh3d,
577 ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
578 let index = self.instance_index(object_id)?;
579 self.validate_mesh_owner(mesh)?;
580 validate_mesh_style(mesh, self.instances[index].style)?;
581 let incoming = mesh_resources(mesh);
582 let outgoing = mesh_resources(&self.instances[index].mesh);
583 let [
584 peak_mesh_cpu_bytes,
585 peak_mesh_gpu_bytes,
586 peak_texture_cpu_bytes,
587 peak_texture_gpu_bytes,
588 ] = self.validate_resource_change(&incoming, Some(&outgoing))?;
589 let removed_keys = outgoing
590 .iter()
591 .filter(|resource| {
592 !incoming.iter().any(|r| r.key == resource.key)
593 && self
594 .resources
595 .binary_search_by_key(&resource.key, |r| r.key)
596 .ok()
597 .is_some_and(|i| self.resources[i].references == 1)
598 })
599 .count();
600 self.reserve_storage(
601 0,
602 0,
603 self.missing_resources(&incoming)
604 .saturating_sub(removed_keys),
605 )?;
606 for resource in outgoing {
607 self.remove_resource(resource.key);
608 }
609 for resource in incoming {
610 self.add_resource(resource);
611 }
612 self.instances[index].mesh = mesh.clone();
613 Ok(Scene3dMeshUpdateReport {
614 statistics: self.statistics(),
615 peak_mesh_cpu_bytes,
616 peak_mesh_gpu_bytes,
617 peak_texture_cpu_bytes,
618 peak_texture_gpu_bytes,
619 })
620 }
621
622 pub(super) fn prepare_dynamic_mesh_change(
623 &self,
624 object_id: Object3dId,
625 source: &Mesh3d,
626 gpu_bytes: usize,
627 replace_buffers: bool,
628 ) -> Result<DynamicSceneMeshChange, Scene3dError> {
629 let index = self.instance_index(object_id)?;
630 validate_mesh_source_style(source, self.instances[index].style)?;
631 let outgoing = mesh_resources(&self.instances[index].mesh);
632 let mut incoming = outgoing;
633 incoming[0].key.1 = source.vertices().as_ptr() as usize;
634 incoming[0].bytes = source.recovery_memory_bytes();
635 if replace_buffers {
636 incoming[1].key.1 = 0;
639 }
640 incoming[1].bytes = gpu_bytes;
641 self.prepare_resource_change(index, incoming, outgoing)
642 }
643
644 pub(super) fn prepare_dynamic_texture_change(
645 &self,
646 object_id: Object3dId,
647 cpu_bytes: usize,
648 gpu_bytes: usize,
649 detached: bool,
650 ) -> Result<DynamicSceneMeshChange, Scene3dError> {
651 let index = self.instance_index(object_id)?;
652 let outgoing = mesh_resources(&self.instances[index].mesh);
653 let mut incoming = outgoing;
654 incoming[2].key.1 = 0;
657 incoming[2].bytes = cpu_bytes;
658 incoming[3].bytes = gpu_bytes;
659 if detached {
660 incoming[3].key.1 = 0;
661 }
662 self.prepare_resource_change(index, incoming, outgoing)
663 }
664
665 fn prepare_resource_change(
666 &self,
667 index: usize,
668 incoming: [ResourceUsage; 4],
669 outgoing: [ResourceUsage; 4],
670 ) -> Result<DynamicSceneMeshChange, Scene3dError> {
671 self.validate_resource_change(&incoming, Some(&outgoing))?;
672 let retired = outgoing
673 .iter()
674 .filter(|resource| {
675 !incoming
676 .iter()
677 .any(|candidate| candidate.key == resource.key)
678 && self
679 .resources
680 .binary_search_by_key(&resource.key, |entry| entry.key)
681 .ok()
682 .is_some_and(|index| self.resources[index].references == 1)
683 })
684 .count();
685 let additional = self.missing_resources(&incoming).saturating_sub(retired);
686 let mut capacity = planned_capacity(
687 &self.resources,
688 additional,
689 self.budget.max_objects.saturating_mul(4),
690 );
691 if storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity)
692 > self.budget.max_storage_bytes
693 {
694 capacity = self
695 .resources
696 .capacity()
697 .max(self.resources.len().saturating_add(additional));
698 }
699 check_scene_limit(
700 Scene3dBudgetResource::StorageBytes,
701 self.budget.max_storage_bytes,
702 storage_bytes(self.instances.capacity(), self.slots.capacity(), capacity),
703 )?;
704 let resources = replacement_capacity(&self.resources, capacity)?;
705 check_scene_limit(
706 Scene3dBudgetResource::StorageBytes,
707 self.budget.max_storage_bytes,
708 storage_bytes(
709 self.instances.capacity(),
710 self.slots.capacity(),
711 resources
712 .as_ref()
713 .map_or(self.resources.capacity(), Vec::capacity),
714 ),
715 )?;
716 Ok(DynamicSceneMeshChange {
717 index,
718 outgoing,
719 resources,
720 })
721 }
722
723 pub(super) fn commit_dynamic_mesh_change(
724 &mut self,
725 change: DynamicSceneMeshChange,
726 mesh: RetainedMesh3d,
727 ) -> Scene3dStatistics {
728 if let Some(resources) = change.resources {
729 self.resources = resources;
730 }
731 for resource in change.outgoing {
732 self.remove_resource(resource.key);
733 }
734 for resource in mesh_resources(&mesh) {
735 self.add_resource(resource);
736 }
737 self.instances[change.index].mesh = mesh;
738 self.statistics()
739 }
740
741 pub(super) fn commit_dynamic_texture_change(&mut self, change: DynamicSceneMeshChange) {
742 if let Some(resources) = change.resources {
743 self.resources = resources;
744 }
745 for resource in change.outgoing {
746 self.remove_resource(resource.key);
747 }
748 for resource in mesh_resources(&self.instances[change.index].mesh) {
749 self.add_resource(resource);
750 }
751 }
752
753 pub fn visible_object_count(&self) -> usize {
756 self.visible_count
757 }
758
759 pub fn set_transform(
761 &mut self,
762 object_id: Object3dId,
763 transform: Transform3d,
764 ) -> Result<(), Scene3dError> {
765 validate_scene3d_transform(transform)?;
766 let instance = self.instance_mut(object_id)?;
767 instance.transform = transform;
768 Ok(())
769 }
770
771 pub fn set_style(
773 &mut self,
774 object_id: Object3dId,
775 style: MeshStyle3d,
776 ) -> Result<(), Scene3dError> {
777 let instance = self.instance_mut(object_id)?;
778 validate_mesh_style(&instance.mesh, style)?;
779 instance.style = style;
780 Ok(())
781 }
782
783 pub fn set_visible(
785 &mut self,
786 object_id: Object3dId,
787 visible: bool,
788 ) -> Result<(), Scene3dError> {
789 let index = self.instance_index(object_id)?;
790 let instance = &mut self.instances[index];
791 if instance.visible != visible {
792 if visible {
793 self.visible_count += 1;
794 } else {
795 self.visible_count -= 1;
796 }
797 instance.visible = visible;
798 }
799 Ok(())
800 }
801
802 pub fn set_wireframe(
804 &mut self,
805 object_id: Object3dId,
806 wireframe: Option<WireframeStyle3d>,
807 ) -> Result<(), Scene3dError> {
808 let instance = self.instance_mut(object_id)?;
809 let surface = instance.style.surface_style();
810 let style = match (surface, wireframe) {
811 (Some(surface), Some(wireframe)) => {
812 MeshStyle3d::surface(surface).with_wireframe(wireframe)
813 }
814 (Some(surface), None) => MeshStyle3d::surface(surface),
815 (None, Some(wireframe)) => MeshStyle3d::wireframe(wireframe),
816 (None, None) => return Err(Scene3dError::EmptyStyle),
817 };
818 validate_mesh_style(&instance.mesh, style)?;
819 instance.style = style;
820 Ok(())
821 }
822
823 fn instance_mut(&mut self, object_id: Object3dId) -> Result<&mut Mesh3dInstance, Scene3dError> {
824 let index = self.instance_index(object_id)?;
825 Ok(&mut self.instances[index])
826 }
827
828 fn instance_index(&self, object_id: Object3dId) -> Result<usize, Scene3dError> {
829 let index = (object_id.scene_id == self.scene_id)
830 .then_some(())
831 .and_then(|()| self.slots.get(object_id.slot))
832 .and_then(|slot| slot.dense_index)
833 .filter(|&index| {
834 self.instances
835 .get(index)
836 .is_some_and(|instance| instance.id == object_id)
837 });
838 index.ok_or(Scene3dError::ObjectNotFound { object_id })
839 }
840
841 fn validate_mesh_owner(&self, mesh: &RetainedMesh3d) -> Result<(), Scene3dError> {
842 if mesh
843 .material()
844 .is_some_and(|material| !material.texture().belongs_to(&mesh.renderer_identity))
845 {
846 return Err(Scene3dError::RendererMismatch);
847 }
848 if self
849 .renderer_identity
850 .as_ref()
851 .is_some_and(|identity| !Arc::ptr_eq(identity, &mesh.renderer_identity))
852 {
853 Err(Scene3dError::RendererMismatch)
854 } else {
855 Ok(())
856 }
857 }
858
859 fn missing_resources(&self, incoming: &[ResourceUsage]) -> usize {
860 incoming
861 .iter()
862 .filter(|r| {
863 r.bytes > 0
864 && self
865 .resources
866 .binary_search_by_key(&r.key, |r| r.key)
867 .is_err()
868 })
869 .count()
870 }
871
872 fn add_resource(&mut self, resource: ResourceUsage) {
873 if resource.bytes == 0 {
874 return;
875 }
876 match self
877 .resources
878 .binary_search_by_key(&resource.key, |r| r.key)
879 {
880 Ok(index) => self.resources[index].references += 1,
881 Err(index) => {
882 self.resources.insert(index, resource);
883 let category = resource.key.0 as usize;
884 self.resource_totals.bytes[category] += resource.bytes;
885 self.resource_totals.counts[category] += 1;
886 }
887 }
888 }
889
890 fn remove_resource(&mut self, key: (u8, usize)) {
891 if let Ok(index) = self.resources.binary_search_by_key(&key, |r| r.key) {
892 self.resources[index].references -= 1;
893 if self.resources[index].references == 0 {
894 let removed = self.resources.remove(index);
897 let category = removed.key.0 as usize;
898 self.resource_totals.bytes[category] -= removed.bytes;
899 self.resource_totals.counts[category] -= 1;
900 }
901 }
902 }
903
904 fn validate_resource_change(
905 &self,
906 incoming: &[ResourceUsage],
907 outgoing: Option<&[ResourceUsage]>,
908 ) -> Result<[usize; 4], Scene3dError> {
909 let mut bytes = self.resource_totals.bytes;
910 for resource in incoming {
911 if self
912 .resources
913 .binary_search_by_key(&resource.key, |r| r.key)
914 .is_err()
915 {
916 bytes[resource.key.0 as usize] =
917 bytes[resource.key.0 as usize].saturating_add(resource.bytes);
918 }
919 }
920 let peak = bytes;
921 for resource in outgoing.into_iter().flatten() {
922 if !incoming.iter().any(|r| r.key == resource.key)
923 && self
924 .resources
925 .binary_search_by_key(&resource.key, |r| r.key)
926 .ok()
927 .is_some_and(|i| self.resources[i].references == 1)
928 {
929 bytes[resource.key.0 as usize] -= resource.bytes;
930 }
931 }
932 check_scene_limit(
933 Scene3dBudgetResource::MeshCpuBytes,
934 self.budget.max_mesh_cpu_bytes,
935 bytes[0],
936 )?;
937 check_scene_limit(
938 Scene3dBudgetResource::MeshGpuBytes,
939 self.budget.max_mesh_gpu_bytes,
940 bytes[1],
941 )?;
942 check_scene_limit(
943 Scene3dBudgetResource::TextureCpuBytes,
944 self.budget.max_texture_cpu_bytes,
945 bytes[2],
946 )?;
947 check_scene_limit(
948 Scene3dBudgetResource::TextureGpuBytes,
949 self.budget.max_texture_gpu_bytes,
950 bytes[3],
951 )?;
952 Ok(peak)
953 }
954
955 fn reserve_storage(
956 &mut self,
957 instances: usize,
958 slots: usize,
959 resources: usize,
960 ) -> Result<(), Scene3dError> {
961 let mut capacities = [
962 planned_capacity(&self.instances, instances, self.budget.max_objects),
963 planned_capacity(&self.slots, slots, self.budget.max_objects),
964 planned_capacity(
965 &self.resources,
966 resources,
967 self.budget.max_objects.saturating_mul(4),
968 ),
969 ];
970 if storage_bytes(capacities[0], capacities[1], capacities[2])
971 > self.budget.max_storage_bytes
972 {
973 capacities = [
974 self.instances
975 .capacity()
976 .max(self.instances.len().saturating_add(instances)),
977 self.slots
978 .capacity()
979 .max(self.slots.len().saturating_add(slots)),
980 self.resources
981 .capacity()
982 .max(self.resources.len().saturating_add(resources)),
983 ];
984 }
985 let planned_bytes = storage_bytes(capacities[0], capacities[1], capacities[2]);
986 check_scene_limit(
987 Scene3dBudgetResource::StorageBytes,
988 self.budget.max_storage_bytes,
989 planned_bytes,
990 )?;
991 let new_instances = replacement_capacity(&self.instances, capacities[0])?;
992 let new_slots = replacement_capacity(&self.slots, capacities[1])?;
993 let new_resources = replacement_capacity(&self.resources, capacities[2])?;
994 let bytes = storage_bytes(
995 new_instances
996 .as_ref()
997 .map_or(self.instances.capacity(), Vec::capacity),
998 new_slots
999 .as_ref()
1000 .map_or(self.slots.capacity(), Vec::capacity),
1001 new_resources
1002 .as_ref()
1003 .map_or(self.resources.capacity(), Vec::capacity),
1004 );
1005 check_scene_limit(
1006 Scene3dBudgetResource::StorageBytes,
1007 self.budget.max_storage_bytes,
1008 bytes,
1009 )?;
1010 if let Some(values) = new_instances {
1011 self.instances = values;
1012 }
1013 if let Some(values) = new_slots {
1014 self.slots = values;
1015 }
1016 if let Some(values) = new_resources {
1017 self.resources = values;
1018 }
1019 Ok(())
1020 }
1021
1022 pub(super) fn rebuild_resource_keys(&mut self) {
1023 self.resources.clear();
1027 self.resource_totals = ResourceTotals::default();
1028 self.visible_count = 0;
1029 for index in 0..self.instances.len() {
1030 for resource in mesh_resources(&self.instances[index].mesh) {
1031 self.add_resource(resource);
1032 }
1033 if self.instances[index].visible {
1034 self.visible_count += 1;
1035 }
1036 }
1037 }
1038}
1039
1040fn mesh_resources(mesh: &RetainedMesh3d) -> [ResourceUsage; 4] {
1041 [
1042 ResourceUsage {
1043 key: (0, mesh.source.vertices().as_ptr() as usize),
1044 references: 1,
1045 bytes: mesh.recovery_memory_bytes(),
1046 },
1047 ResourceUsage {
1048 key: (1, Arc::as_ptr(&mesh.vertex_buffer) as usize),
1049 references: 1,
1050 bytes: mesh.gpu_allocation_bytes(),
1051 },
1052 ResourceUsage {
1053 key: (
1054 2,
1055 mesh.material()
1056 .map_or(0, |material| material.texture().identity_key()),
1057 ),
1058 references: 1,
1059 bytes: mesh
1060 .material()
1061 .map_or(0, |material| material.texture().recovery_memory_bytes()),
1062 },
1063 ResourceUsage {
1064 key: (
1065 3,
1066 mesh.material()
1067 .map_or(0, |material| material.texture().identity_key()),
1068 ),
1069 references: 1,
1070 bytes: mesh
1071 .material()
1072 .map_or(0, |material| material.texture().gpu_allocation_bytes()),
1073 },
1074 ]
1075}
1076
1077fn check_scene_limit(
1078 resource: Scene3dBudgetResource,
1079 limit: usize,
1080 actual: usize,
1081) -> Result<(), Scene3dError> {
1082 if actual > limit {
1083 Err(Scene3dError::BudgetExceeded {
1084 resource,
1085 limit,
1086 actual,
1087 })
1088 } else {
1089 Ok(())
1090 }
1091}
1092
1093fn storage_bytes(instances: usize, slots: usize, resources: usize) -> usize {
1094 instances
1095 .saturating_mul(std::mem::size_of::<Mesh3dInstance>())
1096 .saturating_add(slots.saturating_mul(std::mem::size_of::<ObjectSlot>()))
1097 .saturating_add(resources.saturating_mul(std::mem::size_of::<ResourceUsage>()))
1098}
1099
1100fn replacement_capacity<T: Clone>(
1101 current: &Vec<T>,
1102 capacity: usize,
1103) -> Result<Option<Vec<T>>, Scene3dError> {
1104 if capacity <= current.capacity() {
1105 return Ok(None);
1106 }
1107 let mut values = Vec::new();
1108 values
1109 .try_reserve_exact(capacity)
1110 .map_err(|_| Scene3dError::AllocationFailed {
1111 requested_bytes: capacity.saturating_mul(std::mem::size_of::<T>()),
1112 })?;
1113 values.extend_from_slice(current);
1114 Ok(Some(values))
1115}
1116
1117fn planned_capacity<T>(current: &Vec<T>, additional: usize, maximum: usize) -> usize {
1118 let needed = current.len().saturating_add(additional);
1119 if needed <= current.capacity() {
1120 current.capacity()
1121 } else {
1122 needed
1123 .max(current.capacity().saturating_mul(2))
1124 .min(maximum)
1125 }
1126}
1127
1128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1130pub enum Scene3dError {
1131 Texture(Texture3dError),
1133 MissingNormals,
1135 InvalidBudget,
1137 RendererMismatch,
1139 BudgetExceeded {
1141 resource: Scene3dBudgetResource,
1143 limit: usize,
1145 actual: usize,
1147 },
1148 InvalidBackground,
1150 EmptyStyle,
1152 StyleHasNoMatchingGeometry,
1154 InvalidTransform,
1156 SceneIdExhausted,
1158 ObjectIdExhausted,
1160 AllocationFailed {
1162 requested_bytes: usize,
1164 },
1165 ObjectNotFound {
1167 object_id: Object3dId,
1169 },
1170}
1171
1172impl fmt::Display for Scene3dError {
1173 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
1174 match self {
1175 Self::Texture(error) => write!(formatter, "3D scene material: {error}"),
1176 Self::MissingNormals => write!(
1177 formatter,
1178 "Lambert surface requires application-supplied model normals"
1179 ),
1180 Self::InvalidBudget => write!(formatter, "3D scene budget limits must be nonzero"),
1181 Self::RendererMismatch => {
1182 write!(formatter, "3D mesh belongs to another renderer generation")
1183 }
1184 Self::BudgetExceeded {
1185 resource,
1186 limit,
1187 actual,
1188 } => write!(
1189 formatter,
1190 "3D scene {resource:?} budget exceeded: {actual} > {limit}"
1191 ),
1192 Self::InvalidBackground => write!(
1193 formatter,
1194 "3D scene background must be normalized; legacy constructors also require opaque alpha"
1195 ),
1196 Self::EmptyStyle => write!(formatter, "3D object requires a surface or wireframe"),
1197 Self::StyleHasNoMatchingGeometry => write!(
1198 formatter,
1199 "3D object style has no matching triangles or display edges"
1200 ),
1201 Self::InvalidTransform => {
1202 write!(
1203 formatter,
1204 "3D model transform is outside the portable shader envelope"
1205 )
1206 }
1207 Self::SceneIdExhausted => write!(formatter, "3D scene identifiers exhausted"),
1208 Self::ObjectIdExhausted => write!(formatter, "3D scene object identifiers exhausted"),
1209 Self::AllocationFailed { requested_bytes } => write!(
1210 formatter,
1211 "could not reserve {requested_bytes} bytes for another 3D scene object"
1212 ),
1213 Self::ObjectNotFound { object_id } => write!(
1214 formatter,
1215 "3D scene object {} does not exist in this scene",
1216 object_id.get()
1217 ),
1218 }
1219 }
1220}
1221
1222impl Error for Scene3dError {
1223 fn source(&self) -> Option<&(dyn Error + 'static)> {
1224 match self {
1225 Self::Texture(error) => Some(error),
1226 _ => None,
1227 }
1228 }
1229}