nsh-core 0.8.0

Platform-independent core: shadow tree, styles, layout and mount instructions.
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
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
//! Tiles of a panned and zoomed drawing: the planning behind compositing a
//! large drawing from rasterized tiles instead of replaying it on every
//! frame.
//!
//! A drawing panned as a whole by a `translate` ([`pan_zoom`]), maybe zoomed
//! by a `scale` right after it, is the same picture at every pan and zoom
//! in its content space (the coordinates after both). A platform
//! rasterizes it in square tiles of [`TILE_PX`] device pixels at a zoom
//! level ([`level_for`]) and, while the pan and zoom animate, only moves and
//! scales the tiles on the GPU. Levels step by √2, so a tile shows at most
//! √2 times larger or smaller than it was rasterized; the platform
//! rasterizes at a new level once the zoom has rested for [`SETTLE_MS`].
//!
//! [`TileCache`] keeps the tiles of a canvas within a budget that follows
//! its view ([`budget_for`]) and says each frame which to composite and which to rasterize
//! ([`TileCache::plan`]). A frame never waits for a tile: one not ready yet is
//! stood in for by the previous drawing's tile or another level's, and the
//! tiles of a previous drawing stay until the new one's visible tiles are all
//! there, so a new drawing appears at once rather than tile by tile.

use std::{collections::HashMap, sync::OnceLock};

use super::{CanvasOp, Damage, DamageScan, Num};
use crate::geometry::{Bounds, Points, Size, rect};

/// The side of a tile, in device pixels.
pub const TILE_PX: u32 = 256;

/// How many bytes of tiles a canvas keeps at least ([`budget_for`]); the
/// least recently drawn go first.
pub const TILE_BUDGET_BYTES: usize = 64 << 20;

/// How many bytes of tiles a canvas keeps at most, however large its view
/// ([`budget_for`]).
pub const TILE_BUDGET_MAX_BYTES: usize = 512 << 20;

/// How long the zoom rests, in milliseconds, before tiles are rasterized at
/// its level; until then the tiles of the previous level are scaled.
pub const SETTLE_MS: u64 = 150;

/// The fewest operations after the pan for which a drawing is tiled: a
/// shorter one replays faster than tiles composite.
pub const MIN_TILED_OPS: usize = 512;

/// How many levels coarser a missing tile's stand-in may be (8 times).
const FALLBACK_LEVELS: i32 = 6;

/// How many levels finer a missing tile's stand-in may be (2 times), when no
/// coarser level has one (just after zooming out).
const FINER_FALLBACK_LEVELS: i32 = 2;

/// The range of levels ([`level_for`]): zooms of 2^-20 to 2^20.
const LEVELS: std::ops::RangeInclusive<i32> = -40..=40;

/// The bytes of one tile's pixels (RGBA).
const TILE_BYTES: usize = (TILE_PX * TILE_PX * 4) as usize;

/// Whether panned drawings are tiled: unless the environment variable
/// `NSH_CANVAS_TILES` is `0` (read once).
pub fn tiles_enabled() -> bool {
    static ENABLED: OnceLock<bool> = OnceLock::new();
    *ENABLED.get_or_init(|| std::env::var_os("NSH_CANVAS_TILES").is_none_or(|v| v != "0"))
}

/// The pan, and the zoom, of a drawing ([`pan_zoom`]).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct PanZoom {
    /// The index of the `translate` that pans the drawing.
    pub index: usize,
    /// Its horizontal offset.
    pub x: Num,
    /// Its vertical offset.
    pub y: Num,
    /// The value of the `scale` right after it, the same horizontally and
    /// vertically, when the drawing is zoomed by one (an animated value
    /// that nothing after it reads).
    pub zoom: Option<Num>,
}

/// Whether the drawing is panned as a whole by a `translate` at `split` (its
/// first operation reading a slot, [`super::first_animated`]): nothing before
/// it paints, transforms or clips, and nothing after it reads its slots,
/// sets the transform or paints outside the `save` it is in. A pan of such a
/// drawing moves all of it by the pan's change, in the view's points.
///
/// Other slots may still be read. When the operation right after the
/// `translate` is a `scale` by one animated value in both directions that
/// nothing after it reads, that value is the drawing's zoom
/// ([`PanZoom::zoom`]): a zoom of such a drawing scales all of it around
/// the pan's origin.
pub fn pan_zoom(ops: &[CanvasOp], split: usize) -> Option<PanZoom> {
    let CanvasOp::Translate(x, y) = ops.get(split)? else {
        return None;
    };
    if !matches!(x, Num::Slot(_)) && !matches!(y, Num::Slot(_)) {
        return None;
    }
    let mut depth = 0i32;
    for op in &ops[..split] {
        match op {
            CanvasOp::Save => depth += 1,
            CanvasOp::Restore => depth -= 1,
            CanvasOp::Translate(..)
            | CanvasOp::Scale(..)
            | CanvasOp::Rotate(_)
            | CanvasOp::Transform(_)
            | CanvasOp::SetTransform(_)
            | CanvasOp::Clip(..) => return None,
            op if op.paints() => return None,
            _ => {}
        }
    }
    let rest = &ops[split + 1..];
    let own = |k: u16| [x, y].iter().any(|v| matches!(v, Num::Slot(s) if *s == k));
    let mut scan = DamageScan::default();
    if scan.damage(rest, |_| 0.0, own) != Damage::None {
        return None;
    }
    let pan_depth = depth;
    let mut below = false;
    for op in rest {
        match op {
            CanvasOp::Save => depth += 1,
            CanvasOp::Restore => {
                depth -= 1;
                below |= depth < pan_depth;
            }
            CanvasOp::SetTransform(_) => return None,
            op if below && op.paints() => return None,
            _ => {}
        }
    }
    let zoom = match rest.first() {
        Some(&CanvasOp::Scale(sx @ Num::Slot(z), sy))
            if sx == sy
                && !own(z)
                && scan.damage(&rest[1..], |_| 0.0, |k| k == z) == Damage::None =>
        {
            Some(sx)
        }
        _ => None,
    };
    Some(PanZoom {
        index: split,
        x: *x,
        y: *y,
        zoom,
    })
}

/// The bounds of what the drawing paints in its content space (after the
/// pan and zoom, [`pan_zoom`]), other slots read through `slots`; `None`
/// when it paints nothing or its bounds are unknown ([`Damage::All`]).
pub fn content_bounds(
    ops: &[CanvasOp],
    pz: &PanZoom,
    slots: impl Fn(u16) -> f32,
) -> Option<Bounds<Points>> {
    let value = content_values(pz, slots);
    let Damage::Rect(b) = DamageScan::default().painted_after(ops, pz.index + 1, value) else {
        return None;
    };
    Some(to_content(pz, b))
}

