Skip to main content

mln_engine/draw/
store.rs

1//! The context's stores of what draws share on the GPU: textures, indexes,
2//! vertices, meshes and render targets. Each entry is held through [`Shared`] handles, which the
3//! entry's owner and every draw, bindings or geometry that reads it clone:
4//! the entry stays while a handle to it does, so nothing names one that is
5//! gone. When the last handle drops, its key goes to the renderer's release
6//! queue, and the context removes the entry the next time it destroys what
7//! the renderer released.
8
9use std::marker::PhantomData;
10use std::rc::{Rc, Weak};
11
12use crate::draw::release::{Release, ReleaseQueue};
13
14/// Where an entry is in its store: its slot, and which of the entries the
15/// slot held in turn it is.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct EntryKey {
18    slot: usize,
19    version: u32,
20}
21
22/// The key of an entry of a store, which only the store makes.
23pub trait Key: Copy + Into<StoreKey> {
24    fn new(entry: EntryKey) -> Self;
25    fn entry(self) -> EntryKey;
26}
27
28macro_rules! keys {
29    ($($(#[$meta:meta])* $name:ident => $variant:ident,)*) => {$(
30        $(#[$meta])*
31        #[derive(Clone, Copy, Debug, PartialEq, Eq)]
32        pub struct $name(EntryKey);
33
34        impl Key for $name {
35            fn new(entry: EntryKey) -> Self {
36                $name(entry)
37            }
38
39            fn entry(self) -> EntryKey {
40                self.0
41            }
42        }
43
44        impl From<$name> for StoreKey {
45            fn from(key: $name) -> StoreKey {
46                StoreKey::$variant(key)
47            }
48        }
49    )*};
50}
51
52keys! {
53    /// A texture of the context's store.
54    TextureKey => Texture,
55    /// Indexes of the context's store.
56    IndexesKey => Indexes,
57    /// Vertices of the context's store.
58    VerticesKey => Vertices,
59    /// A mesh of the context's store.
60    MeshKey => Mesh,
61    /// A layer's render target of the context's store.
62    TargetKey => Target,
63}
64
65/// A key of one of the context's stores.
66#[derive(Clone, Copy, Debug, PartialEq, Eq)]
67pub enum StoreKey {
68    Texture(TextureKey),
69    Indexes(IndexesKey),
70    Vertices(VerticesKey),
71    Mesh(MeshKey),
72    Target(TargetKey),
73}
74
75/// A handle of the store entry `key`, which stays in its store while a
76/// clone of the handle does.
77pub struct Shared<K: Key>(Rc<Holder<K>>);
78
79/// What the clones of a [`Shared`] share: the key, and the queue it goes to
80/// once the last of them drops.
81struct Holder<K: Key> {
82    key: K,
83    queue: Rc<ReleaseQueue>,
84}
85
86impl<K: Key> Drop for Holder<K> {
87    fn drop(&mut self) {
88        self.queue.push(Release::Entry(self.key.into()));
89    }
90}
91
92impl<K: Key> Shared<K> {
93    /// The entry's key in its store.
94    #[must_use]
95    pub(crate) fn key(&self) -> K {
96        self.0.key
97    }
98
99    /// A handle that finds the entry while a clone of this one lasts,
100    /// without keeping it.
101    #[must_use]
102    pub(crate) fn downgrade(&self) -> WeakShared<K> {
103        WeakShared(Rc::downgrade(&self.0))
104    }
105}
106
107/// A handle of a store entry that doesn't keep it in its store.
108pub(crate) struct WeakShared<K: Key>(Weak<Holder<K>>);
109
110impl<K: Key> WeakShared<K> {
111    /// A handle of the entry, while a [`Shared`] of it lasts.
112    #[must_use]
113    pub(crate) fn upgrade(&self) -> Option<Shared<K>> {
114        self.0.upgrade().map(Shared)
115    }
116}
117
118impl<K: Key> WeakShared<K> {
119    /// Whether a [`Shared`] of the entry lasts.
120    #[must_use]
121    pub(crate) fn is_held(&self) -> bool {
122        self.0.strong_count() > 0
123    }
124}
125
126impl<K: Key> Clone for WeakShared<K> {
127    fn clone(&self) -> Self {
128        WeakShared(Weak::clone(&self.0))
129    }
130}
131
132impl<K: Key> Default for WeakShared<K> {
133    /// A handle of no entry.
134    fn default() -> Self {
135        WeakShared(Weak::new())
136    }
137}
138
139/// Handles are equal where they hold the same entry.
140impl<K: Key> PartialEq for Shared<K> {
141    fn eq(&self, other: &Self) -> bool {
142        Rc::ptr_eq(&self.0, &other.0)
143    }
144}
145
146impl<K: Key> Eq for Shared<K> {}
147
148impl<K: Key> Clone for Shared<K> {
149    fn clone(&self) -> Self {
150        Shared(Rc::clone(&self.0))
151    }
152}
153
154impl<K: Key + std::fmt::Debug> std::fmt::Debug for Shared<K> {
155    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
156        f.debug_tuple("Shared").field(&self.0.key).finish()
157    }
158}
159
160/// A texture of the context's store.
161pub type SharedTexture = Shared<TextureKey>;
162
163/// Indexes of the context's store.
164pub type SharedIndexes = Shared<IndexesKey>;
165
166/// The slots of a store's chunk.
167const CHUNK: usize = 32;
168
169/// A store of the context: its entries by key, in chunks of slots. An entry
170/// takes the lowest vacant slot, so the entries gather in the first chunks,
171/// and the store frees its last chunks once they are empty: it keeps the
172/// chunks up to its last entry's, rather than as many as it ever filled.
173pub(crate) struct Store<K, V> {
174    chunks: Vec<Box<Chunk<V>>>,
175    /// The lowest chunk with a vacant slot, or past the last chunk.
176    first_vacant: usize,
177    /// The version of the next entry. Each entry has its own, so a key of an
178    /// entry the store removed names none of those it adds after.
179    next_version: u32,
180    key: PhantomData<fn() -> K>,
181}
182
183/// Slots of a store, with which of them are vacant.
184struct Chunk<V> {
185    slots: [Slot<V>; CHUNK],
186    /// A bit for each slot, set where it is vacant.
187    vacant: u32,
188}
189
190/// A slot of a store: its entry, if any, with the entry's version.
191struct Slot<V> {
192    version: u32,
193    value: Option<V>,
194}
195
196impl<V> Chunk<V> {
197    fn new() -> Box<Chunk<V>> {
198        Box::new(Chunk { slots: std::array::from_fn(|_| Slot { version: 0, value: None }), vacant: u32::MAX })
199    }
200}
201
202impl<K, V> Default for Store<K, V> {
203    fn default() -> Self {
204        Store { chunks: Vec::new(), first_vacant: 0, next_version: 0, key: PhantomData }
205    }
206}
207
208impl<K: Key, V> Store<K, V> {
209    /// Keeps `value`, while a clone of the returned handle lasts, whose key
210    /// goes to `queue` once the last clone drops.
211    pub(crate) fn add(&mut self, value: V, queue: &Rc<ReleaseQueue>) -> Shared<K> {
212        let version = self.next_version;
213        self.next_version = version.wrapping_add(1);
214        if let Some(offset) = self.chunks.iter().skip(self.first_vacant).position(|chunk| chunk.vacant != 0) {
215            self.first_vacant += offset;
216        } else {
217            self.first_vacant = self.chunks.len();
218            self.chunks.push(Chunk::new());
219        }
220        let at = self.first_vacant;
221        let chunk = &mut self.chunks[at];
222        let index = chunk.vacant.trailing_zeros() as usize;
223        chunk.vacant &= !(1 << index);
224        chunk.slots[index] = Slot { version, value: Some(value) };
225        Shared(Rc::new(Holder { key: K::new(EntryKey { slot: at * CHUNK + index, version }), queue: Rc::clone(queue) }))
226    }
227
228    /// The slot that `key` names, if the store has its entry.
229    fn slot_mut(&mut self, key: K) -> Option<&mut Slot<V>> {
230        let EntryKey { slot, version } = key.entry();
231        let slot = self.chunks.get_mut(slot / CHUNK)?.slots.get_mut(slot % CHUNK)?;
232        (slot.version == version && slot.value.is_some()).then_some(slot)
233    }
234
235    /// The entry `key` names, if the store has it.
236    fn slot(&self, key: K) -> Option<&V> {
237        let EntryKey { slot, version } = key.entry();
238        let slot = self.chunks.get(slot / CHUNK)?.slots.get(slot % CHUNK)?;
239        slot.value.as_ref().filter(|_| slot.version == version)
240    }
241
242    /// The entry of `handle`, which is there while the handle is.
243    pub(crate) fn get(&self, handle: &Shared<K>) -> Option<&V> {
244        let entry = self.slot(handle.key());
245        debug_assert!(entry.is_some(), "a handle outlived its store entry");
246        entry
247    }
248
249    /// [`get`](Self::get), to change.
250    pub(crate) fn get_mut(&mut self, handle: &Shared<K>) -> Option<&mut V> {
251        let entry = self.slot_mut(handle.key()).and_then(|slot| slot.value.as_mut());
252        debug_assert!(entry.is_some(), "a handle outlived its store entry");
253        entry
254    }
255
256    /// Whether the store has the entry `key`.
257    #[cfg(test)]
258    pub(crate) fn contains(&self, key: K) -> bool {
259        self.slot(key).is_some()
260    }
261
262    /// Takes out the entry `key`, whose last handle dropped, and frees the
263    /// chunks past the last entry.
264    pub(crate) fn remove(&mut self, key: K) -> Option<V> {
265        let value = self.slot_mut(key)?.value.take();
266        let slot = key.entry().slot;
267        let chunk = slot / CHUNK;
268        if let Some(of) = self.chunks.get_mut(chunk) {
269            of.vacant |= 1 << (slot % CHUNK);
270        }
271        self.first_vacant = self.first_vacant.min(chunk);
272        while self.chunks.last().is_some_and(|last| last.vacant == u32::MAX) {
273            self.chunks.pop();
274        }
275        self.first_vacant = self.first_vacant.min(self.chunks.len());
276        value
277    }
278
279    /// Drops every entry.
280    pub(crate) fn clear(&mut self) {
281        self.chunks.clear();
282        self.first_vacant = 0;
283    }
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289
290    fn store() -> (Store<VerticesKey, u32>, Rc<ReleaseQueue>) {
291        (Store::default(), Rc::default())
292    }
293
294    // A slot an entry left takes the next entry, whose key isn't the key of
295    // the one before.
296    #[test]
297    fn a_removed_entrys_key_names_no_later_entry() {
298        let (mut store, released) = store();
299        let kept = store.add(0, &released);
300        let first = store.add(1, &released);
301        let key = first.key();
302        drop(first);
303        assert_eq!(store.remove(key), Some(1));
304        let second = store.add(2, &released);
305        assert_eq!(second.key().entry().slot, key.entry().slot);
306        assert!(!store.contains(key));
307        assert_eq!(store.get(&second), Some(&2));
308        assert_eq!(store.get(&kept), Some(&0));
309        assert_eq!(store.remove(key), None);
310    }
311
312    // Entries take the lowest vacant slots, and a store frees its chunks
313    // past its last entry.
314    #[test]
315    fn a_store_frees_its_empty_last_chunks() {
316        let (mut store, released) = store();
317        let handles: Vec<_> = (0..100).map(|value| store.add(value, &released)).collect();
318        let keys: Vec<_> = handles.iter().map(Shared::key).collect();
319        drop(handles);
320        assert_eq!(store.chunks.len(), 4);
321        for &key in keys.iter().skip(10) {
322            store.remove(key);
323        }
324        assert_eq!(store.chunks.len(), 1);
325        store.remove(keys[2]);
326        let next = store.add(100, &released);
327        assert_eq!(next.key().entry().slot, 2);
328        let after = store.add(101, &released);
329        assert_eq!(after.key().entry().slot, 10);
330        assert!(keys.iter().take(10).enumerate().all(|(at, &key)| (at == 2) != store.contains(key)));
331        for &key in keys.iter().take(10) {
332            store.remove(key);
333        }
334        store.remove(next.key());
335        assert_eq!(store.chunks.len(), 1);
336        store.remove(after.key());
337        assert!(store.chunks.is_empty());
338    }
339}