frus-gpu 0.4.0

frus — GPU context and 2D rendering engine (Milestone 0)
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
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
//! Render orchestration: gathers the content painters — rectangles, images,
//! paths, text — and handles **layers** ([`Primitive::Layer`]).
//!
//! A layer is rendered **separately** into a full-surface texture (a pre-pass,
//! submitted on its own so the instance buffers are not aliased), then composited
//! as a single block at its group opacity by the [`CompositePainter`]. Group alpha
//! is therefore correct, with no double-blending where children overlap.
//!
//! Every pipeline is created up front ([`Painters::new`]) then **warmed up**
//! ([`Painters::warm_up`]): the first real frame compiles no shader, so it never
//! stutters.

use crate::batch;
use bytemuck::{Pod, Zeroable};
use frus_core::{
    BoxFit, Color, ColorFilter, ImageData, ImageFilter, LayerFilter, MaskShader, Path, Point,
    Primitive, Rect, Scene,
};
use std::collections::HashMap;
use wgpu::util::DeviceExt;

use crate::filter::FilterPainter;
use crate::image::ImagePainter;
use crate::painter::Painter;
use crate::path::PathPainter;
use crate::text::TextPainter;

/// A vertex of the unit quad, which covers the whole surface.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct QuadVertex {
    pos: [f32; 2],
}

impl QuadVertex {
    fn layout() -> wgpu::VertexBufferLayout<'static> {
        const ATTRS: [wgpu::VertexAttribute; 1] = wgpu::vertex_attr_array![0 => Float32x2];
        wgpu::VertexBufferLayout {
            array_stride: std::mem::size_of::<QuadVertex>() as wgpu::BufferAddress,
            step_mode: wgpu::VertexStepMode::Vertex,
            attributes: &ATTRS,
        }
    }
}

const QUAD_VERTICES: &[QuadVertex] = &[
    QuadVertex { pos: [0.0, 0.0] },
    QuadVertex { pos: [1.0, 0.0] },
    QuadVertex { pos: [1.0, 1.0] },
    QuadVertex { pos: [0.0, 0.0] },
    QuadVertex { pos: [1.0, 1.0] },
    QuadVertex { pos: [0.0, 1.0] },
];
const QUAD_VERTEX_COUNT: u32 = 6;

/// A composite instance: the clip, the **inverse** transform (screen → texture)
/// and the group opacity.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct CompInstance {
    clip: [f32; 4],
    /// The linear part of the affine inverse: `ia, ib, ic, id`.
    inv_lin: [f32; 4],
    /// `ie, if, opacity, _` — the inverse's translation plus the group opacity.
    inv_tr_opacity: [f32; 4],
    /// The clip shape: `[kind, _, _, _]` (0 = rect, 1 = rrect, 2 = oval).
    shape: [f32; 4],
    /// The corner radii of a rrect: `[tl, tr, br, bl]`.
    radii: [f32; 4],
    /// Where the layer's texture lies on the target: `[x, y, width, height]`, in pixels
    /// (milestone 610). The whole target for a layer that may draw anywhere.
    region: [f32; 4],
}

#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Viewport {
    size: [f32; 2],
    _pad: [f32; 2],
}

/// A layer's colour filter and mask, as the fragment shader reads them.
///
/// This rides in a **uniform** rather than in the instance, because a colour matrix
/// alone is twenty floats and a vertex attribute budget is a small, fixed thing. Each
/// layer already has its own bind group for its texture, so a slice of one shared
/// buffer costs nothing extra.
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable, Default)]
struct FilterParams {
    /// `[colour kind, mask kind, colour blend, mask blend]`. Colour kind: 0 none,
    /// 1 matrix, 2 a colour blended in. Mask kind: 0 none, 1 linear, 2 radial.
    flags: [f32; 4],
    /// The colour matrix, one row per output channel, then the constant column.
    rows: [[f32; 4]; 4],
    constants: [f32; 4],
    /// The colour of a `Mode` colour filter.
    mode_color: [f32; 4],
    /// Linear: `(from.x, from.y, to.x, to.y)`. Radial: `(cx, cy, radius, _)`.
    mask_geom: [f32; 4],
    mask_c0: [f32; 4],
    mask_c1: [f32; 4],
    /// `[mode + 1, _, _, _]`: how the layer meets what is under it, `0` painting it over
    /// (milestone 646).
    blend: [f32; 4],
}

impl FilterParams {
    /// Uniform bindings must start at a device-aligned offset; 256 bytes is the
    /// strictest alignment in practice, so the layers take one slot each.
    const STRIDE: wgpu::BufferAddress = 256;

    /// Translates a scene-level filter into the numbers the shader wants. The image
    /// filter is not here: it has already run, as a pre-pass over the layer texture.
    fn new(filter: &LayerFilter) -> FilterParams {
        let mut p = FilterParams::default();
        match filter.color {
            None => {}
            Some(ColorFilter::Matrix(m)) => {
                p.flags[0] = 1.0;
                for row in 0..4 {
                    p.rows[row] = [m[row * 5], m[row * 5 + 1], m[row * 5 + 2], m[row * 5 + 3]];
                    p.constants[row] = m[row * 5 + 4];
                }
            }
            Some(ColorFilter::Mode(color, mode)) => {
                p.flags[0] = 2.0;
                p.flags[2] = mode.code() as f32;
                p.mode_color = color.to_array();
            }
        }
        if let Some(mask) = filter.mask {
            p.flags[1] = mask.shader.code() as f32 + 1.0;
            p.flags[3] = mask.blend.code() as f32;
            let (geom, c0, c1) = match mask.shader {
                MaskShader::Linear {
                    from,
                    to,
                    from_color,
                    to_color,
                } => ([from.x, from.y, to.x, to.y], from_color, to_color),
                MaskShader::Radial {
                    center,
                    radius,
                    from_color,
                    to_color,
                } => ([center.x, center.y, radius, 0.0], from_color, to_color),
            };
            p.mask_geom = geom;
            p.mask_c0 = c0.to_array();
            p.mask_c1 = c1.to_array();
        }
        if let Some(mode) = filter.blend {
            p.blend[0] = mode.code() as f32 + 1.0;
        }
        p
    }
}

/// The MSAA sample count we aim for: 4× is a good quality/cost trade-off and the
/// most widely supported, including the llvmpipe software rasteriser.
pub(crate) const MSAA_SAMPLES: u32 = 4;

/// Returns the MSAA sample count to use for `format` on this adapter:
/// [`MSAA_SAMPLES`] when supported, otherwise 1, which disables MSAA. Called once
/// at init by the windowed renderer and by the offscreen path alike.
pub(crate) fn preferred_sample_count(adapter: &wgpu::Adapter, format: wgpu::TextureFormat) -> u32 {
    let flags = adapter.get_texture_format_features(format).flags;
    if flags.sample_count_supported(MSAA_SAMPLES) {
        MSAA_SAMPLES
    } else {
        1
    }
}

/// A layer ready to be composited: its texture, opacity and clip, plus the
/// **inverse** transform (screen → texture) to apply when sampling.
struct LayerComposite {
    view: wgpu::TextureView,
    /// The coverage mask (`ClipShape::Path`): the path rendered in white. Other
    /// shapes get a solid 1×1 white texture, a neutral multiplication.
    mask: wgpu::TextureView,
    opacity: f32,
    clip: [f32; 4],
    /// The clip shape: `[kind, _, _, _]` — `kind` 0 = rect, 1 = rrect, 2 = oval,
    /// 3 = path, meaning a mask.
    shape: [f32; 4],
    /// The corner radii of a rrect: `[tl, tr, br, bl]`.
    radii: [f32; 4],
    /// The affine inverse `[ia, ib, ic, id, ie, if]`; identity means no transform.
    inverse: [f32; 6],
    /// The colour filter and mask, applied in the compositing fragment.
    filter: LayerFilter,
    /// Where its texture lies on the target, when it is not the whole of it.
    region: Option<[f32; 4]>,
}