/// The slot values that put the drawing in its content space: no pan (but
/// its constant part, [`to_content`]), a zoom of 1, other slots `slots`.
fn content_values(pz: &PanZoom, slots: impl Fn(u16) -> f32) -> impl Fn(u16) -> f32 {
    move |k: u16| {
        if pz.zoom == Some(Num::Slot(k)) {
            1.0
        } else if pz.x == Num::Slot(k) || pz.y == Num::Slot(k) {
            0.0
        } else {
            slots(k)
        }
    }
}

/// `b`, scanned with [`content_values`], in content points: a constant
/// offset of the pan is not part of the content.
fn to_content(pz: &PanZoom, b: Bounds<Points>) -> Bounds<Points> {
    let constant = |v: Num| match v {
        Num::Const(c) => c,
        Num::Slot(_) => 0.0,
    };
    rect(
        b.origin.x.0 - constant(pz.x),
        b.origin.y.0 - constant(pz.y),
        b.size.width.0,
        b.size.height.0,
    )
}

/// Where each painting operation of a panned drawing ([`pan_zoom`]) paints
/// in its content space, to rasterize a tile with only the paints that
/// reach it ([`PaintIndex::paints_in`]).
///
/// A tile replayed with every operation that is not a paint (`save` /
/// `restore`, transforms, clips, styles, fonts, paths: what later paints
/// depend on) and only the paints meeting its area ([`tile_cull_rect`])
/// has the pixels of a full replay: a skipped paint changes no pixel of
/// the tile. A paint whose area can not be told from its shape (a
/// composite operation other than `source-over`, a shadow, an image at its
/// natural size, unbounded geometry) is in every tile.
///
/// Built once per drawing and slot values (off the main thread: a scan of
/// every operation), queried once per tile; paints are bucketed in a grid
/// over the content so a query looks only at those near its area.
#[derive(Debug, Clone, Default)]
pub struct PaintIndex {
    /// How many operations the drawing has (the bitset's length).
    ops: usize,
    /// The bounded paints: operation index and bounds (`x0, y0, x1, y1`).
    paints: Vec<(u32, [f32; 4])>,
    /// The paints in every tile.
    unbounded: Vec<u32>,
    /// Paints too large for the grid (in more than [`GRID_SPREAD`] cells):
    /// indices into `paints`, checked by every query.
    large: Vec<u32>,
    /// The grid: its origin, cell side and size in cells.
    origin: [f32; 2],
    cell: f32,
    cols: usize,
    rows: usize,
    /// The paints of each cell (indices into `paints`), row by row: those
    /// of cell `i` are `entries[starts[i]..starts[i + 1]]`.
    starts: Vec<u32>,
    entries: Vec<u32>,
}

/// The most cells along a side of a [`PaintIndex`]'s grid.
const GRID_MAX: usize = 256;

/// The most cells a paint is listed in; larger ones are checked by every
/// query.
const GRID_SPREAD: usize = 64;

impl PaintIndex {
    /// Indexes the paints after the pan (and the zoom) of `ops`, panned by
    /// `pz` ([`pan_zoom`]), other slots read through `slots`.
    pub fn build(ops: &[CanvasOp], pz: &PanZoom, slots: impl Fn(u16) -> f32) -> PaintIndex {
        let mut index = PaintIndex {
            ops: ops.len(),
            ..PaintIndex::default()
        };
        let value = content_values(pz, slots);
        let mut lo = [f32::INFINITY; 2];
        let mut hi = [f32::NEG_INFINITY; 2];
        DamageScan::default().each_paint(ops, pz.index + 1, value, |i, bounds| {
            let Some(b) = bounds else {
                index.unbounded.push(i as u32);
                return;
            };
            let b = to_content(pz, b);
            let b = [b.origin.x.0, b.origin.y.0, b.right().0, b.bottom().0];
            lo = [lo[0].min(b[0]), lo[1].min(b[1])];
            hi = [hi[0].max(b[2]), hi[1].max(b[3])];
            index.paints.push((i as u32, b));
        });
        if index.paints.is_empty() {
            return index;
        }
        // About two paints a cell, square cells.
        let (w, h) = ((hi[0] - lo[0]).max(1.0), (hi[1] - lo[1]).max(1.0));
        let cells = (index.paints.len() / 2).max(1) as f32;
        let mut cell = (w * h / cells).sqrt();
        cell = cell.max(w / GRID_MAX as f32).max(h / GRID_MAX as f32);
        index.origin = lo;
        index.cell = cell;
        index.cols = ((w / cell).ceil() as usize).clamp(1, GRID_MAX);
        index.rows = ((h / cell).ceil() as usize).clamp(1, GRID_MAX);
        // Counted, then placed (compressed rows).
        let mut counts = vec![0u32; index.cols * index.rows + 1];
        let mut spans = Vec::with_capacity(index.paints.len());
        for (k, (_, b)) in index.paints.iter().enumerate() {
            let (cols, rows) = index.span(*b);
            if cols.len() * rows.len() > GRID_SPREAD {
                index.large.push(k as u32);
                spans.push(None);
                continue;
            }
            for row in rows.clone() {
                for col in cols.clone() {
                    counts[row * index.cols + col] += 1;
                }
            }
            spans.push(Some((cols, rows)));
        }
        let mut starts = Vec::with_capacity(counts.len());
        let mut total = 0u32;
        for count in &counts {
            starts.push(total);
            total += count;
        }
        let mut next = starts.clone();
        index.entries = vec![0; total as usize];
        for (k, span) in spans.into_iter().enumerate() {
            let Some((cols, rows)) = span else { continue };
            for row in rows {
                for col in cols.clone() {
                    let at = &mut next[row * index.cols + col];
                    index.entries[*at as usize] = k as u32;
                    *at += 1;
                }
            }
        }
        index.starts = starts;
        index
    }

    /// The columns and rows of the grid that `b` (`x0, y0, x1, y1`) meets,
    /// clamped to the grid.
    fn span(&self, b: [f32; 4]) -> (std::ops::Range<usize>, std::ops::Range<usize>) {
        let at = |v: f32, origin: f32, n: usize| {
            let c = ((v - origin) / self.cell).floor();
            c.clamp(0.0, (n - 1) as f32) as usize
        };
        let cols = at(b[0], self.origin[0], self.cols)..at(b[2], self.origin[0], self.cols) + 1;
        let rows = at(b[1], self.origin[1], self.rows)..at(b[3], self.origin[1], self.rows) + 1;
        (cols, rows)
    }

