ferravex_graphics/
cache.rs

1use crate::{Bounds, Mat4, Mesh, MeshError};
2
3/// Stable CPU mesh handle; generation prevents reuse of a released slot.
4#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
5pub struct MeshId {
6    pub index: u32,
7    pub generation: u64,
8}
9struct Entry {
10    mesh: Mesh,
11    bounds: Bounds,
12    unit_normals: bool,
13}
14impl Entry {
15    fn new(mesh: Mesh, bounds: Bounds) -> Self {
16        let unit_normals = mesh
17            .vertices
18            .iter()
19            .all(|v| (v.normal.length_squared() - 1.0).abs() <= 1.0e-4);
20        Self {
21            mesh,
22            bounds,
23            unit_normals,
24        }
25    }
26}
27struct Slot {
28    generation: u64,
29    entry: Option<Entry>,
30}
31#[derive(Default)]
32pub struct MeshCache {
33    slots: Vec<Slot>,
34    free: Vec<u32>,
35    live: usize,
36}
37#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
38pub struct CacheStats {
39    pub meshes: usize,
40    pub allocated_slots: usize,
41    pub vertices: usize,
42    pub indices: usize,
43}
44impl MeshCache {
45    pub fn new() -> Self {
46        Self::default()
47    }
48    pub fn insert(&mut self, mesh: Mesh) -> Result<MeshId, MeshError> {
49        let bounds = mesh.validate()?;
50        let entry = Some(Entry::new(mesh, bounds));
51        let id = if let Some(index) = self.free.pop() {
52            let slot = &mut self.slots[index as usize];
53            slot.entry = entry;
54            MeshId {
55                index,
56                generation: slot.generation,
57            }
58        } else {
59            let index = u32::try_from(self.slots.len()).map_err(|_| MeshError::TooLarge)?;
60            self.slots.push(Slot {
61                generation: 1,
62                entry,
63            });
64            MeshId {
65                index,
66                generation: 1,
67            }
68        };
69        self.live += 1;
70        Ok(id)
71    }
72    pub fn get(&self, id: MeshId) -> Option<&Mesh> {
73        self.entry(id).map(|entry| &entry.mesh)
74    }
75    pub fn bounds(&self, id: MeshId) -> Option<Bounds> {
76        self.entry(id).map(|entry| entry.bounds)
77    }
78    pub(crate) fn mesh_entry(&self, id: MeshId) -> Option<(&Mesh, Bounds, bool)> {
79        self.entry(id)
80            .map(|entry| (&entry.mesh, entry.bounds, entry.unit_normals))
81    }
82    fn entry(&self, id: MeshId) -> Option<&Entry> {
83        let slot = self.slots.get(id.index as usize)?;
84        if slot.generation != id.generation {
85            return None;
86        }
87        slot.entry.as_ref()
88    }
89    /// Replaces geometry in-place after complete validation. Old data survives a bad update.
90    pub fn update(&mut self, id: MeshId, mesh: Mesh) -> Result<bool, MeshError> {
91        let bounds = mesh.validate()?;
92        let Some(slot) = self.slots.get_mut(id.index as usize) else {
93            return Ok(false);
94        };
95        if slot.generation != id.generation || slot.entry.is_none() {
96            return Ok(false);
97        }
98        slot.entry = Some(Entry::new(mesh, bounds));
99        Ok(true)
100    }
101    pub fn remove(&mut self, id: MeshId) -> Option<Mesh> {
102        let slot = self.slots.get_mut(id.index as usize)?;
103        if slot.generation != id.generation {
104            return None;
105        }
106        let entry = slot.entry.take()?;
107        self.live -= 1;
108        // Retire the slot rather than wrapping a generation and reviving stale handles.
109        if let Some(next) = slot.generation.checked_add(1) {
110            slot.generation = next;
111            self.free.push(id.index);
112        }
113        Some(entry.mesh)
114    }
115    pub fn stats(&self) -> CacheStats {
116        let mut result = CacheStats {
117            meshes: self.live,
118            allocated_slots: self.slots.len(),
119            ..Default::default()
120        };
121        for entry in self.slots.iter().filter_map(|slot| slot.entry.as_ref()) {
122            result.vertices += entry.mesh.vertices.len();
123            result.indices += entry.mesh.indices.len();
124        }
125        result
126    }
127}
128#[derive(Clone, Copy, Debug)]
129pub struct RenderItem {
130    pub mesh: MeshId,
131    pub transform: Mat4,
132}
133impl RenderItem {
134    pub const fn new(mesh: MeshId, transform: Mat4) -> Self {
135        Self { mesh, transform }
136    }
137}
138#[derive(Debug)]
139pub struct InstanceBatch {
140    pub mesh: MeshId,
141    pub transforms: Vec<Mat4>,
142}
143/// Groups identical mesh handles. This is CPU submission grouping, not a GPU draw call.
144pub fn instance_batches(items: &[RenderItem]) -> Vec<InstanceBatch> {
145    let mut sorted = items.to_vec();
146    sorted.sort_by_key(|item| item.mesh);
147    let mut batches: Vec<InstanceBatch> = Vec::new();
148    for item in sorted {
149        if let Some(last) = batches.last_mut().filter(|batch| batch.mesh == item.mesh) {
150            last.transforms.push(item.transform);
151        } else {
152            batches.push(InstanceBatch {
153                mesh: item.mesh,
154                transforms: vec![item.transform],
155            });
156        }
157    }
158    batches
159}