/// **The part of the target a layer can draw on**, in whole pixels: its clip, held to the
/// target (milestone 610). `None` when it may draw anywhere, and has the whole target: a
/// layer that is transformed, filtered, painted over a backdrop, or clipped to a path, or
/// one with such a layer inside it. Those move or spread their content past its clip, or
/// hold geometry in the target's own coordinates.
///
/// A layer used to be rendered into a texture the size of the target and composited by a
/// quad covering it, whatever it held: on a phone, a group-opacity layer of 56 × 32 px cost
/// two passes over 1080 × 2340 multisampled pixels a frame.
fn layer_region(
    clip: Rect,
    clip_shape: &frus_core::ClipShape,
    transform: &Option<frus_core::LayerTransform>,
    filter: &LayerFilter,
    primitives: &[Primitive],
    w: u32,
    h: u32,
) -> Option<Rect> {
    if transform.is_some()
        || filter.image.is_some_and(|f| !f.is_identity())
        || filter.backdrop.is_some()
        || matches!(clip_shape, frus_core::ClipShape::Path(_))
        || !primitives.iter().all(boundable)
    {
        return None;
    }
    let x0 = clip.x.max(0.0).floor();
    let y0 = clip.y.max(0.0).floor();
    let x1 = (clip.x + clip.width).min(w as f32).ceil();
    let y1 = (clip.y + clip.height).min(h as f32).ceil();
    if x1 - x0 < 1.0 || y1 - y0 < 1.0 {
        // Nothing of it is on the target: one pixel, which draws nothing.
        return Some(Rect::new(
            x0.min(w as f32 - 1.0).max(0.0),
            y0.min(h as f32 - 1.0).max(0.0),
            1.0,
            1.0,
        ));
    }
    // Nothing gained, and a texture of a different size, for a layer that covers it all.
    if x0 <= 0.0 && y0 <= 0.0 && x1 >= w as f32 && y1 >= h as f32 {
        return None;
    }
    Some(Rect::new(x0, y0, x1 - x0, y1 - y0))
}

/// Whether a primitive can be drawn moved: everything but a layer that needs the whole
/// target, by [`layer_region`]'s rule.
fn boundable(primitive: &Primitive) -> bool {
    match primitive {
        Primitive::Layer {
            primitives,
            clip_shape,
            transform,
            filter,
            ..
        } => {
            transform.is_none()
                && filter.image.is_none_or(|f| f.is_identity())
                && filter.backdrop.is_none()
                && !matches!(clip_shape, frus_core::ClipShape::Path(_))
                && primitives.iter().all(boundable)
        }
        _ => true,
    }
}

/// `primitives` moved into a region's own frame, its corner at the origin.
fn into_region(
    primitives: &[Primitive],
    region: Option<Rect>,
) -> std::borrow::Cow<'_, [Primitive]> {
    match region {
        Some(r) => std::borrow::Cow::Owned(
            primitives
                .iter()
                .map(|p| p.translated(-r.x, -r.y))
                .collect(),
        ),
        None => std::borrow::Cow::Borrowed(primitives),
    }
}

/// A draw waiting for the frame underneath it to exist: a backdrop, or a layer that
/// blends with what is under it. The frame is drawn up to it, read, and the draw pointed
/// at what was read.
struct Cut {
    /// Its index in the composite draw list. Everything before it is what it reads.
    at: usize,
    /// The scene index of the layer it belongs to, which is how the frame is cut: the
    /// copy is taken just before the **batch** that draws that layer.
    scene: usize,
    kind: CutKind,
}

/// What a [`Cut`] does with the frame it reads.
enum CutKind {
    /// Filters it, and draws the result.
    Backdrop {
        filter: ImageFilter,
        /// `true` for [`frus_core::BlendMode::Src`]: the filtered copy **replaces** what
        /// it was copied from rather than being painted over it.
        replace: bool,
        /// The sharing key, when several backdrops are filtered once between them.
        key: Option<u64>,
    },
    /// Copies it as it is, for the layer to blend with (milestone 646).
    Blend,
}

/// A copy of `source`, `w × h`, to read while `source` is drawn on.
fn copy_of(
    device: &wgpu::Device,
    queue: &wgpu::Queue,
    format: wgpu::TextureFormat,
    source: &wgpu::Texture,
    w: u32,
    h: u32,
) -> wgpu::Texture {
    let size = wgpu::Extent3d {
        width: w.max(1),
        height: h.max(1),
        depth_or_array_layers: 1,
    };
    let copy = device.create_texture(&wgpu::TextureDescriptor {
        label: Some("frus.under"),
        size,
        mip_level_count: 1,
        sample_count: 1,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
        view_formats: &[],
    });
    let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
        label: Some("frus.encoder.under"),
    });
    encoder.copy_texture_to_texture(source.as_image_copy(), copy.as_image_copy(), size);
    queue.submit(std::iter::once(encoder.finish()));
    copy
}

/// This frame's draws, prepared once and replayed by whichever pass draws them.
///
/// The batches are the **whole** order of the frame, layers included: a layer is one
/// batch of its own, holding the scene index of the group, and `layer_draws` says which
/// composite draws that batch issues — two when the layer takes a backdrop (the filtered
/// copy, then the layer over it), one otherwise.
struct ContentPlan<'a> {
    batches: &'a [batch::Batch],
    rect_ranges: &'a [std::ops::Range<u32>],
    image_ranges: &'a [std::ops::Range<u32>],
    path_ranges: &'a [std::ops::Range<u32>],
    decoration_ranges: &'a [std::ops::Range<u32>],
    decoration_base: u32,
    /// Scene index of a layer → the composite draws that put it on the screen.
    layer_draws: &'a HashMap<usize, std::ops::Range<usize>>,
    /// How many text batches precede each batch, so a pass over a *range* of batches
    /// still hands the text painter the right renderer.
    text_slots: &'a [usize],
}

/// A layer texture **kept across frames** — a repaint boundary on the GPU side —
/// together with a snapshot of its content and its dimensions: as long as those do
/// not change the texture is reused as is, and the pre-pass (submit, tessellation
/// and draw) is skipped entirely.
struct CachedLayer {
    /// What the layer draws, **in its own frame**: moved so that its region starts at
    /// the origin. A layer carried across the screen whole — a row scrolled — draws the
    /// same there, and is not rendered again (milestone 610).
    primitives: Vec<Primitive>,
    width: u32,
    height: u32,
    texture: wgpu::Texture,
    /// The image filter already baked into `texture`. Part of the key: the same
    /// primitives blurred by a different amount are a different picture, and an
    /// animated blur would otherwise hold the first frame it drew for ever.
    image: Option<ImageFilter>,
}

/// An intermediate MSAA texture reused as a render target: painting happens there,
/// multisampled, then **resolves** to the single-sample target. One is enough — the
/// layer pre-passes and the main pass are all full-surface and take turns using it,
/// since their submits are sequential.
struct MsaaScratch {
    width: u32,
    height: u32,
    format: wgpu::TextureFormat,
    texture: wgpu::Texture,
}

/// The layer compositing pipeline.
struct CompositePainter {
    pipeline: wgpu::RenderPipeline,
    /// The same pipeline with blending off, so a draw can **replace** what is under
    /// it instead of painting over it. Only a backdrop asks for that
    /// ([`frus_core::BlendMode::Src`]).
    pipeline_src: wgpu::RenderPipeline,
    viewport_buffer: wgpu::Buffer,
    viewport_bind_group: wgpu::BindGroup,
    texture_layout: wgpu::BindGroupLayout,
    sampler: wgpu::Sampler,
    quad_vertex_buffer: wgpu::Buffer,
    instance_buffer: wgpu::Buffer,
    instance_capacity: usize,
    /// The bind groups for this frame's layer textures.
    bind_groups: Vec<wgpu::BindGroup>,
    /// The **neutral** mask, 1×1 opaque white: bound when a layer has no path clip,
    /// so alpha is multiplied by 1 and nothing changes.
    white_mask: wgpu::Texture,
    /// This frame's filter parameters, one aligned slot per layer.
    filter_buffer: wgpu::Buffer,
    filter_capacity: usize,
}

impl CompositePainter {
    /// A view of the neutral mask, opaque white, bound to layers with no path clip.
    fn white_mask_view(&self) -> wgpu::TextureView {
        self.white_mask
            .create_view(&wgpu::TextureViewDescriptor::default())
    }
}

