frus-core 0.5.0

frus — shared foundation types (geometry, colour)
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
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
//! The [`Scene`]: a pure display list, independent of any rendering backend.
//!
//! It describes *what to draw* — primitives — while knowing nothing about the
//! GPU. `frus-gpu` consumes it to produce GPU commands; `frus-widgets` produces
//! it from a widget tree.
//!
//! Every primitive carries a **clip rectangle**, set through
//! [`Scene::set_clip`] before primitives are added.

use std::sync::Arc;

use crate::{
    Affine, BorderRadius, Color, FontWeight, ImageHandle, LayerFilter, Path, PathVerb, Point, Rect,
    ResolvedTextStyle, ShaderMask, ShapeBorder, Size, Stroke, TextAlign, TextDecoration, TextRun,
    TileMode,
};

/// The transform applied to a **layer** ([`Primitive::Layer`]) at compositing time:
/// an arbitrary [`Affine`] (translation, per-axis scale, rotation, or any
/// composition of them) in screen pixels. The layer is first rendered **flat** into
/// a texture, as with group opacity, then composited **transformed** — so a single
/// pass transforms a whole subtree (rects, text, images) without touching any
/// individual primitive's shaders.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LayerTransform {
    /// The local (flat) → screen transform.
    pub affine: Affine,
}

impl LayerTransform {
    /// Wraps any [`Affine`].
    pub const fn new(affine: Affine) -> Self {
        Self { affine }
    }

    /// A rotation of `angle` radians about `pivot`, in screen pixels.
    pub fn rotation(angle: f32, pivot: Point) -> Self {
        Self {
            affine: Affine::rotation(angle).about(pivot),
        }
    }

    /// Conjugates the transform by a scale, so it follows `Primitive::scaled`:
    /// `S ∘ M ∘ S⁻¹`, which is what makes a DPI change scale the whole layer, its
    /// transform included.
    pub fn scaled(self, factor: f32) -> Self {
        self.scaled_xy(factor, factor)
    }

    /// Like [`LayerTransform::scaled`], but per axis.
    pub fn scaled_xy(self, sx: f32, sy: f32) -> Self {
        let conj = Affine::scale(1.0 / sx, 1.0 / sy)
            .then(self.affine)
            .then(Affine::scale(sx, sy));
        Self { affine: conj }
    }

    /// Conjugates by a translation, so it follows `Primitive::translated`.
    pub fn translated(self, dx: f32, dy: f32) -> Self {
        let conj = Affine::translation(-dx, -dy)
            .then(self.affine)
            .then(Affine::translation(dx, dy));
        Self { affine: conj }
    }
}

/// **A gradient with any number of stops**, for a path: its shape, its colours, what it
/// does past its ends, and where it sits.
///
/// The shape is in the gradient's own space and `transform` takes it to the path's, so a
/// gradient that is turned, skewed or squashed — an SVG `gradientTransform`, a bounding
/// box's units — is drawn exactly: the renderer maps each pixel back into the gradient's
/// space, where the shape is simple.
///
/// ```
/// use frus_core::{Affine, Color, GradientRamp, Point, RampShape, TileMode};
/// let ramp = GradientRamp {
///     shape: RampShape::Linear { from: Point::new(0.0, 0.0), to: Point::new(100.0, 0.0) },
///     stops: vec![(0.0, Color::BLACK), (1.0, Color::WHITE)],
///     tile: TileMode::Clamp,
///     transform: Affine::default(),
/// };
/// assert_eq!(ramp.t_at(Point::new(25.0, 40.0)), Some(0.25));
/// ```
#[derive(Clone, Debug, PartialEq)]
pub struct GradientRamp {
    /// Where the colours run, in the gradient's own space.
    pub shape: RampShape,
    /// `(offset, colour)` pairs, offsets from `0` to `1` in order. A colour holds before
    /// the first stop and after the last.
    pub stops: Vec<(f32, Color)>,
    /// What happens past the ends of the shape.
    pub tile: TileMode,
    /// The gradient's space to the path's.
    pub transform: Affine,
}

/// Where a [`GradientRamp`]'s colours run.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum RampShape {
    /// The first stop at `from`, the last at `to`, constant across the line.
    Linear {
        /// Where offset `0` is.
        from: Point,
        /// Where offset `1` is.
        to: Point,
    },
    /// Offset `0` on the circle about `focal` of radius `focal_radius`, offset `1` on the
    /// circle about `center` of radius `radius`, and the circles between them for the
    /// offsets between. With the focal point at the centre and no focal radius, it is the
    /// plain outward fade.
    Radial {
        /// The centre of the outer circle.
        center: Point,
        /// The radius of the outer circle.
        radius: f32,
        /// The centre of the inner circle.
        focal: Point,
        /// The radius of the inner circle.
        focal_radius: f32,
    },
}

impl GradientRamp {
    /// How far through the gradient the point `p` (in the path's space) is, tiled; `None`
    /// where nothing is drawn — past the ends of a [`TileMode::Decal`] one, or outside
    /// both circles' reach. What the renderer computes for every pixel.
    pub fn t_at(&self, p: Point) -> Option<f32> {
        let p = self.transform.inverse().apply(p);
        let t = match self.shape {
            RampShape::Linear { from, to } => {
                let (dx, dy) = (to.x - from.x, to.y - from.y);
                ((p.x - from.x) * dx + (p.y - from.y) * dy) / (dx * dx + dy * dy).max(1e-6)
            }
            RampShape::Radial {
                center,
                radius,
                focal,
                focal_radius,
            } => {
                // The largest t whose circle — centre and radius moving from the focal
                // circle's to the outer one's — passes through p.
                let (cdx, cdy) = (center.x - focal.x, center.y - focal.y);
                let dr = radius - focal_radius;
                let (pdx, pdy) = (p.x - focal.x, p.y - focal.y);
                let a = cdx * cdx + cdy * cdy - dr * dr;
                let b = pdx * cdx + pdy * cdy + focal_radius * dr;
                let c = pdx * pdx + pdy * pdy - focal_radius * focal_radius;
                if a.abs() < 1e-4 {
                    c / (2.0 * b).max(1e-6)
                } else {
                    let disc = b * b - a * c;
                    if disc < 0.0 {
                        return None;
                    }
                    let root = disc.sqrt();
                    let t = (b + root) / a;
                    if focal_radius + t * dr < 0.0 {
                        (b - root) / a
                    } else {
                        t
                    }
                }
            }
        };
        crate::tile(t, self.tile)
    }

    /// The colour at offset `t`, between the stops either side of it.
    pub fn sample(&self, t: f32) -> Color {
        match self.stops.as_slice() {
            [] => Color::TRANSPARENT,
            [(_, only)] => *only,
            stops => {
                if t <= stops[0].0 {
                    return stops[0].1;
                }
                for pair in stops.windows(2) {
                    let ((a, from), (b, to)) = (pair[0], pair[1]);
                    if t <= b {
                        let k = if b > a { (t - a) / (b - a) } else { 1.0 };
                        return from.lerp(to, k);
                    }
                }
                stops[stops.len() - 1].1
            }
        }
    }

    /// The colour at the point `p`, in the path's space: transparent where nothing is
    /// drawn.
    pub fn color_at(&self, p: Point) -> Color {
        self.t_at(p).map_or(Color::TRANSPARENT, |t| self.sample(t))
    }

    /// The same gradient after its path is moved by `then`.
    fn followed_by(&self, then: Affine) -> GradientRamp {
        GradientRamp {
            transform: self.transform.then(then),
            ..self.clone()
        }
    }
}

/// How a path's fill **fades**: along a line, or outwards from a centre.
///
/// The geometry is in the same space as the path, deliberately, so a fade can be
/// aimed at something real — the edge a glow springs from, the ellipse whose cap is
/// the glow — rather than at whatever bounding box the geometry happens to have.
#[derive(Clone, Debug, PartialEq)]
pub enum PathGradient {
    /// The fill colour at `from`, `to_color` at `to`, clamped outside that span.
    Linear {
        /// The colour at `to`. The colour at `from` is the primitive's `fill`.
        to_color: Color,
        /// Where the fill colour holds.
        from: Point,
        /// Where `to_color` holds.
        to: Point,
    },
    /// The fill colour on the ellipse of radii `inner × radii` about `center`,
    /// `to_color` on the ellipse of radii `radii`, clamped outside.
    ///
    /// A curved edge needs this. A linear fade can only reach zero along a *line*,
    /// so a shape whose boundary curves away from that line stops while the fade is
    /// unfinished, and the leftover shows as an edge — which is the very thing a
    /// glow must not have (milestone 302).
    Radial {
        /// The colour on the outer ellipse.
        to_color: Color,
        /// The centre of both ellipses.
        center: Point,
        /// The outer ellipse's radii, where `to_color` holds.
        radii: Size,
        /// Where the fade starts, as a fraction of `radii`. `0` fades from the
        /// centre outwards; a value near `1` confines it to a thin rind.
        inner: f32,
    },
    /// **Any number of colour stops**, along a line or between two circles, in a space of
    /// its own — what vector artwork's gradients are. The primitive's fill colour
    /// multiplies it: white leaves it as it is, and a faded white fades it.
    Ramp(Arc<GradientRamp>),
}

impl PathGradient {
    /// Scales the geometry per axis, as a DPI or paint scale does.
    pub fn scaled_xy(self, sx: f32, sy: f32) -> Self {
        match self {
            Self::Linear { to_color, from, to } => Self::Linear {
                to_color,
                from: Point::new(from.x * sx, from.y * sy),
                to: Point::new(to.x * sx, to.y * sy),
            },
            Self::Radial {
                to_color,
                center,
                radii,
                inner,
            } => Self::Radial {
                to_color,
                center: Point::new(center.x * sx, center.y * sy),
                radii: Size::new(radii.width * sx, radii.height * sy),
                inner,
            },
            Self::Ramp(ramp) => Self::Ramp(Arc::new(ramp.followed_by(Affine::scale(sx, sy)))),
        }
    }

