Skip to main content

sim_engine/renderer/
mesh3d_objects.rs

1//! Stable object addressing and bounded scene lifetime.
2
3use super::*;
4
5/// Stable scene handle for a retained 3D object.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
7pub struct Object3dId {
8    pub(super) scene_id: u64,
9    pub(super) object_id: u64,
10    slot: usize,
11}
12
13impl Object3dId {
14    /// Returns the stable scene-local numeric value for diagnostics.
15    ///
16    /// Equality and hashing also include private scene provenance. Store the
17    /// complete handle, rather than only this number, in host object maps.
18    pub const fn get(self) -> u64 {
19        self.object_id
20    }
21}
22
23/// One retained mesh reference plus its independent model transform and style.
24#[derive(Clone)]
25pub struct Mesh3dInstance {
26    pub(super) id: Object3dId,
27    pub(super) mesh: RetainedMesh3d,
28    pub(super) transform: Transform3d,
29    pub(super) style: MeshStyle3d,
30    pub(super) visible: bool,
31}
32
33impl Mesh3dInstance {
34    fn new(
35        id: Object3dId,
36        mesh: &RetainedMesh3d,
37        transform: Transform3d,
38        style: MeshStyle3d,
39    ) -> Self {
40        Self {
41            id,
42            mesh: mesh.clone(),
43            transform,
44            style,
45            visible: true,
46        }
47    }
48
49    /// Returns the stable scene object identifier.
50    pub const fn id(&self) -> Object3dId {
51        self.id
52    }
53
54    /// Returns the retained GPU mesh reference.
55    pub const fn mesh(&self) -> &RetainedMesh3d {
56        &self.mesh
57    }
58
59    /// Returns this object's model-to-world transform.
60    pub const fn transform(&self) -> Transform3d {
61        self.transform
62    }
63
64    /// Returns its extensible surface/edge material bundle.
65    pub const fn style(&self) -> MeshStyle3d {
66        self.style
67    }
68
69    /// Returns whether this object participates in drawing and render counts.
70    pub const fn is_visible(&self) -> bool {
71        self.visible
72    }
73
74    /// Returns explicit edge presentation when enabled for this object.
75    pub const fn wireframe(&self) -> Option<WireframeStyle3d> {
76        self.style.wireframe_style()
77    }
78}
79
80/// Ready 3D visual state rendered with one camera and depth attachment.
81pub struct Scene3d {
82    pub(super) scene_id: u64,
83    pub(super) background: Color,
84    pub(super) instances: Vec<Mesh3dInstance>,
85    pub(super) next_object_id: u64,
86    pub(super) renderer_identity: Option<Arc<()>>,
87    slots: Vec<ObjectSlot>,
88    free_slot: Option<usize>,
89    resources: Vec<ResourceUsage>,
90    budget: Scene3dBudget,
91}
92
93#[derive(Clone)]
94struct ObjectSlot {
95    dense_index: Option<usize>,
96    next_free: Option<usize>,
97}
98
99#[derive(Clone)]
100struct ResourceUsage {
101    key: (u8, usize),
102    references: usize,
103    bytes: usize,
104}
105
106/// Bounds scene-owned slots and distinct retained mesh allocations.
107///
108/// Object storage includes dense instances, reusable lookup slots and resource
109/// accounting. Mesh CPU/GPU bytes are deduplicated by allocation identity. Host
110/// references outside this scene and in-flight driver allocations are excluded.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub struct Scene3dBudget {
113    max_objects: usize,
114    max_storage_bytes: usize,
115    max_mesh_cpu_bytes: usize,
116    max_mesh_gpu_bytes: usize,
117    max_texture_cpu_bytes: usize,
118    max_texture_gpu_bytes: usize,
119}
120
121impl Scene3dBudget {
122    /// Creates nonzero object, storage, recovery-topology and GPU-buffer limits.
123    pub fn new(
124        max_objects: usize,
125        max_storage_bytes: usize,
126        max_mesh_cpu_bytes: usize,
127        max_mesh_gpu_bytes: usize,
128    ) -> Result<Self, Scene3dError> {
129        if [
130            max_objects,
131            max_storage_bytes,
132            max_mesh_cpu_bytes,
133            max_mesh_gpu_bytes,
134        ]
135        .contains(&0)
136        {
137            return Err(Scene3dError::InvalidBudget);
138        }
139        Ok(Self {
140            max_objects,
141            max_storage_bytes,
142            max_mesh_cpu_bytes,
143            max_mesh_gpu_bytes,
144            max_texture_cpu_bytes: 64 * 1024 * 1024,
145            max_texture_gpu_bytes: 64 * 1024 * 1024,
146        })
147    }
148    /// Maximum simultaneous live objects; removed lookup slots can be reused.
149    pub const fn max_objects(self) -> usize {
150        self.max_objects
151    }
152    /// Maximum retained CPU bookkeeping capacity in bytes.
153    pub const fn max_storage_bytes(self) -> usize {
154        self.max_storage_bytes
155    }
156    /// Maximum distinct source topology capacity in bytes.
157    pub const fn max_mesh_cpu_bytes(self) -> usize {
158        self.max_mesh_cpu_bytes
159    }
160    /// Maximum distinct mesh buffer bytes referenced by the scene.
161    pub const fn max_mesh_gpu_bytes(self) -> usize {
162        self.max_mesh_gpu_bytes
163    }
164    /// Sets deduplicated texture recovery/GPU texel limits; zero prohibits
165    /// textured resources. Mesh and bookkeeping limits remain independent.
166    pub const fn with_texture_limits(mut self, cpu_bytes: usize, gpu_bytes: usize) -> Self {
167        self.max_texture_cpu_bytes = cpu_bytes;
168        self.max_texture_gpu_bytes = gpu_bytes;
169        self
170    }
171    /// Maximum distinct retained texture-pixel capacity in bytes.
172    pub const fn max_texture_cpu_bytes(self) -> usize {
173        self.max_texture_cpu_bytes
174    }
175    /// Maximum distinct nominal GPU texture texel bytes.
176    pub const fn max_texture_gpu_bytes(self) -> usize {
177        self.max_texture_gpu_bytes
178    }
179}
180
181impl Default for Scene3dBudget {
182    fn default() -> Self {
183        Self {
184            max_objects: 65_536,
185            max_storage_bytes: 64 * 1024 * 1024,
186            max_mesh_cpu_bytes: 256 * 1024 * 1024,
187            max_mesh_gpu_bytes: 256 * 1024 * 1024,
188            max_texture_cpu_bytes: 64 * 1024 * 1024,
189            max_texture_gpu_bytes: 64 * 1024 * 1024,
190        }
191    }
192}
193
194/// Bounded scene resource whose limit rejected a mutation.
195#[derive(Debug, Clone, Copy, PartialEq, Eq)]
196pub enum Scene3dBudgetResource {
197    /// Distinct retained CPU texture-pixel capacities.
198    TextureCpuBytes,
199    /// Distinct nominal GPU texture texel-storage bytes.
200    TextureGpuBytes,
201    /// Simultaneously live object count.
202    Objects,
203    /// Dense instances, lookup slots and allocation-accounting storage.
204    StorageBytes,
205    /// Distinct retained source topology bytes.
206    MeshCpuBytes,
207    /// Distinct retained GPU mesh buffer bytes.
208    MeshGpuBytes,
209}
210
211/// Current scene-owned capacities and unique mesh allocations, excluding drivers.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213pub struct Scene3dStatistics {
214    object_count: usize,
215    slot_capacity: usize,
216    storage_bytes: usize,
217    mesh_count: usize,
218    mesh_cpu_bytes: usize,
219    mesh_gpu_bytes: usize,
220    texture_count: usize,
221    texture_cpu_bytes: usize,
222    texture_gpu_bytes: usize,
223}
224
225impl Scene3dStatistics {
226    /// Distinct shared textures referenced by live objects, including hidden ones.
227    pub const fn texture_count(self) -> usize {
228        self.texture_count
229    }
230    /// Unique retained texture-pixel capacity, excluding fixed binding metadata.
231    pub const fn texture_cpu_bytes(self) -> usize {
232        self.texture_cpu_bytes
233    }
234    /// Unique nominal GPU texel storage, excluding driver overhead.
235    pub const fn texture_gpu_bytes(self) -> usize {
236        self.texture_gpu_bytes
237    }
238    /// Number of live objects, including hidden ones.
239    pub const fn object_count(self) -> usize {
240        self.object_count
241    }
242    /// Retained lookup-slot capacity, reused after removals.
243    pub const fn slot_capacity(self) -> usize {
244        self.slot_capacity
245    }
246    /// CPU bookkeeping capacity; does not include source topology.
247    pub const fn storage_bytes(self) -> usize {
248        self.storage_bytes
249    }
250    /// Distinct retained GPU meshes, not the number of references.
251    pub const fn mesh_count(self) -> usize {
252        self.mesh_count
253    }
254    /// Unique source topology bytes; two GPU uploads of one source count once.
255    pub const fn mesh_cpu_bytes(self) -> usize {
256        self.mesh_cpu_bytes
257    }
258    /// Unique GPU buffer bytes; excludes opaque driver/in-flight allocations.
259    pub const fn mesh_gpu_bytes(self) -> usize {
260        self.mesh_gpu_bytes
261    }
262}
263
264/// Accounting for an immutable mesh rebinding, including old/new overlap.
265#[derive(Debug, Clone, Copy, PartialEq, Eq)]
266pub struct Scene3dMeshUpdateReport {
267    statistics: Scene3dStatistics,
268    peak_mesh_cpu_bytes: usize,
269    peak_mesh_gpu_bytes: usize,
270    peak_texture_cpu_bytes: usize,
271    peak_texture_gpu_bytes: usize,
272}
273
274impl Scene3dMeshUpdateReport {
275    /// Unique old-plus-new texture-pixel capacity during rebinding.
276    pub const fn peak_texture_cpu_bytes(self) -> usize {
277        self.peak_texture_cpu_bytes
278    }
279    /// Unique old-plus-new GPU texel bytes during rebinding, not driver retirement.
280    pub const fn peak_texture_gpu_bytes(self) -> usize {
281        self.peak_texture_gpu_bytes
282    }
283    /// Accepted scene capacities and unique resource bytes.
284    pub const fn statistics(self) -> Scene3dStatistics {
285        self.statistics
286    }
287    /// Unique old-plus-new topology bytes during the rebind.
288    pub const fn peak_mesh_cpu_bytes(self) -> usize {
289        self.peak_mesh_cpu_bytes
290    }
291    /// Unique old-plus-new buffer bytes during the rebind, not driver retirement.
292    pub const fn peak_mesh_gpu_bytes(self) -> usize {
293        self.peak_mesh_gpu_bytes
294    }
295}
296
297impl Scene3d {
298    /// Creates an empty scene with a normalized opaque clear color.
299    pub fn new(background: Color) -> Result<Self, Scene3dError> {
300        Self::with_budget(background, Scene3dBudget::default())
301    }
302
303    /// Creates a lazily allocated scene with explicit live-resource limits.
304    pub fn with_budget(background: Color, budget: Scene3dBudget) -> Result<Self, Scene3dError> {
305        if !background.is_normalized() || background.alpha() != 1.0 {
306            return Err(Scene3dError::InvalidBackground);
307        }
308        let scene_id = NEXT_SCENE3D_ID
309            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |current| {
310                current.checked_add(1)
311            })
312            .map_err(|_| Scene3dError::SceneIdExhausted)?;
313        Ok(Self {
314            scene_id,
315            background,
316            instances: Vec::new(),
317            next_object_id: 0,
318            renderer_identity: None,
319            slots: Vec::new(),
320            free_slot: None,
321            resources: Vec::new(),
322            budget,
323        })
324    }
325
326    /// Adds a retained object and returns a stable handle for later updates.
327    pub fn try_push(
328        &mut self,
329        mesh: &RetainedMesh3d,
330        transform: Transform3d,
331        style: MeshStyle3d,
332    ) -> Result<Object3dId, Scene3dError> {
333        validate_mesh_style(mesh, style)?;
334        validate_scene3d_transform(transform)?;
335        self.validate_mesh_owner(mesh)?;
336        check_scene_limit(
337            Scene3dBudgetResource::Objects,
338            self.budget.max_objects,
339            self.instances.len().saturating_add(1),
340        )?;
341        let next_object_id = self
342            .next_object_id
343            .checked_add(1)
344            .ok_or(Scene3dError::ObjectIdExhausted)?;
345        let keys = mesh_resources(mesh);
346        self.validate_resource_change(&keys, None)?;
347        self.reserve_storage(
348            1,
349            usize::from(self.free_slot.is_none()),
350            self.missing_resources(&keys),
351        )?;
352        let slot = self.free_slot.unwrap_or(self.slots.len());
353        let id = Object3dId {
354            scene_id: self.scene_id,
355            object_id: self.next_object_id,
356            slot,
357        };
358        if let Some(free) = self.free_slot {
359            self.free_slot = self.slots[free].next_free;
360            self.slots[free] = ObjectSlot {
361                dense_index: Some(self.instances.len()),
362                next_free: None,
363            };
364        } else {
365            self.slots.push(ObjectSlot {
366                dense_index: Some(self.instances.len()),
367                next_free: None,
368            });
369        }
370        for resource in keys {
371            self.add_resource(resource);
372        }
373        self.renderer_identity = Some(Arc::clone(&mesh.renderer_identity));
374        self.instances
375            .push(Mesh3dInstance::new(id, mesh, transform, style));
376        self.next_object_id = next_object_id;
377        Ok(id)
378    }
379
380    /// Returns the normalized finite opaque target clear color.
381    pub const fn background(&self) -> Color {
382        self.background
383    }
384
385    /// Returns objects in host insertion order; depth determines visibility.
386    pub fn instances(&self) -> &[Mesh3dInstance] {
387        &self.instances
388    }
389
390    /// Returns the number of independently transformed objects.
391    pub fn object_count(&self) -> usize {
392        self.instances.len()
393    }
394
395    /// Returns the configured simultaneous-live and retained-capacity limits.
396    pub const fn budget(&self) -> Scene3dBudget {
397        self.budget
398    }
399
400    /// Returns deduplicated allocation accounting without allocating scratch.
401    pub fn statistics(&self) -> Scene3dStatistics {
402        Scene3dStatistics {
403            texture_count: self.resources.iter().filter(|r| r.key.0 == 3).count(),
404            texture_cpu_bytes: self
405                .resources
406                .iter()
407                .filter(|r| r.key.0 == 2)
408                .map(|r| r.bytes)
409                .sum(),
410            texture_gpu_bytes: self
411                .resources
412                .iter()
413                .filter(|r| r.key.0 == 3)
414                .map(|r| r.bytes)
415                .sum(),
416            object_count: self.instances.len(),
417            slot_capacity: self.slots.capacity(),
418            storage_bytes: storage_bytes(
419                self.instances.capacity(),
420                self.slots.capacity(),
421                self.resources.capacity(),
422            ),
423            mesh_count: self.resources.iter().filter(|r| r.key.0 == 1).count(),
424            mesh_cpu_bytes: self
425                .resources
426                .iter()
427                .filter(|r| r.key.0 == 0)
428                .map(|r| r.bytes)
429                .sum(),
430            mesh_gpu_bytes: self
431                .resources
432                .iter()
433                .filter(|r| r.key.0 == 1)
434                .map(|r| r.bytes)
435                .sum(),
436        }
437    }
438
439    /// Resolves a live scene-provenance-checked handle in constant time.
440    pub fn instance(&self, object_id: Object3dId) -> Result<&Mesh3dInstance, Scene3dError> {
441        let index = self.instance_index(object_id)?;
442        Ok(&self.instances[index])
443    }
444
445    /// Removes an object, preserving survivor IDs and insertion order.
446    ///
447    /// Removal shifts dense storage in O(N); transform/style/visibility lookups
448    /// remain O(1). Lookup slots are reused with never-repeated numeric IDs.
449    /// The returned instance owns its retired mesh reference. Dropping it releases
450    /// that reference, not necessarily in-flight driver memory.
451    pub fn remove(&mut self, object_id: Object3dId) -> Result<Mesh3dInstance, Scene3dError> {
452        let index = self.instance_index(object_id)?;
453        let removed = self.instances.remove(index);
454        for instance in &self.instances[index..] {
455            if let Some(dense) = &mut self.slots[instance.id.slot].dense_index {
456                *dense -= 1;
457            }
458        }
459        self.slots[object_id.slot] = ObjectSlot {
460            dense_index: None,
461            next_free: self.free_slot,
462        };
463        self.free_slot = Some(object_id.slot);
464        for resource in mesh_resources(&removed.mesh) {
465            self.remove_resource(resource.key);
466        }
467        Ok(removed)
468    }
469
470    /// Rebinds only this object to an immutable mesh after complete validation.
471    ///
472    /// Shared users of the old mesh are unchanged. Transform, style, visibility
473    /// and ID survive. The accepted resource limits apply to final scene state;
474    /// replacement overlap is at most old plus incoming mesh and is reported.
475    /// Synchronous errors preserve all live visual state. In-flight submissions
476    /// retain their old GPU references; no immediate driver retirement is promised.
477    pub fn set_mesh(
478        &mut self,
479        object_id: Object3dId,
480        mesh: &RetainedMesh3d,
481    ) -> Result<Scene3dMeshUpdateReport, Scene3dError> {
482        let index = self.instance_index(object_id)?;
483        self.validate_mesh_owner(mesh)?;
484        validate_mesh_style(mesh, self.instances[index].style)?;
485        let incoming = mesh_resources(mesh);
486        let outgoing = mesh_resources(&self.instances[index].mesh);
487        let [
488            peak_mesh_cpu_bytes,
489            peak_mesh_gpu_bytes,
490            peak_texture_cpu_bytes,
491            peak_texture_gpu_bytes,
492        ] = self.validate_resource_change(&incoming, Some(&outgoing))?;
493        let removed_keys = outgoing
494            .iter()
495            .filter(|resource| {
496                !incoming.iter().any(|r| r.key == resource.key)
497                    && self
498                        .resources
499                        .binary_search_by_key(&resource.key, |r| r.key)
500                        .ok()
501                        .is_some_and(|i| self.resources[i].references == 1)
502            })
503            .count();
504        self.reserve_storage(
505            0,
506            0,
507            self.missing_resources(&incoming)
508                .saturating_sub(removed_keys),
509        )?;
510        for resource in outgoing {
511            self.remove_resource(resource.key);
512        }
513        for resource in incoming {
514            self.add_resource(resource);
515        }
516        self.instances[index].mesh = mesh.clone();
517        Ok(Scene3dMeshUpdateReport {
518            statistics: self.statistics(),
519            peak_mesh_cpu_bytes,
520            peak_mesh_gpu_bytes,
521            peak_texture_cpu_bytes,
522            peak_texture_gpu_bytes,
523        })
524    }
525
526    /// Returns objects currently participating in rendering.
527    pub fn visible_object_count(&self) -> usize {
528        self.instances
529            .iter()
530            .filter(|instance| instance.visible)
531            .count()
532    }
533
534    /// Replaces one object's model transform without touching retained topology.
535    pub fn set_transform(
536        &mut self,
537        object_id: Object3dId,
538        transform: Transform3d,
539    ) -> Result<(), Scene3dError> {
540        validate_scene3d_transform(transform)?;
541        let instance = self.instance_mut(object_id)?;
542        instance.transform = transform;
543        Ok(())
544    }
545
546    /// Replaces one object's complete extensible visual material bundle.
547    pub fn set_style(
548        &mut self,
549        object_id: Object3dId,
550        style: MeshStyle3d,
551    ) -> Result<(), Scene3dError> {
552        let instance = self.instance_mut(object_id)?;
553        validate_mesh_style(&instance.mesh, style)?;
554        instance.style = style;
555        Ok(())
556    }
557
558    /// Shows or hides one object without releasing retained topology.
559    pub fn set_visible(
560        &mut self,
561        object_id: Object3dId,
562        visible: bool,
563    ) -> Result<(), Scene3dError> {
564        let instance = self.instance_mut(object_id)?;
565        instance.visible = visible;
566        Ok(())
567    }
568
569    /// Enables or disables explicit visible/hidden edges for one object.
570    pub fn set_wireframe(
571        &mut self,
572        object_id: Object3dId,
573        wireframe: Option<WireframeStyle3d>,
574    ) -> Result<(), Scene3dError> {
575        let instance = self.instance_mut(object_id)?;
576        let surface = instance.style.surface_style();
577        let style = match (surface, wireframe) {
578            (Some(surface), Some(wireframe)) => {
579                MeshStyle3d::surface(surface).with_wireframe(wireframe)
580            }
581            (Some(surface), None) => MeshStyle3d::surface(surface),
582            (None, Some(wireframe)) => MeshStyle3d::wireframe(wireframe),
583            (None, None) => return Err(Scene3dError::EmptyStyle),
584        };
585        validate_mesh_style(&instance.mesh, style)?;
586        instance.style = style;
587        Ok(())
588    }
589
590    fn instance_mut(&mut self, object_id: Object3dId) -> Result<&mut Mesh3dInstance, Scene3dError> {
591        let index = self.instance_index(object_id)?;
592        Ok(&mut self.instances[index])
593    }
594
595    fn instance_index(&self, object_id: Object3dId) -> Result<usize, Scene3dError> {
596        let index = (object_id.scene_id == self.scene_id)
597            .then_some(())
598            .and_then(|()| self.slots.get(object_id.slot))
599            .and_then(|slot| slot.dense_index)
600            .filter(|&index| {
601                self.instances
602                    .get(index)
603                    .is_some_and(|instance| instance.id == object_id)
604            });
605        index.ok_or(Scene3dError::ObjectNotFound { object_id })
606    }
607
608    fn validate_mesh_owner(&self, mesh: &RetainedMesh3d) -> Result<(), Scene3dError> {
609        if mesh
610            .material()
611            .is_some_and(|material| !material.texture().belongs_to(&mesh.renderer_identity))
612        {
613            return Err(Scene3dError::RendererMismatch);
614        }
615        if self
616            .renderer_identity
617            .as_ref()
618            .is_some_and(|identity| !Arc::ptr_eq(identity, &mesh.renderer_identity))
619        {
620            Err(Scene3dError::RendererMismatch)
621        } else {
622            Ok(())
623        }
624    }
625
626    fn missing_resources(&self, incoming: &[ResourceUsage]) -> usize {
627        incoming
628            .iter()
629            .filter(|r| {
630                r.bytes > 0
631                    && self
632                        .resources
633                        .binary_search_by_key(&r.key, |r| r.key)
634                        .is_err()
635            })
636            .count()
637    }
638
639    fn add_resource(&mut self, resource: ResourceUsage) {
640        if resource.bytes == 0 {
641            return;
642        }
643        match self
644            .resources
645            .binary_search_by_key(&resource.key, |r| r.key)
646        {
647            Ok(index) => self.resources[index].references += 1,
648            Err(index) => self.resources.insert(index, resource),
649        }
650    }
651
652    fn remove_resource(&mut self, key: (u8, usize)) {
653        if let Ok(index) = self.resources.binary_search_by_key(&key, |r| r.key) {
654            self.resources[index].references -= 1;
655            if self.resources[index].references == 0 {
656                self.resources.remove(index);
657            }
658        }
659    }
660
661    fn validate_resource_change(
662        &self,
663        incoming: &[ResourceUsage],
664        outgoing: Option<&[ResourceUsage]>,
665    ) -> Result<[usize; 4], Scene3dError> {
666        let stats = self.statistics();
667        let mut bytes = [
668            stats.mesh_cpu_bytes,
669            stats.mesh_gpu_bytes,
670            stats.texture_cpu_bytes,
671            stats.texture_gpu_bytes,
672        ];
673        for resource in incoming {
674            if self
675                .resources
676                .binary_search_by_key(&resource.key, |r| r.key)
677                .is_err()
678            {
679                bytes[resource.key.0 as usize] =
680                    bytes[resource.key.0 as usize].saturating_add(resource.bytes);
681            }
682        }
683        let peak = bytes;
684        for resource in outgoing.into_iter().flatten() {
685            if !incoming.iter().any(|r| r.key == resource.key)
686                && self
687                    .resources
688                    .binary_search_by_key(&resource.key, |r| r.key)
689                    .ok()
690                    .is_some_and(|i| self.resources[i].references == 1)
691            {
692                bytes[resource.key.0 as usize] -= resource.bytes;
693            }
694        }
695        check_scene_limit(
696            Scene3dBudgetResource::MeshCpuBytes,
697            self.budget.max_mesh_cpu_bytes,
698            bytes[0],
699        )?;
700        check_scene_limit(
701            Scene3dBudgetResource::MeshGpuBytes,
702            self.budget.max_mesh_gpu_bytes,
703            bytes[1],
704        )?;
705        check_scene_limit(
706            Scene3dBudgetResource::TextureCpuBytes,
707            self.budget.max_texture_cpu_bytes,
708            bytes[2],
709        )?;
710        check_scene_limit(
711            Scene3dBudgetResource::TextureGpuBytes,
712            self.budget.max_texture_gpu_bytes,
713            bytes[3],
714        )?;
715        Ok(peak)
716    }
717
718    fn reserve_storage(
719        &mut self,
720        instances: usize,
721        slots: usize,
722        resources: usize,
723    ) -> Result<(), Scene3dError> {
724        let mut capacities = [
725            planned_capacity(&self.instances, instances, self.budget.max_objects),
726            planned_capacity(&self.slots, slots, self.budget.max_objects),
727            planned_capacity(
728                &self.resources,
729                resources,
730                self.budget.max_objects.saturating_mul(4),
731            ),
732        ];
733        if storage_bytes(capacities[0], capacities[1], capacities[2])
734            > self.budget.max_storage_bytes
735        {
736            capacities = [
737                self.instances
738                    .capacity()
739                    .max(self.instances.len().saturating_add(instances)),
740                self.slots
741                    .capacity()
742                    .max(self.slots.len().saturating_add(slots)),
743                self.resources
744                    .capacity()
745                    .max(self.resources.len().saturating_add(resources)),
746            ];
747        }
748        let planned_bytes = storage_bytes(capacities[0], capacities[1], capacities[2]);
749        check_scene_limit(
750            Scene3dBudgetResource::StorageBytes,
751            self.budget.max_storage_bytes,
752            planned_bytes,
753        )?;
754        let new_instances = replacement_capacity(&self.instances, capacities[0])?;
755        let new_slots = replacement_capacity(&self.slots, capacities[1])?;
756        let new_resources = replacement_capacity(&self.resources, capacities[2])?;
757        let bytes = storage_bytes(
758            new_instances
759                .as_ref()
760                .map_or(self.instances.capacity(), Vec::capacity),
761            new_slots
762                .as_ref()
763                .map_or(self.slots.capacity(), Vec::capacity),
764            new_resources
765                .as_ref()
766                .map_or(self.resources.capacity(), Vec::capacity),
767        );
768        check_scene_limit(
769            Scene3dBudgetResource::StorageBytes,
770            self.budget.max_storage_bytes,
771            bytes,
772        )?;
773        if let Some(values) = new_instances {
774            self.instances = values;
775        }
776        if let Some(values) = new_slots {
777            self.slots = values;
778        }
779        if let Some(values) = new_resources {
780            self.resources = values;
781        }
782        Ok(())
783    }
784
785    pub(super) fn rebuild_resource_keys(&mut self) {
786        // Recovery preserves topology sharing and distinct mesh count, so the
787        // existing table capacity suffices. New GPU allocation identities replace
788        // old keys only after the complete recovery candidate has been accepted.
789        self.resources.clear();
790        for index in 0..self.instances.len() {
791            for resource in mesh_resources(&self.instances[index].mesh) {
792                self.add_resource(resource);
793            }
794        }
795    }
796}
797
798fn mesh_resources(mesh: &RetainedMesh3d) -> [ResourceUsage; 4] {
799    [
800        ResourceUsage {
801            key: (0, mesh.source.vertices().as_ptr() as usize),
802            references: 1,
803            bytes: mesh.recovery_memory_bytes(),
804        },
805        ResourceUsage {
806            key: (1, Arc::as_ptr(&mesh.vertex_buffer) as usize),
807            references: 1,
808            bytes: mesh.gpu_allocation_bytes(),
809        },
810        ResourceUsage {
811            key: (
812                2,
813                mesh.material()
814                    .map_or(0, |material| material.texture().identity_key()),
815            ),
816            references: 1,
817            bytes: mesh
818                .material()
819                .map_or(0, |material| material.texture().recovery_memory_bytes()),
820        },
821        ResourceUsage {
822            key: (
823                3,
824                mesh.material()
825                    .map_or(0, |material| material.texture().identity_key()),
826            ),
827            references: 1,
828            bytes: mesh
829                .material()
830                .map_or(0, |material| material.texture().gpu_allocation_bytes()),
831        },
832    ]
833}
834
835fn check_scene_limit(
836    resource: Scene3dBudgetResource,
837    limit: usize,
838    actual: usize,
839) -> Result<(), Scene3dError> {
840    if actual > limit {
841        Err(Scene3dError::BudgetExceeded {
842            resource,
843            limit,
844            actual,
845        })
846    } else {
847        Ok(())
848    }
849}
850
851fn storage_bytes(instances: usize, slots: usize, resources: usize) -> usize {
852    instances
853        .saturating_mul(std::mem::size_of::<Mesh3dInstance>())
854        .saturating_add(slots.saturating_mul(std::mem::size_of::<ObjectSlot>()))
855        .saturating_add(resources.saturating_mul(std::mem::size_of::<ResourceUsage>()))
856}
857
858fn replacement_capacity<T: Clone>(
859    current: &Vec<T>,
860    capacity: usize,
861) -> Result<Option<Vec<T>>, Scene3dError> {
862    if capacity <= current.capacity() {
863        return Ok(None);
864    }
865    let mut values = Vec::new();
866    values
867        .try_reserve_exact(capacity)
868        .map_err(|_| Scene3dError::AllocationFailed {
869            requested_bytes: capacity.saturating_mul(std::mem::size_of::<T>()),
870        })?;
871    values.extend_from_slice(current);
872    Ok(Some(values))
873}
874
875fn planned_capacity<T>(current: &Vec<T>, additional: usize, maximum: usize) -> usize {
876    let needed = current.len().saturating_add(additional);
877    if needed <= current.capacity() {
878        current.capacity()
879    } else {
880        needed
881            .max(current.capacity().saturating_mul(2))
882            .min(maximum)
883    }
884}
885
886/// Rejection reason for 3D scene visual state.
887#[derive(Debug, Clone, Copy, PartialEq, Eq)]
888pub enum Scene3dError {
889    /// Each explicit scene budget limit must be nonzero.
890    InvalidBudget,
891    /// The incoming mesh belongs to another logical renderer generation.
892    RendererMismatch,
893    /// A mutation would exceed a configured live-resource or storage limit.
894    BudgetExceeded {
895        /// Rejected resource category.
896        resource: Scene3dBudgetResource,
897        /// Configured maximum.
898        limit: usize,
899        /// Required count or bytes.
900        actual: usize,
901    },
902    /// The target clear color must be normalized and opaque.
903    InvalidBackground,
904    /// Surface and wireframe were both disabled.
905    EmptyStyle,
906    /// The selected surface/edge modes have no corresponding mesh topology.
907    StyleHasNoMatchingGeometry,
908    /// A model transform cannot be represented portably by the GPU shader.
909    InvalidTransform,
910    /// No more process-unique scene identifiers can be allocated.
911    SceneIdExhausted,
912    /// No more stable object identifiers can be allocated.
913    ObjectIdExhausted,
914    /// CPU storage for another retained object could not be reserved.
915    AllocationFailed {
916        /// Additional bytes requested for the rejected object.
917        requested_bytes: usize,
918    },
919    /// An object update referenced a missing stable handle.
920    ObjectNotFound {
921        /// Stable handle that is absent from this scene.
922        object_id: Object3dId,
923    },
924}
925
926impl fmt::Display for Scene3dError {
927    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
928        match self {
929            Self::InvalidBudget => write!(formatter, "3D scene budget limits must be nonzero"),
930            Self::RendererMismatch => {
931                write!(formatter, "3D mesh belongs to another renderer generation")
932            }
933            Self::BudgetExceeded {
934                resource,
935                limit,
936                actual,
937            } => write!(
938                formatter,
939                "3D scene {resource:?} budget exceeded: {actual} > {limit}"
940            ),
941            Self::InvalidBackground => write!(formatter, "3D scene background must be opaque"),
942            Self::EmptyStyle => write!(formatter, "3D object requires a surface or wireframe"),
943            Self::StyleHasNoMatchingGeometry => write!(
944                formatter,
945                "3D object style has no matching triangles or display edges"
946            ),
947            Self::InvalidTransform => {
948                write!(
949                    formatter,
950                    "3D model transform is outside the portable shader envelope"
951                )
952            }
953            Self::SceneIdExhausted => write!(formatter, "3D scene identifiers exhausted"),
954            Self::ObjectIdExhausted => write!(formatter, "3D scene object identifiers exhausted"),
955            Self::AllocationFailed { requested_bytes } => write!(
956                formatter,
957                "could not reserve {requested_bytes} bytes for another 3D scene object"
958            ),
959            Self::ObjectNotFound { object_id } => write!(
960                formatter,
961                "3D scene object {} does not exist in this scene",
962                object_id.get()
963            ),
964        }
965    }
966}
967
968impl Error for Scene3dError {}