impl CompositePainter {
    fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        sample_count: u32,
        cache: Option<&wgpu::PipelineCache>,
    ) -> Self {
        let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
            label: Some("frus.composite.shader"),
            source: wgpu::ShaderSource::Wgsl(include_str!("shaders/composite.wgsl").into()),
        });

        let viewport_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("frus.composite.viewport"),
            size: std::mem::size_of::<Viewport>() as wgpu::BufferAddress,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let viewport_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("frus.composite.viewport.bgl"),
            entries: &[wgpu::BindGroupLayoutEntry {
                binding: 0,
                // The fragment also reads `viewport.size`, to counter-rotate a layer.
                visibility: wgpu::ShaderStages::VERTEX_FRAGMENT,
                ty: wgpu::BindingType::Buffer {
                    ty: wgpu::BufferBindingType::Uniform,
                    has_dynamic_offset: false,
                    min_binding_size: None,
                },
                count: None,
            }],
        });

        let viewport_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("frus.composite.viewport.bind_group"),
            layout: &viewport_layout,
            entries: &[wgpu::BindGroupEntry {
                binding: 0,
                resource: viewport_buffer.as_entire_binding(),
            }],
        });

        let texture_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
            label: Some("frus.composite.texture.bgl"),
            entries: &[
                wgpu::BindGroupLayoutEntry {
                    binding: 0,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                wgpu::BindGroupLayoutEntry {
                    binding: 1,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
                    count: None,
                },
                // The path clip mask, sampled in the fragment shader.
                wgpu::BindGroupLayoutEntry {
                    binding: 2,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
                // The colour filter and mask.
                wgpu::BindGroupLayoutEntry {
                    binding: 3,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Buffer {
                        ty: wgpu::BufferBindingType::Uniform,
                        has_dynamic_offset: false,
                        min_binding_size: None,
                    },
                    count: None,
                },
                // What is under a layer that blends with it (milestone 646).
                wgpu::BindGroupLayoutEntry {
                    binding: 4,
                    visibility: wgpu::ShaderStages::FRAGMENT,
                    ty: wgpu::BindingType::Texture {
                        sample_type: wgpu::TextureSampleType::Float { filterable: true },
                        view_dimension: wgpu::TextureViewDimension::D2,
                        multisampled: false,
                    },
                    count: None,
                },
            ],
        });

        let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
            label: Some("frus.composite.sampler"),
            mag_filter: wgpu::FilterMode::Nearest,
            min_filter: wgpu::FilterMode::Nearest,
            ..Default::default()
        });

        let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
            label: Some("frus.composite.pipeline_layout"),
            bind_group_layouts: &[Some(&viewport_layout), Some(&texture_layout)],
            immediate_size: 0,
        });

        let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("frus.composite.pipeline"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[Some(QuadVertex::layout()), Some(comp_instance_layout())],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    // **Premultiplied**, unlike every other pipeline here, because
                    // what this one samples is a layer texture and a layer texture is
                    // premultiplied: it was painted over a transparent target. Passing
                    // it through the straight-alpha blend would multiply the colour by
                    // the coverage a second time, which is invisible on opaque content
                    // and wrong everywhere else — a mask fade would run to black
                    // instead of to the background.
                    blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: sample_count,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache,
        });

        let pipeline_src = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
            label: Some("frus.composite.pipeline.src"),
            layout: Some(&pipeline_layout),
            vertex: wgpu::VertexState {
                module: &shader,
                entry_point: Some("vs_main"),
                buffers: &[Some(QuadVertex::layout()), Some(comp_instance_layout())],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            },
            fragment: Some(wgpu::FragmentState {
                module: &shader,
                entry_point: Some("fs_main"),
                targets: &[Some(wgpu::ColorTargetState {
                    format,
                    // No blending at all: the source is written as it stands.
                    blend: None,
                    write_mask: wgpu::ColorWrites::ALL,
                })],
                compilation_options: wgpu::PipelineCompilationOptions::default(),
            }),
            primitive: wgpu::PrimitiveState {
                topology: wgpu::PrimitiveTopology::TriangleList,
                ..Default::default()
            },
            depth_stencil: None,
            multisample: wgpu::MultisampleState {
                count: sample_count,
                mask: !0,
                alpha_to_coverage_enabled: false,
            },
            multiview_mask: None,
            cache,
        });

        let quad_vertex_buffer = device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
            label: Some("frus.composite.quad_vertex_buffer"),
            contents: bytemuck::cast_slice(QUAD_VERTICES),
            usage: wgpu::BufferUsages::VERTEX,
        });
        let instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("frus.composite.instance_buffer"),
            size: (8 * std::mem::size_of::<CompInstance>()) as wgpu::BufferAddress,
            usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        let filter_buffer = device.create_buffer(&wgpu::BufferDescriptor {
            label: Some("frus.composite.filter_buffer"),
            size: FilterParams::STRIDE * 8,
            usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
            mapped_at_creation: false,
        });

        // The neutral mask: 1×1 opaque white, so alpha is 1 everywhere.
        let white = device.create_texture_with_data(
            queue,
            &wgpu::TextureDescriptor {
                label: Some("frus.composite.white_mask"),
                size: wgpu::Extent3d {
                    width: 1,
                    height: 1,
                    depth_or_array_layers: 1,
                },
                mip_level_count: 1,
                sample_count: 1,
                dimension: wgpu::TextureDimension::D2,
                format: wgpu::TextureFormat::Rgba8Unorm,
                usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
                view_formats: &[],
            },
            wgpu::util::TextureDataOrder::LayerMajor,
            &[255, 255, 255, 255],
        );

        Self {
            pipeline,
            pipeline_src,
            viewport_buffer,
            viewport_bind_group,
            texture_layout,
            sampler,
            quad_vertex_buffer,
            instance_buffer,
            instance_capacity: 8,
            bind_groups: Vec::new(),
            white_mask: white,
            filter_buffer,
            filter_capacity: 8,
        }
    }

    /// Prepares the compositing of `layers`: instances and bind groups.
    fn prepare(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        layers: &[LayerComposite],
        w: f32,
        h: f32,
    ) {
        let viewport = Viewport {
            size: [w.max(1.0), h.max(1.0)],
            _pad: [0.0, 0.0],
        };
        queue.write_buffer(&self.viewport_buffer, 0, bytemuck::bytes_of(&viewport));

        self.bind_groups.clear();
        if layers.is_empty() {
            return;
        }
        let instances: Vec<CompInstance> = layers
            .iter()
            .map(|l| {
                let i = l.inverse;
                CompInstance {
                    clip: l.clip,
                    inv_lin: [i[0], i[1], i[2], i[3]],
                    inv_tr_opacity: [i[4], i[5], l.opacity, 0.0],
                    shape: l.shape,
                    radii: l.radii,
                    region: l.region.unwrap_or([0.0, 0.0, w.max(1.0), h.max(1.0)]),
                }
            })
            .collect();
        if instances.len() > self.instance_capacity {
            let cap = instances.len().next_power_of_two();
            self.instance_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("frus.composite.instance_buffer"),
                size: (cap * std::mem::size_of::<CompInstance>()) as wgpu::BufferAddress,
                usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            self.instance_capacity = cap;
        }
        queue.write_buffer(&self.instance_buffer, 0, bytemuck::cast_slice(&instances));

        if layers.len() > self.filter_capacity {
            let cap = layers.len().next_power_of_two();
            self.filter_buffer = device.create_buffer(&wgpu::BufferDescriptor {
                label: Some("frus.composite.filter_buffer"),
                size: FilterParams::STRIDE * cap as wgpu::BufferAddress,
                usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
                mapped_at_creation: false,
            });
            self.filter_capacity = cap;
        }
        for (i, layer) in layers.iter().enumerate() {
            let params = FilterParams::new(&layer.filter);
            queue.write_buffer(
                &self.filter_buffer,
                i as wgpu::BufferAddress * FilterParams::STRIDE,
                bytemuck::bytes_of(&params),
            );
        }

        let white = self.white_mask_view();
        for (i, layer) in layers.iter().enumerate() {
            let group = self.bind_group(device, i, &layer.view, &layer.mask, &white);
            self.bind_groups.push(group);
        }
    }

    /// The bind group of draw `index`: its texture, its clip mask, its slot of the filter
    /// buffer, and what is under it — read only by a layer that blends with it.
    fn bind_group(
        &self,
        device: &wgpu::Device,
        index: usize,
        view: &wgpu::TextureView,
        mask: &wgpu::TextureView,
        under: &wgpu::TextureView,
    ) -> wgpu::BindGroup {
        device.create_bind_group(&wgpu::BindGroupDescriptor {
            label: Some("frus.composite.texture.bind_group"),
            layout: &self.texture_layout,
            entries: &[
                wgpu::BindGroupEntry {
                    binding: 0,
                    resource: wgpu::BindingResource::TextureView(view),
                },
                wgpu::BindGroupEntry {
                    binding: 1,
                    resource: wgpu::BindingResource::Sampler(&self.sampler),
                },
                wgpu::BindGroupEntry {
                    binding: 2,
                    resource: wgpu::BindingResource::TextureView(mask),
                },
                wgpu::BindGroupEntry {
                    binding: 3,
                    resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding {
                        buffer: &self.filter_buffer,
                        offset: index as wgpu::BufferAddress * FilterParams::STRIDE,
                        size: wgpu::BufferSize::new(std::mem::size_of::<FilterParams>() as u64),
                    }),
                },
                wgpu::BindGroupEntry {
                    binding: 4,
                    resource: wgpu::BindingResource::TextureView(under),
                },
            ],
        })
    }

    /// Points draw `index` at a texture that did not exist when the frame was
    /// prepared — which is every backdrop, since what a backdrop filters is the frame
    /// itself and the frame is drawn after this.
    fn rebind(&mut self, device: &wgpu::Device, index: usize, view: &wgpu::TextureView) {
        let white = self.white_mask_view();
        self.bind_groups[index] = self.bind_group(device, index, view, &white, &white);
    }

    /// Gives draw `index` — a layer that blends with what is under it — the copy of
    /// what is under it, which exists only once the frame has been drawn that far.
    fn rebind_under(
        &mut self,
        device: &wgpu::Device,
        index: usize,
        layer: &LayerComposite,
        under: &wgpu::TextureView,
    ) {
        self.bind_groups[index] = self.bind_group(device, index, &layer.view, &layer.mask, under);
    }

    /// Draws a **range** of the composite list. `replace_at` names the one draw that
    /// writes instead of blending, which only a backdrop asks for.
    fn draw_range<'pass>(
        &'pass self,
        pass: &mut wgpu::RenderPass<'pass>,
        range: std::ops::Range<usize>,
        replace_at: Option<usize>,
    ) {
        if range.is_empty() || self.bind_groups.is_empty() {
            return;
        }
        pass.set_bind_group(0, &self.viewport_bind_group, &[]);
        pass.set_vertex_buffer(0, self.quad_vertex_buffer.slice(..));
        pass.set_vertex_buffer(1, self.instance_buffer.slice(..));
        // `None` rather than `Some(false)`, so the first draw always sets a pipeline.
        let mut bound: Option<bool> = None;
        for i in range {
            let replace = replace_at == Some(i);
            if bound != Some(replace) {
                pass.set_pipeline(if replace {
                    &self.pipeline_src
                } else {
                    &self.pipeline
                });
                bound = Some(replace);
            }
            pass.set_bind_group(1, &self.bind_groups[i], &[]);
            let inst = i as u32;
            pass.draw(0..QUAD_VERTEX_COUNT, inst..inst + 1);
        }
    }
}