    /// Moves the geometry with the shape it describes.
    pub fn translated(self, dx: f32, dy: f32) -> Self {
        match self {
            Self::Linear { to_color, from, to } => Self::Linear {
                to_color,
                from: Point::new(from.x + dx, from.y + dy),
                to: Point::new(to.x + dx, to.y + dy),
            },
            Self::Radial {
                to_color,
                center,
                radii,
                inner,
            } => Self::Radial {
                to_color,
                center: Point::new(center.x + dx, center.y + dy),
                radii,
                inner,
            },
            Self::Ramp(ramp) => Self::Ramp(Arc::new(ramp.followed_by(Affine::translation(dx, dy)))),
        }
    }

    /// The colour the fade ends on.
    pub fn to_color(self) -> Color {
        match self {
            Self::Linear { to_color, .. } | Self::Radial { to_color, .. } => to_color,
            Self::Ramp(ramp) => ramp.stops.last().map_or(Color::TRANSPARENT, |(_, c)| *c),
        }
    }

    /// Fades the end colour with the fill it belongs to.
    pub fn faded(self, opacity: f32) -> Self {
        match self {
            Self::Linear { to_color, from, to } => Self::Linear {
                to_color: to_color.fade(opacity),
                from,
                to,
            },
            Self::Radial {
                to_color,
                center,
                radii,
                inner,
            } => Self::Radial {
                to_color: to_color.fade(opacity),
                center,
                radii,
                inner,
            },
            // The fill colour multiplies a ramp, and the fill is faded with it.
            Self::Ramp(ramp) => Self::Ramp(ramp),
        }
    }
}

/// **Which side of a shape a blur keeps** (milestone 645), the reference's `BlurStyle`.
///
/// A blurred shape fades across its edge, half in and half out. The other three styles
/// keep one side of that fade and fill or empty the other: a solid shape with a glow, a
/// glow with a hole where the shape was, a shape whose edge darkens inward.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum BlurStyle {
    /// Fuzzy inside and outside: the shape blurred, what a shadow is.
    #[default]
    Normal,
    /// Solid inside, fuzzy outside.
    Solid,
    /// Nothing inside, fuzzy outside.
    Outer,
    /// Fuzzy inside, nothing outside.
    Inner,
}

impl BlurStyle {
    /// The number the renderer reads.
    pub const fn code(self) -> u32 {
        match self {
            BlurStyle::Normal => 0,
            BlurStyle::Solid => 1,
            BlurStyle::Outer => 2,
            BlurStyle::Inner => 3,
        }
    }
}

/// The clip shape of a [`Primitive::Layer`], **inscribed** in its `clip` rectangle.
/// Compositing multiplies the layer's alpha by the shape's coverage, with
/// antialiased edges. This is the building block of the `ClipRRect`, `ClipOval`
/// and `ClipPath` widgets.
#[derive(Clone, Debug, Default, PartialEq)]
pub enum ClipShape {
    /// A crisp rectangular clip — the layer's `clip`, unchanged.
    #[default]
    Rect,
    /// A **rounded-corner** rectangle, with a **per-corner** radius
    /// ([`BorderRadius`], logical px) clamped to half the `clip`'s smaller side. A
    /// uniform radius is still `BorderRadius::uniform(r)`.
    RRect(BorderRadius),
    /// An **ellipse** inscribed in the `clip` — a circle when the `clip` is square.
    Oval,
    /// An **arbitrary path**, in absolute screen coordinates: compositing renders it
    /// into a coverage **mask** which it multiplies into the layer's alpha. The
    /// building block of `ClipPath` — stars, notches, free-form shapes.
    Path(Path),
}

impl ClipShape {
    /// Follows a **per-axis** scaling of the layer (DPI, paint scale): only a
    /// rounded radius changes, by the average of the two factors, since it has no
    /// axis. The ellipse follows its `clip`, and the rectangle has nothing to scale.
    pub fn scaled_xy(self, sx: f32, sy: f32) -> ClipShape {
        match self {
            ClipShape::RRect(br) => ClipShape::RRect(br.scale((sx + sy) * 0.5)),
            // The path is in absolute coordinates, so DPI scaling follows it
            // (uniformly — at DPI, `sx == sy`).
            ClipShape::Path(p) => ClipShape::Path(p.scaled((sx + sy) * 0.5)),
            other => other,
        }
    }
}

/// A drawing primitive.
#[derive(Clone, Debug, PartialEq)]
pub enum Primitive {
    /// A rectangle: rounded corners, border, gradient and/or soft shadow.
    Rect {
        /// The rectangle's bounds.
        rect: Rect,
        /// Fill colour — the start colour when there is a gradient.
        color: Color,
        /// The gradient's end colour (`== color` when flat).
        color2: Color,
        /// Gradient direction in `[0,1]²` space; `(0,0)` means flat.
        gradient_dir: [f32; 2],
        /// Corner radii, per corner.
        radius: BorderRadius,
        /// Border width, in logical pixels; `0` draws no border.
        border_width: f32,
        /// Border colour.
        border_color: Color,
        /// Edge softening, in pixels (0 = crisp; > 0 = a blurred shadow).
        blur: f32,
        /// Clip rectangle: nothing is drawn outside it.
        clip: Rect,
        /// The emitting widget's identity, used for exit animation.
        owner: u64,
        /// **A gradient filling the shape** (milestone 644), as the reference describes it:
        /// relative to `rect`, so it scales with it. When set it replaces `color`,
        /// `color2` and `gradient_dir`, which hold its first and last colours for
        /// whatever reads a rectangle's colour.
        shader: Option<std::sync::Arc<crate::Gradient>>,
        /// Where a blurred edge keeps its strength: either side of the shape, inside
        /// only, outside only (milestone 645). Read only when `blur` is above nought.
        blur_style: BlurStyle,
    },
    /// A line of text, anchored by its top-left corner.
    Text {
        /// The top-left corner the text is anchored at.
        position: Point,
        /// The text itself.
        text: String,
        /// The font size, in logical pixels.
        size: f32,
        /// The text's colour.
        color: Color,
        /// Font weight.
        weight: FontWeight,
        /// Italic.
        italic: bool,
        /// The width of the box the text was given (`None` = unbounded, in which case
        /// explicit `\n` characters make the lines). It is what `soft_wrap` wraps at
        /// and what `align` aligns inside.
        max_width: Option<f32>,
        /// Whether `max_width` **wraps** the text or only bounds the alignment. A line
        /// that is told where its box ends but not to wrap runs past it, which is what
        /// an ellipsised or clipped single line does.
        soft_wrap: bool,
        /// How the lines sit inside `max_width`. Ignored when there is no width to sit
        /// inside — and deliberately so: handing the renderer a width it did not have
        /// changes where right-to-left text lands.
        align: TextAlign,
        /// Decoration lines (underline, strikethrough, and so on).
        decoration: TextDecoration,
        /// Decoration colour; `None` means the text's own colour.
        decoration_color: Option<Color>,
        /// The line's height as a **multiple of `size`**; `None` means
        /// [`crate::DEFAULT_LINE_HEIGHT`]. Carried on the primitive because the renderer
        /// has to lay the lines out at the height the measurement used, and it cannot
        /// derive that from the size alone.
        height: Option<f32>,
        /// The font family; `None` means the application's default. Carried for the same
        /// reason as `height`: the renderer must shape with the face the measurement used,
        /// and it cannot know which that was from the words alone.
        family: Option<crate::FontFamily>,
        /// The room added after every character, in logical pixels — carried for the same
        /// reason again: the renderer must space the glyphs as the measurement did
        /// (milestone 623).
        letter_spacing: f32,
        /// Clip rectangle.
        clip: Rect,
        /// The box the text was laid out in — the emitting widget's, so an
        /// over-estimate of what the glyphs actually cover, never an under-estimate.
        /// The renderer needs it to know what the text covers; without it text can
        /// only be painted above everything else in the frame. `Rect::UNBOUNDED` when
        /// a scene is built by hand rather than by the widget walk, which the renderer
        /// reads as "unknown, keep it on top".
        bounds: Rect,
        /// The emitting widget's identity.
        owner: u64,
    },
    /// **Rich** text: a sequence of resolved runs, mixing styles and colours, laid
    /// out as one piece, on a single shared baseline.
    RichText {
        /// The top-left corner the text is anchored at.
        position: Point,
        /// The resolved runs, in reading order, sharing one baseline.
        runs: Vec<TextRun>,
        /// The width of the box the runs were given. See [`Primitive::Text`].
        max_width: Option<f32>,
        /// Whether `max_width` wraps the runs or only bounds the alignment.
        soft_wrap: bool,
        /// How the lines sit inside `max_width`.
        align: TextAlign,
        /// Clip rectangle.
        clip: Rect,
        /// The box the text was laid out in. See [`Primitive::Text`].
        bounds: Rect,
        /// The emitting widget's identity.
        owner: u64,
    },
    /// A **vector path**: arbitrary 2D geometry, filled (`fill`) and/or stroked
    /// (`stroke`). The building block of icons and custom drawing.
    Path {
        /// The geometry to fill and/or stroke.
        path: Path,
        /// Interior fill colour (`None` = no fill), and the gradient's start colour
        /// when there is one.
        fill: Option<Color>,
        /// A gradient across the fill, straight or radial; `None` leaves it flat.
        gradient: Option<PathGradient>,
        /// Outline (colour plus width); `None` = no outline.
        stroke: Option<Stroke>,
        /// Clip rectangle.
        clip: Rect,
        /// The emitting widget's identity.
        owner: u64,
    },
    /// A bitmap **image**, sampled into a destination rectangle.
    Image {
        /// Shared handle to the pixels (GPU-cached by [`crate::ImageData::id`]).
        image: ImageHandle,
        /// Destination rectangle, already fitted per the [`crate::BoxFit`].
        rect: Rect,
        /// The sampled sub-region of the texture, in `0..1` (the `Cover` crop).
        uv: Rect,
        /// Multiplicative tint (white = unchanged; the alpha drives fading).
        tint: Color,
        /// Whether sampling stays **strictly** inside `uv` (milestone 645): a filtered
        /// sample never reaches the texels around it. The parts of a sliced picture
        /// need it, or each would bleed its neighbours along its edges; a picture drawn
        /// whole or cropped does without, as the reference's does.
        strict: bool,
        /// Clip rectangle.
        clip: Rect,
        /// The emitting widget's identity.
        owner: u64,
    },
    /// A **layer**: a subgroup of primitives composited **as one** at `opacity`.
    /// It is rendered separately into a texture at full opacity, then composited,
    /// which is what makes the group alpha correct: no double blending where the
    /// inner primitives overlap.
    Layer {
        /// The group's primitives, in absolute coordinates like the parent scene.
        primitives: Vec<Primitive>,
        /// Group opacity applied to the whole layer (`0..1`).
        opacity: f32,
        /// The layer's clip rectangle.
        clip: Rect,
        /// The clip **shape** inscribed in `clip` (rounded or elliptical); its
        /// coverage modulates alpha at compositing time. [`ClipShape::Rect`] is a
        /// plain rectangular clip, and the default.
        clip_shape: ClipShape,
        /// The affine transform (rotation) applied at compositing. `None` means the
        /// layer is simply composited in place, with group opacity.
        transform: Option<LayerTransform>,
        /// The **pixel effects** applied when the layer is composited: an image
        /// filter, a colour filter, a mask. [`LayerFilter::NONE`] — the usual
        /// case — leaves compositing on its original path.
        filter: LayerFilter,
        /// The emitting widget's identity.
        owner: u64,
    },
}

