tilo-vello-encoding 0.5.0

vello_encoding 0.9.0 (https://github.com/linebender/vello) with the BumpBudget sizing tilo-vello uses. Tilo's fork; see TILO-FORK.md.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
// Copyright 2022 the Vello Authors
// SPDX-License-Identifier: Apache-2.0 OR MIT

use guillotiere::{AllocId, AtlasAllocator, size2};
use peniko::ImageData;
use std::collections::HashMap;
use std::collections::hash_map::Entry;

const DEFAULT_ATLAS_SIZE: i32 = 1024;
const MAX_ATLAS_SIZE: i32 = 8192;
const EVICT_AFTER_GENERATIONS: u64 = 2;
/// Consecutive resolves the atlas must stay mostly empty before it halves.
/// Long enough that one frame without a window (a close animation, a
/// workspace switch) does not throw the atlas away only to grow it back.
const SHRINK_AFTER_RESOLVES: u32 = 60;
/// Resolves after [`ImageCache::shrink_soon`] in which a sparse atlas
/// shrinks at once: enough for the images that went to age out
/// ([`EVICT_AFTER_GENERATIONS`]) and the atlas to come down.
const SHRINK_SOON_RESOLVES: u32 = 16;
/// The atlas halves only while its residents cover at most `1 / N` of it,
/// so the halved atlas is at most half full and the next frame's
/// replacement images still fit without growing straight back.
const SHRINK_WHEN_AREA_AT_MOST_ONE_IN: u64 = 8;
/// Deltas followed back from an image to one the atlas holds (Tilo patch):
/// a renderer that missed a few frames still takes over the slot.
const MAX_DELTA_CHAIN: usize = 4;

/// What the image cache holds, for memory diagnostics.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ImageCacheStats {
    /// Side length of the square atlas, in pixels.
    pub atlas_side: u32,
    /// Images resident in the atlas.
    pub resident: usize,
    /// Bytes of CPU pixels the residents keep alive (their blobs). A blob
    /// the caller still holds is shared, not copied, so this is an upper
    /// bound on what the cache alone keeps.
    pub resident_cpu_bytes: u64,
    /// Area of the residents, in atlas pixels.
    pub resident_area: u64,
    /// Residents evicted over the cache's lifetime.
    pub evicted_total: u64,
    /// Times the atlas halved because its residents no longer needed it.
    pub shrinks_total: u64,
    /// Images omitted over the cache's lifetime.
    pub omitted_total: u64,
}

#[derive(Default)]
pub struct Images<'a> {
    /// Width of the square image atlas texture.
    pub width: u32,
    /// Height of the square image atlas texture.
    pub height: u32,
    /// Number of resident images evicted during the current resolve pass.
    ///
    /// This is only used for renderer-side debug logging.
    pub evicted: usize,
    /// Images omitted because they could not be allocated this resolve pass.
    pub omitted: usize,
    /// Images omitted over the lifetime of this cache.
    pub omitted_total: u64,
    /// Images that must be uploaded in the current resolve pass, with atlas locations.
    pub images: &'a [(ImageData, u32, u32)],
    /// Rects of images that must be uploaded in the current resolve pass
    /// (Tilo patch): the image, its atlas location, and the rect of it.
    pub regions: &'a [(ImageData, u32, u32, crate::ImageRect)],
}

#[derive(Clone)]
struct ResidentImage {
    image: ImageData,
    alloc_id: AllocId,
    x: u32,
    y: u32,
    dirty: bool,
    last_used_generation: u64,
}