fn comp_instance_layout() -> wgpu::VertexBufferLayout<'static> {
    const ATTRS: [wgpu::VertexAttribute; 6] = wgpu::vertex_attr_array![
        1 => Float32x4,
        2 => Float32x4,
        3 => Float32x4,
        4 => Float32x4,
        5 => Float32x4,
        6 => Float32x4,
    ];
    wgpu::VertexBufferLayout {
        array_stride: std::mem::size_of::<CompInstance>() as wgpu::BufferAddress,
        step_mode: wgpu::VertexStepMode::Instance,
        attributes: &ATTRS,
    }
}

/// The full set of content painters, plus layer compositing.
pub(crate) struct Painters {
    rect: Painter,
    image: ImagePainter,
    path: PathPainter,
    text: TextPainter,
    composite: CompositePainter,
    /// The separable image-filter pre-pass: blur, dilate, erode.
    filter: FilterPainter,
    /// The MSAA sample count; 1 means no multisampling.
    sample_count: u32,
    /// The intermediate MSAA texture, created on demand and recreated on resize.
    /// The multisampled scratch targets, one per size drawn at: the surface's, and each
    /// layer region's (milestone 610).
    msaa: Vec<MsaaScratch>,
    /// The staging texture a frame **with backdrops** is built in, so that a backdrop
    /// can read the frame so far. `None` until the first such frame.
    stage: Option<MsaaScratch>,
    /// Layer textures kept across frames, indexed by the layer's rank.
    layer_cache: Vec<CachedLayer>,
    /// How many layer pre-passes were actually rendered — the cache's proof.
    #[allow(dead_code)]
    layer_renders: u64,
}

impl Painters {
    /// `cache`, where the device keeps compiled pipelines between launches (Vulkan): the
    /// pipelines are built through it (milestone 685, #217).
    pub(crate) fn new(
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        sample_count: u32,
        cache: Option<&wgpu::PipelineCache>,
    ) -> Self {
        Self {
            rect: Painter::new(device, format, sample_count, cache),
            image: ImagePainter::new(device, format, sample_count, cache),
            path: PathPainter::new(device, format, sample_count, cache),
            text: TextPainter::new(device, queue, format, sample_count),
            composite: CompositePainter::new(device, queue, format, sample_count, cache),
            filter: FilterPainter::new(device, format, cache),
            sample_count,
            msaa: Vec::new(),
            stage: None,
            layer_cache: Vec::new(),
            layer_renders: 0,
        }
    }

    /// Layer pre-passes rendered since creation, for the cache test.
    #[cfg(test)]
    pub(crate) fn layer_render_count(&self) -> u64 {
        self.layer_renders
    }