    /// The indices of the painting operations that may paint in `area` (in
    /// content points): those whose bounds meet it and those that are
    /// unbounded, in order. An area that is not finite has all of them.
    pub fn paints_in(&self, area: Bounds<Points>) -> impl Iterator<Item = usize> + use<> {
        let mut bits = vec![0u64; self.ops.div_ceil(64)];
        let mut set = |i: u32| bits[i as usize / 64] |= 1 << (i % 64);
        for &i in &self.unbounded {
            set(i);
        }
        let r = [
            area.origin.x.0,
            area.origin.y.0,
            area.right().0,
            area.bottom().0,
        ];
        if !r.iter().all(|v| v.is_finite()) {
            for &(i, _) in &self.paints {
                set(i);
            }
        } else {
            let meets = |b: &[f32; 4]| b[0] <= r[2] && r[0] <= b[2] && b[1] <= r[3] && r[1] <= b[3];
            let mut check = |k: u32| {
                let (i, b) = &self.paints[k as usize];
                if meets(b) {
                    set(*i);
                }
            };
            for &k in &self.large {
                check(k);
            }
            let grid = [
                self.origin[0],
                self.origin[1],
                self.origin[0] + self.cols as f32 * self.cell,
                self.origin[1] + self.rows as f32 * self.cell,
            ];
            if !self.starts.is_empty() && meets(&grid) {
                let (cols, rows) = self.span(r);
                for row in rows {
                    for col in cols.clone() {
                        let cell = row * self.cols + col;
                        let (a, b) = (self.starts[cell], self.starts[cell + 1]);
                        for &k in &self.entries[a as usize..b as usize] {
                            check(k);
                        }
                    }
                }
            }
        }
        bits.into_iter().enumerate().flat_map(|(word, mut w)| {
            std::iter::from_fn(move || {
                (w != 0).then(|| {
                    let bit = w.trailing_zeros() as usize;
                    w &= w - 1;
                    word * 64 + bit
                })
            })
        })
    }

    /// How many painting operations it indexes (after the pan).
    pub fn paint_count(&self) -> usize {
        self.paints.len() + self.unbounded.len()
    }
}

/// The level of tiles for `zoom`: `round(2·log2(zoom))`, each level √2 times
/// the scale of the one before ([`level_scale`]), within -40 ..= 40. A zoom
/// of zero or less takes the coarsest level, one that is not a number
/// level 0.
pub fn level_for(zoom: f32) -> i32 {
    if zoom.is_nan() {
        0
    } else if zoom <= 0.0 {
        *LEVELS.start()
    } else {
        let level = (2.0 * zoom.log2()).round();
        level.clamp(*LEVELS.start() as f32, *LEVELS.end() as f32) as i32
    }
}

/// The scale of level `level` ([`level_for`]): `2^(level/2)`, exact for even
/// levels.
pub fn level_scale(level: i32) -> f32 {
    let whole = 2f32.powi(level.div_euclid(2));
    if level.rem_euclid(2) == 0 {
        whole
    } else {
        whole * std::f32::consts::SQRT_2
    }
}

/// A tile of a drawing: the one at column `col` and row `row` of the grid of
/// level `level` ([`level_for`]), counted from the content's origin.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub struct TileKey {
    /// The zoom level it is rasterized at.
    pub level: i32,
    /// Its column.
    pub col: i32,
    /// Its row.
    pub row: i32,
}

/// The side of a tile of `level` in content points.
fn tile_side(level: i32, pixel_ratio: f32) -> f32 {
    TILE_PX as f32 / (pixel_ratio * level_scale(level))
}

/// The area of the content that tile `key` shows, in content points, at
/// `pixel_ratio` device pixels per point.
pub fn tile_rect(key: TileKey, pixel_ratio: f32) -> Bounds<Points> {
    let side = tile_side(key.level, pixel_ratio);
    rect(key.col as f32 * side, key.row as f32 * side, side, side)
}

/// The area of the content whose paints can reach the pixels of tile
/// `key` ([`tile_rect`] grown by a device pixel, for anti-aliasing): a tile
/// replays only the paints meeting it ([`PaintIndex::paints_in`]).
pub fn tile_cull_rect(key: TileKey, pixel_ratio: f32) -> Bounds<Points> {
    let r = tile_rect(key, pixel_ratio);
    let px = 1.0 / (pixel_ratio * level_scale(key.level));
    rect(
        r.origin.x.0 - px,
        r.origin.y.0 - px,
        r.size.width.0 + 2.0 * px,
        r.size.height.0 + 2.0 * px,
    )
}

/// The transform (`a, b, c, d, e, f`, as `setTransform` takes it) to replay
/// the drawing with in place of its pan and zoom when rasterizing tile `key`
/// into a bitmap of [`TILE_PX`] × [`TILE_PX`] device pixels: it maps content
/// points to the tile's pixels, the tile's top left corner to (0, 0).
pub fn tile_transform(key: TileKey, pixel_ratio: f32) -> [f64; 6] {
    let scale = f64::from(pixel_ratio) * f64::from(level_scale(key.level));
    let px = f64::from(TILE_PX);
    [
        scale,
        0.0,
        0.0,
        scale,
        -f64::from(key.col) * px,
        -f64::from(key.row) * px,
    ]
}

