Skip to main content

vello_encoding/
image_cache.rs

1// Copyright 2022 the Vello Authors
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use guillotiere::{AllocId, AtlasAllocator, size2};
5use peniko::ImageData;
6use std::collections::HashMap;
7use std::collections::hash_map::Entry;
8
9const DEFAULT_ATLAS_SIZE: i32 = 1024;
10const MAX_ATLAS_SIZE: i32 = 8192;
11const EVICT_AFTER_GENERATIONS: u64 = 2;
12/// Consecutive resolves the atlas must stay mostly empty before it halves.
13/// Long enough that one frame without a window (a close animation, a
14/// workspace switch) does not throw the atlas away only to grow it back.
15const SHRINK_AFTER_RESOLVES: u32 = 60;
16/// Resolves after [`ImageCache::shrink_soon`] in which a sparse atlas
17/// shrinks at once: enough for the images that went to age out
18/// ([`EVICT_AFTER_GENERATIONS`]) and the atlas to come down.
19const SHRINK_SOON_RESOLVES: u32 = 16;
20/// The atlas halves only while its residents cover at most `1 / N` of it,
21/// so the halved atlas is at most half full and the next frame's
22/// replacement images still fit without growing straight back.
23const SHRINK_WHEN_AREA_AT_MOST_ONE_IN: u64 = 8;
24/// Deltas followed back from an image to one the atlas holds (Tilo patch):
25/// a renderer that missed a few frames still takes over the slot.
26const MAX_DELTA_CHAIN: usize = 4;
27
28/// What the image cache holds, for memory diagnostics.
29#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
30pub struct ImageCacheStats {
31    /// Side length of the square atlas, in pixels.
32    pub atlas_side: u32,
33    /// Images resident in the atlas.
34    pub resident: usize,
35    /// Bytes of CPU pixels the residents keep alive (their blobs). A blob
36    /// the caller still holds is shared, not copied, so this is an upper
37    /// bound on what the cache alone keeps.
38    pub resident_cpu_bytes: u64,
39    /// Area of the residents, in atlas pixels.
40    pub resident_area: u64,
41    /// Residents evicted over the cache's lifetime.
42    pub evicted_total: u64,
43    /// Times the atlas halved because its residents no longer needed it.
44    pub shrinks_total: u64,
45    /// Images omitted over the cache's lifetime.
46    pub omitted_total: u64,
47}
48
49#[derive(Default)]
50pub struct Images<'a> {
51    /// Width of the square image atlas texture.
52    pub width: u32,
53    /// Height of the square image atlas texture.
54    pub height: u32,
55    /// Number of resident images evicted during the current resolve pass.
56    ///
57    /// This is only used for renderer-side debug logging.
58    pub evicted: usize,
59    /// Images omitted because they could not be allocated this resolve pass.
60    pub omitted: usize,
61    /// Images omitted over the lifetime of this cache.
62    pub omitted_total: u64,
63    /// Images that must be uploaded in the current resolve pass, with atlas locations.
64    pub images: &'a [(ImageData, u32, u32)],
65    /// Rects of images that must be uploaded in the current resolve pass
66    /// (Tilo patch): the image, its atlas location, and the rect of it.
67    pub regions: &'a [(ImageData, u32, u32, crate::ImageRect)],
68}
69
70#[derive(Clone)]
71struct ResidentImage {
72    image: ImageData,
73    alloc_id: AllocId,
74    x: u32,
75    y: u32,
76    dirty: bool,
77    last_used_generation: u64,
78}
79
80pub(crate) struct ImageCache {
81    atlas: AtlasAllocator,
82    /// Side length the atlas starts at, and never shrinks below.
83    min_size: i32,
84    /// Maximum side length for the square image atlas texture.
85    max_size: i32,
86    /// Resolves in a row whose residents fit in a fraction of the atlas; see
87    /// [`SHRINK_AFTER_RESOLVES`].
88    sparse_resolves: u32,
89    /// Resolves left in which a sparse atlas shrinks without waiting for
90    /// [`SHRINK_AFTER_RESOLVES`]; see [`Self::shrink_soon`].
91    shrink_soon_resolves: u32,
92    /// Residents evicted over the cache's lifetime.
93    evicted_total: u64,
94    /// Times the atlas halved.
95    shrinks_total: u64,
96    /// Monotonic counter for resolve passes, used to track when resident images were last used.
97    generation: u64,
98    /// Number of resident images evicted during the current resolve pass.
99    ///
100    /// This is exposed through [`Images::evicted`] for renderer-side debug logging, and also
101    /// prevents repeated stale-eviction scans during the same resolve pass.
102    evicted_in_resolve: usize,
103    /// Images omitted during the current resolve pass.
104    omitted_in_resolve: usize,
105    /// Images omitted over the lifetime of this cache.
106    omitted_total: u64,
107    /// Map from image blob id to atlas residency.
108    map: HashMap<u64, ResidentImage>,
109    /// Images that must be uploaded in the current resolve pass, with atlas locations.
110    images: Vec<(ImageData, u32, u32)>,
111    /// Rects of images that took over an earlier image's slot this pass.
112    regions: Vec<(ImageData, u32, u32, crate::ImageRect)>,
113}
114
115impl Default for ImageCache {
116    fn default() -> Self {
117        Self::new()
118    }
119}
120
121impl ImageCache {
122    pub(crate) fn new() -> Self {
123        Self::new_with_sizes(DEFAULT_ATLAS_SIZE, MAX_ATLAS_SIZE)
124    }
125
126    fn new_with_sizes(initial_size: i32, max_size: i32) -> Self {
127        Self {
128            atlas: AtlasAllocator::new(size2(initial_size, initial_size)),
129            min_size: initial_size,
130            max_size,
131            sparse_resolves: 0,
132            shrink_soon_resolves: 0,
133            evicted_total: 0,
134            shrinks_total: 0,
135            generation: 0,
136            evicted_in_resolve: 0,
137            omitted_in_resolve: 0,
138            omitted_total: 0,
139            map: HashMap::default(),
140            images: Vec::default(),
141            regions: Vec::default(),
142        }
143    }
144
145    /// Limit atlas growth to `max_size` pixels per side. A smaller limit only
146    /// stops further growth; the atlas comes down on its own once its
147    /// residents fit in a fraction of it (see [`Self::finish_resolve`]).
148    pub(crate) fn set_max_size(&mut self, max_size: i32) {
149        self.max_size = max_size.max(DEFAULT_ATLAS_SIZE);
150    }
151
152    /// What the cache holds now.
153    pub(crate) fn stats(&self) -> ImageCacheStats {
154        ImageCacheStats {
155            atlas_side: self.atlas.size().width as u32,
156            resident: self.map.len(),
157            resident_cpu_bytes: self
158                .map
159                .values()
160                .map(|resident| resident.image.data.len() as u64)
161                .sum(),
162            resident_area: self.resident_area(),
163            evicted_total: self.evicted_total,
164            shrinks_total: self.shrinks_total,
165            omitted_total: self.omitted_total,
166        }
167    }
168
169    pub(crate) fn begin_resolve(&mut self) {
170        self.generation = self.generation.wrapping_add(1);
171        self.evicted_in_resolve = 0;
172        self.omitted_in_resolve = 0;
173        self.images.clear();
174        self.regions.clear();
175        // Halve here, before this pass looks anything up: every position this
176        // pass hands out is then one in the halved atlas. Halving in
177        // `finish_resolve` would move images the pass just encoded.
178        let soon = self.shrink_soon_resolves > 0;
179        self.shrink_soon_resolves = self.shrink_soon_resolves.saturating_sub(1);
180        if soon && self.sparse_resolves > 0 {
181            // The caller said the images went for good: come down as far as
182            // the residents allow now, each halving as safe as a slow one.
183            self.sparse_resolves = 0;
184            let area = self.resident_area();
185            loop {
186                let side = self.atlas.size().width;
187                let half = side / 2;
188                if half < self.min_size
189                    || area.saturating_mul(SHRINK_WHEN_AREA_AT_MOST_ONE_IN)
190                        > (side as u64) * (side as u64)
191                    || !self.repack_to_size(half)
192                {
193                    break;
194                }
195                self.shrinks_total = self.shrinks_total.saturating_add(1);
196            }
197        } else if self.sparse_resolves >= SHRINK_AFTER_RESOLVES {
198            self.sparse_resolves = 0;
199            let half = self.atlas.size().width / 2;
200            if half >= self.min_size && self.repack_to_size(half) {
201                self.shrinks_total = self.shrinks_total.saturating_add(1);
202            }
203        }
204    }
205
206    /// Images went for good (a window closed): for the next
207    /// [`SHRINK_SOON_RESOLVES`] resolves, an atlas far bigger than its
208    /// residents shrinks at once instead of after [`SHRINK_AFTER_RESOLVES`]
209    /// sparse ones. A desktop that goes idle after a close draws too few
210    /// frames to bring a grown atlas down the slow way, and keeps its memory.
211    pub(crate) fn shrink_soon(&mut self) {
212        self.shrink_soon_resolves = SHRINK_SOON_RESOLVES;
213    }
214
215    pub(crate) fn restart_resolve_pass(&mut self) {
216        self.images.clear();
217        self.regions.clear();
218        let previous_generation = self.generation.wrapping_sub(1);
219        for resident in self.map.values_mut() {
220            if resident.last_used_generation == self.generation {
221                resident.last_used_generation = previous_generation;
222            }
223        }
224    }
225
226    pub(crate) fn images(&self) -> Images<'_> {
227        Images {
228            width: self.atlas.size().width as u32,
229            height: self.atlas.size().height as u32,
230            evicted: self.evicted_in_resolve,
231            omitted: self.omitted_in_resolve,
232            omitted_total: self.omitted_total,
233            images: &self.images,
234            regions: &self.regions,
235        }
236    }
237
238    pub(crate) fn bump_size(&mut self) -> bool {
239        let mut new_size = self.atlas.size().width * 2;
240        while new_size <= self.max_size {
241            if self.repack_to_size(new_size) {
242                self.images.clear();
243                self.regions.clear();
244                return true;
245            }
246            new_size *= 2;
247        }
248        false
249    }
250
251    pub(crate) fn get_or_insert(&mut self, image: &ImageData) -> Option<(u32, u32)> {
252        if !self.map.contains_key(&image.data.id())
253            && let Some(xy) = self.take_over(image)
254        {
255            return Some(xy);
256        }
257        match self.map.entry(image.data.id()) {
258            Entry::Occupied(mut occupied) => {
259                let resident = occupied.get_mut();
260                let xy = (resident.x, resident.y);
261                if resident.last_used_generation != self.generation {
262                    resident.last_used_generation = self.generation;
263                    if resident.dirty {
264                        self.images
265                            .push((resident.image.clone(), resident.x, resident.y));
266                    }
267                }
268                Some(xy)
269            }
270            Entry::Vacant(vacant) => {
271                let alloc = self
272                    .atlas
273                    .allocate(size2(image.width as _, image.height as _))?;
274                let x = alloc.rectangle.min.x as u32;
275                let y = alloc.rectangle.min.y as u32;
276                let resident = ResidentImage {
277                    image: image.clone(),
278                    alloc_id: alloc.id,
279                    x,
280                    y,
281                    dirty: true,
282                    last_used_generation: self.generation,
283                };
284                self.images.push((image.clone(), x, y));
285                vacant.insert(resident);
286                Some((x, y))
287            }
288        }
289    }
290
291    /// Give `image` the slot of the image it changes a few rects of
292    /// ([`crate::register_image_delta`]), if the atlas holds that image
293    /// as it was uploaded and this pass has not drawn it, and upload only
294    /// those rects (Tilo patch).
295    fn take_over(&mut self, image: &ImageData) -> Option<(u32, u32)> {
296        let mut rects = Vec::new();
297        let mut id = image.data.id();
298        for _ in 0..MAX_DELTA_CHAIN {
299            let (from, changed) = crate::image_delta::image_delta(id)?;
300            rects.extend_from_slice(&changed);
301            let Some(resident) = self.map.get(&from) else {
302                id = from;
303                continue;
304            };
305            if resident.dirty
306                || resident.last_used_generation == self.generation
307                || resident.image.width != image.width
308                || resident.image.height != image.height
309                || resident.image.format != image.format
310                || resident.image.alpha_type != image.alpha_type
311            {
312                return None;
313            }
314            let mut resident = self.map.remove(&from)?;
315            let (x, y) = (resident.x, resident.y);
316            for rect in rects {
317                let [rx, ry, width, height] = rect;
318                if width == 0
319                    || height == 0
320                    || rx >= image.width
321                    || ry >= image.height
322                    || width > image.width - rx
323                    || height > image.height - ry
324                {
325                    continue;
326                }
327                self.regions.push((image.clone(), x, y, rect));
328            }
329            resident.image = image.clone();
330            resident.last_used_generation = self.generation;
331            // A pass that restarts repacks the atlas and uploads it whole.
332            resident.dirty = true;
333            self.map.insert(image.data.id(), resident);
334            return Some((x, y));
335        }
336        None
337    }
338
339    /// End a resolve pass: release what the last few passes stopped drawing,
340    /// and note whether the atlas is far bigger than its residents need.
341    ///
342    /// Eviction used to wait for an allocation to fail. A client frame is a
343    /// new image every commit, so every superseded frame kept its CPU pixels
344    /// alive until the atlas was full — and the atlas grew to its maximum
345    /// first, which it then kept for the life of the process.
346    pub(crate) fn finish_resolve(&mut self) {
347        for resident in self.map.values_mut() {
348            if resident.last_used_generation == self.generation {
349                resident.dirty = false;
350            }
351        }
352        // This pass's high-water mark, before the stale entries go: the
353        // atlas had to hold all of it.
354        let peak_area = self.resident_area();
355        self.evict_unused();
356        let side = self.atlas.size().width;
357        let atlas_area = (side as u64) * (side as u64);
358        if side > self.min_size
359            && peak_area.saturating_mul(SHRINK_WHEN_AREA_AT_MOST_ONE_IN) <= atlas_area
360        {
361            self.sparse_resolves = self.sparse_resolves.saturating_add(1);
362        } else {
363            self.sparse_resolves = 0;
364        }
365    }
366
367    fn resident_area(&self) -> u64 {
368        self.map
369            .values()
370            .map(|resident| u64::from(resident.image.width) * u64::from(resident.image.height))
371            .sum()
372    }
373
374    /// Evict every resident no pass drew in the last
375    /// [`EVICT_AFTER_GENERATIONS`] passes. Returns how many went.
376    fn evict_unused(&mut self) -> usize {
377        let Some(stale_before) = self.generation.checked_sub(EVICT_AFTER_GENERATIONS) else {
378            return 0;
379        };
380        let mut evicted = 0;
381        for (_id, resident) in self
382            .map
383            .extract_if(|_, resident| resident.last_used_generation < stale_before)
384        {
385            self.atlas.deallocate(resident.alloc_id);
386            evicted += 1;
387        }
388        self.evicted_in_resolve += evicted;
389        self.evicted_total = self.evicted_total.saturating_add(evicted as u64);
390        evicted
391    }
392
393    /// Evict every resident the current pass has not drawn, however recently
394    /// an earlier pass did. The last resort once the atlas cannot grow: a
395    /// client's superseded frame is a resident of its own, and an image over
396    /// half the atlas's side cannot be allocated beside it, so waiting out
397    /// [`EVICT_AFTER_GENERATIONS`] omits the frame that replaced it. Returns
398    /// how many went.
399    pub(crate) fn evict_superseded(&mut self) -> usize {
400        let mut evicted = 0;
401        for (_id, resident) in self
402            .map
403            .extract_if(|_, resident| resident.last_used_generation != self.generation)
404        {
405            self.atlas.deallocate(resident.alloc_id);
406            evicted += 1;
407        }
408        self.evicted_in_resolve += evicted;
409        self.evicted_total = self.evicted_total.saturating_add(evicted as u64);
410        evicted
411    }
412
413    pub(crate) fn mark_dirty(&mut self, image: &ImageData) {
414        if let Some(resident) = self.map.get_mut(&image.data.id()) {
415            resident.dirty = true;
416        }
417    }
418
419    pub(crate) fn can_fit_image(&self, image: &ImageData) -> bool {
420        image.width <= self.atlas.size().width as u32
421            && image.height <= self.atlas.size().height as u32
422    }
423
424    pub(crate) fn record_omission(&mut self) {
425        self.omitted_in_resolve = self.omitted_in_resolve.saturating_add(1);
426        self.omitted_total = self.omitted_total.saturating_add(1);
427    }
428
429    pub(crate) fn evict_stale_entries(&mut self) -> bool {
430        if self.evicted_in_resolve != 0 {
431            return false;
432        }
433        self.evict_unused() != 0
434    }
435
436    fn repack_to_size(&mut self, size: i32) -> bool {
437        let mut atlas = AtlasAllocator::new(size2(size, size));
438        let mut entries: Vec<_> = self.map.iter().collect();
439        entries.sort_by_key(|(id, _)| *id);
440        let mut map = HashMap::with_capacity(self.map.len());
441        for (id, resident) in entries {
442            let Some(alloc) =
443                atlas.allocate(size2(resident.image.width as _, resident.image.height as _))
444            else {
445                return false;
446            };
447            let mut resident = resident.clone();
448            resident.alloc_id = alloc.id;
449            resident.x = alloc.rectangle.min.x as u32;
450            resident.y = alloc.rectangle.min.y as u32;
451            resident.dirty = true;
452            map.insert(*id, resident);
453        }
454        self.atlas = atlas;
455        self.map = map;
456        true
457    }
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use peniko::{Blob, ImageAlphaType, ImageFormat};
464    use std::sync::Arc;
465
466    fn image(id_byte: u8, width: u32, height: u32) -> ImageData {
467        let len = (width * height * 4) as usize;
468        ImageData {
469            data: Blob::new(Arc::new(vec![id_byte; len])),
470            format: ImageFormat::Rgba8,
471            width,
472            height,
473            alpha_type: ImageAlphaType::Alpha,
474        }
475    }
476
477    #[test]
478    fn atlas_size_persists_after_growth() {
479        let mut cache = ImageCache::new_with_sizes(16, 64);
480        assert_eq!(cache.atlas.size().width, 16);
481        assert!(cache.bump_size());
482        assert_eq!(cache.atlas.size().width, 32);
483        cache.begin_resolve();
484        assert_eq!(cache.atlas.size().width, 32);
485    }
486
487    #[test]
488    fn a_lowered_maximum_stops_atlas_growth() {
489        let mut cache = ImageCache::new();
490        cache.set_max_size(2048);
491        assert!(cache.bump_size());
492        assert_eq!(cache.atlas.size().width, 2048);
493        assert!(!cache.bump_size(), "grew past the 2048 limit");
494        assert_eq!(cache.atlas.size().width, 2048);
495    }
496
497    #[test]
498    fn omission_count_is_per_pass_and_cumulative() {
499        let mut cache = ImageCache::new_with_sizes(16, 16);
500        cache.begin_resolve();
501        cache.record_omission();
502        cache.record_omission();
503        assert_eq!(cache.images().omitted, 2);
504        assert_eq!(cache.images().omitted_total, 2);
505
506        cache.begin_resolve();
507        assert_eq!(cache.images().omitted, 0);
508        assert_eq!(cache.images().omitted_total, 2);
509    }
510
511    #[test]
512    fn an_image_that_changed_a_rect_takes_over_the_slot_and_uploads_the_rect() {
513        let mut cache = ImageCache::new_with_sizes(64, 64);
514        let first = image(1, 16, 16);
515        cache.begin_resolve();
516        let xy = cache.get_or_insert(&first).unwrap();
517        cache.finish_resolve();
518
519        // A caret's rect changed: the new image takes the slot, and only
520        // the rect is uploaded.
521        let second = image(2, 16, 16);
522        crate::register_image_delta(first.data.id(), second.data.id(), &[[3, 4, 2, 5]]);
523        cache.begin_resolve();
524        assert_eq!(cache.get_or_insert(&second), Some(xy));
525        assert!(cache.images.is_empty(), "nothing is uploaded whole");
526        assert_eq!(cache.regions.len(), 1, "one rect is uploaded");
527        let (uploaded, x, y, rect) = &cache.regions[0];
528        assert_eq!(uploaded.data.id(), second.data.id(), "from the new image");
529        assert_eq!(((*x, *y), *rect), (xy, [3, 4, 2, 5]), "into its slot");
530        assert!(
531            !cache.map.contains_key(&first.data.id()),
532            "the slot changed hands"
533        );
534        cache.finish_resolve();
535
536        // A renderer that missed a frame follows the deltas back to the
537        // image it holds.
538        let third = image(3, 16, 16);
539        let fourth = image(4, 16, 16);
540        crate::register_image_delta(second.data.id(), third.data.id(), &[[0, 0, 1, 1]]);
541        crate::register_image_delta(third.data.id(), fourth.data.id(), &[[8, 8, 2, 2]]);
542        cache.begin_resolve();
543        assert_eq!(cache.get_or_insert(&fourth), Some(xy));
544        let rects: Vec<_> = cache.regions.iter().map(|region| region.3).collect();
545        assert_eq!(rects, [[8, 8, 2, 2], [0, 0, 1, 1]], "both changes");
546        cache.finish_resolve();
547
548        // An image this pass draws keeps its slot: the next is uploaded
549        // whole, as is an image the atlas has no earlier image of.
550        let fifth = image(5, 16, 16);
551        crate::register_image_delta(fourth.data.id(), fifth.data.id(), &[[0, 0, 1, 1]]);
552        cache.begin_resolve();
553        assert_eq!(cache.get_or_insert(&fourth), Some(xy));
554        assert_ne!(cache.get_or_insert(&fifth), Some(xy), "a slot of its own");
555        let unrelated = image(6, 16, 16);
556        cache.get_or_insert(&unrelated);
557        assert!(cache.regions.is_empty(), "no rect uploads");
558        assert_eq!(cache.images.len(), 2, "both uploaded whole");
559    }
560
561    #[test]
562    fn resident_entries_are_reused_across_resolves() {
563        let mut cache = ImageCache::new_with_sizes(32, 64);
564        let image = image(7, 8, 8);
565
566        cache.begin_resolve();
567        let first = cache.get_or_insert(&image).unwrap();
568        assert_eq!(cache.images.len(), 1);
569        cache.finish_resolve();
570
571        cache.begin_resolve();
572        let second = cache.get_or_insert(&image).unwrap();
573        assert_eq!(first, second);
574        assert_eq!(cache.images.len(), 0);
575        assert_eq!(cache.map.len(), 1);
576    }
577
578    #[test]
579    fn marked_dirty_resident_entries_are_uploaded_again() {
580        let mut cache = ImageCache::new_with_sizes(32, 64);
581        let image = image(7, 8, 8);
582
583        cache.begin_resolve();
584        let first = cache.get_or_insert(&image).unwrap();
585        cache.finish_resolve();
586
587        cache.mark_dirty(&image);
588        cache.begin_resolve();
589        let second = cache.get_or_insert(&image).unwrap();
590        assert_eq!(first, second);
591        assert_eq!(cache.images.len(), 1);
592        assert_eq!(cache.images[0].0.data.id(), image.data.id());
593        assert_eq!((cache.images[0].1, cache.images[0].2), first);
594        cache.finish_resolve();
595
596        cache.begin_resolve();
597        assert_eq!(cache.get_or_insert(&image), Some(first));
598        assert_eq!(cache.images.len(), 0);
599    }
600
601    #[test]
602    fn marked_dirty_unused_entries_stay_dirty() {
603        let mut cache = ImageCache::new_with_sizes(32, 64);
604        let image = image(7, 8, 8);
605
606        cache.begin_resolve();
607        let xy = cache.get_or_insert(&image).unwrap();
608        cache.finish_resolve();
609
610        cache.mark_dirty(&image);
611        cache.begin_resolve();
612        cache.finish_resolve();
613
614        cache.begin_resolve();
615        assert_eq!(cache.get_or_insert(&image), Some(xy));
616        assert_eq!(cache.images.len(), 1);
617    }
618
619    #[test]
620    fn stale_entries_can_be_evicted_under_pressure() {
621        let mut cache = ImageCache::new_with_sizes(16, 16);
622        let image_a = image(1, 10, 10);
623        let image_b = image(2, 10, 10);
624
625        cache.begin_resolve();
626        assert!(cache.get_or_insert(&image_a).is_some());
627
628        cache.begin_resolve();
629
630        cache.begin_resolve();
631        cache.begin_resolve();
632        assert!(cache.get_or_insert(&image_b).is_none());
633        assert!(cache.evict_stale_entries());
634        assert!(cache.get_or_insert(&image_b).is_some());
635        assert!(!cache.map.contains_key(&image_a.data.id()));
636    }
637
638    #[test]
639    fn stale_entries_are_evicted_at_most_once_per_resolve() {
640        let mut cache = ImageCache::new_with_sizes(32, 32);
641        let image_a = image(1, 8, 8);
642        let image_b = image(2, 8, 8);
643
644        cache.begin_resolve();
645        assert!(cache.get_or_insert(&image_a).is_some());
646        cache.finish_resolve();
647
648        cache.begin_resolve();
649        assert!(cache.get_or_insert(&image_b).is_some());
650        cache.finish_resolve();
651
652        cache.begin_resolve();
653        cache.begin_resolve();
654        cache.begin_resolve();
655
656        assert!(cache.evict_stale_entries());
657        assert!(!cache.evict_stale_entries());
658    }
659
660    /// One resolve pass drawing `images`, as `Resolver::resolve` and its
661    /// `resolve_pending_images` run it: evict under pressure, else grow and
662    /// start the pass over.
663    fn pass(cache: &mut ImageCache, images: &[&ImageData]) -> Vec<(u32, u32)> {
664        cache.begin_resolve();
665        let at = 'outer: loop {
666            cache.restart_resolve_pass();
667            let mut at = Vec::new();
668            for image in images {
669                let xy = loop {
670                    if let Some(xy) = cache.get_or_insert(image) {
671                        break xy;
672                    }
673                    if cache.can_fit_image(image) && cache.evict_stale_entries() {
674                        continue;
675                    }
676                    assert!(
677                        cache.bump_size(),
678                        "no room for a {}x{}",
679                        image.width,
680                        image.height
681                    );
682                    continue 'outer;
683                };
684                at.push(xy);
685            }
686            break at;
687        };
688        cache.finish_resolve();
689        at
690    }
691
692    #[test]
693    fn stale_residents_are_released_without_allocation_pressure() {
694        let mut cache = ImageCache::new_with_sizes(64, 64);
695        let image_a = image(1, 8, 8);
696        let image_b = image(2, 8, 8);
697        let weak_a = image_a.data.downgrade();
698
699        pass(&mut cache, &[&image_a]);
700        drop(image_a);
701        assert!(
702            weak_a.upgrade().is_some(),
703            "a just-drawn image stays resident"
704        );
705
706        for _ in 0..3 {
707            pass(&mut cache, &[&image_b]);
708        }
709        assert!(
710            weak_a.upgrade().is_none(),
711            "the cache let go of A's pixels with the atlas nowhere near full"
712        );
713        let stats = cache.stats();
714        assert_eq!(stats.resident, 1);
715        assert_eq!(stats.resident_cpu_bytes, image_b.data.len() as u64);
716        assert_eq!(stats.evicted_total, 1);
717    }
718
719    #[test]
720    fn an_image_survives_two_passes_that_do_not_draw_it() {
721        // Two scenes sharing one renderer (two outputs, a capture beside the
722        // live frame) each skip the other's images; that must not re-upload.
723        let mut cache = ImageCache::new_with_sizes(64, 64);
724        let image_a = image(1, 8, 8);
725        let image_b = image(2, 8, 8);
726        let image_c = image(3, 8, 8);
727        for _ in 0..10 {
728            pass(&mut cache, &[&image_a]);
729            pass(&mut cache, &[&image_b]);
730            pass(&mut cache, &[&image_c]);
731        }
732        assert_eq!(cache.stats().evicted_total, 0);
733        assert_eq!(cache.stats().resident, 3);
734    }
735
736    #[test]
737    fn a_window_that_keeps_committing_holds_three_frames_at_most() {
738        let mut cache = ImageCache::new_with_sizes(256, 1024);
739        let frame_bytes = (100 * 80 * 4) as u64;
740        for commit in 0..200_u32 {
741            let frame = image(u8::try_from(commit % 251).unwrap(), 100, 80);
742            pass(&mut cache, &[&frame]);
743            assert!(
744                cache.stats().resident_cpu_bytes <= 3 * frame_bytes,
745                "commit {commit}: {:?}",
746                cache.stats()
747            );
748        }
749        assert_eq!(cache.stats().atlas_side, 256, "never grew");
750    }
751
752    #[test]
753    fn atlas_shrinks_after_residency_drops() {
754        let mut cache = ImageCache::new_with_sizes(1024, 4096);
755        let big: Vec<_> = (0..4).map(|i| image(i, 1500, 1500)).collect();
756        let small = image(9, 256, 256);
757        pass(&mut cache, &big.iter().collect::<Vec<_>>());
758        assert_eq!(cache.atlas.size().width, 4096);
759        drop(big);
760
761        for _ in 0..(3 * (SHRINK_AFTER_RESOLVES + 1)) {
762            pass(&mut cache, &[&small]);
763        }
764        let stats = cache.stats();
765        assert_eq!(stats.atlas_side, 1024, "{stats:?}");
766        assert_eq!(stats.shrinks_total, 2);
767        assert_eq!(stats.resident, 1);
768    }
769
770    /// #4104: a desktop that goes idle after a close draws only a few
771    /// frames. Told the images went, the atlas comes all the way down in
772    /// those, and a busy atlas still does not.
773    #[test]
774    fn told_images_went_the_atlas_shrinks_within_a_few_resolves() {
775        let mut cache = ImageCache::new_with_sizes(1024, 8192);
776        let wallpaper = image(0, 1920, 1080);
777        let windows: Vec<_> = (1..5).map(|i| image(i, 1800, 1000)).collect();
778        let mut all = vec![&wallpaper];
779        all.extend(windows.iter());
780        pass(&mut cache, &all);
781        let grown = cache.stats().atlas_side;
782        assert!(grown >= 4096, "{:?}", cache.stats());
783        drop(windows);
784
785        cache.shrink_soon();
786        for _ in 0..6 {
787            pass(&mut cache, &[&wallpaper]);
788        }
789        let stats = cache.stats();
790        assert_eq!(
791            stats.atlas_side, 2048,
792            "the wallpaper alone needs 2048: {stats:?}"
793        );
794        assert_eq!(stats.resident, 1);
795
796        // The request runs out: a sparse atlas waits the long way again.
797        let mut cache = ImageCache::new_with_sizes(32, 64);
798        let large = image(1, 40, 40);
799        let small = image(2, 8, 8);
800        pass(&mut cache, &[&large, &small]);
801        cache.shrink_soon();
802        for _ in 0..SHRINK_SOON_RESOLVES {
803            pass(&mut cache, &[&large, &small]);
804        }
805        drop(large);
806        for _ in 0..8 {
807            pass(&mut cache, &[&small]);
808        }
809        assert_eq!(cache.stats().atlas_side, 64, "{:?}", cache.stats());
810    }
811
812    #[test]
813    fn a_shrunk_atlas_uploads_its_residents_again_where_it_draws_them() {
814        let mut cache = ImageCache::new_with_sizes(32, 64);
815        let large = image(1, 40, 40);
816        let small = image(2, 8, 8);
817        pass(&mut cache, &[&large, &small]);
818        assert_eq!(cache.atlas.size().width, 64);
819        drop(large);
820
821        let mut uploads = Vec::new();
822        for _ in 0..(SHRINK_AFTER_RESOLVES + 4) {
823            cache.begin_resolve();
824            let xy = cache.get_or_insert(&small).expect("fits");
825            uploads.extend(
826                cache
827                    .images
828                    .iter()
829                    .map(|(image, x, y)| (image.data.id(), (*x, *y), xy)),
830            );
831            cache.finish_resolve();
832        }
833        assert_eq!(cache.stats().atlas_side, 32);
834        // Uploaded on first use, and once more after the shrink moved it.
835        let after_shrink = uploads.last().expect("re-uploaded");
836        assert_eq!(after_shrink.0, small.data.id());
837        assert_eq!(after_shrink.1, after_shrink.2, "uploaded where it is drawn");
838        assert_eq!(cache.stats().shrinks_total, 1);
839    }
840
841    #[test]
842    fn a_busy_atlas_does_not_shrink() {
843        let mut cache = ImageCache::new_with_sizes(32, 64);
844        let large = image(1, 40, 40);
845        for _ in 0..(4 * SHRINK_AFTER_RESOLVES) {
846            pass(&mut cache, &[&large]);
847        }
848        assert_eq!(cache.stats().atlas_side, 64);
849        assert_eq!(cache.stats().shrinks_total, 0);
850    }
851
852    /// The compositor's open/close cycle: a wallpaper drawn every frame, a
853    /// window that commits a new frame per paint while open, then closes.
854    /// What the cache holds after each close must not grow with the cycles.
855    #[test]
856    fn open_close_cycles_leave_nothing_behind() {
857        let mut cache = ImageCache::new_with_sizes(1024, 8192);
858        let wallpaper = image(0, 1920, 1080);
859        let mut after_close = Vec::new();
860        for cycle in 0..30_u32 {
861            let (width, height) = (800 + 40 * (cycle % 5), 600 + 30 * (cycle % 3));
862            for commit in 0..12_u32 {
863                let frame = image(
864                    u8::try_from((cycle * 12 + commit) % 251).unwrap(),
865                    width,
866                    height,
867                );
868                pass(&mut cache, &[&wallpaper, &frame]);
869            }
870            for _ in 0..(SHRINK_AFTER_RESOLVES + 4) {
871                pass(&mut cache, &[&wallpaper]);
872            }
873            after_close.push(cache.stats());
874        }
875        let first = after_close[0];
876        for (cycle, stats) in after_close.iter().enumerate() {
877            assert_eq!(stats.resident, 1, "cycle {cycle}: {stats:?}");
878            assert_eq!(
879                stats.resident_cpu_bytes,
880                wallpaper.data.len() as u64,
881                "cycle {cycle}: {stats:?}"
882            );
883            assert_eq!(
884                stats.atlas_side, first.atlas_side,
885                "cycle {cycle}: {stats:?}"
886            );
887        }
888        assert!(first.atlas_side <= 2048, "{first:?}");
889    }
890
891    #[test]
892    fn failed_repack_leaves_existing_residency_unchanged() {
893        let mut cache = ImageCache::new_with_sizes(16, 16);
894        let image = image(1, 12, 12);
895
896        cache.begin_resolve();
897        let xy = cache.get_or_insert(&image).unwrap();
898
899        assert!(!cache.repack_to_size(8));
900        assert_eq!(cache.atlas.size().width, 16);
901        assert_eq!(cache.get_or_insert(&image), Some(xy));
902        assert_eq!(cache.map.len(), 1);
903    }
904
905    #[test]
906    fn a_superseded_frame_makes_room_when_the_atlas_cannot_grow() {
907        // The atlas is full at its maximum: a replacement frame more than
908        // half its side cannot sit beside the frame it replaces.
909        let mut cache = ImageCache::new_with_sizes(16, 16);
910        cache.begin_resolve();
911        assert!(cache.get_or_insert(&image(1, 12, 12)).is_some());
912        cache.finish_resolve();
913        cache.begin_resolve();
914        let next = image(2, 12, 12);
915        assert!(
916            cache.get_or_insert(&next).is_none(),
917            "no room beside the old frame"
918        );
919        assert!(!cache.evict_stale_entries(), "one pass is not stale");
920        assert!(!cache.bump_size(), "already at the maximum");
921        assert_eq!(cache.evict_superseded(), 1);
922        assert!(cache.get_or_insert(&next).is_some());
923        // What this pass drew stays.
924        assert_eq!(cache.evict_superseded(), 0);
925    }
926}