impl Primitive {
    /// The identity of the widget that emitted this primitive.
    pub fn owner(&self) -> u64 {
        match self {
            Primitive::Rect { owner, .. } => *owner,
            Primitive::Text { owner, .. } => *owner,
            Primitive::RichText { owner, .. } => *owner,
            Primitive::Path { owner, .. } => *owner,
            Primitive::Image { owner, .. } => *owner,
            Primitive::Layer { owner, .. } => *owner,
        }
    }

    /// Scales the **geometry** by `factor` — position, size, radius, border, blur,
    /// clip, font size. Colours and text are unchanged. This is how a logical scene
    /// becomes a physical one (DPI).
    pub fn scaled(&self, factor: f32) -> Primitive {
        self.scaled_xy(factor, factor)
    }

    /// Scales the geometry **per axis** (`sx` horizontal, `sy` vertical).
    /// Rectangles and images stretch exactly; **scalar** quantities (corner radius,
    /// border, blur, path) follow the average of the two factors, having no axis of
    /// their own; font size follows `sy` and wrap width follows `sx` — approximations
    /// with no consequence when `sx == sy`, as with a uniform scale or DPI. This is
    /// the basis of **non-uniform** subtree scaling.
    pub fn scaled_xy(&self, sx: f32, sy: f32) -> Primitive {
        let avg = (sx + sy) * 0.5;
        match self.clone() {
            Primitive::Rect {
                rect,
                color,
                color2,
                gradient_dir,
                radius,
                border_width,
                border_color,
                blur,
                clip,
                owner,
                shader,
                blur_style,
            } => Primitive::Rect {
                rect: rect.scale_xy(sx, sy),
                color,
                color2,
                gradient_dir,
                radius: radius.scale(avg),
                border_width: border_width * avg,
                border_color,
                blur: blur * avg,
                clip: clip.scale_xy(sx, sy),
                owner,
                shader,
                blur_style,
            },
            Primitive::Text {
                position,
                text,
                size,
                color,
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing,
                clip,
                bounds,
                owner,
            } => Primitive::Text {
                position: position.scale_xy(sx, sy),
                text,
                size: size * sy,
                color,
                weight,
                italic,
                max_width: max_width.map(|w| w * sx),
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing: letter_spacing * sx,
                clip: clip.scale_xy(sx, sy),
                bounds: bounds.scale_xy(sx, sy),
                owner,
            },
            Primitive::RichText {
                position,
                mut runs,
                max_width,
                soft_wrap,
                align,
                clip,
                bounds,
                owner,
            } => {
                for run in &mut runs {
                    run.size *= sy;
                }
                Primitive::RichText {
                    position: position.scale_xy(sx, sy),
                    runs,
                    max_width: max_width.map(|w| w * sx),
                    soft_wrap,
                    align,
                    clip: clip.scale_xy(sx, sy),
                    bounds: bounds.scale_xy(sx, sy),
                    owner,
                }
            }
            Primitive::Path {
                path,
                fill,
                gradient,
                stroke,
                clip,
                owner,
            } => Primitive::Path {
                path: path.scaled(avg),
                fill,
                gradient: gradient.map(|g| g.scaled_xy(sx, sy)),
                stroke: stroke.map(|s| Stroke::new(s.color, s.width * avg)),
                clip: clip.scale_xy(sx, sy),
                owner,
            },
            Primitive::Image {
                image,
                rect,
                uv,
                tint,
                strict,
                clip,
                owner,
            } => Primitive::Image {
                image,
                rect: rect.scale_xy(sx, sy),
                // The UV is in 0..1, so it is independent of scale.
                uv,
                tint,
                strict,
                clip: clip.scale_xy(sx, sy),
                owner,
            },
            Primitive::Layer {
                primitives,
                opacity,
                clip,
                clip_shape,
                transform,
                filter,
                owner,
            } => Primitive::Layer {
                primitives: primitives.iter().map(|p| p.scaled_xy(sx, sy)).collect(),
                opacity,
                clip: clip.scale_xy(sx, sy),
                clip_shape: clip_shape.scaled_xy(sx, sy),
                transform: transform.map(|t| t.scaled_xy(sx, sy)),
                filter: filter.scaled_xy(sx, sy),
                owner,
            },
        }
    }

    /// Offsets the **geometry** by `(dx, dy)` (position, clip); colours, sizes and
    /// text are unchanged. Combined with [`Primitive::scaled`], it scales a subtree
    /// **about a pivot**:
    /// `p.scaled(f).translated(pivot.x * (1 - f), pivot.y * (1 - f))`.
    pub fn translated(&self, dx: f32, dy: f32) -> Primitive {
        match self.clone() {
            Primitive::Rect {
                rect,
                color,
                color2,
                gradient_dir,
                radius,
                border_width,
                border_color,
                blur,
                clip,
                owner,
                shader,
                blur_style,
            } => Primitive::Rect {
                rect: rect.translate(dx, dy),
                color,
                color2,
                gradient_dir,
                radius,
                border_width,
                border_color,
                blur,
                clip: clip.translate(dx, dy),
                owner,
                shader,
                blur_style,
            },
            Primitive::Text {
                position,
                text,
                size,
                color,
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing,
                clip,
                bounds,
                owner,
            } => Primitive::Text {
                position: Point::new(position.x + dx, position.y + dy),
                text,
                size,
                color,
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing,
                clip: clip.translate(dx, dy),
                bounds: bounds.translate(dx, dy),
                owner,
            },
            Primitive::RichText {
                position,
                runs,
                max_width,
                soft_wrap,
                align,
                clip,
                bounds,
                owner,
            } => Primitive::RichText {
                position: Point::new(position.x + dx, position.y + dy),
                runs,
                max_width,
                soft_wrap,
                align,
                clip: clip.translate(dx, dy),
                bounds: bounds.translate(dx, dy),
                owner,
            },
            Primitive::Path {
                path,
                fill,
                gradient,
                stroke,
                clip,
                owner,
            } => Primitive::Path {
                path: path.translated(dx, dy),
                fill,
                gradient: gradient.map(|g| g.translated(dx, dy)),
                stroke,
                clip: clip.translate(dx, dy),
                owner,
            },
            Primitive::Image {
                image,
                rect,
                uv,
                tint,
                strict,
                clip,
                owner,
            } => Primitive::Image {
                image,
                rect: rect.translate(dx, dy),
                uv,
                tint,
                strict,
                clip: clip.translate(dx, dy),
                owner,
            },
            Primitive::Layer {
                primitives,
                opacity,
                clip,
                clip_shape,
                transform,
                filter,
                owner,
            } => {
                Primitive::Layer {
                    primitives: primitives.iter().map(|p| p.translated(dx, dy)).collect(),
                    opacity,
                    clip: clip.translate(dx, dy),
                    // Radius and ellipse are translation-invariant; only the `clip`
                    // rectangle moves, which is handled above.
                    clip_shape,
                    transform: transform.map(|t| t.translated(dx, dy)),
                    // A blur radius is a length, and does not move; a mask's geometry is
                    // held in the scene's coordinates once resolved from its box, and moves
                    // with what it covers (milestone 610: it was left behind).
                    filter: filter.translated(dx, dy),
                    owner,
                }
            }
        }
    }

