Skip to main content

cranpose_render_common/scene_store/
shape_chunks.rs

1// The shapes of the draws that are plain data, a background's among them,
2// recorded into chunks that the runs of the whole store share: a shape item
3// names its chunk and its segments there, and a packet leases a chunk whole.
4// A chunk takes new shapes only while no packet holds it, and a chunk that
5// no item names any more takes new shapes again once no packet holds it.
6// A background drawn anew each frame leaves its old shapes behind. The
7// shapes an item took last go with the item at once. A chunk whose next
8// shape would grow it, or that is full, first drops the shapes no item
9// draws once they are a quarter of it and at least `MIN_DEAD_SHAPES`.
10
11use std::{num::NonZeroU32, ops::Range, sync::Arc};
12
13use cranpose_core::collections::growth_slack::GrowthSlack;
14use cranpose_ui_graphics::{DrawPrimitive, Rect, ShapeRecorder};
15
16use super::{Item, ItemKind, SceneStore, slab::Slab};
17
18// The most shapes a chunk takes: a chunk that one item still names keeps
19// the room of this many.
20const CHUNK_SHAPES: usize = 256;
21// The most chunks no item names that the store keeps for reuse.
22// A packet in flight holds the chunks it draws, so a frame that redraws a
23// shape writes into an empty chunk that the packets of the frames before
24// let go of.
25const KEPT_EMPTY_CHUNKS: usize = 4;
26// The fewest shapes no item draws for which a chunk moves the others: a
27// chunk of a few shapes grows to room for this many before it does.
28const MIN_DEAD_SHAPES: usize = 16;
29
30// A chunk's place in the store's list of chunks, past 0, so a slab of
31// runs needs no room for the absence of one.
32#[derive(Clone, Copy, Debug, PartialEq, Eq)]
33struct ChunkId(NonZeroU32);
34
35impl ChunkId {
36    fn at(index: usize) -> Self {
37        Self(
38            u32::try_from(index + 1)
39                .ok()
40                .and_then(NonZeroU32::new)
41                .expect("a store holds fewer than 2^32 shape chunks"),
42        )
43    }
44
45    fn index(self) -> usize {
46        self.0.get() as usize - 1
47    }
48}
49
50/// The shapes of one shape item in its chunk.
51#[derive(Clone, Debug)]
52pub struct ShapeRun {
53    chunk: ChunkId,
54    // How many shapes the item draws, and the rect they cover when it
55    // draws any: a collect reads them for every item it draws.
56    shapes: u32,
57    coverage: Rect,
58    segments: Range<u32>,
59    // A hash of what the shapes draw, which the chunk's other shapes leave
60    // alone, from what recorded them.
61    print: u64,
62}
63
64/// A shape item as a reader sees it: shapes recorded into a chunk that
65/// other items share.
66#[derive(Clone, Copy)]
67pub struct ShapeRef<'a> {
68    recorder: &'a Arc<ShapeRecorder>,
69    run: &'a ShapeRun,
70}
71
72impl<'a> ShapeRef<'a> {
73    /// The recorder of the chunk the shapes sit in, which a packet leases.
74    pub fn recorder(self) -> &'a Arc<ShapeRecorder> {
75        self.recorder
76    }
77
78    /// The segments of the chunk the shapes take.
79    pub fn segments(self) -> Range<u32> {
80        self.run.segments.clone()
81    }
82
83    /// How many shapes the item draws.
84    #[inline]
85    pub fn shape_count(self) -> u32 {
86        self.run.shapes
87    }
88
89    /// The rect the item's pixels lie within, in its record's space; `None`
90    /// for an item that draws nothing.
91    #[inline]
92    pub fn coverage(self) -> Option<Rect> {
93        (self.run.shapes > 0).then_some(self.run.coverage)
94    }
95
96    /// A hash of what the item draws, which the other items of its chunk
97    /// leave alone.
98    #[inline]
99    pub fn print(self) -> u64 {
100        self.run.print
101    }
102
103    /// The primitives the item draws, in order.
104    pub fn primitives(self) -> impl Iterator<Item = DrawPrimitive> + 'a {
105        self.recorder.shape_primitives_in(&self.run.segments)
106    }
107}
108
109#[derive(Clone, Default)]
110pub(super) struct ShapeChunks {
111    // By chunk id; `None` for an id whose chunk went.
112    chunks: Vec<Option<ShapeChunk>>,
113    // The chunk that took the last shapes.
114    open: Option<ChunkId>,
115    // The chunks no item names, which take shapes again once no packet
116    // holds them.
117    empty: Vec<ChunkId>,
118    // One bit a segment of the chunk that drops its dead shapes, set for
119    // the segments a run names: room the next such chunk takes again.
120    live: Vec<u64>,
121}
122
123#[derive(Clone)]
124struct ShapeChunk {
125    recorder: Arc<ShapeRecorder>,
126    // How many items name the chunk, and how many shapes they draw.
127    items: u32,
128    shapes: u32,
129}
130
131impl ShapeChunks {
132    // Records the shapes of one item with `record`, which draw what `print`
133    // hashes, into a chunk that takes them, and returns where they went.
134    // Out of line: a background drawn again unchanged keeps its shapes.
135    #[inline(never)]
136    fn record(
137        &mut self,
138        runs: &mut Slab<ShapeRun>,
139        print: u64,
140        record: impl FnOnce(&mut ShapeRecorder),
141    ) -> ShapeRun {
142        let chunk = self.writable_chunk(runs);
143        let entry = self.chunks[chunk.index()]
144            .as_mut()
145            .expect("a writable chunk is there");
146        let recorder = Arc::get_mut(&mut entry.recorder).expect("no packet holds a writable chunk");
147        let start = recorder.all_segments().end;
148        record(recorder);
149        recorder.end_segment();
150        let segments = start..recorder.all_segments().end;
151        let shapes = recorder.shape_count_in(&segments);
152        entry.items += 1;
153        entry.shapes += shapes;
154        ShapeRun {
155            chunk,
156            shapes,
157            coverage: recorder.coverage_in(&segments).unwrap_or_default(),
158            segments,
159            print,
160        }
161    }
162
163    // A chunk with room that no packet holds: the open one, rid of the
164    // shapes no item draws when it holds enough of them, an empty one
165    // emptied of its old shapes, or a new one.
166    fn writable_chunk(&mut self, runs: &mut Slab<ShapeRun>) -> ChunkId {
167        if let Some(open) = self.open
168            && let Some(chunk) = self.chunks[open.index()].as_mut()
169            && let Some(recorder) = Arc::get_mut(&mut chunk.recorder)
170        {
171            let held = recorder.tables().shapes.len();
172            let full = held >= CHUNK_SHAPES;
173            let dead = held - chunk.shapes as usize;
174            if (full || held >= recorder.shape_capacity())
175                && dead >= (held / 4).max(MIN_DEAD_SHAPES)
176            {
177                keep_live_runs(open, recorder, runs, &mut self.live);
178                return open;
179            }
180            if !full {
181                return open;
182            }
183        }
184        let reused = self.empty.iter().position(|&id| {
185            self.chunks[id.index()]
186                .as_mut()
187                .is_some_and(|chunk| Arc::get_mut(&mut chunk.recorder).is_some())
188        });
189        let id = match reused {
190            Some(at) => {
191                let id = self.empty.swap_remove(at);
192                if let Some(recorder) = self.chunks[id.index()]
193                    .as_mut()
194                    .and_then(|chunk| Arc::get_mut(&mut chunk.recorder))
195                {
196                    recorder.clear();
197                }
198                id
199            }
200            None => self.add_chunk(),
201        };
202        self.open = Some(id);
203        id
204    }
205
206    #[cold]
207    fn add_chunk(&mut self) -> ChunkId {
208        let chunk = Some(ShapeChunk {
209            recorder: Arc::default(),
210            items: 0,
211            shapes: 0,
212        });
213        let id = match self.chunks.iter().position(Option::is_none) {
214            Some(id) => {
215                self.chunks[id] = chunk;
216                id
217            }
218            None => {
219                self.chunks.push(chunk);
220                self.chunks.len() - 1
221            }
222        };
223        ChunkId::at(id)
224    }
225
226    // Notes that the item of `run` went. The open chunk no item names takes
227    // the next shapes from its start once no packet holds it; another such
228    // chunk waits for reuse, and past the few kept, it goes.
229    fn release(&mut self, run: &ShapeRun) {
230        let chunk = run.chunk;
231        let open = self.open == Some(chunk);
232        let Some(entry) = self.chunks[chunk.index()].as_mut() else {
233            return;
234        };
235        entry.items -= 1;
236        entry.shapes -= run.shapes;
237        if let Some(recorder) = Arc::get_mut(&mut entry.recorder) {
238            if entry.items == 0 && open {
239                recorder.clear();
240                return;
241            }
242            if !run.segments.is_empty() && run.segments.end == recorder.all_segments().end {
243                recorder.truncate_segments(run.segments.start);
244            }
245        }
246        if entry.items > 0 {
247            return;
248        }
249        if open {
250            self.open = None;
251        }
252        if self.empty.len() < KEPT_EMPTY_CHUNKS {
253            self.empty.push(chunk);
254        } else {
255            self.chunks[chunk.index()] = None;
256        }
257    }
258
259    // Gives back at rest the chunks no item names and, in each chunk no
260    // packet holds, the shapes no item draws and the room of its growth.
261    // A packet keeps a chunk it holds until it lets go.
262    #[cold]
263    fn trim(&mut self, runs: &mut Slab<ShapeRun>) {
264        for id in self.empty.drain(..) {
265            self.chunks[id.index()] = None;
266        }
267        for (index, slot) in self.chunks.iter_mut().enumerate() {
268            let Some(chunk) = slot else {
269                continue;
270            };
271            let id = ChunkId::at(index);
272            if chunk.items == 0 {
273                *slot = None;
274                if self.open == Some(id) {
275                    self.open = None;
276                }
277                continue;
278            }
279            let Some(recorder) = Arc::get_mut(&mut chunk.recorder) else {
280                continue;
281            };
282            // Each move scans every run: only a chunk that a quarter of dead
283            // shapes fills moves, as a chunk that takes shapes does.
284            let held = recorder.tables().shapes.len();
285            if held - chunk.shapes as usize >= (held / 4).max(MIN_DEAD_SHAPES) {
286                keep_live_runs(id, recorder, runs, &mut self.live);
287            }
288            recorder.trim_growth();
289        }
290        while self.chunks.last().is_some_and(Option::is_none) {
291            self.chunks.pop();
292        }
293        self.chunks.trim_growth_slack();
294        self.live = Vec::new();
295    }
296
297    // The heap the chunks hold: their lists and every chunk's recorder.
298    fn heap_bytes(&self) -> usize {
299        self.chunks.capacity() * size_of::<Option<ShapeChunk>>()
300            + self.empty.capacity() * size_of::<ChunkId>()
301            + self.live.capacity() * size_of::<u64>()
302            + self
303                .chunks
304                .iter()
305                .flatten()
306                .map(|chunk| size_of::<ShapeRecorder>() + chunk.recorder.tables().heap_bytes())
307                .sum::<usize>()
308    }
309
310    fn recorder(&self, chunk: ChunkId) -> &Arc<ShapeRecorder> {
311        &self.chunks[chunk.index()]
312            .as_ref()
313            .expect("a shape item names a live chunk")
314            .recorder
315    }
316}
317
318// Moves the shapes of the runs in `chunk` to the front of its recorder, in
319// record order, and drops the shapes no run names. `live` is room for one
320// bit a segment.
321#[cold]
322#[inline(never)]
323fn keep_live_runs(
324    chunk: ChunkId,
325    recorder: &mut ShapeRecorder,
326    runs: &mut Slab<ShapeRun>,
327    live: &mut Vec<u64>,
328) {
329    live.clear();
330    live.resize(recorder.all_segments().end.div_ceil(64) as usize, 0);
331    for run in runs.values().filter(|run| run.chunk == chunk) {
332        for segment in run.segments.clone() {
333            live[segment as usize / 64] |= 1 << (segment % 64);
334        }
335    }
336    recorder.keep_segments(|segment| live[segment as usize / 64] & (1 << (segment % 64)) != 0);
337    // A run now starts past the live segments before it.
338    for run in runs.values_mut().filter(|run| run.chunk == chunk) {
339        let (word, bit) = (run.segments.start as usize / 64, run.segments.start % 64);
340        let start = live[..word]
341            .iter()
342            .map(|bits| bits.count_ones())
343            .sum::<u32>()
344            + live
345                .get(word)
346                .map_or(0, |bits| (bits & ((1 << bit) - 1)).count_ones());
347        run.segments = start..start + (run.segments.end - run.segments.start);
348    }
349}
350
351#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
352impl SceneStore {
353    /// Adds an item of the shapes `record` records into a chunk the store
354    /// shares among its shape items. `print` is a hash of what they draw,
355    /// the same for the same shapes.
356    pub fn add_shapes(&mut self, print: u64, record: impl FnOnce(&mut ShapeRecorder)) -> Item {
357        let run = self
358            .shape_chunks
359            .record(&mut self.shape_runs, print, record);
360        Item::new(ItemKind::Shape, self.shape_runs.insert(run))
361    }
362
363    // Records the shapes of the shape item `item` anew through `record`,
364    // as `print` names them: the item keeps its handle, and its old shapes
365    // go at once.
366    pub(crate) fn redraw_shapes(
367        &mut self,
368        item: Item,
369        print: u64,
370        record: impl FnOnce(&mut ShapeRecorder),
371    ) {
372        let index = item.index();
373        let Some(old) = self.shape_runs.lend(index) else {
374            return;
375        };
376        self.shape_chunks.release(&old);
377        let run = self
378            .shape_chunks
379            .record(&mut self.shape_runs, print, record);
380        self.shape_runs.put(index, run);
381    }
382
383    // A hash of what the shape item `item` draws: two items of one print
384    // draw alike.
385    #[inline]
386    pub(crate) fn shapes_print(&self, item: Item) -> u64 {
387        self.shape_runs[item.index()].print
388    }
389
390    /// The shapes of a shape item.
391    #[inline]
392    pub fn shapes(&self, item: Item) -> ShapeRef<'_> {
393        let run = &self.shape_runs[item.index()];
394        ShapeRef {
395            recorder: self.shape_chunks.recorder(run.chunk),
396            run,
397        }
398    }
399
400    // Removes the shape item at `index` of the shape runs and lets go of
401    // its shapes.
402    pub(super) fn remove_shapes(&mut self, index: usize) {
403        if let Some(run) = self.shape_runs.take(index) {
404            self.shape_chunks.release(&run);
405        }
406    }
407
408    // The heap the shape items and their chunks hold.
409    pub(super) fn shapes_heap_bytes(&self) -> usize {
410        self.shape_runs.heap_bytes() + self.shape_chunks.heap_bytes()
411    }
412
413    // Gives back at rest the room of the shapes no item draws.
414    pub(super) fn trim_shapes(&mut self) {
415        self.shape_chunks.trim(&mut self.shape_runs);
416    }
417
418    pub(super) fn shape_item_count(&self) -> usize {
419        self.shape_runs.values().count()
420    }
421
422    pub(super) fn clear_shapes(&mut self) {
423        self.shape_runs.clear();
424        self.shape_chunks = ShapeChunks::default();
425    }
426}