pub(crate) struct ImageCache {
    atlas: AtlasAllocator,
    /// Side length the atlas starts at, and never shrinks below.
    min_size: i32,
    /// Maximum side length for the square image atlas texture.
    max_size: i32,
    /// Resolves in a row whose residents fit in a fraction of the atlas; see
    /// [`SHRINK_AFTER_RESOLVES`].
    sparse_resolves: u32,
    /// Resolves left in which a sparse atlas shrinks without waiting for
    /// [`SHRINK_AFTER_RESOLVES`]; see [`Self::shrink_soon`].
    shrink_soon_resolves: u32,
    /// Residents evicted over the cache's lifetime.
    evicted_total: u64,
    /// Times the atlas halved.
    shrinks_total: u64,
    /// Monotonic counter for resolve passes, used to track when resident images were last used.
    generation: u64,
    /// Number of resident images evicted during the current resolve pass.
    ///
    /// This is exposed through [`Images::evicted`] for renderer-side debug logging, and also
    /// prevents repeated stale-eviction scans during the same resolve pass.
    evicted_in_resolve: usize,
    /// Images omitted during the current resolve pass.
    omitted_in_resolve: usize,
    /// Images omitted over the lifetime of this cache.
    omitted_total: u64,
    /// Map from image blob id to atlas residency.
    map: HashMap<u64, ResidentImage>,
    /// Images that must be uploaded in the current resolve pass, with atlas locations.
    images: Vec<(ImageData, u32, u32)>,
    /// Rects of images that took over an earlier image's slot this pass.
    regions: Vec<(ImageData, u32, u32, crate::ImageRect)>,
}

impl Default for ImageCache {
    fn default() -> Self {
        Self::new()
    }
}

impl ImageCache {
    pub(crate) fn new() -> Self {
        Self::new_with_sizes(DEFAULT_ATLAS_SIZE, MAX_ATLAS_SIZE)
    }

    fn new_with_sizes(initial_size: i32, max_size: i32) -> Self {
        Self {
            atlas: AtlasAllocator::new(size2(initial_size, initial_size)),
            min_size: initial_size,
            max_size,
            sparse_resolves: 0,
            shrink_soon_resolves: 0,
            evicted_total: 0,
            shrinks_total: 0,
            generation: 0,
            evicted_in_resolve: 0,
            omitted_in_resolve: 0,
            omitted_total: 0,
            map: HashMap::default(),
            images: Vec::default(),
            regions: Vec::default(),
        }
    }

    /// Limit atlas growth to `max_size` pixels per side. A smaller limit only
    /// stops further growth; the atlas comes down on its own once its
    /// residents fit in a fraction of it (see [`Self::finish_resolve`]).
    pub(crate) fn set_max_size(&mut self, max_size: i32) {
        self.max_size = max_size.max(DEFAULT_ATLAS_SIZE);
    }

    /// What the cache holds now.
    pub(crate) fn stats(&self) -> ImageCacheStats {
        ImageCacheStats {
            atlas_side: self.atlas.size().width as u32,
            resident: self.map.len(),
            resident_cpu_bytes: self
                .map
                .values()
                .map(|resident| resident.image.data.len() as u64)
                .sum(),
            resident_area: self.resident_area(),
            evicted_total: self.evicted_total,
            shrinks_total: self.shrinks_total,
            omitted_total: self.omitted_total,
        }
    }

    pub(crate) fn begin_resolve(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        self.evicted_in_resolve = 0;
        self.omitted_in_resolve = 0;
        self.images.clear();
        self.regions.clear();
        // Halve here, before this pass looks anything up: every position this
        // pass hands out is then one in the halved atlas. Halving in
        // `finish_resolve` would move images the pass just encoded.
        let soon = self.shrink_soon_resolves > 0;
        self.shrink_soon_resolves = self.shrink_soon_resolves.saturating_sub(1);
        if soon && self.sparse_resolves > 0 {
            // The caller said the images went for good: come down as far as
            // the residents allow now, each halving as safe as a slow one.
            self.sparse_resolves = 0;
            let area = self.resident_area();
            loop {
                let side = self.atlas.size().width;
                let half = side / 2;
                if half < self.min_size
                    || area.saturating_mul(SHRINK_WHEN_AREA_AT_MOST_ONE_IN)
                        > (side as u64) * (side as u64)
                    || !self.repack_to_size(half)
                {
                    break;
                }
                self.shrinks_total = self.shrinks_total.saturating_add(1);
            }
        } else if self.sparse_resolves >= SHRINK_AFTER_RESOLVES {
            self.sparse_resolves = 0;
            let half = self.atlas.size().width / 2;
            if half >= self.min_size && self.repack_to_size(half) {
                self.shrinks_total = self.shrinks_total.saturating_add(1);
            }
        }
    }