    /// Returns a fresh view of the MSAA texture, recreating it when the size or the
    /// format changes, or `None` when MSAA is off (`sample_count == 1`). The view is
    /// created on the fly — it is cheap — and returned by value, which releases the
    /// borrow of `self` before the render pass opens.
    fn ensure_msaa(
        &mut self,
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
        w: u32,
        h: u32,
    ) -> Option<wgpu::TextureView> {
        if self.sample_count == 1 {
            return None;
        }
        let at = self
            .msaa
            .iter()
            .position(|s| s.width == w && s.height == h && s.format == format);
        let at = match at {
            Some(at) => at,
            None => {
                // A handful of sizes are drawn at from one frame to the next; a list
                // that grows past that is regions that have changed, and is started
                // again rather than kept.
                if self.msaa.len() >= 16 {
                    self.msaa.clear();
                }
                let texture = device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("frus.msaa.scratch"),
                    size: wgpu::Extent3d {
                        width: w.max(1),
                        height: h.max(1),
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: self.sample_count,
                    dimension: wgpu::TextureDimension::D2,
                    format,
                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
                    view_formats: &[],
                });
                self.msaa.push(MsaaScratch {
                    width: w,
                    height: h,
                    format,
                    texture,
                });
                self.msaa.len() - 1
            }
        };
        Some(
            self.msaa[at]
                .texture
                .create_view(&wgpu::TextureViewDescriptor::default()),
        )
    }

    fn set_viewport(&self, queue: &wgpu::Queue, w: f32, h: f32) {
        self.rect.set_viewport(queue, w, h);
        self.image.set_viewport(queue, w, h);
        self.path.set_viewport(queue, w, h);
    }

    /// Renders `scene`, layers included, into `target` of size `w×h`. `clear` is
    /// `Some(colour)` to clear the target, `None` to paint over it. **Submitted
    /// internally**: one pass per layer, plus the main pass — and, when a layer asks
    /// for a backdrop, one more pass per backdrop.
    ///
    /// Note: under MSAA, `clear == None` — painting over — is not supported, since
    /// the multisampled target does not hold `target`'s existing content. Every
    /// current caller passes `Some(_)`.
    // The device, the queue, the target and its size: a render call's irreducible
    // arguments.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn render(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        target: &wgpu::TextureView,
        w: u32,
        h: u32,
        scene: &Scene,
        clear: Option<wgpu::Color>,
    ) {
        self.set_viewport(queue, w as f32, h as f32);

        // Pre-passes: each layer into its own full-surface texture — but **reused**
        // as is when its content has not changed, which is the GPU-side cache.
        //
        // The result is a flat list of composite draws in the order they happen. A
        // layer that asks for a backdrop contributes **two** entries: the filtered
        // copy of what is underneath, and then the layer itself over it.
        let mut draws: Vec<LayerComposite> = Vec::new();
        let mut cuts: Vec<Cut> = Vec::new();
        // Which composite draws each layer issues, by its index in the scene. The batch
        // planner orders layers among the content, and this is how a layer batch finds
        // the draws that belong to it.
        let mut layer_draws: HashMap<usize, std::ops::Range<usize>> = HashMap::new();
        let mut layer_index = 0usize;
        for (scene_index, primitive) in scene.primitives().iter().enumerate() {
            if let Primitive::Layer {
                primitives,
                opacity,
                clip,
                clip_shape,
                transform,
                filter,
                ..
            } = primitive
            {
                let region = layer_region(*clip, clip_shape, transform, filter, primitives, w, h);
                let (rw, rh) = region.map_or((w, h), |r| (r.width as u32, r.height as u32));
                let local = into_region(primitives, region);
                let view = self.layer_texture(
                    device,
                    queue,
                    format,
                    layer_index,
                    &local,
                    filter.image.filter(|f| !f.is_identity()),
                    rw,
                    rh,
                );
                let mut entry = self.layer_entry(
                    device, queue, format, view, *opacity, *clip, clip_shape, transform, filter, w,
                    h,
                );
                entry.region = region.map(|r| r.to_array());
                let first_draw = draws.len();
                // The backdrop goes **first**: it is a picture of what was already
                // there, and the layer is painted over it. It borrows the layer's clip
                // and shape, which is the region it applies to.
                if let Some(backdrop) = filter.backdrop {
                    cuts.push(Cut {
                        at: draws.len(),
                        scene: scene_index,
                        kind: CutKind::Backdrop {
                            filter: backdrop.filter,
                            replace: backdrop.blend == frus_core::BlendMode::Src,
                            key: backdrop.key,
                        },
                    });
                    draws.push(LayerComposite {
                        // Filled in once the frame so far has actually been drawn;
                        // until then any texture will do, since nothing samples it.
                        view: self.composite.white_mask_view(),
                        mask: self.composite.white_mask_view(),
                        opacity: 1.0,
                        clip: entry.clip,
                        shape: entry.shape,
                        radii: entry.radii,
                        // The copy is of the screen, at the screen's own coordinates.
                        inverse: frus_core::Affine::IDENTITY.m,
                        filter: LayerFilter::NONE,
                        region: None,
                    });
                } else if filter.blend.is_some() {
                    // A layer that blends reads what is under it: the frame is cut at it
                    // too, and the layer itself is the draw that reads.
                    cuts.push(Cut {
                        at: draws.len(),
                        scene: scene_index,
                        kind: CutKind::Blend,
                    });
                }
                draws.push(entry);
                layer_draws.insert(scene_index, first_draw..draws.len());
                layer_index += 1;
            }
        }
        // Forget vanished layers: the scene has fewer than it had last frame.
        self.layer_cache.truncate(layer_index);
        // Each layer set the painters to its own size: the frame is the surface's again.
        self.set_viewport(queue, w as f32, h as f32);

        self.composite
            .prepare(device, queue, &draws, w as f32, h as f32);
        // What may share a draw call, and in what order — see `batch`. The plan comes
        // first now: text is interleaved with the rest, so the text painter needs to
        // know the batches before it can prepare a renderer for each.
        let batches = batch::plan(scene);
        let (decorations, decoration_ranges) = self
            .text
            .prepare_frame(device, queue, scene, w, h, &batches);
        let (rect_ranges, decoration_base) =
            self.rect
                .prepare_frame(device, queue, scene, &decorations, &batches);
        let image_ranges = self.image.prepare_frame(device, queue, scene, &batches);
        let path_ranges = self.path.prepare_frame(device, queue, scene, &batches);
        // The text painter keeps one renderer per text batch, in order; a pass drawing
        // batches `a..b` needs to know how many of them came before `a`.
        let mut text_slots = Vec::with_capacity(batches.len());
        let mut slots = 0usize;
        for batch in &batches {
            text_slots.push(slots);
            if batch.kind == batch::Kind::Text {
                slots += 1;
            }
        }
        let content = ContentPlan {
            batches: &batches,
            rect_ranges: &rect_ranges,
            image_ranges: &image_ranges,
            path_ranges: &path_ranges,
            decoration_ranges: &decoration_ranges,
            decoration_base: decoration_base.start,
            layer_draws: &layer_draws,
            text_slots: &text_slots,
        };

        // With MSAA we paint into the multisampled texture then resolve; without it
        // we paint straight into whatever the pass is aimed at.
        let msaa_view = self.ensure_msaa(device, format, w, h);
        let load = match clear {
            Some(c) => wgpu::LoadOp::Clear(c),
            None => wgpu::LoadOp::Load,
        };

        if cuts.is_empty() {
            // The ordinary frame: one pass, straight into the target, exactly as it
            // was before backdrops existed.
            let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                label: Some("frus.encoder"),
            });
            self.pass(
                &mut encoder,
                msaa_view.as_ref(),
                target,
                load,
                &content,
                0..batches.len(),
                None,
            );
            queue.submit(std::iter::once(encoder.finish()));
            return;
        }

        // A backdrop is a filter of **what is already painted**, and a blended layer
        // meets it, so the frame has to be readable half-way through. It cannot be read
        // out of `target`: a surface texture is a render attachment and nothing else. So
        // the frame is built in a staging texture we own, cut into segments at each
        // backdrop and blend, and blitted to the target at the end.
        let stage = self.stage(device, format, w, h).clone();
        self.draw_segmented(
            device,
            queue,
            format,
            msaa_view.as_ref(),
            &stage,
            load,
            &content,
            &cuts,
            &draws,
        );
        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("frus.encoder.blit"),
        });
        // And the staged frame onto the target it was always meant for.
        let stage_view = stage.create_view(&wgpu::TextureViewDescriptor::default());
        self.filter
            .blit(device, queue, &mut encoder, &stage_view, target);
        queue.submit(std::iter::once(encoder.finish()));
    }

    /// Draws `content` into `target`, stopping at each **cut** to read what has been
    /// drawn so far: filtered for a backdrop, copied as it is for a layer that blends
    /// with it. The cut's draw is then pointed at what was read, and replaces what is
    /// under it rather than painting over it. With no cuts, one pass.
    ///
    /// The top of the frame does this in its staging texture; a group does it in its
    /// own, so a layer blending inside a group meets the group's own drawing.
    #[allow(clippy::too_many_arguments)]
    fn draw_segmented(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        msaa_view: Option<&wgpu::TextureView>,
        target: &wgpu::Texture,
        load: wgpu::LoadOp<wgpu::Color>,
        content: &ContentPlan,
        cuts: &[Cut],
        draws: &[LayerComposite],
    ) {
        let (w, h) = (target.width(), target.height());
        let view = target.create_view(&wgpu::TextureViewDescriptor::default());
        // Backdrops sharing a key are filtered **once**: the copy is taken before the
        // first of them and every other one reads the same texture. That is what
        // turns a list of frosted rows from one full-surface blur per row into one.
        let mut shared: HashMap<u64, wgpu::Texture> = HashMap::new();
        // The frame is cut at the **batch** that draws the cut's layer, because that is
        // where "what is already painted" ends now that layers are ordered among the
        // content rather than after it.
        let batches = content.batches;
        let cut_at = |scene: usize| {
            batches
                .iter()
                .position(|b| b.kind == batch::Kind::Layer && b.members.first() == Some(&scene))
                .unwrap_or(batches.len())
        };
        let mut cursor = 0usize;
        let mut first = true;
        // Every segment after the first **starts** with a cut — that is what ends the
        // segment before it — so a segment has at most one draw that replaces, and this
        // is it.
        let mut replace_at: Option<usize> = None;
        for cut in cuts {
            {
                let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
                    label: Some("frus.encoder.segment"),
                });
                self.pass(
                    &mut encoder,
                    msaa_view,
                    &view,
                    if first { load } else { wgpu::LoadOp::Load },
                    content,
                    cursor..cut_at(cut.scene),
                    replace_at,
                );
                // Submitted here and not at the end: what follows reads the target, and
                // a command buffer still being recorded has not written it yet.
                queue.submit(std::iter::once(encoder.finish()));
            }
            first = false;
            match cut.kind {
                CutKind::Backdrop {
                    filter,
                    replace,
                    key,
                } => {
                    let reuse = key
                        .and_then(|k| shared.get(&k))
                        .map(|t| t.create_view(&wgpu::TextureViewDescriptor::default()));
                    let filtered = match reuse {
                        Some(view) => view,
                        None => {
                            let filtered = self
                                .filter
                                .apply(device, queue, format, target, filter, w, h);
                            let view =
                                filtered.create_view(&wgpu::TextureViewDescriptor::default());
                            if let Some(k) = key {
                                shared.insert(k, filtered);
                            }
                            view
                        }
                    };
                    self.composite.rebind(device, cut.at, &filtered);
                    replace_at = replace.then_some(cut.at);
                }
                CutKind::Blend => {
                    let under = copy_of(device, queue, format, target, w, h)
                        .create_view(&wgpu::TextureViewDescriptor::default());
                    self.composite
                        .rebind_under(device, cut.at, &draws[cut.at], &under);
                    replace_at = Some(cut.at);
                }
            }
            cursor = cut_at(cut.scene);
        }

        let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor {
            label: Some("frus.encoder.tail"),
        });
        self.pass(
            &mut encoder,
            msaa_view,
            &view,
            if first { load } else { wgpu::LoadOp::Load },
            content,
            cursor..batches.len(),
            replace_at,
        );
        queue.submit(std::iter::once(encoder.finish()));
    }

    /// Turns one [`Primitive::Layer`] into the composite draw that puts it on the
    /// screen: its clip shape as an SDF kind plus radii, or a rendered coverage mask
    /// for a free path, and the **inverse** of its transform, since the fragment
    /// samples at the counter-transformed position.
    ///
    /// Shared by the top-level frame and by a group compositing the layers nested
    /// inside it: the two ask exactly the same question.
    #[allow(clippy::too_many_arguments)]
    fn layer_entry(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        view: wgpu::TextureView,
        opacity: f32,
        clip: Rect,
        clip_shape: &frus_core::ClipShape,
        transform: &Option<frus_core::LayerTransform>,
        filter: &LayerFilter,
        w: u32,
        h: u32,
    ) -> LayerComposite {
        let inverse = match transform {
            Some(t) => t.affine.inverse().m,
            None => frus_core::Affine::IDENTITY.m,
        };
        let (shape, radii) = match clip_shape {
            frus_core::ClipShape::Rect => ([0.0, 0.0, 0.0, 0.0], [0.0; 4]),
            frus_core::ClipShape::RRect(br) => ([1.0, 0.0, 0.0, 0.0], br.to_array()),
            frus_core::ClipShape::Oval => ([2.0, 0.0, 0.0, 0.0], [0.0; 4]),
            frus_core::ClipShape::Path(_) => ([3.0, 0.0, 0.0, 0.0], [0.0; 4]),
        };
        let mask = match clip_shape {
            frus_core::ClipShape::Path(path) => self.render_mask(device, queue, format, path, w, h),
            _ => self.composite.white_mask_view(),
        };
        LayerComposite {
            view,
            mask,
            opacity,
            clip: clip.to_array(),
            shape,
            radii,
            inverse,
            // The image filter has already been spent, in the pre-pass; the backdrop
            // is a draw of its own. A layer over a backdrop is painted over it: the
            // frame is cut once at a layer, for its backdrop.
            filter: LayerFilter {
                image: None,
                backdrop: None,
                blend: filter.blend.filter(|_| filter.backdrop.is_none()),
                ..*filter
            },
            region: None,
        }
    }

    /// One render pass: the content batches (when `content` is given — only the first
    /// pass of a frame draws them) followed by a range of composite draws.
    ///
    /// `replace_at` names a draw that **replaces** rather than paints over, which only
    /// a backdrop asks for.
    // A pass is its attachment, its load, and what to put in it; the arguments are the
    // pass.
    #[allow(clippy::too_many_arguments)]
    /// One render pass over a **range of batches**, in order.
    ///
    /// The order is the whole point. A layer is composited from a texture of its own,
    /// and for a long time every layer was composited after all of the content — so a
    /// group that something had covered came back on top of it. A device found it as the
    /// home screen's translucent square painted over the Kanban board (milestone 349).
    /// The batches now hold the layers too, in the order they must be drawn, and this
    /// walks them: content pipelines and composite draws interleaved.
    fn pass(
        &self,
        encoder: &mut wgpu::CommandEncoder,
        msaa_view: Option<&wgpu::TextureView>,
        target: &wgpu::TextureView,
        load: wgpu::LoadOp<wgpu::Color>,
        content: &ContentPlan,
        batches: std::ops::Range<usize>,
        replace_at: Option<usize>,
    ) {
        // An empty range still has to run when the pass is the one that clears: a frame
        // with nothing in it is a frame of the clear colour, not a frame of whatever was
        // in the buffer before.
        if batches.is_empty() && !matches!(load, wgpu::LoadOp::Clear(_)) {
            return;
        }
        let (view, resolve_target) = match msaa_view {
            Some(msaa) => (msaa, Some(target)),
            None => (target, None),
        };
        let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
            label: Some("frus.render_pass"),
            color_attachments: &[Some(wgpu::RenderPassColorAttachment {
                view,
                depth_slice: None,
                resolve_target,
                ops: wgpu::Operations {
                    load,
                    store: wgpu::StoreOp::Store,
                },
            })],
            depth_stencil_attachment: None,
            timestamp_writes: None,
            occlusion_query_set: None,
            multiview_mask: None,
        });
        for i in batches {
            let batch = &content.batches[i];
            match batch.kind {
                batch::Kind::Rect => self.rect.draw(&mut pass, content.rect_ranges[i].clone()),
                batch::Kind::Image => self.image.draw(&mut pass, content.image_ranges[i].clone()),
                batch::Kind::Path => self.path.draw(&mut pass, content.path_ranges[i].clone()),
                batch::Kind::Text => {
                    // The underlines first — they are rectangles, and they belong
                    // beneath the glyphs they decorate rather than in a batch of
                    // their own.
                    let base = content.decoration_base;
                    let d = &content.decoration_ranges[i];
                    self.rect.draw(&mut pass, base + d.start..base + d.end);
                    self.text.draw(&mut pass, content.text_slots[i]);
                }
                batch::Kind::Layer => {
                    // One member, always: the scene index of the group. Its draws are
                    // the layer itself, preceded by its backdrop when it takes one.
                    if let Some(range) = batch
                        .members
                        .first()
                        .and_then(|scene| content.layer_draws.get(scene))
                    {
                        self.composite
                            .draw_range(&mut pass, range.clone(), replace_at);
                    }
                }
            }
        }
    }

    /// The staging texture a frame with backdrops is built in, created on demand and
    /// recreated on resize. It exists because a backdrop has to *read* the frame so
    /// far, and a surface texture cannot be read.
    fn stage(
        &mut self,
        device: &wgpu::Device,
        format: wgpu::TextureFormat,
        w: u32,
        h: u32,
    ) -> &wgpu::Texture {
        let stale = match &self.stage {
            Some(s) => s.width != w || s.height != h || s.format != format,
            None => true,
        };
        if stale {
            self.stage = Some(MsaaScratch {
                width: w,
                height: h,
                format,
                texture: device.create_texture(&wgpu::TextureDescriptor {
                    label: Some("frus.stage"),
                    size: wgpu::Extent3d {
                        width: w.max(1),
                        height: h.max(1),
                        depth_or_array_layers: 1,
                    },
                    mip_level_count: 1,
                    sample_count: 1,
                    dimension: wgpu::TextureDimension::D2,
                    format,
                    // Copied from, for a layer that blends with it.
                    usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                        | wgpu::TextureUsages::TEXTURE_BINDING
                        | wgpu::TextureUsages::COPY_SRC,
                    view_formats: &[],
                }),
            });
        }
        &self.stage.as_ref().expect("just created").texture
    }

    /// Returns the view of a layer's texture: **reused** as is when its content and
    /// dimensions are unchanged since the previous frame, otherwise (re)rendered by
    /// [`Painters::render_group`] and, if the layer asks for one, put through the
    /// image-filter pre-pass. `index` is the layer's rank in the scene, a stable
    /// cache key; a key that slips — because layers were reordered — only misses the
    /// cache, which re-renders correctly and never wrongly.
    // Same as `render`, one layer at a time.
    #[allow(clippy::too_many_arguments)]
    fn layer_texture(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        index: usize,
        primitives: &[Primitive],
        image: Option<ImageFilter>,
        w: u32,
        h: u32,
    ) -> wgpu::TextureView {
        let hit = matches!(
            self.layer_cache.get(index),
            Some(c) if c.width == w && c.height == h && c.image == image
                && c.primitives.as_slice() == primitives
        );
        if !hit {
            let mut texture = self.render_group(device, queue, format, primitives, w, h);
            if let Some(f) = image {
                texture = self.filter.apply(device, queue, format, &texture, f, w, h);
            }
            let entry = CachedLayer {
                primitives: primitives.to_vec(),
                width: w,
                height: h,
                texture,
                image,
            };
            if index < self.layer_cache.len() {
                self.layer_cache[index] = entry;
            } else {
                self.layer_cache.push(entry);
            }
        }
        self.layer_cache[index]
            .texture
            .create_view(&wgpu::TextureViewDescriptor::default())
    }

    /// Renders a **clip mask**: `path`, in absolute screen coordinates, filled with
    /// opaque white on a transparent background, at the surface's size. The returned
    /// view keeps the texture alive, since wgpu counts references.
    fn render_mask(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        path: &frus_core::Path,
        w: u32,
        h: u32,
    ) -> wgpu::TextureView {
        let prim = Primitive::Path {
            path: path.clone(),
            fill: Some(frus_core::Color::WHITE),
            // A coverage mask is flat by definition.
            gradient: None,
            stroke: None,
            clip: frus_core::Rect::UNBOUNDED,
            owner: 0,
        };
        let tex = self.render_group(device, queue, format, &[prim], w, h);
        tex.create_view(&wgpu::TextureViewDescriptor::default())
    }

    /// Renders a group of primitives into a full-surface texture with a transparent
    /// background, for later compositing.
    fn render_group(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
        primitives: &[Primitive],
        w: u32,
        h: u32,
    ) -> wgpu::Texture {
        self.layer_renders += 1;

        // **Nested** layers first, depth-first: each rendered into a texture of its
        // own so that this group's pass can composite it. Without this a layer inside
        // a layer simply vanished — a rounded card around a fading group, a clip
        // around a transform — because a group's pass draws primitives and a layer is
        // not one.
        //
        // The recursion is safe to interleave with the shared instance buffers because
        // every level prepares, records and **submits** before returning: the deepest
        // group is on the queue before its parent writes a single instance.
        let mut nested: Vec<LayerComposite> = Vec::new();
        // Which nested composite belongs to which primitive, so the pass below can put
        // it back in scene order among this group's own drawing rather than after all
        // of it — the same ordering the top-level frame does.
        let mut nested_of: HashMap<usize, usize> = HashMap::new();
        // The nested layers that blend with this group's drawing under them.
        let mut cuts: Vec<Cut> = Vec::new();
        for (scene_index, primitive) in primitives.iter().enumerate() {
            if let Primitive::Layer {
                primitives: inner,
                opacity,
                clip,
                clip_shape,
                transform,
                filter,
                ..
            } = primitive
            {
                let region = layer_region(*clip, clip_shape, transform, filter, inner, w, h);
                let (rw, rh) = region.map_or((w, h), |r| (r.width as u32, r.height as u32));
                let local = into_region(inner, region);
                let mut texture = self.render_group(device, queue, format, &local, rw, rh);
                if let Some(f) = filter.image.filter(|f| !f.is_identity()) {
                    texture = self
                        .filter
                        .apply(device, queue, format, &texture, f, rw, rh);
                }
                // The view holds a reference to its texture, so the texture outlives
                // this loop without being named again.
                let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
                let mut entry = self.layer_entry(
                    device, queue, format, view, *opacity, *clip, clip_shape, transform, filter, w,
                    h,
                );
                entry.region = region.map(|r| r.to_array());
                nested_of.insert(scene_index, nested.len());
                if filter.blend.is_some() && filter.backdrop.is_none() {
                    cuts.push(Cut {
                        at: nested.len(),
                        scene: scene_index,
                        kind: CutKind::Blend,
                    });
                }
                nested.push(entry);
            }
        }

        let mut sub = Scene::new();
        for primitive in primitives {
            sub.push_primitive(primitive.clone());
        }

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("frus.layer.texture"),
            size: wgpu::Extent3d {
                width: w,
                height: h,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            // Copied from, for a nested layer that blends with it.
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT
                | wgpu::TextureUsages::TEXTURE_BINDING
                | wgpu::TextureUsages::COPY_SRC,
            view_formats: &[],
        });

        // Its own size for the painters: a nested layer set them to its own.
        self.set_viewport(queue, w as f32, h as f32);
        let batches = batch::plan(&sub);
        let (decorations, decoration_ranges) =
            self.text.prepare_frame(device, queue, &sub, w, h, &batches);
        let (rect_ranges, decoration_base) =
            self.rect
                .prepare_frame(device, queue, &sub, &decorations, &batches);
        let image_ranges = self.image.prepare_frame(device, queue, &sub, &batches);
        let path_ranges = self.path.prepare_frame(device, queue, &sub, &batches);
        if !nested.is_empty() {
            self.composite
                .prepare(device, queue, &nested, w as f32, h as f32);
        }

        // With MSAA the layer is painted multisampled then resolved to its
        // single-sample texture, the one the compositor samples afterwards.
        let msaa_view = self.ensure_msaa(device, format, w, h);

        // The same plan the top of the frame draws from: a nested layer in its place
        // among this group's own drawing.
        let mut text_slots = Vec::with_capacity(batches.len());
        let mut slots = 0usize;
        for batch in &batches {
            text_slots.push(slots);
            if batch.kind == batch::Kind::Text {
                slots += 1;
            }
        }
        let layer_draws: HashMap<usize, std::ops::Range<usize>> =
            nested_of.iter().map(|(&s, &n)| (s, n..n + 1)).collect();
        let content = ContentPlan {
            batches: &batches,
            rect_ranges: &rect_ranges,
            image_ranges: &image_ranges,
            path_ranges: &path_ranges,
            decoration_ranges: &decoration_ranges,
            decoration_base: decoration_base.start,
            layer_draws: &layer_draws,
            text_slots: &text_slots,
        };
        // Transparent background: a layer covers only its primitives.
        self.draw_segmented(
            device,
            queue,
            format,
            msaa_view.as_ref(),
            &texture,
            wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT),
            &content,
            &cuts,
            &nested,
        );
        texture
    }

    /// **Warms up** every pipeline by rendering a small scene that exercises each
    /// render path — rectangle, image, path, text, layer → composite — so the first
    /// real frame compiles nothing.
    pub(crate) fn warm_up(
        &mut self,
        device: &wgpu::Device,
        queue: &wgpu::Queue,
        format: wgpu::TextureFormat,
    ) {
        let mut scene = Scene::new();
        scene.fill_rect(Rect::new(0.0, 0.0, 2.0, 2.0), Color::WHITE);
        scene.fill_path(&Path::rect(Rect::new(0.0, 0.0, 2.0, 2.0)), Color::WHITE);
        let img = ImageData::from_rgba(1, 1, vec![255, 255, 255, 255]).into_handle();
        scene.image(&img, Rect::new(0.0, 0.0, 2.0, 2.0), BoxFit::Fill);
        scene.text(
            Point::new(0.0, 0.0),
            "x",
            &frus_core::ResolvedTextStyle::exact(8.0),
            Color::WHITE,
        );
        scene.layer(0.5, |inner| {
            inner.fill_rect(Rect::new(0.0, 0.0, 2.0, 2.0), Color::WHITE)
        });

        let texture = device.create_texture(&wgpu::TextureDescriptor {
            label: Some("frus.warmup.texture"),
            size: wgpu::Extent3d {
                width: 4,
                height: 4,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
            view_formats: &[],
        });
        let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
        self.render(
            device,
            queue,
            format,
            &view,
            4,
            4,
            &scene,
            Some(wgpu::Color::BLACK),
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn headless() -> Option<(wgpu::Device, wgpu::Queue)> {
        let instance = wgpu::Instance::new(wgpu::InstanceDescriptor {
            backends: wgpu::Backends::all(),
            ..wgpu::InstanceDescriptor::new_without_display_handle()
        });
        let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
            power_preference: wgpu::PowerPreference::default(),
            compatible_surface: None,
            force_fallback_adapter: false,
            ..Default::default()
        }))
        .ok()?;
        pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
            label: Some("frus.compositor.test.device"),
            required_features: wgpu::Features::empty(),
            required_limits: wgpu::Limits::downlevel_defaults(),
            memory_hints: wgpu::MemoryHints::default(),
            ..Default::default()
        }))
        .ok()
    }

    fn target(device: &wgpu::Device, format: wgpu::TextureFormat, n: u32) -> wgpu::Texture {
        device.create_texture(&wgpu::TextureDescriptor {
            label: Some("frus.compositor.test.target"),
            size: wgpu::Extent3d {
                width: n,
                height: n,
                depth_or_array_layers: 1,
            },
            mip_level_count: 1,
            sample_count: 1,
            dimension: wgpu::TextureDimension::D2,
            format,
            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
            view_formats: &[],
        })
    }

    /// A **static** layer is rendered once: the second frame reuses its texture, with
    /// no new pre-pass. Changing its content forces a re-render; removing it purges
    /// the cache.
    #[test]
    fn static_layer_texture_is_reused_across_frames() {
        let Some((device, queue)) = headless() else {
            eprintln!("no GPU adapter available: test skipped");
            return;
        };
        let format = wgpu::TextureFormat::Rgba8UnormSrgb;
        // sample_count 1: the cache does not depend on MSAA.
        let mut painters = Painters::new(&device, &queue, format, 1, None);
        let tex = target(&device, format, 16);
        let view = tex.create_view(&wgpu::TextureViewDescriptor::default());
        let clear = Some(wgpu::Color::BLACK);

        let red =
            |s: &mut Scene| s.fill_rect(Rect::new(0.0, 0.0, 8.0, 8.0), Color::rgb(1.0, 0.0, 0.0));
        let mut scene = Scene::new();
        scene.layer(0.5, red);

        painters.render(&device, &queue, format, &view, 16, 16, &scene, clear);
        assert_eq!(
            painters.layer_render_count(),
            1,
            "first frame: layer rendered"
        );
        painters.render(&device, &queue, format, &view, 16, 16, &scene, clear);
        assert_eq!(
            painters.layer_render_count(),
            1,
            "layer unchanged: texture reused"
        );

        // Content changed → re-render.
        let mut scene2 = Scene::new();
        scene2.layer(0.5, |s| {
            s.fill_rect(Rect::new(0.0, 0.0, 8.0, 8.0), Color::rgb(0.0, 1.0, 0.0))
        });
        painters.render(&device, &queue, format, &view, 16, 16, &scene2, clear);
        assert_eq!(
            painters.layer_render_count(),
            2,
            "content changed: re-render"
        );

        // Layer gone → the cache is purged, with no pre-pass.
        painters.render(&device, &queue, format, &view, 16, 16, &Scene::new(), clear);
        assert_eq!(
            painters.layer_render_count(),
            2,
            "no layer left: nothing to render"
        );
        assert!(painters.layer_cache.is_empty(), "cache purged");
    }

    fn layer(
        clip: Rect,
        primitives: Vec<Primitive>,
    ) -> (
        Rect,
        frus_core::ClipShape,
        Option<frus_core::LayerTransform>,
        LayerFilter,
        Vec<Primitive>,
    ) {
        (
            clip,
            frus_core::ClipShape::Rect,
            None,
            LayerFilter::NONE,
            primitives,
        )
    }

    fn square() -> Primitive {
        let mut scene = Scene::new();
        scene.fill_rect(Rect::new(10.0, 10.0, 20.0, 20.0), frus_core::Color::WHITE);
        scene.primitives()[0].clone()
    }

    /// **A layer's region is its clip in whole pixels, held to the target** (milestone
    /// 610): a texture of that size, not the target's.
    #[test]
    fn a_layer_is_drawn_in_its_clip_and_no_more() {
        let (clip, shape, transform, filter, prims) =
            layer(Rect::new(10.5, 20.2, 56.0, 32.0), vec![square()]);
        let region = layer_region(clip, &shape, &transform, &filter, &prims, 1080, 2340);
        assert_eq!(region, Some(Rect::new(10.0, 20.0, 57.0, 33.0)));
        // Partly off the target: what is on it.
        let region = layer_region(
            Rect::new(-30.0, 2300.0, 100.0, 100.0),
            &shape,
            &transform,
            &filter,
            &prims,
            1080,
            2340,
        );
        assert_eq!(region, Some(Rect::new(0.0, 2300.0, 70.0, 40.0)));
        // Wholly off it: a pixel, which draws nothing.
        let region = layer_region(
            Rect::new(2000.0, 10.0, 50.0, 50.0),
            &shape,
            &transform,
            &filter,
            &prims,
            1080,
            2340,
        );
        assert_eq!(region.map(|r| (r.width, r.height)), Some((1.0, 1.0)));
        // Covering it all, or unbounded: the target, as before.
        assert_eq!(
            layer_region(
                Rect::UNBOUNDED,
                &shape,
                &transform,
                &filter,
                &prims,
                1080,
                2340
            ),
            None
        );
    }

    /// **What may draw past its clip, or holds the target's own coordinates, keeps the
    /// target**: a transform, an image filter, a backdrop, a path clip, or such a layer
    /// anywhere inside.
    #[test]
    fn what_may_draw_anywhere_keeps_the_whole_target() {
        let clip = Rect::new(10.0, 10.0, 100.0, 100.0);
        let none = LayerFilter::NONE;
        let moved = Some(frus_core::LayerTransform::new(
            frus_core::Affine::translation(5.0, 0.0),
        ));
        assert_eq!(
            layer_region(
                clip,
                &frus_core::ClipShape::Rect,
                &moved,
                &none,
                &[square()],
                1080,
                2340
            ),
            None
        );
        let blurred = LayerFilter {
            image: Some(ImageFilter::Blur {
                sigma_x: 4.0,
                sigma_y: 4.0,
            }),
            ..LayerFilter::NONE
        };
        assert_eq!(
            layer_region(
                clip,
                &frus_core::ClipShape::Rect,
                &None,
                &blurred,
                &[square()],
                1080,
                2340
            ),
            None
        );
        let path = frus_core::ClipShape::Path(frus_core::Path::oval(clip));
        assert_eq!(
            layer_region(clip, &path, &None, &none, &[square()], 1080, 2340),
            None
        );
        // Inside: a path-clipped layer in a plain one.
        let mut scene = Scene::new();
        scene.push_primitive(Primitive::Layer {
            primitives: vec![square()],
            opacity: 0.5,
            clip,
            clip_shape: frus_core::ClipShape::Path(frus_core::Path::oval(clip)),
            transform: None,
            filter: LayerFilter::NONE,
            owner: 0,
        });
        let inner = scene.primitives().to_vec();
        assert_eq!(
            layer_region(
                clip,
                &frus_core::ClipShape::Rect,
                &None,
                &none,
                &inner,
                1080,
                2340
            ),
            None
        );
        // Two levels down: a plain layer holding the path-clipped one.
        let wrapped = vec![Primitive::Layer {
            primitives: inner.clone(),
            opacity: 1.0,
            clip,
            clip_shape: frus_core::ClipShape::Rect,
            transform: None,
            filter: LayerFilter::NONE,
            owner: 0,
        }];
        assert_eq!(
            layer_region(
                clip,
                &frus_core::ClipShape::Rect,
                &None,
                &none,
                &wrapped,
                1080,
                2340
            ),
            None
        );
        // A plain layer inside a plain one is fine.
        assert!(boundable(&Primitive::Layer {
            primitives: vec![square()],
            opacity: 0.5,
            clip,
            clip_shape: frus_core::ClipShape::RRect(frus_core::BorderRadius::uniform(4.0)),
            transform: None,
            filter: LayerFilter::NONE,
            owner: 0,
        }));
    }
}