cranpose_render_common/scene_store/
shape_chunks.rs1use 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
18const CHUNK_SHAPES: usize = 256;
21const KEPT_EMPTY_CHUNKS: usize = 4;
26const MIN_DEAD_SHAPES: usize = 16;
29
30#[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#[derive(Clone, Debug)]
52pub struct ShapeRun {
53 chunk: ChunkId,
54 shapes: u32,
57 coverage: Rect,
58 segments: Range<u32>,
59 print: u64,
62}
63
64#[derive(Clone, Copy)]
67pub struct ShapeRef<'a> {
68 recorder: &'a Arc<ShapeRecorder>,
69 run: &'a ShapeRun,
70}
71
72impl<'a> ShapeRef<'a> {
73 pub fn recorder(self) -> &'a Arc<ShapeRecorder> {
75 self.recorder
76 }
77
78 pub fn segments(self) -> Range<u32> {
80 self.run.segments.clone()
81 }
82
83 #[inline]
85 pub fn shape_count(self) -> u32 {
86 self.run.shapes
87 }
88
89 #[inline]
92 pub fn coverage(self) -> Option<Rect> {
93 (self.run.shapes > 0).then_some(self.run.coverage)
94 }
95
96 #[inline]
99 pub fn print(self) -> u64 {
100 self.run.print
101 }
102
103 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 chunks: Vec<Option<ShapeChunk>>,
113 open: Option<ChunkId>,
115 empty: Vec<ChunkId>,
118 live: Vec<u64>,
121}
122
123#[derive(Clone)]
124struct ShapeChunk {
125 recorder: Arc<ShapeRecorder>,
126 items: u32,
128 shapes: u32,
129}
130
131impl ShapeChunks {
132 #[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 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 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 #[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 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 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#[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 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 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 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 #[inline]
386 pub(crate) fn shapes_print(&self, item: Item) -> u64 {
387 self.shape_runs[item.index()].print
388 }
389
390 #[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 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 pub(super) fn shapes_heap_bytes(&self) -> usize {
410 self.shape_runs.heap_bytes() + self.shape_chunks.heap_bytes()
411 }
412
413 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}