    /// This primitive's (approximate) bounding box, in scene coordinates.
    /// Text is not measured in this module, so a `Text` or `RichText` primitive
    /// returns a **point** rectangle at its position, enough as an x reference.
    pub fn bounds(&self) -> Rect {
        match self {
            Primitive::Rect { rect, .. } | Primitive::Image { rect, .. } => *rect,
            Primitive::Text { position, .. } | Primitive::RichText { position, .. } => {
                Rect::new(position.x, position.y, 0.0, 0.0)
            }
            Primitive::Path { path, .. } => {
                // The control points' bounding box — conservative bounds, since it
                // encloses the Bézier controls and so is never smaller than the curve.
                // Accumulated without allocating: min/max updated point by point.
                let mut bbox: Option<(f32, f32, f32, f32)> = None;
                let mut include = |p: Point| {
                    bbox = Some(match bbox {
                        None => (p.x, p.y, p.x, p.y),
                        Some((x0, y0, x1, y1)) => {
                            (x0.min(p.x), y0.min(p.y), x1.max(p.x), y1.max(p.y))
                        }
                    });
                };
                for v in path.verbs() {
                    match *v {
                        PathVerb::MoveTo(p) | PathVerb::LineTo(p) => include(p),
                        PathVerb::QuadTo { ctrl, to } => {
                            include(ctrl);
                            include(to);
                        }
                        PathVerb::CubicTo { c1, c2, to } => {
                            include(c1);
                            include(c2);
                            include(to);
                        }
                        PathVerb::Close => {}
                    }
                }
                match bbox {
                    None => Rect::new(0.0, 0.0, 0.0, 0.0),
                    Some((x0, y0, x1, y1)) => Rect::new(x0, y0, x1 - x0, y1 - y0),
                }
            }
            Primitive::Layer { primitives, .. } => primitives
                .iter()
                .map(|p| p.bounds())
                .reduce(|a, b| a.union(b))
                .unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0)),
        }
    }

    /// A copy of this primitive with its **clip** replaced by `clip` — used to
    /// "un-clip" a captured primitive replayed elsewhere, such as the ghost of a
    /// dragged header, which overflows its source column.
    pub fn with_clip(&self, clip: Rect) -> Primitive {
        match self.clone() {
            Primitive::Rect {
                rect,
                color,
                color2,
                gradient_dir,
                radius,
                border_width,
                border_color,
                blur,
                owner,
                ..
            } => Primitive::Rect {
                rect,
                color,
                color2,
                gradient_dir,
                radius,
                border_width,
                border_color,
                blur,
                clip,
                owner,
                shader: None,
                blur_style: crate::BlurStyle::Normal,
            },
            Primitive::Text {
                position,
                text,
                size,
                color,
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing,
                bounds,
                owner,
                ..
            } => Primitive::Text {
                position,
                text,
                size,
                color,
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing,
                clip,
                bounds,
                owner,
            },
            Primitive::RichText {
                position,
                runs,
                max_width,
                soft_wrap,
                align,
                bounds,
                owner,
                ..
            } => Primitive::RichText {
                position,
                runs,
                max_width,
                soft_wrap,
                align,
                clip,
                bounds,
                owner,
            },
            Primitive::Path {
                path,
                fill,
                gradient,
                stroke,
                owner,
                ..
            } => Primitive::Path {
                path,
                fill,
                gradient,
                stroke,
                clip,
                owner,
            },
            Primitive::Image {
                image,
                rect,
                uv,
                tint,
                strict,
                owner,
                ..
            } => Primitive::Image {
                image,
                rect,
                uv,
                tint,
                strict,
                clip,
                owner,
            },
            Primitive::Layer {
                primitives,
                opacity,
                clip_shape,
                transform,
                filter,
                owner,
                ..
            } => Primitive::Layer {
                primitives,
                opacity,
                clip,
                clip_shape,
                transform,
                filter,
                owner,
            },
        }
    }

    /// Scales the geometry by `factor` **about `pivot`**, which stays fixed:
    /// `pos' = pivot + (pos - pivot) * factor`. Sizes, font, radii and strokes all
    /// follow the scale.
    pub fn scaled_about(&self, pivot: Point, factor: f32) -> Primitive {
        self.scaled_about_xy(pivot, factor, factor)
    }

    /// Like [`Primitive::scaled_about`], but with **per-axis** factors (`sx`, `sy`)
    /// — a non-uniform scale about `pivot`.
    pub fn scaled_about_xy(&self, pivot: Point, sx: f32, sy: f32) -> Primitive {
        self.scaled_xy(sx, sy)
            .translated(pivot.x * (1.0 - sx), pivot.y * (1.0 - sy))
    }
}

/// The box a block of text is laid out in: how wide it is, whether the text wraps at
/// that width, and where the lines sit inside it. See [`Scene::text_block`].
#[derive(Clone, Copy, Debug, PartialEq, Default)]
pub struct TextBlock {
    /// The box's width; `None` leaves the text unbounded, and alignment with it.
    pub width: Option<f32>,
    /// Whether the text wraps at `width` rather than running past it.
    pub soft_wrap: bool,
    /// Where the lines sit inside `width`.
    pub align: TextAlign,
}

/// A 2D scene: the declarative description of what to draw.
#[derive(Clone, Debug)]
pub struct Scene {
    primitives: Vec<Primitive>,
    current_clip: Rect,
    current_owner: u64,
    /// The box of the widget currently painting — what text primitives record so the
    /// renderer knows what they cover. `UNBOUNDED` until a walk sets it.
    current_bounds: Rect,
}

impl Default for Scene {
    fn default() -> Self {
        Self {
            primitives: Vec::new(),
            current_clip: Rect::UNBOUNDED,
            current_owner: 0,
            current_bounds: Rect::UNBOUNDED,
        }
    }
}

impl Scene {
    /// Creates an empty scene, with a neutral clip.
    pub fn new() -> Self {
        Self::default()
    }

    /// Empties the scene so it can be reused on the next frame.
    pub fn clear(&mut self) {
        self.primitives.clear();
        self.current_clip = Rect::UNBOUNDED;
        self.current_owner = 0;
        self.current_bounds = Rect::UNBOUNDED;
    }

    /// Sets the clip rectangle applied to subsequent primitives.
    pub fn set_clip(&mut self, clip: Rect) {
        self.current_clip = clip;
    }

    /// The current clip rectangle, for intersecting with local bounds.
    pub fn current_clip(&self) -> Rect {
        self.current_clip
    }

    /// Sets the emitting widget's identity for subsequent primitives.
    pub fn set_owner(&mut self, owner: u64) {
        self.current_owner = owner;
    }

    /// The emitting widget's identity, as the next primitive will carry it.
    pub fn current_owner(&self) -> u64 {
        self.current_owner
    }

    /// Declares the box the widget about to paint was laid out in. Text primitives
    /// record it, which is how the renderer knows what a line of text covers — a
    /// `Primitive::Text` otherwise says only where it begins. Set by the widget walk
    /// before every `paint`; a scene built by hand leaves it `UNBOUNDED`, and the
    /// renderer then keeps that text above everything, as it always did.
    pub fn set_bounds(&mut self, bounds: Rect) {
        self.current_bounds = bounds;
    }

    /// The box currently being painted into.
    pub fn current_bounds(&self) -> Rect {
        self.current_bounds
    }

    /// Appends an **already-formed** primitive, with its clip and owner already
    /// baked in. This replays a cached subtree (a repaint boundary) as-is, without
    /// repainting it.
    pub fn push_primitive(&mut self, primitive: Primitive) {
        self.primitives.push(primitive);
    }

    /// Removes and returns the primitives from index `start` onwards, preserving
    /// order. This **wraps** an already-painted subtree in a layer
    /// ([`Primitive::Layer`]): paint the subtree, then move its range of primitives
    /// into a layer, giving it group opacity.
    pub fn split_off(&mut self, start: usize) -> Vec<Primitive> {
        self.primitives.split_off(start)
    }

    /// Replays an existing primitive at reduced opacity — an exit fade.
    pub fn push_faded(&mut self, primitive: &Primitive, opacity: f32) {
        let faded = match primitive.clone() {
            Primitive::Rect {
                rect,
                color,
                color2,
                gradient_dir,
                radius,
                border_width,
                border_color,
                blur,
                clip,
                owner,
                shader,
                blur_style,
            } => Primitive::Rect {
                rect,
                color: color.fade(opacity),
                color2: color2.fade(opacity),
                gradient_dir,
                radius,
                border_width,
                border_color: border_color.fade(opacity),
                blur,
                clip,
                owner,
                shader: shader.map(|g| std::sync::Arc::new(g.scale(opacity))),
                blur_style,
            },
            Primitive::Text {
                position,
                text,
                size,
                color,
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color,
                height,
                family,
                letter_spacing,
                clip,
                bounds,
                owner,
            } => Primitive::Text {
                position,
                text,
                size,
                color: color.fade(opacity),
                weight,
                italic,
                max_width,
                soft_wrap,
                align,
                decoration,
                decoration_color: decoration_color.map(|c| c.fade(opacity)),
                height,
                family,
                letter_spacing,
                clip,
                bounds,
                owner,
            },
            Primitive::RichText {
                position,
                mut runs,
                max_width,
                soft_wrap,
                align,
                clip,
                bounds,
                owner,
            } => {
                for run in &mut runs {
                    run.color = run.color.fade(opacity);
                    run.decoration_color = run.decoration_color.map(|c| c.fade(opacity));
                }
                Primitive::RichText {
                    position,
                    runs,
                    max_width,
                    soft_wrap,
                    align,
                    clip,
                    bounds,
                    owner,
                }
            }
            Primitive::Path {
                path,
                fill,
                gradient,
                stroke,
                clip,
                owner,
            } => Primitive::Path {
                path,
                fill: fill.map(|c| c.fade(opacity)),
                gradient: gradient.map(|g| g.faded(opacity)),
                stroke: stroke.map(|s| Stroke::new(s.color.fade(opacity), s.width)),
                clip,
                owner,
            },
            Primitive::Image {
                image,
                rect,
                uv,
                tint,
                strict,
                clip,
                owner,
            } => Primitive::Image {
                image,
                rect,
                uv,
                tint: tint.fade(opacity),
                strict,
                clip,
                owner,
            },
            Primitive::Layer {
                primitives,
                opacity: group,
                clip,
                clip_shape,
                transform,
                filter,
                owner,
            } => Primitive::Layer {
                primitives,
                // Fading a layer means dimming its group opacity.
                opacity: group * opacity,
                clip,
                clip_shape,
                transform,
                filter,
                owner,
            },
        };
        self.primitives.push(faded);
    }