/// The tiles of `level` that a view of size `view` shows of `content` (in
/// content points, [`content_bounds`]) at pan `pan` (in the view's points)
/// and zoom `zoom`, with one more tile on each side so a pan finds the next
/// ones ready; the nearest to the view's center first.
pub fn visible_tiles(
    view: Size<Points>,
    pan: (f32, f32),
    zoom: f32,
    level: i32,
    pixel_ratio: f32,
    content: Bounds<Points>,
) -> Vec<TileKey> {
    let side = tile_side(level, pixel_ratio);
    let finite = [view.width.0, view.height.0, pan.0, pan.1, zoom, side]
        .iter()
        .all(|v| v.is_finite());
    if !(finite && zoom > 0.0 && side > 0.0) {
        return Vec::new();
    }
    // The view's span along one axis, in tiles of the content.
    let span = |len: f32, pan: f32, lo: f32, hi: f32| {
        let start = ((-pan / zoom) - side).max(lo);
        let end = ((len - pan) / zoom + side).min(hi);
        let first = (start / side).floor() as i32;
        let last = (end / side).ceil() as i32 - 1;
        (start < end).then_some(first..=last)
    };
    let (Some(cols), Some(rows)) = (
        span(view.width.0, pan.0, content.origin.x.0, content.right().0),
        span(view.height.0, pan.1, content.origin.y.0, content.bottom().0),
    ) else {
        return Vec::new();
    };
    let center = (
        (view.width.0 / 2.0 - pan.0) / zoom / side,
        (view.height.0 / 2.0 - pan.1) / zoom / side,
    );
    let mut tiles: Vec<TileKey> = rows
        .flat_map(|row| cols.clone().map(move |col| TileKey { level, col, row }))
        .collect();
    let distance = |k: &TileKey| {
        let dx = k.col as f32 + 0.5 - center.0;
        let dy = k.row as f32 + 0.5 - center.1;
        dx * dx + dy * dy
    };
    tiles.sort_by(|a, b| distance(a).total_cmp(&distance(b)));
    tiles
}

/// The most tiles of a side of `side` content points along one axis that a
/// view `len` points long shows at `zoom`: its span with a tile of margin on
/// each side, in any alignment ([`visible_tiles`]).
fn most_tiles(len: f32, zoom: f32, side: f32) -> f32 {
    (len / zoom / side).ceil() + 3.0
}

/// The bytes of tiles a canvas with a view of `view` points at
/// `pixel_ratio` keeps ([`TileCache::set_budget`], [`fitting_level`]):
/// three times its visible tiles at the zoom's own level (with their
/// margin, at the zoom farthest out that rounds to the level), within
/// [`TILE_BUDGET_BYTES`] ..= [`TILE_BUDGET_MAX_BYTES`]. A view of a
/// Retina window takes many more tiles than a small one: with a fixed
/// budget it would be shown a level coarser than its zoom.
pub fn budget_for(view: Size<Points>, pixel_ratio: f32) -> usize {
    // A zoom rounds to a level within 2^±¼ of its scale (`level_for`).
    let zoom = 2f32.powf(-0.25);
    let side = TILE_PX as f32 / pixel_ratio;
    let count = f64::from(most_tiles(view.width.0, zoom, side))
        * f64::from(most_tiles(view.height.0, zoom, side));
    let bytes = 3.0 * count * TILE_BYTES as f64;
    if !(bytes.is_finite() && pixel_ratio > 0.0) {
        return TILE_BUDGET_BYTES;
    }
    (bytes.min(TILE_BUDGET_MAX_BYTES as f64) as usize).max(TILE_BUDGET_BYTES)
}

/// `level`, or the finest coarser level whose visible tiles ([`visible_tiles`],
/// at any pan) take at most half of `budget` ([`budget_for`]): zoomed far
/// out of the level the tiles were rasterized at, or with a view too large
/// even for [`TILE_BUDGET_MAX_BYTES`], a view would ask for more tiles than
/// the cache keeps, evicting the ones it shows.
pub fn fitting_level(
    view: Size<Points>,
    zoom: f32,
    level: i32,
    pixel_ratio: f32,
    content: Bounds<Points>,
    budget: usize,
) -> i32 {
    // The view's tiles along one axis, or the content's.
    let most = |len: f32, content: f32, side: f32| {
        let view = most_tiles(len, zoom, side);
        let content = (content / side).ceil() + 1.0;
        f64::from(view.min(content).max(0.0))
    };
    let budget = (budget / 2 / TILE_BYTES) as f64;
    let mut level = level.clamp(*LEVELS.start(), *LEVELS.end());
    while level > *LEVELS.start() {
        let side = tile_side(level, pixel_ratio);
        let count = most(view.width.0, content.size.width.0, side)
            * most(view.height.0, content.size.height.0, side);
        // Not a number (an invalid zoom or size) never fits; `visible_tiles`
        // plans nothing then anyway.
        if count <= budget || count.is_nan() {
            break;
        }
        level -= 1;
    }
    level
}

/// What to composite in a frame and what to rasterize ([`TileCache::plan`]).
pub struct TilePlan<'a, T> {
    /// The tiles to draw, in order (stand-ins first, under the tiles they
    /// stand in for), with the area each shows in content points: a
    /// stand-in of another level shows its own area.
    pub draw: Vec<(TileKey, &'a T, Bounds<Points>)>,
    /// The visible tiles of the current drawing that are not ready, to
    /// rasterize (tagged with [`TileCache::epoch`]), in the order they were
    /// asked for. Tiles being rasterized are among them until they are
    /// inserted: the platform skips the ones it already rasterizes.
    pub missing: Vec<TileKey>,
}

/// A rasterized tile.
struct Entry<T> {
    tex: T,
    bytes: usize,
    /// The plan (or insertion) it was last used by.
    used: u64,
}

/// The rasterized tiles of a canvas (`T`: a platform's texture), within a
/// budget of bytes.
///
/// The tiles of the current drawing (its generation, [`Self::set_drawing`])
/// are drawn as they are; tiles of previous drawings, and those marked
/// stale ([`Self::mark_stale`]), stand in for missing ones until the
/// current drawing's visible tiles are all ready.
///
/// A tile is rasterized for the cache's [`Self::epoch`], which every change
/// of what tiles show advances (a new drawing, [`Self::mark_stale`],
/// [`Self::clear`], a new pixel ratio): a tile rasterized for an earlier
/// epoch is dropped when it arrives ([`Self::insert`]).
pub struct TileCache<T> {
    budget: usize,
    bytes: usize,
    generation: u64,
    epoch: u64,
    pixel_ratio: f32,
    /// Counts plans and insertions, for least recently used eviction.
    tick: u64,
    current: HashMap<TileKey, Entry<T>>,
    /// Tiles that only stand in for missing ones.
    fallback: HashMap<TileKey, Entry<T>>,
}

impl<T> TileCache<T> {
    /// An empty cache keeping at most `budget_bytes` of tiles, at a pixel
    /// ratio of 1 ([`Self::set_pixel_ratio`]).
    pub fn new(budget_bytes: usize) -> Self {
        TileCache {
            budget: budget_bytes,
            bytes: 0,
            generation: 0,
            epoch: 0,
            pixel_ratio: 1.0,
            tick: 0,
            current: HashMap::new(),
            fallback: HashMap::new(),
        }
    }