    /// Images went for good (a window closed): for the next
    /// [`SHRINK_SOON_RESOLVES`] resolves, an atlas far bigger than its
    /// residents shrinks at once instead of after [`SHRINK_AFTER_RESOLVES`]
    /// sparse ones. A desktop that goes idle after a close draws too few
    /// frames to bring a grown atlas down the slow way, and keeps its memory.
    pub(crate) fn shrink_soon(&mut self) {
        self.shrink_soon_resolves = SHRINK_SOON_RESOLVES;
    }

    pub(crate) fn restart_resolve_pass(&mut self) {
        self.images.clear();
        self.regions.clear();
        let previous_generation = self.generation.wrapping_sub(1);
        for resident in self.map.values_mut() {
            if resident.last_used_generation == self.generation {
                resident.last_used_generation = previous_generation;
            }
        }
    }

    pub(crate) fn images(&self) -> Images<'_> {
        Images {
            width: self.atlas.size().width as u32,
            height: self.atlas.size().height as u32,
            evicted: self.evicted_in_resolve,
            omitted: self.omitted_in_resolve,
            omitted_total: self.omitted_total,
            images: &self.images,
            regions: &self.regions,
        }
    }

    pub(crate) fn bump_size(&mut self) -> bool {
        let mut new_size = self.atlas.size().width * 2;
        while new_size <= self.max_size {
            if self.repack_to_size(new_size) {
                self.images.clear();
                self.regions.clear();
                return true;
            }
            new_size *= 2;
        }
        false
    }

    pub(crate) fn get_or_insert(&mut self, image: &ImageData) -> Option<(u32, u32)> {
        if !self.map.contains_key(&image.data.id())
            && let Some(xy) = self.take_over(image)
        {
            return Some(xy);
        }
        match self.map.entry(image.data.id()) {
            Entry::Occupied(mut occupied) => {
                let resident = occupied.get_mut();
                let xy = (resident.x, resident.y);
                if resident.last_used_generation != self.generation {
                    resident.last_used_generation = self.generation;
                    if resident.dirty {
                        self.images
                            .push((resident.image.clone(), resident.x, resident.y));
                    }
                }
                Some(xy)
            }
            Entry::Vacant(vacant) => {
                let alloc = self
                    .atlas
                    .allocate(size2(image.width as _, image.height as _))?;
                let x = alloc.rectangle.min.x as u32;
                let y = alloc.rectangle.min.y as u32;
                let resident = ResidentImage {
                    image: image.clone(),
                    alloc_id: alloc.id,
                    x,
                    y,
                    dirty: true,
                    last_used_generation: self.generation,
                };
                self.images.push((image.clone(), x, y));
                vacant.insert(resident);
                Some((x, y))
            }
        }
    }

    /// Give `image` the slot of the image it changes a few rects of
    /// ([`crate::register_image_delta`]), if the atlas holds that image
    /// as it was uploaded and this pass has not drawn it, and upload only
    /// those rects (Tilo patch).
    fn take_over(&mut self, image: &ImageData) -> Option<(u32, u32)> {
        let mut rects = Vec::new();
        let mut id = image.data.id();
        for _ in 0..MAX_DELTA_CHAIN {
            let (from, changed) = crate::image_delta::image_delta(id)?;
            rects.extend_from_slice(&changed);
            let Some(resident) = self.map.get(&from) else {
                id = from;
                continue;
            };
            if resident.dirty
                || resident.last_used_generation == self.generation
                || resident.image.width != image.width
                || resident.image.height != image.height
                || resident.image.format != image.format
                || resident.image.alpha_type != image.alpha_type
            {
                return None;
            }
            let mut resident = self.map.remove(&from)?;
            let (x, y) = (resident.x, resident.y);
            for rect in rects {
                let [rx, ry, width, height] = rect;
                if width == 0
                    || height == 0
                    || rx >= image.width
                    || ry >= image.height
                    || width > image.width - rx
                    || height > image.height - ry
                {
                    continue;
                }
                self.regions.push((image.clone(), x, y, rect));
            }
            resident.image = image.clone();
            resident.last_used_generation = self.generation;
            // A pass that restarts repacks the atlas and uploads it whole.
            resident.dirty = true;
            self.map.insert(image.data.id(), resident);
            return Some((x, y));
        }
        None
    }

    /// End a resolve pass: release what the last few passes stopped drawing,
    /// and note whether the atlas is far bigger than its residents need.
    ///
    /// Eviction used to wait for an allocation to fail. A client frame is a
    /// new image every commit, so every superseded frame kept its CPU pixels
    /// alive until the atlas was full — and the atlas grew to its maximum
    /// first, which it then kept for the life of the process.
    pub(crate) fn finish_resolve(&mut self) {
        for resident in self.map.values_mut() {
            if resident.last_used_generation == self.generation {
                resident.dirty = false;
            }
        }
        // This pass's high-water mark, before the stale entries go: the
        // atlas had to hold all of it.
        let peak_area = self.resident_area();
        self.evict_unused();
        let side = self.atlas.size().width;
        let atlas_area = (side as u64) * (side as u64);
        if side > self.min_size
            && peak_area.saturating_mul(SHRINK_WHEN_AREA_AT_MOST_ONE_IN) <= atlas_area
        {
            self.sparse_resolves = self.sparse_resolves.saturating_add(1);
        } else {
            self.sparse_resolves = 0;
        }
    }

    fn resident_area(&self) -> u64 {
        self.map
            .values()
            .map(|resident| u64::from(resident.image.width) * u64::from(resident.image.height))
            .sum()
    }

    /// Evict every resident no pass drew in the last
    /// [`EVICT_AFTER_GENERATIONS`] passes. Returns how many went.
    fn evict_unused(&mut self) -> usize {
        let Some(stale_before) = self.generation.checked_sub(EVICT_AFTER_GENERATIONS) else {
            return 0;
        };
        let mut evicted = 0;
        for (_id, resident) in self
            .map
            .extract_if(|_, resident| resident.last_used_generation < stale_before)
        {
            self.atlas.deallocate(resident.alloc_id);
            evicted += 1;
        }
        self.evicted_in_resolve += evicted;
        self.evicted_total = self.evicted_total.saturating_add(evicted as u64);
        evicted
    }

    /// Evict every resident the current pass has not drawn, however recently
    /// an earlier pass did. The last resort once the atlas cannot grow: a
    /// client's superseded frame is a resident of its own, and an image over
    /// half the atlas's side cannot be allocated beside it, so waiting out
    /// [`EVICT_AFTER_GENERATIONS`] omits the frame that replaced it. Returns
    /// how many went.
    pub(crate) fn evict_superseded(&mut self) -> usize {
        let mut evicted = 0;
        for (_id, resident) in self
            .map
            .extract_if(|_, resident| resident.last_used_generation != self.generation)
        {
            self.atlas.deallocate(resident.alloc_id);
            evicted += 1;
        }
        self.evicted_in_resolve += evicted;
        self.evicted_total = self.evicted_total.saturating_add(evicted as u64);
        evicted
    }

    pub(crate) fn mark_dirty(&mut self, image: &ImageData) {
        if let Some(resident) = self.map.get_mut(&image.data.id()) {
            resident.dirty = true;
        }
    }

    pub(crate) fn can_fit_image(&self, image: &ImageData) -> bool {
        image.width <= self.atlas.size().width as u32
            && image.height <= self.atlas.size().height as u32
    }

    pub(crate) fn record_omission(&mut self) {
        self.omitted_in_resolve = self.omitted_in_resolve.saturating_add(1);
        self.omitted_total = self.omitted_total.saturating_add(1);
    }

    pub(crate) fn evict_stale_entries(&mut self) -> bool {
        if self.evicted_in_resolve != 0 {
            return false;
        }
        self.evict_unused() != 0
    }

    fn repack_to_size(&mut self, size: i32) -> bool {
        let mut atlas = AtlasAllocator::new(size2(size, size));
        let mut entries: Vec<_> = self.map.iter().collect();
        entries.sort_by_key(|(id, _)| *id);
        let mut map = HashMap::with_capacity(self.map.len());
        for (id, resident) in entries {
            let Some(alloc) =
                atlas.allocate(size2(resident.image.width as _, resident.image.height as _))
            else {
                return false;
            };
            let mut resident = resident.clone();
            resident.alloc_id = alloc.id;
            resident.x = alloc.rectangle.min.x as u32;
            resident.y = alloc.rectangle.min.y as u32;
            resident.dirty = true;
            map.insert(*id, resident);
        }
        self.atlas = atlas;
        self.map = map;
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use peniko::{Blob, ImageAlphaType, ImageFormat};
    use std::sync::Arc;

    fn image(id_byte: u8, width: u32, height: u32) -> ImageData {
        let len = (width * height * 4) as usize;
        ImageData {
            data: Blob::new(Arc::new(vec![id_byte; len])),
            format: ImageFormat::Rgba8,
            width,
            height,
            alpha_type: ImageAlphaType::Alpha,
        }
    }

    #[test]
    fn atlas_size_persists_after_growth() {
        let mut cache = ImageCache::new_with_sizes(16, 64);
        assert_eq!(cache.atlas.size().width, 16);
        assert!(cache.bump_size());
        assert_eq!(cache.atlas.size().width, 32);
        cache.begin_resolve();
        assert_eq!(cache.atlas.size().width, 32);
    }

    #[test]
    fn a_lowered_maximum_stops_atlas_growth() {
        let mut cache = ImageCache::new();
        cache.set_max_size(2048);
        assert!(cache.bump_size());
        assert_eq!(cache.atlas.size().width, 2048);
        assert!(!cache.bump_size(), "grew past the 2048 limit");
        assert_eq!(cache.atlas.size().width, 2048);
    }

    #[test]
    fn omission_count_is_per_pass_and_cumulative() {
        let mut cache = ImageCache::new_with_sizes(16, 16);
        cache.begin_resolve();
        cache.record_omission();
        cache.record_omission();
        assert_eq!(cache.images().omitted, 2);
        assert_eq!(cache.images().omitted_total, 2);

        cache.begin_resolve();
        assert_eq!(cache.images().omitted, 0);
        assert_eq!(cache.images().omitted_total, 2);
    }

    #[test]
    fn an_image_that_changed_a_rect_takes_over_the_slot_and_uploads_the_rect() {
        let mut cache = ImageCache::new_with_sizes(64, 64);
        let first = image(1, 16, 16);
        cache.begin_resolve();
        let xy = cache.get_or_insert(&first).unwrap();
        cache.finish_resolve();

        // A caret's rect changed: the new image takes the slot, and only
        // the rect is uploaded.
        let second = image(2, 16, 16);
        crate::register_image_delta(first.data.id(), second.data.id(), &[[3, 4, 2, 5]]);
        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&second), Some(xy));
        assert!(cache.images.is_empty(), "nothing is uploaded whole");
        assert_eq!(cache.regions.len(), 1, "one rect is uploaded");
        let (uploaded, x, y, rect) = &cache.regions[0];
        assert_eq!(uploaded.data.id(), second.data.id(), "from the new image");
        assert_eq!(((*x, *y), *rect), (xy, [3, 4, 2, 5]), "into its slot");
        assert!(
            !cache.map.contains_key(&first.data.id()),
            "the slot changed hands"
        );
        cache.finish_resolve();

        // A renderer that missed a frame follows the deltas back to the
        // image it holds.
        let third = image(3, 16, 16);
        let fourth = image(4, 16, 16);
        crate::register_image_delta(second.data.id(), third.data.id(), &[[0, 0, 1, 1]]);
        crate::register_image_delta(third.data.id(), fourth.data.id(), &[[8, 8, 2, 2]]);
        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&fourth), Some(xy));
        let rects: Vec<_> = cache.regions.iter().map(|region| region.3).collect();
        assert_eq!(rects, [[8, 8, 2, 2], [0, 0, 1, 1]], "both changes");
        cache.finish_resolve();

        // An image this pass draws keeps its slot: the next is uploaded
        // whole, as is an image the atlas has no earlier image of.
        let fifth = image(5, 16, 16);
        crate::register_image_delta(fourth.data.id(), fifth.data.id(), &[[0, 0, 1, 1]]);
        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&fourth), Some(xy));
        assert_ne!(cache.get_or_insert(&fifth), Some(xy), "a slot of its own");
        let unrelated = image(6, 16, 16);
        cache.get_or_insert(&unrelated);
        assert!(cache.regions.is_empty(), "no rect uploads");
        assert_eq!(cache.images.len(), 2, "both uploaded whole");
    }

    #[test]
    fn resident_entries_are_reused_across_resolves() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let image = image(7, 8, 8);

        cache.begin_resolve();
        let first = cache.get_or_insert(&image).unwrap();
        assert_eq!(cache.images.len(), 1);
        cache.finish_resolve();

        cache.begin_resolve();
        let second = cache.get_or_insert(&image).unwrap();
        assert_eq!(first, second);
        assert_eq!(cache.images.len(), 0);
        assert_eq!(cache.map.len(), 1);
    }

    #[test]
    fn marked_dirty_resident_entries_are_uploaded_again() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let image = image(7, 8, 8);

        cache.begin_resolve();
        let first = cache.get_or_insert(&image).unwrap();
        cache.finish_resolve();

        cache.mark_dirty(&image);
        cache.begin_resolve();
        let second = cache.get_or_insert(&image).unwrap();
        assert_eq!(first, second);
        assert_eq!(cache.images.len(), 1);
        assert_eq!(cache.images[0].0.data.id(), image.data.id());
        assert_eq!((cache.images[0].1, cache.images[0].2), first);
        cache.finish_resolve();

        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&image), Some(first));
        assert_eq!(cache.images.len(), 0);
    }

    #[test]
    fn marked_dirty_unused_entries_stay_dirty() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let image = image(7, 8, 8);

        cache.begin_resolve();
        let xy = cache.get_or_insert(&image).unwrap();
        cache.finish_resolve();

        cache.mark_dirty(&image);
        cache.begin_resolve();
        cache.finish_resolve();

        cache.begin_resolve();
        assert_eq!(cache.get_or_insert(&image), Some(xy));
        assert_eq!(cache.images.len(), 1);
    }

    #[test]
    fn stale_entries_can_be_evicted_under_pressure() {
        let mut cache = ImageCache::new_with_sizes(16, 16);
        let image_a = image(1, 10, 10);
        let image_b = image(2, 10, 10);

        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_a).is_some());

        cache.begin_resolve();

        cache.begin_resolve();
        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_b).is_none());
        assert!(cache.evict_stale_entries());
        assert!(cache.get_or_insert(&image_b).is_some());
        assert!(!cache.map.contains_key(&image_a.data.id()));
    }

    #[test]
    fn stale_entries_are_evicted_at_most_once_per_resolve() {
        let mut cache = ImageCache::new_with_sizes(32, 32);
        let image_a = image(1, 8, 8);
        let image_b = image(2, 8, 8);

        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_a).is_some());
        cache.finish_resolve();

        cache.begin_resolve();
        assert!(cache.get_or_insert(&image_b).is_some());
        cache.finish_resolve();

        cache.begin_resolve();
        cache.begin_resolve();
        cache.begin_resolve();

        assert!(cache.evict_stale_entries());
        assert!(!cache.evict_stale_entries());
    }

    /// One resolve pass drawing `images`, as `Resolver::resolve` and its
    /// `resolve_pending_images` run it: evict under pressure, else grow and
    /// start the pass over.
    fn pass(cache: &mut ImageCache, images: &[&ImageData]) -> Vec<(u32, u32)> {
        cache.begin_resolve();
        let at = 'outer: loop {
            cache.restart_resolve_pass();
            let mut at = Vec::new();
            for image in images {
                let xy = loop {
                    if let Some(xy) = cache.get_or_insert(image) {
                        break xy;
                    }
                    if cache.can_fit_image(image) && cache.evict_stale_entries() {
                        continue;
                    }
                    assert!(
                        cache.bump_size(),
                        "no room for a {}x{}",
                        image.width,
                        image.height
                    );
                    continue 'outer;
                };
                at.push(xy);
            }
            break at;
        };
        cache.finish_resolve();
        at
    }

    #[test]
    fn stale_residents_are_released_without_allocation_pressure() {
        let mut cache = ImageCache::new_with_sizes(64, 64);
        let image_a = image(1, 8, 8);
        let image_b = image(2, 8, 8);
        let weak_a = image_a.data.downgrade();

        pass(&mut cache, &[&image_a]);
        drop(image_a);
        assert!(
            weak_a.upgrade().is_some(),
            "a just-drawn image stays resident"
        );

        for _ in 0..3 {
            pass(&mut cache, &[&image_b]);
        }
        assert!(
            weak_a.upgrade().is_none(),
            "the cache let go of A's pixels with the atlas nowhere near full"
        );
        let stats = cache.stats();
        assert_eq!(stats.resident, 1);
        assert_eq!(stats.resident_cpu_bytes, image_b.data.len() as u64);
        assert_eq!(stats.evicted_total, 1);
    }

    #[test]
    fn an_image_survives_two_passes_that_do_not_draw_it() {
        // Two scenes sharing one renderer (two outputs, a capture beside the
        // live frame) each skip the other's images; that must not re-upload.
        let mut cache = ImageCache::new_with_sizes(64, 64);
        let image_a = image(1, 8, 8);
        let image_b = image(2, 8, 8);
        let image_c = image(3, 8, 8);
        for _ in 0..10 {
            pass(&mut cache, &[&image_a]);
            pass(&mut cache, &[&image_b]);
            pass(&mut cache, &[&image_c]);
        }
        assert_eq!(cache.stats().evicted_total, 0);
        assert_eq!(cache.stats().resident, 3);
    }

    #[test]
    fn a_window_that_keeps_committing_holds_three_frames_at_most() {
        let mut cache = ImageCache::new_with_sizes(256, 1024);
        let frame_bytes = (100 * 80 * 4) as u64;
        for commit in 0..200_u32 {
            let frame = image(u8::try_from(commit % 251).unwrap(), 100, 80);
            pass(&mut cache, &[&frame]);
            assert!(
                cache.stats().resident_cpu_bytes <= 3 * frame_bytes,
                "commit {commit}: {:?}",
                cache.stats()
            );
        }
        assert_eq!(cache.stats().atlas_side, 256, "never grew");
    }

    #[test]
    fn atlas_shrinks_after_residency_drops() {
        let mut cache = ImageCache::new_with_sizes(1024, 4096);
        let big: Vec<_> = (0..4).map(|i| image(i, 1500, 1500)).collect();
        let small = image(9, 256, 256);
        pass(&mut cache, &big.iter().collect::<Vec<_>>());
        assert_eq!(cache.atlas.size().width, 4096);
        drop(big);

        for _ in 0..(3 * (SHRINK_AFTER_RESOLVES + 1)) {
            pass(&mut cache, &[&small]);
        }
        let stats = cache.stats();
        assert_eq!(stats.atlas_side, 1024, "{stats:?}");
        assert_eq!(stats.shrinks_total, 2);
        assert_eq!(stats.resident, 1);
    }

    /// #4104: a desktop that goes idle after a close draws only a few
    /// frames. Told the images went, the atlas comes all the way down in
    /// those, and a busy atlas still does not.
    #[test]
    fn told_images_went_the_atlas_shrinks_within_a_few_resolves() {
        let mut cache = ImageCache::new_with_sizes(1024, 8192);
        let wallpaper = image(0, 1920, 1080);
        let windows: Vec<_> = (1..5).map(|i| image(i, 1800, 1000)).collect();
        let mut all = vec![&wallpaper];
        all.extend(windows.iter());
        pass(&mut cache, &all);
        let grown = cache.stats().atlas_side;
        assert!(grown >= 4096, "{:?}", cache.stats());
        drop(windows);

        cache.shrink_soon();
        for _ in 0..6 {
            pass(&mut cache, &[&wallpaper]);
        }
        let stats = cache.stats();
        assert_eq!(
            stats.atlas_side, 2048,
            "the wallpaper alone needs 2048: {stats:?}"
        );
        assert_eq!(stats.resident, 1);

        // The request runs out: a sparse atlas waits the long way again.
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let large = image(1, 40, 40);
        let small = image(2, 8, 8);
        pass(&mut cache, &[&large, &small]);
        cache.shrink_soon();
        for _ in 0..SHRINK_SOON_RESOLVES {
            pass(&mut cache, &[&large, &small]);
        }
        drop(large);
        for _ in 0..8 {
            pass(&mut cache, &[&small]);
        }
        assert_eq!(cache.stats().atlas_side, 64, "{:?}", cache.stats());
    }

    #[test]
    fn a_shrunk_atlas_uploads_its_residents_again_where_it_draws_them() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let large = image(1, 40, 40);
        let small = image(2, 8, 8);
        pass(&mut cache, &[&large, &small]);
        assert_eq!(cache.atlas.size().width, 64);
        drop(large);

        let mut uploads = Vec::new();
        for _ in 0..(SHRINK_AFTER_RESOLVES + 4) {
            cache.begin_resolve();
            let xy = cache.get_or_insert(&small).expect("fits");
            uploads.extend(
                cache
                    .images
                    .iter()
                    .map(|(image, x, y)| (image.data.id(), (*x, *y), xy)),
            );
            cache.finish_resolve();
        }
        assert_eq!(cache.stats().atlas_side, 32);
        // Uploaded on first use, and once more after the shrink moved it.
        let after_shrink = uploads.last().expect("re-uploaded");
        assert_eq!(after_shrink.0, small.data.id());
        assert_eq!(after_shrink.1, after_shrink.2, "uploaded where it is drawn");
        assert_eq!(cache.stats().shrinks_total, 1);
    }

    #[test]
    fn a_busy_atlas_does_not_shrink() {
        let mut cache = ImageCache::new_with_sizes(32, 64);
        let large = image(1, 40, 40);
        for _ in 0..(4 * SHRINK_AFTER_RESOLVES) {
            pass(&mut cache, &[&large]);
        }
        assert_eq!(cache.stats().atlas_side, 64);
        assert_eq!(cache.stats().shrinks_total, 0);
    }

    /// The compositor's open/close cycle: a wallpaper drawn every frame, a
    /// window that commits a new frame per paint while open, then closes.
    /// What the cache holds after each close must not grow with the cycles.
    #[test]
    fn open_close_cycles_leave_nothing_behind() {
        let mut cache = ImageCache::new_with_sizes(1024, 8192);
        let wallpaper = image(0, 1920, 1080);
        let mut after_close = Vec::new();
        for cycle in 0..30_u32 {
            let (width, height) = (800 + 40 * (cycle % 5), 600 + 30 * (cycle % 3));
            for commit in 0..12_u32 {
                let frame = image(
                    u8::try_from((cycle * 12 + commit) % 251).unwrap(),
                    width,
                    height,
                );
                pass(&mut cache, &[&wallpaper, &frame]);
            }
            for _ in 0..(SHRINK_AFTER_RESOLVES + 4) {
                pass(&mut cache, &[&wallpaper]);
            }
            after_close.push(cache.stats());
        }
        let first = after_close[0];
        for (cycle, stats) in after_close.iter().enumerate() {
            assert_eq!(stats.resident, 1, "cycle {cycle}: {stats:?}");
            assert_eq!(
                stats.resident_cpu_bytes,
                wallpaper.data.len() as u64,
                "cycle {cycle}: {stats:?}"
            );
            assert_eq!(
                stats.atlas_side, first.atlas_side,
                "cycle {cycle}: {stats:?}"
            );
        }
        assert!(first.atlas_side <= 2048, "{first:?}");
    }

    #[test]
    fn failed_repack_leaves_existing_residency_unchanged() {
        let mut cache = ImageCache::new_with_sizes(16, 16);
        let image = image(1, 12, 12);

        cache.begin_resolve();
        let xy = cache.get_or_insert(&image).unwrap();

        assert!(!cache.repack_to_size(8));
        assert_eq!(cache.atlas.size().width, 16);
        assert_eq!(cache.get_or_insert(&image), Some(xy));
        assert_eq!(cache.map.len(), 1);
    }

    #[test]
    fn a_superseded_frame_makes_room_when_the_atlas_cannot_grow() {
        // The atlas is full at its maximum: a replacement frame more than
        // half its side cannot sit beside the frame it replaces.
        let mut cache = ImageCache::new_with_sizes(16, 16);
        cache.begin_resolve();
        assert!(cache.get_or_insert(&image(1, 12, 12)).is_some());
        cache.finish_resolve();
        cache.begin_resolve();
        let next = image(2, 12, 12);
        assert!(
            cache.get_or_insert(&next).is_none(),
            "no room beside the old frame"
        );
        assert!(!cache.evict_stale_entries(), "one pass is not stale");
        assert!(!cache.bump_size(), "already at the maximum");
        assert_eq!(cache.evict_superseded(), 1);
        assert!(cache.get_or_insert(&next).is_some());
        // What this pass drew stays.
        assert_eq!(cache.evict_superseded(), 0);
    }
}