    /// Adds a solid rectangle, with square corners and no border.
    pub fn fill_rect(&mut self, rect: Rect, color: Color) {
        self.primitives.push(Primitive::Rect {
            rect,
            color,
            color2: color,
            gradient_dir: [0.0, 0.0],
            radius: BorderRadius::ZERO,
            border_width: 0.0,
            border_color: Color::TRANSPARENT,
            blur: 0.0,
            clip: self.current_clip,
            owner: self.current_owner,
            shader: None,
            blur_style: crate::BlurStyle::Normal,
        });
    }

    /// Adds a rectangle with rounded corners (uniform through `f32`, or per corner
    /// through [`BorderRadius`]) and/or a border.
    /// **Fills a shape**, and draws its edge if it has one.
    ///
    /// Three of the four shapes are rounded rectangles once the box is known, so they go
    /// down the same path as [`Scene::draw_rect`] and cost nothing extra; a bevel becomes
    /// a filled path plus a stroked one. A caller who does this by hand at each site gets
    /// the fast path wrong somewhere, which is the whole reason this is one function.
    pub fn draw_shape(&mut self, rect: Rect, shape: ShapeBorder, fill: Color) {
        let side = shape.side();
        if let Some((box_, radius)) = shape.as_rounded(rect) {
            self.draw_rect(
                box_,
                fill,
                radius,
                if side.is_drawn() { side.width } else { 0.0 },
                side.color,
            );
            return;
        }
        let outline = shape.outline(rect);
        self.fill_path(&outline, fill);
        if side.is_drawn() {
            self.stroke_path(&outline, side.color, side.width);
        }
    }

    /// Adds a flat-coloured rectangle, with an optional border.
    pub fn draw_rect(
        &mut self,
        rect: Rect,
        color: Color,
        radius: impl Into<BorderRadius>,
        border_width: f32,
        border_color: Color,
    ) {
        self.primitives.push(Primitive::Rect {
            rect,
            color,
            color2: color,
            gradient_dir: [0.0, 0.0],
            radius: radius.into(),
            border_width,
            border_color,
            blur: 0.0,
            clip: self.current_clip,
            owner: self.current_owner,
            shader: None,
            blur_style: crate::BlurStyle::Normal,
        });
    }

    /// **A rectangle filled with a gradient** (milestone 644): any of the reference's
    /// three, relative to `rect`, with corners and a border as [`Scene::draw_rect`] has
    /// them.
    #[allow(clippy::too_many_arguments)]
    pub fn shaded_rect(
        &mut self,
        rect: Rect,
        gradient: crate::Gradient,
        opacity: f32,
        radius: impl Into<BorderRadius>,
        border_width: f32,
        border_color: Color,
    ) {
        let gradient = if opacity < 1.0 {
            gradient.scale(opacity)
        } else {
            gradient
        };
        let first = gradient
            .colors()
            .first()
            .copied()
            .unwrap_or(Color::TRANSPARENT);
        let last = gradient
            .colors()
            .last()
            .copied()
            .unwrap_or(Color::TRANSPARENT);
        self.primitives.push(Primitive::Rect {
            rect,
            color: first,
            color2: last,
            gradient_dir: [0.0, 0.0],
            radius: radius.into(),
            border_width,
            border_color,
            blur: 0.0,
            clip: self.current_clip,
            owner: self.current_owner,
            shader: Some(std::sync::Arc::new(gradient)),
            blur_style: crate::BlurStyle::Normal,
        });
    }

    /// Adds a linear-gradient rectangle (`color` → `color2` along `dir`).
    // Eight, and every one of them a property of the same rectangle. Grouping them
    // into a struct is an API change with call sites, not a lint fix.
    #[allow(clippy::too_many_arguments)]
    pub fn gradient_rect(
        &mut self,
        rect: Rect,
        color: Color,
        color2: Color,
        dir: [f32; 2],
        radius: impl Into<BorderRadius>,
        border_width: f32,
        border_color: Color,
    ) {
        self.primitives.push(Primitive::Rect {
            rect,
            color,
            color2,
            gradient_dir: dir,
            radius: radius.into(),
            border_width,
            border_color,
            blur: 0.0,
            clip: self.current_clip,
            owner: self.current_owner,
            shader: None,
            blur_style: crate::BlurStyle::Normal,
        });
    }

    /// Adds a soft shadow — a rounded rectangle with a blurred edge, no border.
    pub fn shadow(&mut self, rect: Rect, color: Color, radius: impl Into<BorderRadius>, blur: f32) {
        self.styled_shadow(rect, color, radius, blur, BlurStyle::Normal);
    }

    /// Adds a soft shadow whose blur keeps one side of the shape's edge, or both
    /// ([`BlurStyle`]). As [`Self::shadow`], `rect` already reaches `blur` beyond the
    /// shape, which runs `blur` inside it.
    pub fn styled_shadow(
        &mut self,
        rect: Rect,
        color: Color,
        radius: impl Into<BorderRadius>,
        blur: f32,
        blur_style: BlurStyle,
    ) {
        self.primitives.push(Primitive::Rect {
            rect,
            color,
            color2: color,
            gradient_dir: [0.0, 0.0],
            radius: radius.into(),
            border_width: 0.0,
            border_color: Color::TRANSPARENT,
            blur,
            clip: self.current_clip,
            owner: self.current_owner,
            shader: None,
            blur_style,
        });
    }