    /// Starts drawing generation `generation` (a new drawing): the tiles so
    /// far only stand in for missing ones from now on, until the new
    /// generation's visible tiles are all ready. An older generation than
    /// the current one is ignored.
    pub fn set_drawing(&mut self, generation: u64) {
        if generation > self.generation {
            self.generation = generation;
            self.retire();
        }
    }

    /// What tiles are rasterized for now: a platform tags each tile it
    /// starts rasterizing with it and passes the tag to [`Self::insert`].
    /// Advanced by every change of what tiles show.
    pub fn epoch(&self) -> u64 {
        self.epoch
    }

    /// Adds the tile `key`, of `bytes` bytes, rasterized for epoch `epoch`
    /// ([`Self::epoch`] when its rasterization started), evicting the least
    /// recently drawn tiles (stand-ins first) over the budget. A tile of an
    /// earlier epoch is dropped: what it shows changed while it was
    /// rasterized (a new drawing, a stale one, a new pixel ratio).
    pub fn insert(&mut self, epoch: u64, key: TileKey, tex: T, bytes: usize) {
        if epoch != self.epoch {
            return;
        }
        self.tick += 1;
        if let Some(old) = self.fallback.remove(&key) {
            self.bytes -= old.bytes;
        }
        let entry = Entry {
            tex,
            bytes,
            used: self.tick,
        };
        if let Some(old) = self.current.insert(key, entry) {
            self.bytes -= old.bytes;
        }
        self.bytes += bytes;
        self.evict(Some(key));
    }