    /// Fills a vector path with a flat colour, using the *non-zero* rule.
    pub fn fill_path(&mut self, path: &Path, color: Color) {
        self.primitives.push(Primitive::Path {
            path: path.clone(),
            fill: Some(color),
            gradient: None,
            stroke: None,
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Fills a path with a **linear gradient**: `from_color` at `from`, `to_color` at
    /// `to`, clamped outside that span.
    ///
    /// The two points are in the path's own space rather than relative to its box, so
    /// the fade can be aimed at the thing it is about — the edge a glow springs from,
    /// the depth of a band — which is what an ellipse cap needs, its bounding box
    /// being mostly off screen.
    pub fn fill_path_gradient(
        &mut self,
        path: &Path,
        from_color: Color,
        to_color: Color,
        from: Point,
        to: Point,
    ) {
        self.primitives.push(Primitive::Path {
            path: path.clone(),
            fill: Some(from_color),
            gradient: Some(PathGradient::Linear { to_color, from, to }),
            stroke: None,
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Fills a path with a **radial gradient**: `from_color` on the ellipse of radii
    /// `inner × radii` about `center`, `to_color` on the ellipse of radii `radii`.
    ///
    /// This is what a shape with a **curved** boundary needs in order to fade to
    /// nothing all the way round: a straight fade reaches zero on a line, so it still
    /// leaves an edge wherever the shape turns away from that line.
    pub fn fill_path_radial(
        &mut self,
        path: &Path,
        from_color: Color,
        to_color: Color,
        center: Point,
        radii: Size,
        inner: f32,
    ) {
        self.primitives.push(Primitive::Path {
            path: path.clone(),
            fill: Some(from_color),
            gradient: Some(PathGradient::Radial {
                to_color,
                center,
                radii,
                inner,
            }),
            stroke: None,
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Fills a path with a [`GradientRamp`] — any number of stops, along a line or between
    /// two circles, turned or skewed by its own transform.
    pub fn fill_path_ramp(&mut self, path: &Path, ramp: GradientRamp, opacity: f32) {
        self.primitives.push(Primitive::Path {
            path: path.clone(),
            fill: Some(Color::WHITE.fade(opacity)),
            gradient: Some(PathGradient::Ramp(Arc::new(ramp))),
            stroke: None,
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Strokes a path's outline (colour plus width), with no fill.
    pub fn stroke_path(&mut self, path: &Path, color: Color, width: f32) {
        self.primitives.push(Primitive::Path {
            path: path.clone(),
            fill: None,
            gradient: None,
            stroke: Some(Stroke::new(color, width)),
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Adds a path filled **and/or** stroked — both passes in one primitive.
    pub fn paint_path(&mut self, path: &Path, fill: Option<Color>, stroke: Option<Stroke>) {
        self.primitives.push(Primitive::Path {
            path: path.clone(),
            fill,
            gradient: None,
            stroke,
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Draws an image into `rect`, sampling the `uv` sub-region (in `0..1`) and
    /// tinting it by `tint` (white = unchanged). Low level: see [`Scene::image`]
    /// for automatic fitting through [`crate::BoxFit`].
    pub fn draw_image(&mut self, image: &ImageHandle, rect: Rect, uv: Rect, tint: Color) {
        self.push_image(image, rect, uv, tint, false);
    }

    /// [`Scene::draw_image`], sampled **strictly** inside `uv`: no filtered sample
    /// reaches the texels around it. For one part of a picture stretched apart from the
    /// rest, as a centre slice's are.
    pub fn draw_image_strict(&mut self, image: &ImageHandle, rect: Rect, uv: Rect, tint: Color) {
        self.push_image(image, rect, uv, tint, true);
    }

    fn push_image(&mut self, image: &ImageHandle, rect: Rect, uv: Rect, tint: Color, strict: bool) {
        self.primitives.push(Primitive::Image {
            image: image.clone(),
            rect,
            uv,
            tint,
            strict,
            clip: self.current_clip,
            owner: self.current_owner,
        });
    }

    /// Draws a whole image **through an affine map** from its pixels — `(0, 0)` to
    /// `(width, height)` — to the screen, tinted by `tint`: a bitmap inside vector
    /// artwork, which may be turned, slanted or mirrored with it (milestone 694).
    ///
    /// A map that only scales and moves is one image primitive. Any other draws the image
    /// upright at its size on screen, at the origin, in a [transformed
    /// layer](Scene::transformed) that turns it into place, so it is sampled once at the
    /// resolution it is shown at. Like any transformed layer, an image larger than the
    /// window once on screen loses what lies past the window's size.
    pub fn draw_image_mapped(&mut self, image: &ImageHandle, to_screen: Affine, tint: Color) {
        let (w, h) = (image.width() as f32, image.height() as f32);
        let [a, b, c, d, e, f] = to_screen.m;
        if w == 0.0 || h == 0.0 || !to_screen.m.iter().all(|v| v.is_finite()) {
            return;
        }
        let whole = Rect::new(0.0, 0.0, 1.0, 1.0);
        if b == 0.0 && c == 0.0 && a > 0.0 && d > 0.0 {
            self.draw_image(image, Rect::new(e, f, a * w, d * h), whole, tint);
            return;
        }
        // The length each pixel's sides take on screen.
        let (sx, sy) = (a.hypot(b), c.hypot(d));
        if sx == 0.0 || sy == 0.0 {
            return;
        }
        let flat = Rect::new(0.0, 0.0, w * sx, h * sy);
        let turn = Affine::scale(1.0 / sx, 1.0 / sy).then(to_screen);
        self.transformed(LayerTransform::new(turn), |scene| {
            // The clip around it is the screen's; flat, the image is its own.
            scene.set_clip(flat);
            scene.draw_image(image, flat, whole, tint);
        });
    }

    /// Draws an image fitted into `rect` per `fit` (aspect preserved, letterboxed
    /// or cropped), untinted.
    pub fn image(&mut self, image: &ImageHandle, rect: Rect, fit: crate::BoxFit) {
        let (dst, uv) = fit.apply(image.size(), rect);
        self.draw_image(image, dst, uv, Color::WHITE);
    }

    /// Composes a **layer**: `build` fills a subgroup of primitives, which is then
    /// composited **as one** at `opacity` (`0..1`). Unlike an opacity applied
    /// primitive by primitive, the group alpha stays correct where the inner
    /// primitives overlap. The layer inherits the current clip and owner.
    pub fn layer(&mut self, opacity: f32, build: impl FnOnce(&mut Scene)) {
        let mut inner = Scene::new();
        inner.current_clip = self.current_clip;
        inner.current_owner = self.current_owner;
        build(&mut inner);
        self.primitives.push(Primitive::Layer {
            primitives: inner.primitives,
            opacity,
            clip: self.current_clip,
            clip_shape: ClipShape::Rect,
            transform: None,
            filter: LayerFilter::NONE,
            owner: self.current_owner,
        });
    }

    /// Composes a **transformed layer**: `build` fills a subgroup of primitives, which is
    /// rendered flat and then composited through `transform`.
    ///
    /// The transform belongs to the group and not to the primitives inside it, which is
    /// the whole point: a rotation applies to a rectangle, a line of text and an image at
    /// once, and none of them has to know how to rotate itself.
    ///
    /// **Paint the group where it fits, not where it lands.** The renderer draws the
    /// group flat into a *window-sized* texture and composites that through the
    /// transform, so anything laid out flat beyond the window is gone before the
    /// transform could have brought it back inside. A group that ends up near an edge
    /// should be built at the origin and carried there by the transform.
    pub fn transformed(&mut self, transform: LayerTransform, build: impl FnOnce(&mut Scene)) {
        let mut inner = Scene::new();
        inner.current_clip = self.current_clip;
        inner.current_owner = self.current_owner;
        inner.current_bounds = self.current_bounds;
        build(&mut inner);
        self.primitives.push(Primitive::Layer {
            primitives: inner.primitives,
            opacity: 1.0,
            clip: self.current_clip,
            clip_shape: ClipShape::Rect,
            transform: Some(transform),
            filter: LayerFilter::NONE,
            owner: self.current_owner,
        });
    }

    /// Adds a **masked group**: everything `build` emits is composited as one, with
    /// `mask` multiplied into it, so the shader's alpha becomes the group's transparency.
    ///
    /// A fade has to be a group. Applied primitive by primitive it would fade each of
    /// them against the background separately, and where two of them overlap the result
    /// is neither one nor the other.
    pub fn masked(&mut self, mask: ShaderMask, build: impl FnOnce(&mut Scene)) {
        let mut inner = Scene::new();
        inner.current_clip = self.current_clip;
        inner.current_owner = self.current_owner;
        inner.current_bounds = self.current_bounds;
        build(&mut inner);
        self.primitives.push(Primitive::Layer {
            primitives: inner.primitives,
            opacity: 1.0,
            clip: self.current_clip,
            clip_shape: ClipShape::Rect,
            transform: None,
            filter: LayerFilter {
                mask: Some(mask),
                ..LayerFilter::NONE
            },
            owner: self.current_owner,
        });
    }

    /// Adds a **blended group** (milestone 646): everything `build` emits is composited
    /// as one, meeting what is already painted underneath by `mode` rather than being
    /// painted over it. The group's clip is where it applies; outside it, what was
    /// there stays.
    pub fn blended(&mut self, mode: crate::BlendMode, build: impl FnOnce(&mut Scene)) {
        self.blended_in(mode, ClipShape::Rect, build);
    }

    /// [`Scene::blended`] in a `shape` inscribed in the current clip: rounded corners or
    /// an ellipse, or a path in absolute coordinates.
    pub fn blended_in(
        &mut self,
        mode: crate::BlendMode,
        shape: ClipShape,
        build: impl FnOnce(&mut Scene),
    ) {
        let mut inner = Scene::new();
        inner.current_clip = self.current_clip;
        inner.current_owner = self.current_owner;
        inner.current_bounds = self.current_bounds;
        build(&mut inner);
        self.primitives.push(Primitive::Layer {
            primitives: inner.primitives,
            opacity: 1.0,
            clip: self.current_clip,
            clip_shape: shape,
            transform: None,
            filter: LayerFilter {
                blend: Some(mode),
                ..LayerFilter::NONE
            },
            owner: self.current_owner,
        });
    }

    /// Adds **rich** text: resolved runs, mixing styles and colours, laid out as one
    /// piece, anchored by its top-left corner.
    pub fn rich_text(&mut self, position: Point, runs: Vec<TextRun>) {
        self.primitives.push(Primitive::RichText {
            position,
            runs,
            max_width: None,
            soft_wrap: true,
            align: TextAlign::Start,
            clip: self.current_clip,
            bounds: self.current_bounds,
            owner: self.current_owner,
        });
    }

    /// Adds a **rich paragraph**: the runs wrap beyond `max_width`, and the render's
    /// wrapping matches the layout's.
    pub fn rich_text_wrapped(&mut self, position: Point, runs: Vec<TextRun>, max_width: f32) {
        self.primitives.push(Primitive::RichText {
            position,
            runs,
            max_width: Some(max_width),
            soft_wrap: true,
            align: TextAlign::Start,
            clip: self.current_clip,
            bounds: self.current_bounds,
            owner: self.current_owner,
        });
    }

    /// Adds a line of text, anchored by its top-left corner — size, weight and italics
    /// from the [`ResolvedTextStyle`].
    ///
    /// It takes a **resolved** style and not a [`TextStyle`](crate::TextStyle) because
    /// this is the bottom of the chain: a shaper needs a number and there is nobody left
    /// below to ask one of. `color` is settled the same way, by the caller, usually
    /// against the theme — which is the one answer this crate cannot work out for itself.
    ///
    /// There is deliberately **no form of this that takes a bare `f32` size**. A number
    /// arriving here has been through [`TextStyle::resolved`](crate::TextStyle::resolved),
    /// which is the single place the reader's font size is applied; a second door taking a
    /// raw constant is a door onto text that ignores the reader, and forty-seven call sites
    /// walked through it (milestone 406).
    pub fn text(
        &mut self,
        position: Point,
        text: impl Into<String>,
        style: &ResolvedTextStyle,
        color: Color,
    ) {
        self.primitives.push(Primitive::Text {
            position,
            text: text.into(),
            size: style.size,
            color,
            weight: style.weight,
            italic: style.italic,
            max_width: None,
            soft_wrap: true,
            align: TextAlign::Start,
            decoration: style.decoration,
            decoration_color: style.decoration_color,
            height: style.height,
            family: style.family,
            letter_spacing: style.letter_spacing,
            clip: self.current_clip,
            bounds: self.current_bounds,
            owner: self.current_owner,
        });
    }

    /// Adds a **paragraph**: styled text that wraps beyond `max_width`, the render's
    /// wrapping matching the layout's.
    pub fn text_wrapped(
        &mut self,
        position: Point,
        text: impl Into<String>,
        style: &ResolvedTextStyle,
        color: Color,
        max_width: f32,
    ) {
        self.primitives.push(Primitive::Text {
            position,
            text: text.into(),
            size: style.size,
            color,
            weight: style.weight,
            italic: style.italic,
            max_width: Some(max_width),
            soft_wrap: true,
            align: TextAlign::Start,
            decoration: style.decoration,
            decoration_color: style.decoration_color,
            height: style.height,
            family: style.family,
            letter_spacing: style.letter_spacing,
            clip: self.current_clip,
            bounds: self.current_bounds,
            owner: self.current_owner,
        });
    }

    /// Adds a **block** of styled text: a box of a known width, which the text may be
    /// wrapped in and is aligned inside.
    ///
    /// The three settings travel together because they are one decision. A width with no
    /// wrapping is a line that knows where its box ends and runs past it anyway — which is
    /// what a clipped or ellipsised line is — and an alignment with no width has nothing
    /// to align against.
    pub fn text_block(
        &mut self,
        position: Point,
        text: impl Into<String>,
        style: &ResolvedTextStyle,
        color: Color,
        block: TextBlock,
    ) {
        self.primitives.push(Primitive::Text {
            position,
            text: text.into(),
            size: style.size,
            color,
            weight: style.weight,
            italic: style.italic,
            max_width: block.width,
            soft_wrap: block.soft_wrap,
            align: block.align,
            decoration: style.decoration,
            decoration_color: style.decoration_color,
            height: style.height,
            family: style.family,
            letter_spacing: style.letter_spacing,
            clip: self.current_clip,
            bounds: self.current_bounds,
            owner: self.current_owner,
        });
    }

    /// Adds a **block** of rich text: resolved runs in a box of a known width, which they
    /// may be wrapped in and are aligned inside. The rich counterpart of
    /// [`Scene::text_block`].
    pub fn rich_text_block(&mut self, position: Point, runs: Vec<TextRun>, block: TextBlock) {
        self.primitives.push(Primitive::RichText {
            position,
            runs,
            max_width: block.width,
            soft_wrap: block.soft_wrap,
            align: block.align,
            clip: self.current_clip,
            bounds: self.current_bounds,
            owner: self.current_owner,
        });
    }

    /// The number of primitives in the scene.
    pub fn len(&self) -> usize {
        self.primitives.len()
    }

    /// `true` when the scene holds no primitives at all.
    pub fn is_empty(&self) -> bool {
        self.primitives.is_empty()
    }

    /// The primitives, in insertion order, which is drawing order.
    pub fn primitives(&self) -> &[Primitive] {
        &self.primitives
    }

    /// A copy of the scene with all geometry scaled by `factor` — the logical →
    /// physical conversion for HiDPI rendering.
    pub fn scaled(&self, factor: f32) -> Scene {
        Scene {
            primitives: self.primitives.iter().map(|p| p.scaled(factor)).collect(),
            current_clip: self.current_clip.scale(factor),
            current_owner: self.current_owner,
            current_bounds: self.current_bounds.scale(factor),
        }
    }
}

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

    fn close(a: Option<f32>, b: f32) -> bool {
        a.is_some_and(|a| (a - b).abs() < 1e-4)
    }

    fn ramp(shape: RampShape, tile: TileMode) -> GradientRamp {
        GradientRamp {
            shape,
            stops: vec![
                (0.0, Color::rgb(1.0, 0.0, 0.0)),
                (0.5, Color::rgb(0.0, 1.0, 0.0)),
                (1.0, Color::rgb(0.0, 0.0, 1.0)),
            ],
            tile,
            transform: Affine::default(),
        }
    }

    const LINE: RampShape = RampShape::Linear {
        from: Point::new(10.0, 0.0),
        to: Point::new(30.0, 0.0),
    };

    /// **Along a line**: the offset is the distance along it, the same across it, and the
    /// ends do what the tile mode says.
    #[test]
    fn a_linear_ramp_runs_along_its_line_and_tiles_past_it() {
        let clamp = ramp(LINE, TileMode::Clamp);
        assert!(close(clamp.t_at(Point::new(15.0, 0.0)), 0.25));
        assert!(
            close(clamp.t_at(Point::new(15.0, 99.0)), 0.25),
            "constant across"
        );
        assert!(close(clamp.t_at(Point::new(50.0, 0.0)), 1.0));
        let repeat = ramp(LINE, TileMode::Repeated);
        assert!(close(repeat.t_at(Point::new(35.0, 0.0)), 0.25));
        let mirror = ramp(LINE, TileMode::Mirror);
        assert!(close(mirror.t_at(Point::new(35.0, 0.0)), 0.75));
        let decal = ramp(LINE, TileMode::Decal);
        assert_eq!(
            decal.t_at(Point::new(35.0, 0.0)),
            None,
            "nothing past a decal's end"
        );
        assert_eq!(decal.color_at(Point::new(35.0, 0.0)), Color::TRANSPARENT);
    }

    /// **Between the stops**, the mix of the two either side; before and after, the end
    /// colours.
    #[test]
    fn a_ramp_mixes_the_stops_either_side() {
        let r = ramp(LINE, TileMode::Clamp);
        assert_eq!(r.sample(-1.0), Color::rgb(1.0, 0.0, 0.0));
        assert_eq!(r.sample(0.5), Color::rgb(0.0, 1.0, 0.0));
        let quarter = r.sample(0.25);
        assert!((quarter.r - 0.5).abs() < 1e-6 && (quarter.g - 0.5).abs() < 1e-6);
        assert_eq!(r.sample(2.0), Color::rgb(0.0, 0.0, 1.0));
    }

    /// **Radial**: the distance from the centre in radii, and, with a focal point off the
    /// centre, the circle through the point — nearer on the focal side.
    #[test]
    fn a_radial_ramp_runs_outward_and_bends_towards_its_focal_point() {
        let centred = ramp(
            RampShape::Radial {
                center: Point::new(0.0, 0.0),
                radius: 10.0,
                focal: Point::new(0.0, 0.0),
                focal_radius: 0.0,
            },
            TileMode::Clamp,
        );
        assert!(close(centred.t_at(Point::new(5.0, 0.0)), 0.5));
        assert!(
            close(centred.t_at(Point::new(0.0, -5.0)), 0.5),
            "the same all round"
        );
        let focal = ramp(
            RampShape::Radial {
                center: Point::new(0.0, 0.0),
                radius: 10.0,
                focal: Point::new(5.0, 0.0),
                focal_radius: 0.0,
            },
            TileMode::Clamp,
        );
        // At the focal point, the start; on the outer circle, the end, either side.
        assert!(close(focal.t_at(Point::new(5.0, 0.0)), 0.0));
        assert!(close(focal.t_at(Point::new(10.0, 0.0)), 1.0));
        assert!(close(focal.t_at(Point::new(-10.0, 0.0)), 1.0));
        // Halfway from the focal point to each side's edge is halfway through.
        assert!(close(focal.t_at(Point::new(7.5, 0.0)), 0.5));
        assert!(close(focal.t_at(Point::new(-2.5, 0.0)), 0.5));
    }

    /// **A transformed gradient is drawn exactly**: the point is mapped back into the
    /// gradient's own space, so a turned line runs the turned way.
    #[test]
    fn a_ramp_follows_its_transform() {
        let mut turned = ramp(LINE, TileMode::Clamp);
        // A quarter turn about the origin: the line now runs down the y axis.
        turned.transform = Affine::rotation(std::f32::consts::FRAC_PI_2);
        assert!(close(turned.t_at(Point::new(0.0, 15.0)), 0.25));
        assert!(
            close(turned.t_at(Point::new(40.0, 15.0)), 0.25),
            "constant across it"
        );
    }

    /// **A scaled or moved path takes its gradient with it**: the colour at a point of the
    /// moved shape is the colour the same point had before.
    #[test]
    fn a_ramp_moves_and_scales_with_its_primitive() {
        let mut scene = Scene::new();
        let shape = Path::rect(Rect::new(10.0, 0.0, 20.0, 10.0));
        scene.fill_path_ramp(&shape, ramp(LINE, TileMode::Clamp), 1.0);
        let gradient_of = |p: &Primitive| match p {
            Primitive::Path {
                gradient: Some(PathGradient::Ramp(r)),
                ..
            } => r.clone(),
            _ => panic!("a ramp"),
        };
        let before = gradient_of(&scene.primitives()[0]);
        let scaled = gradient_of(&scene.primitives()[0].scaled_xy(2.0, 3.0));
        assert!(close(
            scaled.t_at(Point::new(30.0, 6.0)),
            before.t_at(Point::new(15.0, 2.0)).unwrap()
        ));
        let moved = gradient_of(&scene.primitives()[0].translated(5.0, 7.0));
        assert!(close(moved.t_at(Point::new(20.0, 7.0)), 0.25));
    }
    use crate::{Color, Rect};

    #[test]
    fn fill_rect_pushes_primitive_with_current_clip() {
        let mut scene = Scene::new();
        assert!(scene.is_empty());
        scene.fill_rect(Rect::new(1.0, 2.0, 3.0, 4.0), Color::WHITE);
        assert_eq!(scene.len(), 1);
        assert_eq!(
            scene.primitives()[0],
            Primitive::Rect {
                rect: Rect::new(1.0, 2.0, 3.0, 4.0),
                color: Color::WHITE,
                color2: Color::WHITE,
                gradient_dir: [0.0, 0.0],
                radius: BorderRadius::ZERO,
                border_width: 0.0,
                border_color: Color::TRANSPARENT,
                blur: 0.0,
                clip: Rect::UNBOUNDED,
                owner: 0,
                shader: None,
                blur_style: crate::BlurStyle::Normal,
            }
        );
    }

    /// A gradient describes geometry, so it has to move with the geometry it
    /// describes — otherwise a fade aimed at the top of a list would stay behind when
    /// the DPI scale or a layer offset moved the shape.
    #[test]
    fn a_radial_gradient_travels_with_its_shape() {
        let mut scene = Scene::new();
        scene.fill_path_radial(
            &Path::oval(Rect::new(0.0, 0.0, 40.0, 20.0)),
            Color::WHITE,
            Color::TRANSPARENT,
            Point::new(20.0, 10.0),
            Size::new(20.0, 10.0),
            0.8,
        );
        let moved = scene.primitives()[0].clone().scaled_xy(2.0, 3.0);
        let Primitive::Path { gradient, .. } = moved.translated(5.0, 7.0) else {
            panic!("a filled path");
        };
        assert_eq!(
            gradient,
            Some(PathGradient::Radial {
                to_color: Color::TRANSPARENT,
                center: Point::new(45.0, 37.0),
                radii: Size::new(40.0, 30.0),
                // The rind is a ratio, so it is the one thing scaling must not touch.
                inner: 0.8,
            })
        );
        assert_eq!(gradient.unwrap().faded(0.5).to_color().a, 0.0);
    }

    #[test]
    fn push_faded_scales_alpha_and_keeps_owner() {
        let mut scene = Scene::new();
        scene.set_owner(42);
        scene.fill_rect(
            Rect::new(0.0, 0.0, 1.0, 1.0),
            Color::rgba(1.0, 0.0, 0.0, 1.0),
        );
        let source = scene.primitives()[0].clone();
        assert_eq!(source.owner(), 42);

        let mut target = Scene::new();
        target.push_faded(&source, 0.5);
        if let Primitive::Rect { color, owner, .. } = target.primitives()[0] {
            assert_eq!(color.a, 0.5);
            assert_eq!(owner, 42);
        } else {
            panic!("expected a rect");
        }
    }

    #[test]
    fn scaled_multiplies_geometry_not_colors() {
        let mut scene = Scene::new();
        scene.draw_rect(
            Rect::new(2.0, 4.0, 10.0, 20.0),
            Color::rgb(1.0, 0.0, 0.0),
            3.0,
            1.0,
            Color::WHITE,
        );
        scene.text(
            Point::new(5.0, 6.0),
            "hi",
            &ResolvedTextStyle::exact(18.0),
            Color::BLACK,
        );

        let big = scene.scaled(2.0);
        match &big.primitives()[0] {
            Primitive::Rect {
                rect,
                radius,
                border_width,
                color,
                ..
            } => {
                assert_eq!(*rect, Rect::new(4.0, 8.0, 20.0, 40.0));
                assert_eq!(*radius, BorderRadius::uniform(6.0));
                assert_eq!(*border_width, 2.0);
                assert_eq!(*color, Color::rgb(1.0, 0.0, 0.0)); // colour unchanged
            }
            _ => panic!("expected a rect"),
        }
        match &big.primitives()[1] {
            Primitive::Text {
                position,
                size,
                text,
                ..
            } => {
                assert_eq!(*position, Point::new(10.0, 12.0));
                assert_eq!(*size, 36.0);
                assert_eq!(text, "hi"); // text unchanged
            }
            _ => panic!("expected text"),
        }
    }

    #[test]
    fn layer_captures_subprimitives_and_opacity() {
        let mut scene = Scene::new();
        scene.set_owner(7);
        scene.set_clip(Rect::new(0.0, 0.0, 50.0, 50.0));
        scene.layer(0.5, |inner| {
            inner.fill_rect(Rect::new(0.0, 0.0, 10.0, 10.0), Color::WHITE);
            inner.fill_rect(Rect::new(5.0, 5.0, 10.0, 10.0), Color::BLACK);
        });
        assert_eq!(scene.len(), 1);
        match &scene.primitives()[0] {
            Primitive::Layer {
                primitives,
                opacity,
                clip,
                owner,
                ..
            } => {
                assert_eq!(primitives.len(), 2);
                assert_eq!(*opacity, 0.5);
                assert_eq!(*clip, Rect::new(0.0, 0.0, 50.0, 50.0));
                assert_eq!(*owner, 7);
            }
            _ => panic!("expected a layer"),
        }
    }

    #[test]
    fn fading_a_layer_scales_its_group_opacity() {
        let mut scene = Scene::new();
        scene.layer(0.8, |inner| {
            inner.fill_rect(Rect::new(0.0, 0.0, 1.0, 1.0), Color::WHITE)
        });
        let layer = scene.primitives()[0].clone();
        let mut target = Scene::new();
        target.push_faded(&layer, 0.5);
        match &target.primitives()[0] {
            Primitive::Layer { opacity, .. } => assert!((*opacity - 0.4).abs() < 1e-6),
            _ => panic!("expected a layer"),
        }
    }

    #[test]
    fn scaling_a_layer_scales_its_children() {
        let mut scene = Scene::new();
        scene.layer(1.0, |inner| {
            inner.fill_rect(Rect::new(2.0, 3.0, 4.0, 5.0), Color::WHITE)
        });
        let big = scene.scaled(2.0);
        match &big.primitives()[0] {
            Primitive::Layer { primitives, .. } => match &primitives[0] {
                Primitive::Rect { rect, .. } => assert_eq!(*rect, Rect::new(4.0, 6.0, 8.0, 10.0)),
                _ => panic!("expected a rect"),
            },
            _ => panic!("expected a layer"),
        }
    }

    #[test]
    fn set_clip_applies_to_following_primitives() {
        let mut scene = Scene::new();
        let clip = Rect::new(0.0, 0.0, 10.0, 10.0);
        scene.set_clip(clip);
        scene.fill_rect(Rect::new(0.0, 0.0, 100.0, 100.0), Color::BLACK);
        if let Primitive::Rect { clip: c, .. } = scene.primitives()[0] {
            assert_eq!(c, clip);
        } else {
            panic!("expected a rect");
        }
    }

    /// **A layer moved moves its mask** (milestone 610): a mask's geometry is held in the
    /// scene's coordinates once resolved from its box, so a layer drawn somewhere else
    /// carries it along. It was left behind, so a moved masked layer was masked where it
    /// had been.
    #[test]
    fn a_moved_layer_carries_its_mask() {
        let mask = crate::ShaderMask {
            shader: crate::MaskShader::Linear {
                from: Point::new(10.0, 0.0),
                to: Point::new(110.0, 0.0),
                from_color: Color::WHITE,
                to_color: Color::TRANSPARENT,
            },
            blend: crate::BlendMode::Modulate,
        };
        let layer = Primitive::Layer {
            primitives: Vec::new(),
            opacity: 1.0,
            clip: Rect::new(10.0, 0.0, 100.0, 20.0),
            clip_shape: ClipShape::Rect,
            transform: None,
            filter: crate::LayerFilter {
                mask: Some(mask),
                ..crate::LayerFilter::NONE
            },
            owner: 0,
        };
        let moved = layer.translated(-10.0, 5.0);
        let Primitive::Layer { filter, clip, .. } = moved else {
            unreachable!()
        };
        assert_eq!(clip, Rect::new(0.0, 5.0, 100.0, 20.0));
        let Some(crate::ShaderMask {
            shader: crate::MaskShader::Linear { from, to, .. },
            ..
        }) = filter.mask
        else {
            panic!("the mask is kept")
        };
        assert_eq!((from, to), (Point::new(0.0, 5.0), Point::new(100.0, 5.0)));
    }

    /// A bitmap only moved and scaled is one image; a turned one is drawn upright at
    /// its size on screen and turned by its layer.
    #[test]
    fn an_image_is_drawn_through_its_map() {
        let image = crate::ImageData::from_rgba(4, 2, vec![255; 32]).into_handle();
        let mut scene = Scene::new();
        scene.set_clip(Rect::new(0.0, 0.0, 500.0, 500.0));
        let placed = Affine::scale(10.0, 5.0).then(Affine::translation(30.0, 40.0));
        scene.draw_image_mapped(&image, placed, Color::WHITE);
        let Primitive::Image { rect, uv, .. } = &scene.primitives()[0] else {
            panic!("{:?}", scene.primitives()[0])
        };
        assert_eq!(*rect, Rect::new(30.0, 40.0, 40.0, 10.0));
        assert_eq!(*uv, Rect::new(0.0, 0.0, 1.0, 1.0));

        let mut scene = Scene::new();
        scene.set_clip(Rect::new(0.0, 0.0, 500.0, 500.0));
        let turned = Affine::scale(10.0, 10.0)
            .then(Affine::rotation(std::f32::consts::FRAC_PI_2))
            .then(Affine::translation(200.0, 100.0));
        scene.draw_image_mapped(&image, turned, Color::WHITE);
        let Primitive::Layer {
            primitives,
            transform: Some(transform),
            clip,
            ..
        } = &scene.primitives()[0]
        else {
            panic!("{:?}", scene.primitives()[0])
        };
        assert_eq!(*clip, Rect::new(0.0, 0.0, 500.0, 500.0), "the screen's");
        let Primitive::Image { rect, clip, .. } = &primitives[0] else {
            panic!()
        };
        assert_eq!(
            *rect,
            Rect::new(0.0, 0.0, 40.0, 20.0),
            "upright, on-screen size"
        );
        assert_eq!(*clip, *rect);
        // The flat image's far corner lands where the map sends the pixels' corner.
        let far = transform.affine.apply(Point::new(40.0, 20.0));
        let want = turned.apply(Point::new(4.0, 2.0));
        assert!(
            (far.x - want.x).abs() < 1e-3 && (far.y - want.y).abs() < 1e-3,
            "{far:?}"
        );

        let mut scene = Scene::new();
        scene.draw_image_mapped(&image, Affine::scale(0.0, 1.0), Color::WHITE);
        assert!(scene.primitives().is_empty(), "flattened to nothing");
    }
}