    /// What to composite and rasterize for the tiles `visible`
    /// ([`visible_tiles`]). A tile not ready is stood in for by a previous
    /// drawing's tile of the same key or else by the tiles of the nearest
    /// coarser level that cover it, or the nearest finer one (all of them
    /// there); once none is missing, previous drawings' tiles are dropped.
    pub fn plan(&mut self, visible: &[TileKey]) -> TilePlan<'_, T> {
        self.tick += 1;
        // (key, of the current drawing): stand-ins of other levels, then
        // tiles of the visible keys.
        let mut under: Vec<(TileKey, bool)> = Vec::new();
        let mut exact: Vec<(TileKey, bool)> = Vec::with_capacity(visible.len());
        let mut missing = Vec::new();
        for &key in visible {
            if self.current.contains_key(&key) {
                exact.push((key, true));
                continue;
            }
            missing.push(key);
            if self.fallback.contains_key(&key) {
                exact.push((key, false));
            } else {
                self.cover(key, &mut under);
            }
        }
        if missing.is_empty() {
            for (_, old) in self.fallback.drain() {
                self.bytes -= old.bytes;
            }
        }
        let tick = self.tick;
        for &(key, current) in under.iter().chain(&exact) {
            let map = if current {
                &mut self.current
            } else {
                &mut self.fallback
            };
            if let Some(e) = map.get_mut(&key) {
                e.used = tick;
            }
        }
        let draw = under
            .iter()
            .chain(&exact)
            .filter_map(|&(key, current)| {
                let map = if current {
                    &self.current
                } else {
                    &self.fallback
                };
                let e = map.get(&key)?;
                Some((key, &e.tex, tile_rect(key, self.pixel_ratio)))
            })
            .collect();
        TilePlan { draw, missing }
    }

    /// Adds to `under` the tiles of the nearest coarser level that cover
    /// `key` and are all there, if a level has them, or else those of the
    /// nearest finer level.
    fn cover(&self, key: TileKey, under: &mut Vec<(TileKey, bool)>) {
        if !LEVELS.contains(&key.level) {
            return;
        }
        // In tiles of `key`'s level, shrunk a little so a shared edge does
        // not count as overlap.
        let (x0, y0) = (key.col as f32 + 1e-3, key.row as f32 + 1e-3);
        let (x1, y1) = (key.col as f32 + 1.0 - 1e-3, key.row as f32 + 1.0 - 1e-3);
        let coarser = (key.level - FALLBACK_LEVELS..key.level).rev();
        let finer = key.level + 1..=key.level + FINER_FALLBACK_LEVELS;
        'levels: for level in coarser.chain(finer) {
            // A tile of `key`'s level is this many tiles of `level`.
            let f = level_scale(level) / level_scale(key.level);
            let start = under.len();
            for row in (y0 * f).floor() as i32..=(y1 * f).floor() as i32 {
                for col in (x0 * f).floor() as i32..=(x1 * f).floor() as i32 {
                    let k = TileKey { level, col, row };
                    let tile = if self.current.contains_key(&k) {
                        (k, true)
                    } else if self.fallback.contains_key(&k) {
                        (k, false)
                    } else {
                        under.truncate(start);
                        continue 'levels;
                    };
                    if !under.contains(&tile) {
                        under.push(tile);
                    }
                }
            }
            return;
        }
    }

    /// Keeps at most `budget_bytes` of tiles from now on ([`budget_for`]),
    /// evicting the least recently drawn over a lower one.
    pub fn set_budget(&mut self, budget_bytes: usize) {
        self.budget = budget_bytes;
        self.evict(None);
    }

    /// Makes the current drawing's tiles stand-ins that are rasterized
    /// again: what they show changed (a slot other than the pan's and the
    /// zoom's, an image that arrived).
    pub fn mark_stale(&mut self) {
        self.retire();
    }

    /// Drops every tile (when the pixel ratio changes).
    pub fn clear(&mut self) {
        self.epoch += 1;
        self.current.clear();
        self.fallback.clear();
        self.bytes = 0;
    }

    /// Sets the device pixels per point tiles are rasterized at, dropping
    /// every tile when it changes ([`Self::clear`]).
    pub fn set_pixel_ratio(&mut self, pixel_ratio: f32) {
        if pixel_ratio != self.pixel_ratio {
            self.pixel_ratio = pixel_ratio;
            self.clear();
        }
    }

    /// Moves the current drawing's tiles to the stand-ins, for a new epoch.
    fn retire(&mut self) {
        self.epoch += 1;
        for (key, entry) in self.current.drain() {
            if let Some(old) = self.fallback.insert(key, entry) {
                self.bytes -= old.bytes;
            }
        }
    }

    /// Evicts the least recently used tiles, stand-ins first, until the
    /// tiles fit the budget; never `keep`.
    fn evict(&mut self, keep: Option<TileKey>) {
        while self.bytes > self.budget {
            let oldest = |map: &HashMap<TileKey, Entry<T>>| {
                map.iter()
                    .filter(|(k, _)| Some(**k) != keep)
                    .min_by_key(|(_, e)| e.used)
                    .map(|(k, _)| *k)
            };
            let victim = if let Some(k) = oldest(&self.fallback) {
                self.fallback.remove(&k)
            } else if let Some(k) = oldest(&self.current) {
                self.current.remove(&k)
            } else {
                return;
            };
            if let Some(e) = victim {
                self.bytes -= e.bytes;
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        canvas::{CanvasOp, Num},
        geometry::{Points, Size, px, rect},
    };

    fn fill() -> CanvasOp {
        let c = Num::Const;
        CanvasOp::FillRect([c(0.0), c(0.0), c(4.0), c(4.0)])
    }

    fn key(level: i32, col: i32, row: i32) -> TileKey {
        TileKey { level, col, row }
    }

    #[test]
    fn pan_zoom_finds_translate_then_scale() {
        let ops = [
            CanvasOp::Save,
            CanvasOp::Translate(Num::Slot(0), Num::Slot(1)),
            CanvasOp::Scale(Num::Slot(2), Num::Slot(2)),
            fill(),
            CanvasOp::Restore,
        ];
        let pz = pan_zoom(&ops, 1).unwrap();
        assert_eq!(pz.index, 1);
        assert_eq!((pz.x, pz.y), (Num::Slot(0), Num::Slot(1)));
        assert_eq!(pz.zoom, Some(Num::Slot(2)));
    }

    #[test]
    fn pan_zoom_rejects_paint_before() {
        let ops = [
            fill(),
            CanvasOp::Translate(Num::Slot(0), Num::Slot(1)),
            fill(),
        ];
        assert_eq!(pan_zoom(&ops, 1), None);
    }

    #[test]
    fn pan_zoom_rejects_unequal_scale() {
        let ops = [
            CanvasOp::Translate(Num::Slot(0), Num::Slot(1)),
            CanvasOp::Scale(Num::Slot(2), Num::Slot(3)),
            fill(),
        ];
        // Still a pan (the platforms' rule), but no zoom: the scale stays
        // part of the content.
        let pz = pan_zoom(&ops, 0).unwrap();
        assert_eq!(pz.zoom, None);
    }

    #[test]
    fn content_bounds_ignore_pan_and_zoom() {
        let c = Num::Const;
        let ops = [
            CanvasOp::Translate(Num::Slot(0), Num::Slot(1)),
            CanvasOp::Scale(Num::Slot(2), Num::Slot(2)),
            CanvasOp::FillRect([c(10.0), c(20.0), c(30.0), c(40.0)]),
        ];
        let pz = pan_zoom(&ops, 0).unwrap();
        let b = content_bounds(&ops, &pz, |_| 5.0).unwrap();
        assert!(b.origin.x <= px(10.0) && b.origin.x >= px(5.0));
        assert!(b.right() >= px(40.0) && b.right() <= px(45.0));
        assert!(b.bottom() >= px(60.0) && b.bottom() <= px(65.0));
    }

    #[test]
    fn paint_index_finds_only_paints_meeting_rect() {
        let c = Num::Const;
        let mut ops = vec![
            CanvasOp::Save,
            CanvasOp::Translate(Num::Slot(0), Num::Slot(1)),
            CanvasOp::Scale(Num::Slot(2), Num::Slot(2)),
        ];
        // 1,000 squares of 10 points, 20 apart: 40 columns, 25 rows.
        let mut squares = Vec::new();
        for i in 0..1000 {
            let (x, y) = ((i % 40) as f32 * 20.0, (i / 40) as f32 * 20.0);
            squares.push((ops.len(), x, y));
            ops.push(CanvasOp::FillRect([c(x), c(y), c(10.0), c(10.0)]));
        }
        // An image at its natural size: unbounded, always replayed.
        let unbounded = ops.len();
        ops.push(CanvasOp::DrawImage {
            image: crate::canvas::CanvasImage {
                uri: "sheet.png".into(),
            },
            source: None,
            dest: [c(5000.0), c(5000.0), c(f32::NAN), c(f32::NAN)],
        });
        // A square moved into the query by a translate in a `save`.
        ops.push(CanvasOp::Save);
        ops.push(CanvasOp::Translate(c(-1000.0), c(-1000.0)));
        let moved = ops.len();
        ops.push(CanvasOp::FillRect([c(1050.0), c(1050.0), c(10.0), c(10.0)]));
        ops.push(CanvasOp::Restore);
        // The same square after the `restore`: far away.
        ops.push(CanvasOp::FillRect([c(1050.0), c(1050.0), c(10.0), c(10.0)]));
        ops.push(CanvasOp::Restore);
        let pz = pan_zoom(&ops, 1).unwrap();
        let index = PaintIndex::build(&ops, &pz, |_| 0.0);
        // Edges in the gaps between squares: anti-aliasing margins do not
        // reach them.
        let query = rect(35.0, 35.0, 60.0, 40.0);
        let mut expected: Vec<usize> = squares
            .iter()
            .filter(|&&(_, x, y)| x + 10.0 > 35.0 && x < 95.0 && y + 10.0 > 35.0 && y < 75.0)
            .map(|&(i, ..)| i)
            .collect();
        assert_eq!(expected.len(), 6, "three columns, two rows");
        expected.push(unbounded);
        expected.push(moved);
        let found: Vec<usize> = index.paints_in(query).collect();
        assert_eq!(found, expected);
        // A rect over nothing finds only what is unbounded.
        let found: Vec<usize> = index
            .paints_in(rect(-500.0, -500.0, 100.0, 100.0))
            .collect();
        assert_eq!(found, vec![unbounded]);
        assert_eq!(index.paint_count(), 1003);
    }

    #[test]
    fn level_round_trips() {
        assert_eq!(level_for(1.0), 0);
        assert_eq!(level_for(2.0), 2);
        assert_eq!(level_for(1.41), 1);
        assert_eq!(level_scale(2), 2.0);
        assert_eq!(level_scale(0), 1.0);
        assert_eq!(level_for(level_scale(-3)), -3);
    }

    #[test]
    fn tile_transform_puts_the_tile_corner_at_the_origin() {
        let k = key(1, 2, -1);
        let r = tile_rect(k, 2.0);
        let [a, _, _, d, e, f] = tile_transform(k, 2.0);
        let x = f64::from(r.origin.x.0) * a + e;
        let y = f64::from(r.origin.y.0) * d + f;
        assert!(x.abs() < 1e-3 && y.abs() < 1e-3);
        let side = f64::from(r.size.width.0) * a;
        assert!((side - f64::from(TILE_PX)).abs() < 1e-3);
    }

    #[test]
    fn visible_tiles_cover_view_plus_margin() {
        let view = Size::<Points> {
            width: px(800.0),
            height: px(600.0),
        };
        let content = rect(-10_000.0, -10_000.0, 20_000.0, 20_000.0);
        let tiles = visible_tiles(view, (0.0, 0.0), 1.0, 0, 2.0, content);
        let rects: Vec<_> = tiles.iter().map(|&k| tile_rect(k, 2.0)).collect();
        let union = rects.iter().skip(1).fold(rects[0], |u, r| u.union(r));
        let need = rect(-128.0, -128.0, 1056.0, 856.0);
        assert!(union.origin.x <= need.origin.x && union.origin.y <= need.origin.y);
        assert!(union.right() >= need.right() && union.bottom() >= need.bottom());
        // Whole tiles, with no gaps: as many as the union holds.
        let area = |b: &crate::geometry::Bounds<Points>| b.size.width.0 * b.size.height.0;
        assert_eq!(rects.len() as f32, area(&union) / area(&rects[0]));
        assert!(rects[0].contains(&crate::geometry::point(px(400.0), px(300.0))));
    }

    #[test]
    fn visible_tiles_clip_to_content() {
        let view = Size::<Points> {
            width: px(800.0),
            height: px(600.0),
        };
        let content = rect(0.0, 0.0, 100.0, 100.0);
        let tiles = visible_tiles(view, (0.0, 0.0), 1.0, 0, 2.0, content);
        assert_eq!(tiles, [key(0, 0, 0)]);
    }

    fn drawn(plan: &TilePlan<'_, u32>) -> Vec<u32> {
        let mut v: Vec<u32> = plan.draw.iter().map(|(_, t, _)| **t).collect();
        v.sort();
        v
    }

    const KEYS: [TileKey; 4] = [
        TileKey {
            level: 0,
            col: 0,
            row: 0,
        },
        TileKey {
            level: 0,
            col: 1,
            row: 0,
        },
        TileKey {
            level: 0,
            col: 0,
            row: 1,
        },
        TileKey {
            level: 0,
            col: 1,
            row: 1,
        },
    ];

    /// Inserts `key` as `tex` (1 byte) for the cache's current epoch.
    fn put(cache: &mut TileCache<u32>, key: TileKey, tex: u32) {
        cache.insert(cache.epoch(), key, tex, 1);
    }

    #[test]
    fn new_drawing_keeps_old_tiles_until_ready() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(1);
        for (i, k) in KEYS.into_iter().enumerate() {
            put(&mut cache, k, 10 + i as u32);
        }
        cache.set_drawing(2);
        let plan = cache.plan(&KEYS);
        assert_eq!(drawn(&plan), [10, 11, 12, 13]);
        assert_eq!(plan.missing.len(), 4);
        put(&mut cache, KEYS[0], 20);
        put(&mut cache, KEYS[1], 21);
        let plan = cache.plan(&KEYS);
        assert_eq!(drawn(&plan), [12, 13, 20, 21]);
        assert_eq!(plan.missing, [KEYS[2], KEYS[3]]);
        put(&mut cache, KEYS[2], 22);
        put(&mut cache, KEYS[3], 23);
        let plan = cache.plan(&KEYS);
        assert_eq!(drawn(&plan), [20, 21, 22, 23]);
        assert!(plan.missing.is_empty());
    }

    #[test]
    fn missing_tiles_fall_back_to_a_coarser_level() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(1);
        put(&mut cache, key(0, 0, 0), 1);
        // Level 2 tiles are half as large: four fit in the level 0 one.
        let fine = [key(2, 0, 0), key(2, 1, 0), key(2, 0, 1), key(2, 1, 1)];
        let plan = cache.plan(&fine);
        assert_eq!(drawn(&plan), [1]);
        assert_eq!(plan.draw[0].2, tile_rect(key(0, 0, 0), 1.0));
        assert_eq!(plan.missing.len(), 4);
    }

    #[test]
    fn odd_level_fallback_takes_every_straddled_tile() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(1);
        // At pixel ratio 1, level 1 tiles are 181 points, level 0 ones 256:
        // level 1 column -2 (-362 .. -181) straddles level 0 columns -2, -1.
        put(&mut cache, key(0, -1, 0), 1);
        assert!(cache.plan(&[key(1, -2, 0)]).draw.is_empty());
        put(&mut cache, key(0, -2, 0), 2);
        let plan = cache.plan(&[key(1, -2, 0)]);
        assert_eq!(drawn(&plan), [1, 2]);
        // Level 1 column -1 (-181 .. 0) lies in level 0 column -1 alone.
        let plan = cache.plan(&[key(1, -1, 0)]);
        assert_eq!(drawn(&plan), [1]);
        assert_eq!(plan.draw[0].2, tile_rect(key(0, -1, 0), 1.0));
    }

    #[test]
    fn zoom_out_falls_back_to_finer_tiles() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(1);
        let fine = [key(2, 0, 0), key(2, 1, 0), key(2, 0, 1)];
        for (i, &k) in fine.iter().enumerate() {
            put(&mut cache, k, i as u32);
        }
        // Not all four finer tiles: nothing stands in.
        assert!(cache.plan(&[key(0, 0, 0)]).draw.is_empty());
        put(&mut cache, key(2, 1, 1), 3);
        let plan = cache.plan(&[key(0, 0, 0)]);
        assert_eq!(drawn(&plan), [0, 1, 2, 3]);
        assert_eq!(plan.missing, [key(0, 0, 0)]);
        for (k, _, r) in &plan.draw {
            assert_eq!(*r, tile_rect(*k, 1.0));
        }
    }

    #[test]
    fn stale_insert_is_dropped() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(2);
        let started = cache.epoch();
        cache.set_drawing(3);
        cache.insert(started, KEYS[0], 1, 1);
        let plan = cache.plan(&KEYS[..1]);
        assert!(plan.draw.is_empty());
        assert_eq!(plan.missing, [KEYS[0]]);
    }

    #[test]
    fn invalidation_drops_tiles_in_flight() {
        let invalidations: [fn(&mut TileCache<u32>); 3] =
            [TileCache::mark_stale, TileCache::clear, |c| {
                c.set_pixel_ratio(2.0)
            }];
        for invalidate in invalidations {
            let mut cache = TileCache::new(1 << 20);
            cache.set_drawing(1);
            let started = cache.epoch();
            invalidate(&mut cache);
            cache.insert(started, KEYS[0], 1, 1);
            let plan = cache.plan(&KEYS[..1]);
            assert!(plan.draw.is_empty());
            assert_eq!(plan.missing, [KEYS[0]]);
        }
        // Setting the same ratio again changes nothing.
        let mut cache = TileCache::new(1 << 20);
        let started = cache.epoch();
        cache.set_pixel_ratio(1.0);
        cache.insert(started, KEYS[0], 1, 1);
        assert!(cache.plan(&KEYS[..1]).missing.is_empty());
    }

    #[test]
    fn budget_evicts_least_recently_planned() {
        let mut cache = TileCache::new(2);
        cache.set_drawing(1);
        put(&mut cache, KEYS[0], 0);
        put(&mut cache, KEYS[1], 1);
        cache.plan(&KEYS[..1]);
        put(&mut cache, KEYS[2], 2);
        let plan = cache.plan(&KEYS[..3]);
        assert_eq!(drawn(&plan), [0, 2]);
        assert_eq!(plan.missing, [KEYS[1]]);
    }

    #[test]
    fn image_arrival_marks_tiles_stale() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(1);
        for (i, k) in KEYS.into_iter().enumerate() {
            put(&mut cache, k, i as u32);
        }
        cache.mark_stale();
        let plan = cache.plan(&KEYS);
        assert_eq!(drawn(&plan), [0, 1, 2, 3]);
        assert_eq!(plan.missing, KEYS);
    }

    #[test]
    fn pixel_ratio_change_drops_tiles() {
        let mut cache = TileCache::new(1 << 20);
        cache.set_drawing(1);
        put(&mut cache, KEYS[0], 0);
        cache.clear();
        let plan = cache.plan(&KEYS[..1]);
        assert!(plan.draw.is_empty());
        put(&mut cache, KEYS[0], 0);
        cache.set_pixel_ratio(2.0);
        assert!(cache.plan(&KEYS[..1]).draw.is_empty());
    }

    #[test]
    fn fitting_level_stays_within_half_budget() {
        let view = Size::<Points> {
            width: px(800.0),
            height: px(600.0),
        };
        let content = rect(-100_000.0, -100_000.0, 200_000.0, 200_000.0);
        let level = fitting_level(view, 0.25, 0, 2.0, content, TILE_BUDGET_BYTES);
        assert!(level < 0);
        let tiles = visible_tiles(view, (0.0, 0.0), 0.25, level, 2.0, content);
        let tile_bytes = (TILE_PX * TILE_PX * 4) as usize;
        assert!(tiles.len() * tile_bytes <= 32 << 20);
        // A level that already fits is kept.
        assert_eq!(
            fitting_level(view, 1.0, 0, 2.0, content, TILE_BUDGET_BYTES),
            0
        );
    }

    #[test]
    fn fitting_level_keeps_exact_level_for_retina_windows() {
        let content = rect(-100_000.0, -100_000.0, 200_000.0, 200_000.0);
        for (w, h) in [(1200.0, 800.0), (3456.0, 2234.0)] {
            let view = Size::<Points> {
                width: px(w),
                height: px(h),
            };
            let budget = budget_for(view, 2.0);
            // At the level's own scale, and at the smallest zoom that
            // rounds to it (most tiles).
            for (zoom, level) in [(1.0, 0), (2f32.powf(-0.249), 0), (2.0, 2), (0.71, -1)] {
                assert_eq!(
                    fitting_level(view, zoom, level, 2.0, content, budget),
                    level,
                    "{w} x {h} at zoom {zoom}"
                );
            }
        }
    }

    #[test]
    fn budget_follows_view() {
        let view = |w: f32, h: f32| Size::<Points> {
            width: px(w),
            height: px(h),
        };
        // A small view keeps the floor.
        assert_eq!(budget_for(view(300.0, 200.0), 1.0), TILE_BUDGET_BYTES);
        // Three times the visible set with its margin.
        let small = budget_for(view(1200.0, 800.0), 2.0);
        assert!(small > TILE_BUDGET_BYTES, "{small}");
        let tiles = visible_tiles(
            view(1200.0, 800.0),
            (0.0, 0.0),
            1.0,
            0,
            2.0,
            rect(-1e5, -1e5, 2e5, 2e5),
        );
        assert!(small >= 3 * tiles.len() * TILE_BYTES);
        // Larger with the view and the pixel ratio, up to the cap.
        assert!(budget_for(view(2400.0, 1600.0), 2.0) > small);
        assert!(budget_for(view(1200.0, 800.0), 3.0) > small);
        assert_eq!(budget_for(view(3456.0, 2234.0), 2.0), TILE_BUDGET_MAX_BYTES);
        assert_eq!(budget_for(view(1e6, 1e6), 2.0), TILE_BUDGET_MAX_BYTES);
        // Nonsense keeps the floor.
        assert_eq!(budget_for(view(f32::NAN, 800.0), 2.0), TILE_BUDGET_BYTES);
        assert_eq!(budget_for(view(1200.0, 800.0), 0.0), TILE_BUDGET_BYTES);
        // A lower budget evicts down to it.
        let mut cache = TileCache::<u32>::new(4 * TILE_BYTES);
        for col in 0..4 {
            cache.insert(cache.epoch(), key(0, col, 0), col as u32, TILE_BYTES);
        }
        cache.set_budget(2 * TILE_BYTES);
        let keys: Vec<_> = (0..4).map(|col| key(0, col, 0)).collect();
        assert_eq!(cache.plan(&keys).missing.len(), 2);
    }

    #[test]
    fn degenerate_input_plans_nothing() {
        let view = Size::<Points> {
            width: px(800.0),
            height: px(600.0),
        };
        let content = rect(0.0, 0.0, 1000.0, 1000.0);
        assert!(visible_tiles(view, (f32::NAN, 0.0), 1.0, 0, 2.0, content).is_empty());
        assert!(visible_tiles(view, (0.0, 0.0), f32::NAN, 0, 2.0, content).is_empty());
        for zoom in [0.0, -1.0, f32::NAN, f32::INFINITY, f32::MIN_POSITIVE, 1e30] {
            let level = level_for(zoom);
            assert!((-40..=40).contains(&level), "{zoom}: {level}");
        }
        // Far levels plan without overflowing.
        let mut cache = TileCache::<u32>::new(1 << 20);
        let far = [key(i32::MIN, 0, 0), key(i32::MAX, 0, 0)];
        assert_eq!(cache.plan(&far).missing, far);
    }
}