lievisual 0.3.3

Declarative visual scene IR + pluggable rendering backends (SVG / vello_cpu / GPU).
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
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
//! Rasterization backend based on `vello_cpu`.
//!
//! Renders a [`Scene`] into a [`crate::Pixmap`] (self-contained, non-premultiplied RGBA8),
//! which can be further exported to PNG. Internally it rasterizes through `vello_cpu` and
//! converts the result to lievisual's own bitmap type, so downstream code never needs to
//! depend on `vello_cpu` directly.
//! Text prefers the caller-provided [`text::TextLayout`]; if absent, it is laid out on the fly
//! via [`text::measure_text`].
//!
//! Notes:
//! - Filling uniformly goes through [`paint_path`](VelloPixmapRenderer::paint_path), supporting
//!   `Solid` / linear / radial / **sweep (conic)** gradient (native `peniko` `Sweep`, exact);
//!   strokes support dashes (`dash_pattern`) and `miter_limit`.
//! - Transforms are maintained with an independent stack (`push_transform` composes with the
//!   parent transform, `pop_transform` restores it), supporting nested Groups.
//! - Node / layer opacity is applied as an **isolated compositing layer** (`RenderContext::
//!   push_layer`), i.e. the alpha scales the *composited result* of the scope — matching the SVG
//!   backend's `<g opacity>` even when sub-shapes overlap.

use kurbo::{BezPath, Circle, Point as VPoint, Rect as VRect, Shape, Stroke as KurboStroke};
use vello_cpu::peniko::color::AlphaColor;
use vello_cpu::{PixelMetadata, Pixmap as VelloPixmap, RenderContext, Resources};

use crate::geometry::{Color, Point, Rect, Transform};
use crate::pixmap::Pixmap;
use crate::render::Renderer;
use crate::scene::{
    BlendMode, ColorMatrix, Fill, FillStrokeStyle, GradientSpread, GradientStop, LinearGradient,
    Scene, SketchFill, Stroke,
};
use crate::text::TextStyle;

/// vello_cpu rasterization renderer.
#[derive(Debug)]
pub struct VelloPixmapRenderer {
    ctx: RenderContext,
    resources: Resources,
    width: u32,
    height: u32,
    background: Option<Color>,
    /// Transform stack: top is the currently active composed transform.
    transform_stack: Vec<vello_cpu::kurbo::Affine>,
    /// Colour-matrix stack: the top (composed) matrix is baked into every paint colour.
    color_matrices: Vec<ColorMatrix>,
    /// Anti-aliasing stack: the top value is the active setting (`true` = anti-aliased).
    antialias_stack: Vec<bool>,
}

/// Clamp a canvas dimension (in device pixels) into vello_cpu's `1..=u16::MAX` range.
///
/// `RenderContext` / `Pixmap` both take `u16`, so an unclamped `as u16` would silently
/// truncate (e.g. 70000 → 4464) and produce a wrong-sized canvas.
fn clamp_canvas(v: f64) -> u16 {
    if !v.is_finite() || v < 1.0 {
        1
    } else {
        v.round().min(u16::MAX as f64) as u16
    }
}

/// Clamp a bitmap dimension (in pixels) into `1..=u16::MAX`.
fn clamp_px(v: f64) -> u32 {
    if !v.is_finite() || v < 1.0 {
        1
    } else {
        (v.ceil() as u32).min(u16::MAX as u32)
    }
}

impl VelloPixmapRenderer {
    /// Create a renderer with the given output canvas size (in device pixels).
    ///
    /// Sizes above `u16::MAX` are clamped (vello_cpu's canvas limit).
    pub fn new(width: u32, height: u32) -> Self {
        let w = width.min(u16::MAX as u32);
        let h = height.min(u16::MAX as u32);
        Self {
            ctx: RenderContext::new(w as u16, h as u16),
            resources: Resources::new(),
            width: w,
            height: h,
            background: None,
            transform_stack: Vec::new(),
            color_matrices: Vec::new(),
            antialias_stack: Vec::new(),
        }
    }

    /// Explicit background color; when unset, [`Scene::background`] is used.
    ///
    /// A fully transparent color (`Color::TRANSPARENT`) keeps the canvas transparent
    /// (no background is painted).
    #[must_use]
    pub fn with_background(mut self, color: Color) -> Self {
        self.background = Some(color);
        self
    }

    /// Render the scene and return a [`crate::Pixmap`] (non-premultiplied RGBA8).
    ///
    /// Reuses the same `RenderContext` / `Resources` (glyph, atlas caches persist across frames);
    /// `reset()` clears the previous frame's scene before each render, so the same renderer can
    /// render multiple frames repeatedly.
    ///
    /// The output canvas is exactly the size given at construction (["renderer size = output
    /// size"](crate::render::SvgRenderer::into_string), same as the SVG backend). The scene is
    /// mapped onto the
    /// logical viewport `输出尺寸 / scene.scale` like SVG's default
    /// `preserveAspectRatio="xMidYMid meet"` (uniform scale plus centering), then that viewport is
    /// scaled up by `scene.scale` — i.e. `scale` is a pure *density* knob, never a silent
    /// enlargement of the canvas.
    pub fn render_scene_to_pixmap(&mut self, scene: &Scene) -> Pixmap {
        // Output canvas = the size given at construction (clamped to vello_cpu's u16 range).
        //
        // Deliberately **not** multiplied by `scene.scale`: downstream (e.g. liepress) builds the
        // scene at final pixel size and passes `scene.width` straight in while also recording
        // `scene.scale = dpi / 72` as metadata — applying it here would enlarge the canvas a
        // second time. Pixel density is the caller's choice via the constructor.
        let out_w = clamp_canvas(self.width as f64);
        let out_h = clamp_canvas(self.height as f64);
        // The viewport equals the canvas, so `meet` centres the scene exactly as before and the
        // region origin is zero — this path stays bit-identical to the pre-0.3.2 implementation.
        let viewport = (f64::from(out_w), f64::from(out_h));
        self.render_frame(scene, viewport, (0.0, 0.0), out_w, out_h)
    }

    /// Render only a rectangular region of the scene and return that region's bitmap.
    ///
    /// This is the incremental-rendering entry point: only pixels inside `region` are
    /// rasterized, so a caller that owns a persistent full-frame buffer can refresh a small
    /// damaged area instead of redrawing the whole window.
    ///
    /// * `viewport` — the **full** canvas size in device pixels. It is used only to compute the
    ///   `preserveAspectRatio="xMidYMid meet"` fit, exactly like
    ///   [`Self::render_scene_to_pixmap`]. Passing the region size here would *rescale* the
    ///   scene instead of cropping it.
    /// * `origin` — top-left corner of the region inside that full canvas, in device pixels.
    ///   Should be integer-aligned: a fractional origin shifts the scene by a subpixel amount
    ///   and shows up as anti-aliasing seams along the region border.
    /// * `width` / `height` — region size in device pixels (clamped to vello_cpu's `u16` range).
    ///
    /// The returned [`crate::Pixmap`] is `width × height`, non-premultiplied RGBA8 — the same
    /// format as [`Self::render_scene_to_pixmap`] — so callers can blit it at `origin` with a
    /// straight copy. The scene background is filled across the whole region, which makes an
    /// overwrite blit correct for opaque backgrounds.
    pub fn render_scene_region(
        &mut self,
        scene: &Scene,
        viewport: (f64, f64),
        origin: (f64, f64),
        width: u16,
        height: u16,
    ) -> Pixmap {
        let out_w = clamp_canvas(f64::from(width));
        let out_h = clamp_canvas(f64::from(height));
        self.render_frame(scene, viewport, origin, out_w, out_h)
    }

    /// Shared implementation of [`Self::render_scene_to_pixmap`] and
    /// [`Self::render_scene_region`].
    ///
    /// `out_w` / `out_h` are the canvas (= returned bitmap) size, `viewport` is the reference
    /// size the `meet` fit maps the scene onto, and `origin` is the device-pixel offset of this
    /// canvas inside the full frame (subtracted last, so it never influences scaling).
    fn render_frame(
        &mut self,
        scene: &Scene,
        viewport: (f64, f64),
        origin: (f64, f64),
        out_w: u16,
        out_h: u16,
    ) -> Pixmap {
        // Clear the previous frame's scene and state (including the transform stack, to avoid
        // residue after an abnormal interruption of the previous frame).
        if self.ctx.width() != out_w || self.ctx.height() != out_h {
            self.ctx.reset_and_resize(out_w, out_h);
        } else {
            self.ctx.reset();
        }
        self.transform_stack.clear();
        self.color_matrices.clear();
        self.antialias_stack.clear();
        // Restore the default (area anti-aliased) state explicitly: `ctx.reset()` is not
        // documented to reset the aliasing threshold, and a previous frame may have left it off.
        self.ctx.set_aliasing_threshold(None);

        // Background: fall back to the scene's background (the Scene is the authoritative IR);
        // skip painting an alpha-0 background so a transparent canvas stays possible.
        let bg = self.background.unwrap_or(scene.background);
        if bg.a > 0 {
            self.ctx.set_transform(vello_cpu::kurbo::Affine::IDENTITY);
            let rect = VRect::new(0.0, 0.0, out_w as f64, out_h as f64);
            // The scene background is not subtree content: never colour-filtered.
            self.ctx.set_paint(vello_color(&bg));
            self.ctx.fill_rect(&rect);
        }

        // Scene coordinates (scene.width × scene.height) must map to the pixel coordinates of
        // the **full viewport**, with `scene.scale` acting as the pixel density — the exact
        // contract of the SVG backend, where the output size is `width/height` and the drawing
        // coordinate system is `viewBox = 输出尺寸 / scale`:
        //
        //   1. scene → viewBox (viewport/scale), via `preserveAspectRatio="xMidYMid meet"`
        //      (uniform scale + centering; scaling by width alone would overflow / crop the
        //      vertical axis whenever the aspect ratios differ).
        //   2. viewBox → device pixels, uniformly by `scale`.
        //   3. device pixels → this canvas, by subtracting `origin` (a pure translate, so the
        //      fit above stays independent of the region size).
        let density = if scene.scale.is_finite() && scene.scale > 0.0 {
            scene.scale
        } else {
            1.0
        };
        let (vw, vh) = (viewport.0 / density, viewport.1 / density);
        let (s, tx, ty) = if scene.width > 0.0 && scene.height > 0.0 {
            let s = (vw / scene.width).min(vh / scene.height);
            (
                s,
                (vw - scene.width * s) / 2.0,
                (vh - scene.height * s) / 2.0,
            )
        } else {
            (1.0, 0.0, 0.0)
        };
        let fit = vello_cpu::kurbo::Affine::new([s, 0.0, 0.0, s, tx, ty]);
        let base = vello_cpu::kurbo::Affine::translate((-origin.0, -origin.1))
            * vello_cpu::kurbo::Affine::scale(density)
            * fit;
        self.ctx.set_transform(base);
        self.transform_stack.push(base);
        // Delegate the default traversal (sorting + Group recursion + node attributes + local
        // transform).
        self.render_scene(scene);
        if self.transform_stack.pop().is_some() {
            self.ctx.set_transform(vello_cpu::kurbo::Affine::IDENTITY);
        }

        let mut vello_pixmap = VelloPixmap::new(out_w, out_h);
        self.ctx.render(&mut vello_pixmap, &mut self.resources);
        // vello 的 Pixmap 是**预乘** RGBA8;对外统一返回 lievisual 自有的**非预乘** RGBA8
        // [`crate::Pixmap`](与 PNG / SVG 内嵌及其它后端同语义),使下游无需依赖 vello_cpu。
        let data = pixmap_to_rgba8(&vello_pixmap);
        // 长度由 `pixmap_to_rgba8`(每像素恒 4 字节)与上方 `VelloPixmap::new(out_w, out_h)`
        // 构造保证,release 下不设 panic 路径:debug 断言不变式,异常时防御性回退透明底。
        let expected = u32::from(out_w) as usize * u32::from(out_h) as usize * 4;
        debug_assert_eq!(data.len(), expected, "渲染输出尺寸与像素缓冲区长度不一致");
        Pixmap::from_rgba8(u32::from(out_w), u32::from(out_h), data).unwrap_or_else(|| {
            Pixmap::from_rgba8(u32::from(out_w), u32::from(out_h), vec![0u8; expected])
                .expect("固定尺寸零缓冲区长度必然匹配")
        })
    }

    /// Render the scene and export PNG bytes (depends on the permanent `png` encoder).
    ///
    /// The PNG size equals the renderer's canvas size (see
    /// [`VelloPixmapRenderer::render_scene_to_pixmap`]); `scene.scale` is not applied.
    pub fn render_png(&mut self, scene: &Scene) -> Vec<u8> {
        self.render_scene_to_pixmap(scene).to_png()
    }

    /// Convert a lievisual color to a vello color, with the **active colour matrix baked in**.
    ///
    /// Node / layer opacity is deliberately **not** baked into the color: it is applied as an
    /// isolated compositing layer (see [`Renderer::push_opacity`]) so a scope's sub-shapes
    /// composite before the alpha is scaled — matching the SVG backend's `<g opacity>`. A colour
    /// matrix *is* baked (the SVG backend does the same), so both agree pixel for pixel; see
    /// [`crate::scene::ColorMatrix`].
    fn to_vello(&self, color: &Color) -> AlphaColor<vello_cpu::color::Srgb> {
        vello_color(&self.current_color_matrix().apply(*color))
    }

    /// The currently active scene (composed) transform: the top of the stack, or identity when
    /// no transform is applied.
    fn current_transform(&self) -> vello_cpu::kurbo::Affine {
        self.transform_stack
            .last()
            .copied()
            .unwrap_or(vello_cpu::kurbo::Affine::IDENTITY)
    }

    /// The colour matrix currently baked into paint colours (identity outside such a scope).
    fn current_color_matrix(&self) -> ColorMatrix {
        self.color_matrices
            .last()
            .copied()
            .unwrap_or(ColorMatrix::IDENTITY)
    }

    /// Set the current brush according to `Fill` (Solid / linear / radial gradient).
    ///
    /// [`Fill::Sketch`] is *not* painted here — a hand-drawn fill is pen strokes, not a brush;
    /// it goes through [`Self::paint_sketch_fill`]. This arm only exists so an accidental direct
    /// call degrades to the pen colour instead of doing nothing.
    fn set_fill(&mut self, fill: &Fill) {
        let scene_transform = self.current_transform();
        let matrix = self.current_color_matrix();
        apply_fill(&mut self.ctx, scene_transform, fill, matrix);
    }

    /// Rasterize a mask into a canvas-sized [`vello_cpu::Mask`] (device space).
    ///
    /// The mask shape/paint are drawn with the node's current transform, so the shape is in the
    /// node's local coordinates — the same space the masked content is drawn in. A new bitmap is
    /// built per masked node (masks are comparatively rare; caching is a possible optimisation).
    fn build_mask(&self, mask: &crate::scene::Mask) -> vello_cpu::Mask {
        let (w, h) = (self.ctx.width(), self.ctx.height());
        let scene_transform = self.current_transform();
        let mut ctx = RenderContext::new(w, h);
        ctx.set_transform(scene_transform);
        // A mask's paint is *scope machinery*, not subtree content: never colour-filtered.
        apply_fill(&mut ctx, scene_transform, &mask.fill, ColorMatrix::IDENTITY);
        ctx.fill_path(&mask.shape.to_bezpath());
        let mut pm = VelloPixmap::new(w, h);
        let mut resources = Resources::new();
        ctx.render(&mut pm, &mut resources);
        vello_cpu::Mask::new_alpha(&pm)
    }

    /// Unified drawing: fill (any type) + optional stroke (including dashes).
    fn paint_path(&mut self, path: &BezPath, style: &FillStrokeStyle) {
        match &style.fill {
            Some(Fill::Sketch(sf)) => self.paint_sketch_fill(path, sf),
            Some(fill) => {
                self.set_fill(fill);
                self.ctx.fill_path(path);
                // A gradient fill set a user-space paint transform; reset it after drawing.
                self.ctx.reset_paint_transform();
            }
            None => {}
        }
        if let Some(s) = &style.stroke {
            self.ctx.set_paint(self.to_vello(&s.color));
            self.ctx.set_stroke(s.to_kurbo());
            self.ctx.stroke_path(path);
        }
    }

    /// Draw a hand-drawn fill: real pen strokes (or dots) clipped to the shape.
    ///
    /// vello has no `<pattern>` equivalent, so the fill is materialised — but the naive "one clip
    /// per stroke" would open hundreds of mask layers for a single shape. Everything belonging
    /// to one element is therefore batched into **one** path under a single clip push/pop.
    fn paint_sketch_fill(&mut self, path: &BezPath, sf: &SketchFill) {
        let bbox = path.bounding_box();
        if !bbox.is_finite() || bbox.width() <= 0.0 || bbox.height() <= 0.0 {
            return;
        }
        let cap = crate::sketch::fill::HARD_CAP;
        self.ctx.set_paint(self.to_vello(&sf.color));
        self.ctx.push_clip_path(path);
        if crate::sketch::fill::is_stroke_style(sf) {
            let mut strokes = BezPath::new();
            for line in crate::sketch::fill::strokes(bbox, sf, cap) {
                let mut it = line.iter();
                if let Some(p0) = it.next() {
                    strokes.move_to(VPoint::new(p0.x, p0.y));
                    for p in it {
                        strokes.line_to(VPoint::new(p.x, p.y));
                    }
                }
            }
            if !strokes.elements().is_empty() {
                self.ctx.set_stroke(KurboStroke {
                    width: sf.weight(),
                    join: kurbo::Join::Round,
                    start_cap: kurbo::Cap::Butt,
                    end_cap: kurbo::Cap::Butt,
                    ..Default::default()
                });
                self.ctx.stroke_path(&strokes);
            }
        } else {
            let (centers, r) = crate::sketch::fill::dots(bbox, sf, cap);
            if !centers.is_empty() {
                let mut dots = BezPath::new();
                for c in centers {
                    dots.extend(Circle::new(VPoint::new(c.x, c.y), r).to_path(0.3));
                }
                self.ctx.fill_path(&dots);
            }
        }
        self.ctx.pop_clip();
    }
}

impl Renderer for VelloPixmapRenderer {
    fn draw_rect(&mut self, rect: Rect, style: &FillStrokeStyle) {
        // 统一转路径绘制,以支持渐变填充与虚线描边。
        let mut path = BezPath::new();
        path.move_to((rect.min_x(), rect.min_y()));
        path.line_to((rect.max_x(), rect.min_y()));
        path.line_to((rect.max_x(), rect.max_y()));
        path.line_to((rect.min_x(), rect.max_y()));
        path.close_path();
        self.paint_path(&path, style);
    }

    fn draw_circle(&mut self, center: Point, radius: f64, style: &FillStrokeStyle) {
        let circle = Circle::new(VPoint::new(center.x, center.y), radius);
        let path = circle.to_path(0.1);
        self.paint_path(&path, style);
    }

    fn draw_line(&mut self, start: Point, end: Point, style: &Stroke) {
        let mut path = BezPath::new();
        path.move_to(VPoint::new(start.x, start.y));
        path.line_to(VPoint::new(end.x, end.y));
        self.ctx.set_paint(self.to_vello(&style.color));
        self.ctx.set_stroke(style.to_kurbo());
        self.ctx.stroke_path(&path);
    }

    fn draw_polyline(&mut self, points: &[Point], style: &Stroke) {
        if points.len() < 2 {
            return;
        }
        let mut path = BezPath::new();
        path.move_to(VPoint::new(points[0].x, points[0].y));
        for p in &points[1..] {
            path.line_to(VPoint::new(p.x, p.y));
        }
        self.ctx.set_paint(self.to_vello(&style.color));
        self.ctx.set_stroke(style.to_kurbo());
        self.ctx.stroke_path(&path);
    }

    fn draw_path(&mut self, path: &BezPath, style: &FillStrokeStyle, closed: bool) {
        let path = if closed {
            let mut p = path.clone();
            p.close_path();
            p
        } else {
            path.clone()
        };
        self.paint_path(&path, style);
    }

    fn draw_gradient_path(
        &mut self,
        path: &BezPath,
        gradient: &LinearGradient,
        stroke: Option<&Stroke>,
    ) {
        use vello_cpu::peniko::{GradientKind, LinearGradientPosition};
        let kind = GradientKind::Linear(LinearGradientPosition::new(
            VPoint::new(gradient.start.x, gradient.start.y),
            VPoint::new(gradient.end.x, gradient.end.y),
        ));
        let scene_transform = self.current_transform();
        let matrix = self.current_color_matrix();
        set_gradient_paint(
            &mut self.ctx,
            scene_transform,
            kind,
            &gradient.stops,
            gradient.spread,
            matrix,
        );
        self.ctx.fill_path(path);
        // 渐变 fill 设置了 user-space paint transform,绘制后复位。
        self.ctx.reset_paint_transform();

        if let Some(s) = stroke {
            self.ctx.set_paint(self.to_vello(&s.color));
            self.ctx.set_stroke(s.to_kurbo());
            self.ctx.stroke_path(path);
        }
    }

    fn draw_image(&mut self, image: &crate::SceneImage, frame: Rect, opacity: f64) {
        let src = &image.pixmap;
        if src.width() == 0 || src.height() == 0 {
            return;
        }
        // 图片自身的 opacity 单独作用于此位图;节点 / 图层的 opacity 由 `push_opacity`
        // 推入的隔离层负责(不再逐图元乘 alpha)。
        let op = opacity.clamp(0.0, 1.0);
        if op <= 0.0 {
            return;
        }

        // frame 已处于 px 坐标(场景坐标即 px);直接换算到设备像素。
        let fx = frame.min_x();
        let fy = frame.min_y();
        let fw = frame.width().max(1.0);
        let fh = frame.height().max(1.0);

        // 按 object_fit 计算图片在 frame 内的实际绘制矩形(局部坐标,相对 frame 原点)。
        let iw = src.width() as f64;
        let ih = src.height() as f64;
        let (dw, dh, offx, offy) = match image.object_fit {
            crate::ObjectFit::Fill => (fw, fh, 0.0, 0.0),
            // A tile is drawn at its natural pixel size and repeated (see the blit below).
            crate::ObjectFit::None | crate::ObjectFit::Tile => (iw, ih, 0.0, 0.0),
            fit => {
                let scale = if fit == crate::ObjectFit::Cover {
                    (fw / iw).max(fh / ih)
                } else {
                    (fw / iw).min(fh / ih)
                };
                let dw = iw * scale;
                let dh = ih * scale;
                (dw, dh, (fw - dw) / 2.0, (fh - dh) / 2.0)
            }
        };

        // 画布之外的图片无需绘制:先做可见性剔除,省掉后续的大块位图分配与 blit。
        let t = self.current_transform();
        let (canvas_w, canvas_h) = (self.ctx.width() as f64, self.ctx.height() as f64);
        let corners = [
            t * VPoint::new(fx, fy),
            t * VPoint::new(fx + fw, fy),
            t * VPoint::new(fx, fy + fh),
            t * VPoint::new(fx + fw, fy + fh),
        ];
        let (min_x, max_x) = corners
            .iter()
            .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| {
                (a.min(p.x), b.max(p.x))
            });
        let (min_y, max_y) = corners
            .iter()
            .fold((f64::INFINITY, f64::NEG_INFINITY), |(a, b), p| {
                (a.min(p.y), b.max(p.y))
            });
        if max_x <= 0.0 || min_x >= canvas_w || max_y <= 0.0 || min_y >= canvas_h {
            return;
        }

        // 中间位图的像素上限:frame / dest 以场景坐标给出,乘当前变换的实际缩放
        // (|det|^0.5)折算到设备像素。极端 frame(如 65535×65535)或"极小图 + Cover"
        // 会放大出 GB 级位图,这里统一按 1/k 降采样(k=1 时行为完全不变)。
        let mag = t.determinant().abs().sqrt().max(1e-6);
        let cap = (canvas_w * canvas_h * 4.0).clamp(16.0 * 1024.0 * 1024.0, 64.0 * 1024.0 * 1024.0);
        let area = (dw * dh).max(fw * fh) * mag * mag;
        let k = if area > cap {
            (area / cap).sqrt().ceil().max(1.0)
        } else {
            1.0
        };

        // 目标帧位图(frame 大小,透明底);cover/none 时图片可能溢出 frame,
        // 用 fill_rect 的裁剪范围(frame)裁掉溢出部分,省去显式 clip。
        let frame_w = clamp_px(fw / k);
        let frame_h = clamp_px(fh / k);
        let dest_w = clamp_px(dw / k);
        let dest_h = clamp_px(dh / k);
        // 缩放源位图(RGBA8)到目标尺寸。
        let rgba = resize_rgba8(
            src.pixels(),
            src.width(),
            src.height(),
            dest_w,
            dest_h,
            image.quality,
        );

        // 应用整体 opacity:预乘到 alpha 通道(frame 透明底,src-over 合成正确)。
        // 位图以 **预乘 RGBA8 字节** 构造:vello_cpu 0.4 的 `Pixmap::from_parts` 收 `Vec<u8>`
        // (旧版收 `Vec<PremulRgba8>`),配合默认 `PixelMetadata`(已预乘 + 可能含透明)。
        let mut dest_pixels: Vec<u8> = vec![0u8; (frame_w * frame_h * 4) as usize];
        let src_pixels: Vec<[u8; 4]> = rgba
            .as_chunks::<4>()
            .0
            .iter()
            .map(|p| {
                let [r, g, b, a] = [p[0], p[1], p[2], p[3]];
                // 四舍五入而非截断,减少大批量像素上的系统性偏暗。
                let a = ((a as f64) * op).round() as u8;
                [premul(r, a), premul(g, a), premul(b, a), a]
            })
            .collect();

        // blit 到 frame 位图:`Tile` 时源按整幅图回卷(平铺),其余按 offx/offy 平移、越界即被
        // frame 裁剪。位图按 1/k 分辨率栅格化,故偏移量同样除以 k。
        let ox = (offx / k).floor() as i64;
        let oy = (offy / k).floor() as i64;
        let tile = image.object_fit == crate::ObjectFit::Tile;
        for row in 0..(frame_h as i64) {
            for col in 0..(frame_w as i64) {
                let (sx, sy) = if tile {
                    (
                        (col - ox).rem_euclid(dest_w as i64),
                        (row - oy).rem_euclid(dest_h as i64),
                    )
                } else {
                    let (sx, sy) = (col - ox, row - oy);
                    if sx < 0 || sx >= dest_w as i64 || sy < 0 || sy >= dest_h as i64 {
                        continue;
                    }
                    (sx, sy)
                };
                let sidx = (sy * dest_w as i64 + sx) as usize;
                let didx = (row * frame_w as i64 + col) as usize * 4;
                dest_pixels[didx..didx + 4].copy_from_slice(&src_pixels[sidx]);
            }
        }

        let dest_pixmap = VelloPixmap::from_parts(
            dest_pixels,
            frame_w as u16,
            frame_h as u16,
            // 显式声明预乘 + 可能含透明,不信任上游 default 的变动(此处位图由上方手工预乘)。
            PixelMetadata::new(vello_cpu::peniko::ImageAlphaType::AlphaPremultiplied, true),
        );
        let brush = vello_cpu::Image {
            image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(dest_pixmap)),
            sampler: vello_cpu::peniko::ImageSampler::default(),
        };
        self.ctx.set_paint(brush);
        // Image paint 以 pixmap 像素坐标 (0,0) 起始绘制;用 paint transform 把它平移到
        // frame 原点(frame 大小即为裁剪框)。位图按 1/k 分辨率栅格化,故再放大 k 倍
        // 铺回原尺寸的 frame(k=1 时等价于纯平移)。
        let rect = VRect::new(fx, fy, fx + fw, fy + fh);
        self.ctx.set_paint_transform(
            vello_cpu::kurbo::Affine::translate((fx, fy)) * vello_cpu::kurbo::Affine::scale(k),
        );
        self.ctx.fill_rect(&rect);
        self.ctx.reset_paint_transform();
    }

    fn draw_text(
        &mut self,
        spans: &[crate::text::RichSpan],
        position: Point,
        style: &TextStyle,
        layout: Option<&crate::text::TextLayout>,
    ) {
        use vello_cpu::kurbo::Affine;

        // 优先使用调用者提供的 layout(直接借用,避免整体克隆);否则经统一
        // TLS 上下文现场排版(layout_text)持有临时 layout。
        let owned_layout;
        let layout = match layout {
            Some(l) => l,
            None => {
                owned_layout = crate::text::layout_text(spans, style.max_width);
                &owned_layout
            }
        };

        // 局部变换:若节点带 transform,已由 push_transform 处理;这里仅处理文本自身旋转。
        // 锚点语义(canvas fillText):把文本块在局部坐标中平移 (dx, dy),使锚点落在
        // position。dx 由 align(水平),dy 由 baseline(垂直)决定;旋转绕锚点。
        let m = crate::text::layout_metrics(layout);
        let dx = match style.align {
            crate::text::TextAlign::Left | crate::text::TextAlign::Justify => 0.0,
            crate::text::TextAlign::Center => -m.width / 2.0,
            crate::text::TextAlign::Right => -m.width,
        };
        let dy = -style.baseline.anchor_offset(&m) - style.baseline_shift;
        let transform = Affine::translate((position.x, position.y))
            * Affine::rotate(style.rotation)
            * Affine::translate((dx, dy));

        // 文本背景(行内高亮):在 layout 局部坐标 [0,0]×[w,h] 画矩形,经 transform
        // 映射到节点坐标,与 glyph 精确定位一致。注意:背景在 push 文本变换**之前**
        // 绘制——bg_rect 已手工变换到场景坐标,且 draw_rect 内部还会应用当前 ctx
        // transform,提前 push 会双重施加。
        if let Some(bg) = style.background_color {
            // kurbo Affine 不支持直接乘 Rect,手动变换对角点得 AABB。
            let p0 = transform * VPoint::new(0.0, 0.0);
            let p1 = transform * VPoint::new(m.width, m.height);
            let bg_rect = Rect::from_points(p0, p1);
            let style = crate::scene::FillStrokeStyle::fill(bg);
            self.draw_rect(bg_rect, &style);
        }

        // 文本块变换(旋转绕锚点 + align/baseline 锚点平移)必须作为**整个 glyph run
        // 的 scene transform**经 `set_transform` 生效,与 Group 的 push_transform
        // 同构(与父变换复合后入栈,画完 pop 恢复)。
        //
        // 历史坑:曾把该变换传给 glifo 的 `glyph_transform`——那是**逐字形**、在
        // glyph 定位之后才施加的 transform(官方用途仅为 skew 伪造斜体,见
        // `DrawProps::positioned_transform`:位置只过 run transform 的线性部分,
        // 轮廓过 run*glyph 全量)。于是每个字符绕**自身**位置旋转、字符间的相对
        // 位置却不旋转,表现为"PNG 里单个字符旋转",而 SVG 的
        // `<text transform="rotate(...)">` 是整体旋转——两端不一致。
        let combined = match self.transform_stack.last() {
            Some(parent) => *parent * transform,
            None => transform,
        };
        self.ctx.set_transform(combined);
        self.transform_stack.push(combined);

        for line in &layout.lines {
            for run in &line.runs {
                let glyphs: Vec<vello_cpu::Glyph> = run
                    .glyphs
                    .iter()
                    .map(|g| vello_cpu::Glyph {
                        id: g.id,
                        x: g.x,
                        y: g.y,
                    })
                    .collect();
                if glyphs.is_empty() {
                    continue;
                }

                // 从自闭环的字体字节构造 vello 字体(与 parley/vello 共享同一 peniko FontData)。
                let font_data = vello_cpu::peniko::FontData::new(
                    vello_cpu::peniko::Blob::from(run.font_data.as_ref().clone()),
                    0,
                );
                self.ctx.set_paint(self.to_vello(&run.color));
                // vello_cpu 0.4:`fill_glyphs` 返回 `Result`——个别字形失败时为 Err,
                // 但其余字形仍会绘制;这里按"尽力绘制"处理,忽略错误。
                let _ = self
                    .ctx
                    .glyph_run(&mut self.resources, &font_data)
                    .font_size(run.font_size)
                    .fill_glyphs(glyphs.into_iter());
            }
        }

        self.pop_transform();
    }

    fn push_transform(&mut self, t: Transform) {
        use vello_cpu::kurbo::Affine;
        let a = Affine::new([t.a, t.b, t.c, t.d, t.e, t.f]);
        let combined = match self.transform_stack.last() {
            Some(parent) => *parent * a,
            None => a,
        };
        self.ctx.set_transform(combined);
        self.transform_stack.push(combined);
    }

    fn pop_transform(&mut self) {
        self.transform_stack.pop();
        match self.transform_stack.last() {
            Some(t) => self.ctx.set_transform(*t),
            None => self.ctx.set_transform(vello_cpu::kurbo::Affine::IDENTITY),
        }
    }

    fn push_opacity(&mut self, opacity: f64) {
        // Isolated layer: the alpha scales the *composited result* of the scope, so a node /
        // layer with overlapping children matches SVG's `<g opacity>` (the previous
        // per-primitive alpha multiplication darkened overlaps).
        self.ctx
            .push_layer(None, None, Some(opacity.clamp(0.0, 1.0) as f32), None, None);
    }

    fn pop_opacity(&mut self) {
        self.ctx.pop_layer();
    }

    fn push_blend(&mut self, mode: BlendMode) {
        // Isolated blend layer: the scope's content is composited with the backdrop using `mode`
        // (matching SVG `mix-blend-mode`).
        self.ctx
            .push_layer(None, Some(to_peniko_blend(mode)), None, None, None);
    }

    fn pop_blend(&mut self) {
        self.ctx.pop_layer();
    }

    fn push_mask(&mut self, mask: &crate::scene::Mask) {
        // The mask is a canvas-sized alpha bitmap applied when compositing the layer.
        let m = self.build_mask(mask);
        self.ctx.push_layer(None, None, None, Some(m), None);
    }

    fn pop_mask(&mut self) {
        self.ctx.pop_layer();
    }

    fn push_filter(&mut self, filter: &crate::scene::Filter) {
        self.ctx
            .push_layer(None, None, None, None, Some(to_vello_filter(filter)));
    }

    fn pop_filter(&mut self) {
        self.ctx.pop_layer();
    }

    fn push_color_matrix(&mut self, matrix: ColorMatrix) {
        // Compose with the enclosing scope: a child's matrix is applied to the raw colours, its
        // ancestors' afterwards (matching the SVG backend).
        let composed = match self.color_matrices.last() {
            Some(outer) => matrix.then(*outer),
            None => matrix,
        };
        self.color_matrices.push(composed);
    }

    fn pop_color_matrix(&mut self) {
        self.color_matrices.pop();
    }

    fn push_antialias(&mut self, enabled: bool) {
        self.antialias_stack.push(enabled);
        // vello: `None` = area (anti-aliased) coverage, `Some(threshold)` = binary coverage.
        self.ctx
            .set_aliasing_threshold(if enabled { None } else { Some(0) });
    }

    fn pop_antialias(&mut self) {
        self.antialias_stack.pop();
        let enabled = self.antialias_stack.last().copied().unwrap_or(true);
        self.ctx
            .set_aliasing_threshold(if enabled { None } else { Some(0) });
    }

    fn push_clip(&mut self, clip: &crate::scene::Clip) {
        // vello_cpu 的 clip 路径按当前 transform(clip_path_transform)应用;
        // 我们 push_transform 已设置 ctx transform,故 clip 与节点变换一致复合。
        let path = clip.to_bezpath();
        self.ctx.push_clip_path(&path);
    }

    fn pop_clip(&mut self) {
        self.ctx.pop_clip();
    }
}

/// 预乘 alpha 的分量还原为直通(非预乘)分量:`c = premul_c * 255 / a`(四舍五入)。
///
/// vello 的 `Pixmap` 保存的是 **预乘** alpha 像素,而 PNG(以及本 crate 的
/// [`crate::Pixmap`] RGBA8 约定)使用非预乘 alpha:直接把预乘值写进 PNG 会让所有
/// alpha<255 的像素(抗锯齿边缘、半透明填充、文字边缘)整体偏暗。
fn unpremultiply(c: u8, a: u8) -> u8 {
    if a == 0 {
        0
    } else if a == 255 {
        c
    } else {
        (((c as u32 * 255) + (a as u32 / 2)) / a as u32).min(255) as u8
    }
}

/// Convert a lievisual color to a vello color (channels used as-is; node / layer opacity is a
/// separate compositing-layer concern, never baked into the color).
fn vello_color(c: &Color) -> AlphaColor<vello_cpu::color::Srgb> {
    AlphaColor::from_rgba8(c.r, c.g, c.b, c.a)
}

/// Build peniko color stops from lievisual gradient stops, baking `matrix` into each stop.
fn peniko_stops(stops: &[GradientStop], matrix: ColorMatrix) -> Vec<vello_cpu::peniko::ColorStop> {
    stops
        .iter()
        .map(|s| vello_cpu::peniko::ColorStop {
            offset: s.offset as f32,
            color: vello_cpu::peniko::color::DynamicColor::from_alpha_color(vello_color(
                &matrix.apply(s.color),
            )),
        })
        .collect()
}

/// Map a lievisual spread mode to peniko's `Extend`.
fn to_peniko_extend(spread: GradientSpread) -> vello_cpu::peniko::Extend {
    use vello_cpu::peniko::Extend;
    match spread {
        GradientSpread::Pad => Extend::Pad,
        GradientSpread::Repeat => Extend::Repeat,
        GradientSpread::Reflect => Extend::Reflect,
    }
}

/// Set a gradient paint on `ctx`, keeping gradient coordinates in user space by cancelling the
/// scene transform (mirrors SVG `gradientUnits="userSpaceOnUse"`). A singular scene transform
/// (det = 0) has no meaningful inverse, so identity is used (the gradient follows the shape).
fn set_gradient_paint(
    ctx: &mut RenderContext,
    scene_transform: vello_cpu::kurbo::Affine,
    kind: vello_cpu::peniko::GradientKind,
    stops: &[GradientStop],
    spread: GradientSpread,
    matrix: ColorMatrix,
) {
    use vello_cpu::peniko::{
        ColorStops, Gradient, InterpolationAlphaSpace, color::ColorSpaceTag, color::HueDirection,
    };
    let stops_vec = peniko_stops(stops, matrix);
    let gradient = Gradient {
        kind,
        extend: to_peniko_extend(spread),
        interpolation_cs: ColorSpaceTag::Srgb,
        hue_direction: HueDirection::default(),
        // 直通(非预乘)alpha 插值:与 SVG `<stop>` 的规范语义及 `scene::sample_stops`(IR 端
        // sweep 楔形采样)一致。默认的 `Premultiplied` 会让半透明 stop 在两后端产生色差。
        interpolation_alpha_space: InterpolationAlphaSpace::Unpremultiplied,
        stops: ColorStops::from(stops_vec.as_slice()),
    };
    if scene_transform.determinant().abs() > 1e-12 {
        ctx.set_paint_transform(scene_transform.inverse());
    } else {
        ctx.set_paint_transform(vello_cpu::kurbo::Affine::IDENTITY);
    }
    ctx.set_paint(gradient);
}

/// Set `fill` as the paint on `ctx` (solid / linear / radial / sweep gradient), with user-space
/// gradient coordinates. Sketch fills degrade to their pen colour (they are drawn as strokes
/// elsewhere).
fn apply_fill(
    ctx: &mut RenderContext,
    scene_transform: vello_cpu::kurbo::Affine,
    fill: &Fill,
    matrix: ColorMatrix,
) {
    use vello_cpu::peniko::{
        GradientKind, LinearGradientPosition, RadialGradientPosition, SweepGradientPosition,
    };
    match fill {
        Fill::Solid(c) => ctx.set_paint(vello_color(&matrix.apply(*c))),
        Fill::LinearGradient(g) => {
            let kind = GradientKind::Linear(LinearGradientPosition::new(
                VPoint::new(g.start.x, g.start.y),
                VPoint::new(g.end.x, g.end.y),
            ));
            set_gradient_paint(ctx, scene_transform, kind, &g.stops, g.spread, matrix);
        }
        Fill::RadialGradient(g) => {
            let kind = GradientKind::Radial(RadialGradientPosition::new(
                VPoint::new(g.center.x, g.center.y),
                g.radius as f32,
            ));
            set_gradient_paint(ctx, scene_transform, kind, &g.stops, g.spread, matrix);
        }
        Fill::SweepGradient(g) => {
            let kind = GradientKind::Sweep(SweepGradientPosition::new(
                VPoint::new(g.center.x, g.center.y),
                g.start_angle as f32,
                g.end_angle as f32,
            ));
            set_gradient_paint(ctx, scene_transform, kind, &g.stops, g.spread, matrix);
        }
        Fill::Sketch(sf) => ctx.set_paint(vello_color(&matrix.apply(sf.color))),
        Fill::Image(f) => {
            if f.image.width() == 0 || f.image.height() == 0 {
                return;
            }
            use vello_cpu::peniko::{Extend, ImageSampler};
            let (iw, ih) = (f.image.width() as f64, f.image.height() as f64);
            let brush = vello_cpu::Image {
                image: vello_cpu::ImageSource::Pixmap(std::sync::Arc::new(pixmap_to_premul(
                    &f.image,
                ))),
                // The tile repeats across the shape.
                sampler: ImageSampler {
                    x_extend: Extend::Repeat,
                    y_extend: Extend::Repeat,
                    ..Default::default()
                },
            };
            // `tile` is one cell in user space: map user space back to image pixels, then cancel
            // the scene transform (the same convention as the gradients above).
            let sx = if f.tile.width().abs() > 1e-12 {
                f.tile.width() / iw
            } else {
                1.0
            };
            let sy = if f.tile.height().abs() > 1e-12 {
                f.tile.height() / ih
            } else {
                1.0
            };
            let user_to_image =
                vello_cpu::kurbo::Affine::translate((-f.tile.min_x(), -f.tile.min_y()))
                    * vello_cpu::kurbo::Affine::scale_non_uniform(1.0 / sx, 1.0 / sy);
            let to_paint = if scene_transform.determinant().abs() > 1e-12 {
                user_to_image * scene_transform.inverse()
            } else {
                user_to_image
            };
            ctx.set_paint_transform(to_paint);
            ctx.set_paint(brush);
        }
    }
}

/// Map a lievisual [`Filter`](crate::scene::Filter) to a vello filter (a single primitive;
/// vello's filter graphs are not yet implemented).
fn to_vello_filter(filter: &crate::scene::Filter) -> vello_cpu::filter_effects::Filter {
    use vello_cpu::filter_effects::{Filter as VFilter, FilterFunction, FilterPrimitive};
    match filter {
        crate::scene::Filter::Blur { std_dev } => VFilter::from_function(FilterFunction::Blur {
            radius: *std_dev as f32,
        }),
        crate::scene::Filter::DropShadow {
            dx,
            dy,
            std_dev,
            color,
        } => VFilter::from_primitive(FilterPrimitive::DropShadow {
            dx: *dx as f32,
            dy: *dy as f32,
            std_deviation: *std_dev as f32,
            color: vello_color(color),
            edge_mode: Default::default(),
        }),
    }
}

/// Map a lievisual [`BlendMode`] to peniko's blend mode (mix function + `SrcOver` composition).
fn to_peniko_blend(mode: BlendMode) -> vello_cpu::peniko::BlendMode {
    use vello_cpu::peniko::{BlendMode as PenikoBlend, Compose, Mix};
    let mix = match mode {
        BlendMode::Normal => Mix::Normal,
        BlendMode::Multiply => Mix::Multiply,
        BlendMode::Screen => Mix::Screen,
        BlendMode::Overlay => Mix::Overlay,
        BlendMode::Darken => Mix::Darken,
        BlendMode::Lighten => Mix::Lighten,
        BlendMode::ColorDodge => Mix::ColorDodge,
        BlendMode::ColorBurn => Mix::ColorBurn,
        BlendMode::HardLight => Mix::HardLight,
        BlendMode::SoftLight => Mix::SoftLight,
        BlendMode::Difference => Mix::Difference,
        BlendMode::Exclusion => Mix::Exclusion,
        BlendMode::Hue => Mix::Hue,
        BlendMode::Saturation => Mix::Saturation,
        BlendMode::Color => Mix::Color,
        BlendMode::Luminosity => Mix::Luminosity,
        // Porter-Duff ops use the identity mix (`Normal`) plus a compose function.
        _ => Mix::Normal,
    };
    let compose = match mode {
        BlendMode::Clear => Compose::Clear,
        BlendMode::Copy => Compose::Copy,
        BlendMode::Dest => Compose::Dest,
        BlendMode::DestOver => Compose::DestOver,
        BlendMode::SrcIn => Compose::SrcIn,
        BlendMode::DestIn => Compose::DestIn,
        BlendMode::SrcOut => Compose::SrcOut,
        BlendMode::DestOut => Compose::DestOut,
        BlendMode::SrcAtop => Compose::SrcAtop,
        BlendMode::DestAtop => Compose::DestAtop,
        BlendMode::Xor => Compose::Xor,
        BlendMode::Plus => Compose::Plus,
        BlendMode::PlusLighter => Compose::PlusLighter,
        _ => Compose::SrcOver,
    };
    PenikoBlend::new(mix, compose)
}

/// vello 预乘 Pixmap → 非预乘 RGBA8 字节。
fn pixmap_to_rgba8(pixmap: &VelloPixmap) -> Vec<u8> {
    let mut data = Vec::with_capacity(pixmap.data().len() * 4);
    for p in pixmap.data() {
        data.extend_from_slice(&[
            unpremultiply(p.r, p.a),
            unpremultiply(p.g, p.a),
            unpremultiply(p.b, p.a),
            p.a,
        ]);
    }
    data
}

/// 通道值按 alpha 预乘(`c * a / 255`,四舍五入)。
fn premul(c: u8, a: u8) -> u8 {
    ((c as u32 * a as u32 + 127) / 255).min(255) as u8
}

/// 直通 RGBA8 → vello 预乘 `Pixmap`(图片填充用;`draw_image` 走自己的缩放/blit 路径)。
fn pixmap_to_premul(pm: &crate::Pixmap) -> VelloPixmap {
    let mut bytes = Vec::with_capacity(pm.pixels().len());
    for p in pm.pixels().as_chunks::<4>().0 {
        let a = p[3];
        bytes.extend_from_slice(&[premul(p[0], a), premul(p[1], a), premul(p[2], a), a]);
    }
    VelloPixmap::from_parts(
        bytes,
        pm.width().min(u32::from(u16::MAX)) as u16,
        pm.height().min(u32::from(u16::MAX)) as u16,
        // 显式声明预乘 + 可能含透明(上方逐像素 `premul` 过)。
        PixelMetadata::new(vello_cpu::peniko::ImageAlphaType::AlphaPremultiplied, true),
    )
}

/// 按 [`ImageQuality`](crate::scene::ImageQuality) 把 RGBA8 从 `sw×sh` 缩放到 `dw×dh`。
///
/// **可分离**滤波:先水平方向到预乘 `f32` 缓冲,再垂直方向回直通 RGBA8。插值在 **预乘**
/// 空间进行 —— 直通 RGBA 直接插值会让半透明像素与透明像素混合出偏暗的边缘(halo)。
///
/// `Nearest` 取最近像素;`Bilinear` 用三角核;`Bicubic` 用 Catmull-Rom(a = -0.5)。缩小时核
/// 会按比例加宽(`filter_scale`)退化为预滤波 —— 而单纯 2 抽头双线性缩小会产生明显锯齿。
/// 落在源之外的抽头按边缘像素钳制(edge extend)。
fn resize_rgba8(
    src: &[u8],
    sw: u32,
    sh: u32,
    dw: u32,
    dh: u32,
    quality: crate::scene::ImageQuality,
) -> Vec<u8> {
    if sw == dw && sh == dh {
        return src.to_vec();
    }
    if sw == 0 || sh == 0 || dw == 0 || dh == 0 {
        return vec![0u8; (dw as usize) * (dh as usize) * 4];
    }
    let xs = axis_weights(quality, sw, dw);
    let ys = axis_weights(quality, sh, dh);

    // 水平:src → 预乘 f32(dw × sh)。
    let mut tmp = vec![0.0f32; (dw as usize) * (sh as usize) * 4];
    for y in 0..sh {
        let row = (y * sw) as usize * 4;
        for (dx, (first, w)) in xs.iter().enumerate() {
            let mut acc = [0.0f32; 4];
            for (i, wi) in w.iter().enumerate() {
                let sx = (*first + i as i64).clamp(0, i64::from(sw) - 1) as usize;
                let p = &src[row + sx * 4..row + sx * 4 + 4];
                let a = f32::from(p[3]) / 255.0;
                let wf = *wi as f32;
                acc[0] += wf * f32::from(p[0]) * a;
                acc[1] += wf * f32::from(p[1]) * a;
                acc[2] += wf * f32::from(p[2]) * a;
                acc[3] += wf * f32::from(p[3]);
            }
            let o = (y as usize * dw as usize + dx) * 4;
            tmp[o..o + 4].copy_from_slice(&acc);
        }
    }

    // 垂直:预乘 f32 → 直通 RGBA8。
    let mut out = vec![0u8; (dw as usize) * (dh as usize) * 4];
    for (dy, (first, w)) in ys.iter().enumerate() {
        for x in 0..dw as usize {
            let mut acc = [0.0f32; 4];
            for (i, wi) in w.iter().enumerate() {
                let sy = (*first + i as i64).clamp(0, i64::from(sh) - 1) as usize;
                let o = (sy * dw as usize + x) * 4;
                let wf = *wi as f32;
                for c in 0..4 {
                    acc[c] += wf * tmp[o + c];
                }
            }
            let a = acc[3].round().clamp(0.0, 255.0) as u8;
            let o = (dy * dw as usize + x) * 4;
            for c in 0..3 {
                out[o + c] = unpremultiply(acc[c].round().clamp(0.0, 255.0) as u8, a);
            }
            out[o + 3] = a;
        }
    }
    out
}

/// One axis of a separable resample: for each output index, the source index its taps start at
/// plus the (normalized) weights.
fn axis_weights(
    quality: crate::scene::ImageQuality,
    src_len: u32,
    dst_len: u32,
) -> Vec<(i64, Vec<f64>)> {
    use crate::scene::ImageQuality;
    let scale = f64::from(src_len) / f64::from(dst_len);
    (0..dst_len)
        .map(|d| {
            let center = (f64::from(d) + 0.5) * scale - 0.5;
            // Nearest ignores the scale: take the pixel the centre falls in (same as SVG's
            // `image-rendering="pixelated"`), so it stays blocky even when shrinking.
            if quality == ImageQuality::Nearest {
                return (center.round() as i64, vec![1.0]);
            }
            // Widening the kernel while minifying turns it into a prefilter.
            let filter_scale = scale.max(1.0);
            let support = if quality == ImageQuality::Bilinear {
                1.0
            } else {
                2.0
            };
            let radius = support * filter_scale;
            let first = (center - radius).ceil() as i64;
            let last = (center + radius).floor() as i64;
            let mut w: Vec<f64> = (first..=last)
                .map(|i| resample_kernel(quality, (i as f64 - center) / filter_scale))
                .collect();
            let sum: f64 = w.iter().sum();
            if sum != 0.0 {
                for v in &mut w {
                    *v /= sum;
                }
            }
            (first, w)
        })
        .collect()
}

/// The 1D reconstruction kernel: box (nearest), triangle (bilinear), Catmull-Rom (bicubic).
fn resample_kernel(quality: crate::scene::ImageQuality, t: f64) -> f64 {
    use crate::scene::ImageQuality;
    let x = t.abs();
    match quality {
        ImageQuality::Nearest => f64::from(x <= 0.5),
        ImageQuality::Bilinear => (1.0 - x).max(0.0),
        // Catmull-Rom with a = -0.5 — the "bicubic" image scalers use.
        ImageQuality::Bicubic => {
            if x < 1.0 {
                1.5 * x * x * x - 2.5 * x * x + 1.0
            } else if x < 2.0 {
                -0.5 * x * x * x + 2.5 * x * x - 4.0 * x + 2.0
            } else {
                0.0
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::{Color, Point, Rect, Transform};
    use crate::scene::{
        BlendMode, Clip, ColorMatrix, Element, FillStrokeStyle, Filter, GradientSpread,
        GradientStop, LinearGradient, Scene, SceneNode, SketchFillStyle, SweepGradient,
    };

    /// 提取 pixmap 像素为 RGBA u8 数组(非预乘,用于比较)。
    fn pixels(pixmap: &Pixmap) -> Vec<u8> {
        pixmap.pixels().to_vec()
    }

    /// 覆盖 transform / opacity / clip(圆角)/ 圆角图元 / 半透明的 120×90 场景,
    /// 用于 `render_scene_region` 与全窗渲染的一致性比较。
    ///
    /// 布局:圆角矩形占左上(x 6..60,含 translate(3,2));裁剪组 clip 到 (20,20)-(80,60),
    /// 其子矩形却延伸到 (110,70) → 右侧被裁掉,`x >= 84` 整列无内容。
    fn scope_rich_scene() -> Scene {
        let mut scene = Scene::new(120.0, 90.0).with_background(Color::rgb(0x10, 0x18, 0x20));

        let translucent = SceneNode::new(Element::rounded_rect(
            Rect::new(6.0, 6.0, 60.0, 40.0),
            9.0,
            FillStrokeStyle::fill(Color::rgba(0xd0, 0x40, 0x30, 0x9a)),
        ))
        .with_transform(Transform::translate(3.0, 2.0));

        let overflowing = SceneNode::new(Element::rect(
            Rect::new(20.0, 20.0, 110.0, 70.0),
            FillStrokeStyle::fill(Color::rgba(0x30, 0x90, 0xe0, 0xcc)),
        ));
        let clipped = SceneNode::group(vec![overflowing])
            .with_clip(Clip::rounded_rect(Rect::new(20.0, 20.0, 80.0, 60.0), 6.0))
            .with_opacity(0.7);

        scene.push_node(translucent);
        scene.push_node(clipped);
        scene
    }

    /// region == 全窗 ⇒ 与 `render_scene_to_pixmap` **逐字节相等**。
    ///
    /// 这是补丁的核心不变量:`origin = (0,0)`、`viewport = 画布尺寸` 时必须完全退化回原实现。
    #[test]
    fn region_equal_to_the_full_canvas_is_bit_identical() {
        let scene = scope_rich_scene();
        let mut renderer = VelloPixmapRenderer::new(120, 90);

        let full = pixels(&renderer.render_scene_to_pixmap(&scene));
        let region = renderer.render_scene_region(&scene, (120.0, 90.0), (0.0, 0.0), 120, 90);

        assert_eq!((region.width(), region.height()), (120, 90));
        assert_eq!(full, pixels(&region));
    }

    /// 子矩形 ⇒ 与全窗渲染的同一区域 **逐像素相等**(整数 origin,不缩放、不偏移)。
    #[test]
    fn region_matches_the_same_area_of_the_full_canvas() {
        let scene = scope_rich_scene();
        let (w, h) = (120u32, 90u32);
        let (ox, oy, rw, rh) = (17u16, 11u16, 43u16, 29u16);

        let mut renderer = VelloPixmapRenderer::new(w, h);
        let full = pixels(&renderer.render_scene_to_pixmap(&scene));
        let region = renderer.render_scene_region(
            &scene,
            (f64::from(w), f64::from(h)),
            (f64::from(ox), f64::from(oy)),
            rw,
            rh,
        );

        assert_eq!(
            (region.width(), region.height()),
            (u32::from(rw), u32::from(rh))
        );
        let patch = pixels(&region);

        // 面积抗锯齿的覆盖率量化依赖画布分块,因此把小画布的结果与全窗结果逐像素比较时,
        // AA 边缘偶尔差 1 个 LSB(实测仅此一档)。偏移 / 缩放 / fit 复刻错误会产生几十以上
        // 的差异,所以 1 LSB 的容差仍能抓住真正的 bug,同时不屏蔽实现细节。
        let mut worst = 0u8;
        let mut worst_at = (0usize, 0usize);
        for y in 0..usize::from(rh) {
            for x in 0..usize::from(rw) {
                let src = ((usize::from(oy) + y) * w as usize + usize::from(ox) + x) * 4;
                let dst = (y * usize::from(rw) + x) * 4;
                for c in 0..4 {
                    let diff = full[src + c].abs_diff(patch[dst + c]);
                    if diff > worst {
                        worst = diff;
                        worst_at = (x, y);
                    }
                }
            }
        }
        assert!(
            worst <= 1,
            "region pixel {worst_at:?} differs by {worst} (>1 LSB) from the full-canvas render"
        );
    }

    /// 背景覆盖整个 region:内容全在 region 之外时,输出应全是背景色。
    ///
    /// 验证"背景按 region 尺寸填充"与"origin 只做平移"——任一处写错都会露出黑色或错位。
    #[test]
    fn region_paints_the_scene_background_across_the_whole_region() {
        let mut scene = Scene::new(120.0, 90.0).with_background(Color::rgb(0x20, 0x40, 0x60));
        scene.push(Element::rect(
            Rect::new(2.0, 2.0, 10.0, 10.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ));

        let mut renderer = VelloPixmapRenderer::new(120, 90);
        let region = renderer.render_scene_region(&scene, (120.0, 90.0), (60.0, 40.0), 40, 30);

        assert_eq!((region.width(), region.height()), (40, 30));
        let patch = pixels(&region);
        for (i, px) in patch.as_chunks::<4>().0.iter().enumerate() {
            assert_eq!(
                px,
                &[0x20, 0x40, 0x60, 0xff],
                "region pixel {i} is not the background"
            );
        }
    }

    /// scope 不被绕过:clip 之外的区域只剩背景(region 渲染必须走完整的 scope 栈)。
    #[test]
    fn region_respects_clip_and_opacity() {
        let scene = scope_rich_scene();
        let mut renderer = VelloPixmapRenderer::new(120, 90);

        // 裁剪框右边界 x=80,圆角矩形右缘 60+3=63 ⇒ (84, 4)-(104, 24) 内无任何内容
        let region = renderer.render_scene_region(&scene, (120.0, 90.0), (84.0, 4.0), 20, 20);

        let patch = pixels(&region);
        for (i, px) in patch.as_chunks::<4>().0.iter().enumerate() {
            assert_eq!(
                px,
                &[0x10, 0x18, 0x20, 0xff],
                "region pixel {i} outside the clip is not background"
            );
        }
    }

    /// 渲染并解码为 RGBA8(走 render_png 全链路,覆盖 PNG 编码)。
    fn render_png_pixels(renderer: &mut VelloPixmapRenderer, scene: &Scene) -> (u32, u32, Vec<u8>) {
        let png = renderer.render_png(scene);
        let pm = crate::Pixmap::decode_png(&png).expect("PNG 解码失败");
        (pm.width(), pm.height(), pm.pixels().to_vec())
    }

    /// 一个横跨矩形、左右颜色差异明显的线性渐变矩形。
    /// `rect` 为矩形坐标;`t` 为节点局部变换(None = 无)。
    fn gradient_rect_scene(rect: Rect, t: Option<Transform>) -> Scene {
        let grad = LinearGradient::new(
            Point::new(10.0, 10.0),
            Point::new(90.0, 10.0),
            vec![
                GradientStop {
                    offset: 0.0,
                    color: Color::rgb(0xff, 0x00, 0x00),
                },
                GradientStop {
                    offset: 1.0,
                    color: Color::rgb(0x00, 0x00, 0xff),
                },
            ],
        );
        let style = FillStrokeStyle {
            fill: Some(grad.into()),
            stroke: None,
        };
        let mut scene = Scene::new(100.0, 100.0);
        let node = SceneNode::new(Element::rect(rect, style));
        scene.push_node(match t {
            Some(t) => node.with_transform(t),
            None => node,
        });
        scene
    }

    /// Bug 1 回归:渐变坐标为用户(根)空间,不受节点局部 transform 影响。
    ///
    /// 场景 A:矩形直接画在 (10,10),无变换,渐变轴 (10,10)->(90,10)。
    /// 场景 B:矩形在 (0,0),节点 transform=translate(10,10),渐变轴仍 (10,10)->(90,10)。
    /// 两者在屏幕上完全一致(图形位置、渐变轴都相同)→ 像素应相同。
    /// 修复前渐变会随 transform 平移,B 的渐变轴变为相对图形偏移,像素不同。
    #[test]
    fn gradient_stays_in_user_space_under_node_transform() {
        let mut ra = VelloPixmapRenderer::new(100, 100);
        let mut rb = VelloPixmapRenderer::new(100, 100);
        let scene_a = gradient_rect_scene(Rect::new(10.0, 10.0, 90.0, 90.0), None);
        let scene_b = gradient_rect_scene(
            Rect::new(0.0, 0.0, 80.0, 80.0),
            Some(Transform::translate(10.0, 10.0)),
        );
        let a = pixels(&ra.render_scene_to_pixmap(&scene_a));
        let b = pixels(&rb.render_scene_to_pixmap(&scene_b));
        assert_eq!(a.len(), b.len());
        // 允许极少量抗锯齿差异(<0.1% 通道字节)。
        let diff = a.iter().zip(b.iter()).filter(|(x, y)| x != y).count();
        assert!(
            diff < a.len() / 1000,
            "渐变在节点 transform 下应保持用户空间,但 {} 个通道字节不同",
            diff
        );
    }

    /// Bug 2 回归:同一渲染器可复用渲染多帧,结果一致(reset 清场 + Resources 复用)。
    #[test]
    fn renderer_reusable_across_frames() {
        let mut renderer = VelloPixmapRenderer::new(60, 60).with_background(Color::WHITE);
        let scene = gradient_rect_scene(Rect::new(5.0, 5.0, 55.0, 55.0), None);

        let p1 = renderer.render_scene_to_pixmap(&scene);
        let p2 = renderer.render_scene_to_pixmap(&scene);

        let d1 = pixels(&p1);
        let d2 = pixels(&p2);
        assert_eq!(d1, d2, "多帧渲染结果应一致");
        // 非全白背景:渐变矩形应覆盖部分像素。
        let non_white = d1
            .as_chunks::<4>()
            .0
            .iter()
            .filter(|px| px[0] < 250 || px[1] < 250 || px[2] < 250)
            .count();
        assert!(non_white > 0, "渐变矩形未渲染出来");
    }

    /// 统计 pixmap 中近似等于给定 RGB 的像素数(容差 tol)。
    fn count_color(pixmap: &Pixmap, rgb: (u8, u8, u8), tol: u8) -> usize {
        pixmap
            .pixels()
            .as_chunks::<4>()
            .0
            .iter()
            .filter(|p| {
                p[0].abs_diff(rgb.0) <= tol
                    && p[1].abs_diff(rgb.1) <= tol
                    && p[2].abs_diff(rgb.2) <= tol
            })
            .count()
    }

    /// 读取 (x, y) 处的像素(RGBA)。越界返回 (0,0,0,0)。
    fn pixel_at(pixmap: &Pixmap, x: u32, y: u32) -> (u8, u8, u8, u8) {
        let w = pixmap.width();
        let h = pixmap.height();
        if x >= w || y >= h {
            return (0, 0, 0, 0);
        }
        let i = ((y * w + x) as usize) * 4;
        let p = &pixmap.pixels()[i..i + 4];
        (p[0], p[1], p[2], p[3])
    }

    // ——— 手绘填充(Fill::Sketch → 排线 + clip)———

    fn sketch_scene(style: SketchFillStyle) -> Scene {
        let mut scene = Scene::new(80.0, 80.0);
        scene.push(Element::rect(
            Rect::new(10.0, 10.0, 70.0, 70.0),
            FillStrokeStyle {
                fill: Some(Fill::Sketch(
                    SketchFill::new(Color::rgb(0xff, 0x00, 0x00)).with_style(style),
                )),
                stroke: None,
            },
        ));
        scene
    }

    /// 排线必须被形状裁住:内部有红色笔触,外部保持背景。
    #[test]
    fn sketch_fill_is_clipped_to_the_shape() {
        let mut r = VelloPixmapRenderer::new(80, 80).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&sketch_scene(SketchFillStyle::Hachure));
        let outside = pixel_at(&pix, 2, 40);
        assert!(
            outside.0 > 240 && outside.1 > 240 && outside.2 > 240,
            "形状外不应有排线: {outside:?}"
        );
        let red = (10..70)
            .flat_map(|y| (10..70).map(move |x| (x, y)))
            .filter(|&(x, y)| {
                let p = pixel_at(&pix, x, y);
                p.0 > 80 && p.1 < 120 && p.2 < 120
            })
            .count();
        assert!(red > 50, "形状内应出现红色排线, got {red}");
    }

    /// 点阵填充同样要落在形状内。
    #[test]
    fn dot_fill_is_clipped_to_the_shape() {
        let mut r = VelloPixmapRenderer::new(80, 80).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&sketch_scene(SketchFillStyle::Dots));
        let outside = pixel_at(&pix, 75, 5);
        assert!(
            outside.0 > 240 && outside.1 > 240 && outside.2 > 240,
            "形状外不应有点: {outside:?}"
        );
        let red = (10..70)
            .flat_map(|y| (10..70).map(move |x| (x, y)))
            .filter(|&(x, y)| {
                let p = pixel_at(&pix, x, y);
                p.0 > 80 && p.1 < 120 && p.2 < 120
            })
            .count();
        assert!(red > 20, "形状内应出现红色点阵, got {red}");
    }

    /// 元素数保护:超大形状 + 极小 gap 也不会把光栅化拖垮(gap 在 sketch pass 里已被抬高)。
    #[test]
    fn sketch_fill_survives_a_huge_shape() {
        let mut scene = Scene::new(200.0, 200.0);
        let mut sf = SketchFill::new(Color::rgb(0x00, 0x80, 0x00)).with_gap(0.01);
        sf.fill_weight = 0.3;
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 200.0, 200.0),
            FillStrokeStyle {
                fill: Some(Fill::Sketch(sf)),
                stroke: None,
            },
        ));
        let mut r = VelloPixmapRenderer::new(200, 200);
        let pix = r.render_scene_to_pixmap(&scene);
        assert_eq!(pix.width(), 200);
    }

    /// 覆盖:圆/椭圆/圆角矩形/多边形/圆弧/扇形 在 vello 端都能渲染出对应颜色。
    #[test]
    fn primitives_render() {
        use crate::geometry::Vec2;
        let mut scene = Scene::new(150.0, 100.0);
        scene.push(Element::circle(
            Point::new(20.0, 20.0),
            10.0,
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ));
        scene.push(Element::ellipse(
            Point::new(50.0, 20.0),
            Vec2::new(15.0, 8.0),
            0.0,
            FillStrokeStyle::fill(Color::rgb(0x00, 0xff, 0x00)),
        ));
        scene.push(Element::rounded_rect(
            Rect::new(75.0, 10.0, 105.0, 30.0),
            5.0,
            FillStrokeStyle::fill(Color::rgb(0x00, 0x00, 0xff)),
        ));
        scene.push(Element::polygon(
            vec![
                Point::new(5.0, 60.0),
                Point::new(30.0, 60.0),
                Point::new(17.0, 85.0),
            ],
            FillStrokeStyle::fill(Color::rgb(0xff, 0xff, 0x00)),
        ));
        scene.push(Element::arc(
            Point::new(70.0, 70.0),
            Vec2::new(20.0, 20.0),
            0.0,
            std::f64::consts::PI,
            Stroke::new(Color::rgb(0x00, 0xff, 0xff), 3.0),
        ));
        scene.push(Element::pie(
            Point::new(110.0, 60.0),
            20.0,
            0.0,
            std::f64::consts::FRAC_PI_2,
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0xff)),
        ));
        let mut r = VelloPixmapRenderer::new(150, 100);
        let pix = r.render_scene_to_pixmap(&scene);
        // 每种填充色都应出现。
        assert!(count_color(&pix, (0xff, 0x00, 0x00), 20) > 0, "圆未渲染");
        assert!(count_color(&pix, (0x00, 0xff, 0x00), 20) > 0, "椭圆未渲染");
        assert!(
            count_color(&pix, (0x00, 0x00, 0xff), 20) > 0,
            "圆角矩形未渲染"
        );
        assert!(
            count_color(&pix, (0xff, 0xff, 0x00), 20) > 0,
            "多边形未渲染"
        );
        assert!(count_color(&pix, (0x00, 0xff, 0xff), 20) > 0, "圆弧未渲染");
        assert!(count_color(&pix, (0xff, 0x00, 0xff), 20) > 0, "扇形未渲染");
    }

    /// 虚线描边:实线与虚线在同一路径上,虚线段数量少于实线(分段断裂)。
    #[test]
    fn dashed_stroke_renders() {
        let mut scene_solid = Scene::new(100.0, 20.0);
        scene_solid.push(Element::line(
            Point::new(5.0, 10.0),
            Point::new(95.0, 10.0),
            Stroke::new(Color::BLACK, 4.0),
        ));
        let mut scene_dashed = Scene::new(100.0, 20.0);
        scene_dashed.push(Element::line(
            Point::new(5.0, 10.0),
            Point::new(95.0, 10.0),
            Stroke::dashed(Color::BLACK, 4.0, vec![8.0, 8.0]),
        ));
        let mut rs = VelloPixmapRenderer::new(100, 20).with_background(Color::WHITE);
        let mut rd = VelloPixmapRenderer::new(100, 20).with_background(Color::WHITE);
        let ps = rs.render_scene_to_pixmap(&scene_solid);
        let pd = rd.render_scene_to_pixmap(&scene_dashed);
        // 沿中线统计黑色不透明像素(排除白色背景)。
        let black_on_line = |pix: &Pixmap| {
            (0..100u32)
                .filter(|&x| {
                    let (r, g, b, a) = pixel_at(pix, x, 10);
                    r < 100 && g < 100 && b < 100 && a > 200
                })
                .count()
        };
        let solid = black_on_line(&ps);
        let dashed = black_on_line(&pd);
        // 实线几乎全段覆盖,虚线约一半。
        assert!(solid > 80, "实线应覆盖中线大部分, got {solid}");
        assert!(
            dashed < solid,
            "虚线覆盖应少于实线, solid={solid} dashed={dashed}"
        );
        assert!(dashed > 5, "虚线应仍有可见段, got {dashed}");
    }

    /// 节点 opacity:半透明绿覆盖红 → 中心为混合色(≈(128,128,0))。
    #[test]
    fn opacity_blends_pixels() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_z(0),
        );
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0x00, 0xff, 0x00)),
            ))
            .with_z(1)
            .with_opacity(0.5),
        );
        let mut r = VelloPixmapRenderer::new(20, 20);
        let pix = r.render_scene_to_pixmap(&scene);
        let (r_, g, b, _) = pixel_at(&pix, 10, 10);
        // 50% 绿 over 红 → 期望 (128,128,0);容差 40。
        assert!(r_.abs_diff(128) <= 40, "R={r_}");
        assert!(g.abs_diff(128) <= 40, "G={g}");
        assert!(b <= 40, "B={b}");
    }

    /// Bug 回归(跨后端一致):Group/Layer 的 opacity 必须是**隔离合成**——子图元重叠处与
    /// 不重叠处结果一致(等价 SVG `<g opacity>`),而非逐图元乘 alpha 让重叠处更暗。
    #[test]
    fn group_opacity_is_isolated() {
        // 两个完全重合的不透明红矩形,放进 opacity=0.5 的 Group,白底。
        let mut scene = Scene::new(20.0, 20.0);
        let mut group = SceneNode::group(vec![
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            )),
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            )),
        ]);
        group.opacity = 0.5;
        scene.push_node(group);
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (pr, pg, pb, _) = pixel_at(&pix, 10, 10);
        // 隔离合成:0.5 × 红 over 白 = (255,128,128)。
        // 旧实现(逐图元乘 alpha)叠加两次 → (255,64,64),会明显偏暗。
        assert!(
            pr > 240 && (124..=131).contains(&pg) && (124..=131).contains(&pb),
            "隔离 opacity 应为 (255,128,128), got ({pr},{pg},{pb})"
        );
    }

    /// sweep 渐变:颜色随**角度**变化(角度 0 → 起点色,角度 π → ramp 中点)。
    #[test]
    fn sweep_gradient_varies_with_angle() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            FillStrokeStyle::fill_gradient(SweepGradient::full(
                Point::new(50.0, 50.0),
                0.0,
                vec![
                    GradientStop {
                        offset: 0.0,
                        color: Color::rgb(0xff, 0x00, 0x00),
                    },
                    GradientStop {
                        offset: 1.0,
                        color: Color::rgb(0x00, 0x00, 0xff),
                    },
                ],
            )),
        ));
        let mut r = VelloPixmapRenderer::new(100, 100);
        let pix = r.render_scene_to_pixmap(&scene);
        let right = pixel_at(&pix, 80, 50); // 角度 0 → 起点(红)
        let left = pixel_at(&pix, 20, 50); // 角度 π → 中点(紫)
        assert!(
            right.0 > left.0 && left.2 > right.2,
            "sweep 应随角度变化: right={right:?} left={left:?}"
        );
    }

    /// sweep(部分角度 + Pad):逐像素按 mod-2π 角度取值——ramp(π/2..π)之前的回卷区域
    /// 取**起始色**,ramp 之后的区域取**结束色**。锁定该语义,与 SVG 楔形近似对齐。
    #[test]
    fn sweep_partial_pad_clamps_wrapped_region_to_start_color() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            FillStrokeStyle::fill_gradient(SweepGradient::new(
                Point::new(50.0, 50.0),
                std::f64::consts::FRAC_PI_2,
                std::f64::consts::PI,
                vec![
                    GradientStop {
                        offset: 0.0,
                        color: Color::rgb(0xff, 0x00, 0x00),
                    },
                    GradientStop {
                        offset: 1.0,
                        color: Color::rgb(0x00, 0x00, 0xff),
                    },
                ],
            )),
        ));
        let mut r = VelloPixmapRenderer::new(100, 100);
        let pix = r.render_scene_to_pixmap(&scene);
        // 角度 0(中心正右):位于 ramp 之前 → 起始色红。
        let (r0, g0, b0, _) = pixel_at(&pix, 90, 50);
        assert!(
            r0 > 240 && g0 < 15 && b0 < 15,
            "角度 0 应为起始色红: ({r0},{g0},{b0})"
        );
        // 角度 π(正左):ramp 终点 → 结束色蓝。
        let (r1, g1, b1, _) = pixel_at(&pix, 10, 50);
        assert!(r1 < 15 && b1 > 240, "角度 π 应为结束色蓝: ({r1},{g1},{b1})");
        // 角度 3π/2(正上,y-down):ramp 之后的 gap → 结束色蓝。
        let (r2, g2, b2, _) = pixel_at(&pix, 50, 10);
        assert!(
            r2 < 15 && b2 > 240,
            "角度 3π/2 应为结束色蓝: ({r2},{g2},{b2})"
        );
    }

    /// spread:`Repeat` 按 ramp 长度平铺(同一相位颜色相同),`Pad` 则夹到端色。
    #[test]
    fn linear_gradient_spread_repeat_tiles() {
        let make = |spread: GradientSpread| {
            let mut scene = Scene::new(60.0, 20.0);
            scene.push(Element::rect(
                Rect::new(0.0, 0.0, 60.0, 20.0),
                FillStrokeStyle::fill_gradient(
                    LinearGradient::new(
                        Point::new(0.0, 0.0),
                        Point::new(20.0, 0.0),
                        vec![
                            GradientStop {
                                offset: 0.0,
                                color: Color::rgb(0x00, 0x00, 0x00),
                            },
                            GradientStop {
                                offset: 1.0,
                                color: Color::rgb(0xff, 0xff, 0xff),
                            },
                        ],
                    )
                    .with_spread(spread),
                ),
            ));
            scene
        };

        let mut rr = VelloPixmapRenderer::new(60, 20);
        let rep = rr.render_scene_to_pixmap(&make(GradientSpread::Repeat));
        // x=5(t=0.25)与 x=25(t=1.25 → 回卷 0.25)落在同一相位。
        let (a, b) = (pixel_at(&rep, 5, 10), pixel_at(&rep, 25, 10));
        assert!(
            a.0.abs_diff(b.0) <= 2 && a.0 < 200,
            "Repeat 应平铺: {a:?} vs {b:?}"
        );

        let mut rp = VelloPixmapRenderer::new(60, 20);
        let pad = rp.render_scene_to_pixmap(&make(GradientSpread::Pad));
        let (c, d) = (pixel_at(&pad, 5, 10), pixel_at(&pad, 25, 10));
        assert!(c.0 < 200 && d.0 > 240, "Pad 应夹到端色: {c:?} vs {d:?}");
    }

    /// 每角圆角:只给左上角圆角时,(1,1) 被切掉(露出背景),右上角仍是直角。
    #[test]
    fn per_corner_radii_round_only_the_given_corner() {
        let radii = crate::scene::CornerRadii::new(20.0, 0.0, 0.0, 0.0);
        let mut scene = Scene::new(40.0, 40.0);
        scene.push(Element::rounded_rect(
            Rect::new(0.0, 0.0, 40.0, 40.0),
            radii,
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ));
        let mut r = VelloPixmapRenderer::new(40, 40).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (tl, tg, _, _) = pixel_at(&pix, 1, 1);
        let (tr, tg2, _, _) = pixel_at(&pix, 38, 1);
        assert!(tl > 240 && tg > 240, "左上应被圆角切掉: ({tl},{tg})");
        assert!(tr > 200 && tg2 < 60, "右上应是直角红: ({tr},{tg2})");
    }

    /// 每角圆角(四角遍历):只给某一角圆角时,仅该角被切掉,其余三角保持直角。
    #[test]
    fn per_corner_radii_round_each_corner_independently() {
        use crate::scene::CornerRadii;
        // 顺时针各角的角落探针(40×40 矩形、半径 20 → 角落探针必在圆角弧线之外)。
        let probes: [(u32, u32); 4] = [(1, 1), (38, 1), (38, 38), (1, 38)];
        for i in 0..4 {
            let mut radii = [0.0f64; 4];
            radii[i] = 20.0;
            let radii = CornerRadii::new(radii[0], radii[1], radii[2], radii[3]);
            let mut scene = Scene::new(40.0, 40.0);
            scene.push(Element::rounded_rect(
                Rect::new(0.0, 0.0, 40.0, 40.0),
                radii,
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ));
            let mut r = VelloPixmapRenderer::new(40, 40).with_background(Color::WHITE);
            let pix = r.render_scene_to_pixmap(&scene);
            for (j, &(x, y)) in probes.iter().enumerate() {
                let (pr, pg, pb, _) = pixel_at(&pix, x, y);
                if j == i {
                    assert!(
                        pr > 240 && pg > 240 && pb > 240,
                        "角 {i} 应被圆角切掉: ({pr},{pg},{pb})"
                    );
                } else {
                    assert!(
                        pr > 200 && pg < 60 && pb < 60,
                        "角 {i} 圆角时角 {j} 应保持直角红: ({pr},{pg},{pb})"
                    );
                }
            }
        }
    }

    /// 4×4 测试图:四个 2×2 象限(左上红 / 右上绿 / 左下蓝 / 右下白)。
    fn quad_pixmap() -> crate::Pixmap {
        let mut px = Vec::with_capacity(4 * 4 * 4);
        for y in 0..4u32 {
            for x in 0..4u32 {
                let (r, g, b) = match (x < 2, y < 2) {
                    (true, true) => (255u8, 0u8, 0u8),
                    (false, true) => (0, 255, 0),
                    (true, false) => (0, 0, 255),
                    (false, false) => (255, 255, 255),
                };
                px.extend_from_slice(&[r, g, b, 255]);
            }
        }
        crate::Pixmap::from_rgba8(4, 4, px).unwrap()
    }

    fn image_scene(image: crate::SceneImage, frame: Rect) -> Scene {
        let mut s = Scene::new(frame.width(), frame.height());
        s.push(Element::image(image, frame));
        s
    }

    /// 采样质量:最近邻保持原值(块状),双线性混合出中间值,且三者互不相同。
    #[test]
    fn image_quality_selects_the_resampling_filter() {
        use crate::scene::ImageQuality;
        let render = |q: ImageQuality| {
            let img = crate::SceneImage::from_pixmap(quad_pixmap())
                .with_object_fit(crate::ObjectFit::Fill)
                .with_quality(q);
            let mut r = VelloPixmapRenderer::new(8, 8);
            pixels(&r.render_scene_to_pixmap(&image_scene(img, Rect::new(0.0, 0.0, 8.0, 8.0))))
        };
        let near = render(ImageQuality::Nearest);
        let bil = render(ImageQuality::Bilinear);
        let bic = render(ImageQuality::Bicubic);

        // 4×4 → 8×8(×2):最近邻是 2×2 的纯色块。
        let at = |buf: &[u8], x: usize, y: usize| -> [u8; 4] {
            let i = (y * 8 + x) * 4;
            [buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
        };
        assert_eq!(at(&near, 1, 1), [255, 0, 0, 255], "左上象限纯红");
        assert_eq!(at(&near, 5, 1), [0, 255, 0, 255], "右上象限纯绿");
        // 双线性在象限交界(x=4)处混色,双三次更"锐"(更贴近主色)。
        assert!(
            at(&bil, 4, 1)[0] > 20 && at(&bil, 4, 1)[1] > 20,
            "双线性应混色"
        );
        assert!(
            at(&bic, 4, 1)[1] > at(&bil, 4, 1)[1],
            "双三次更锐: bic={:?} bil={:?}",
            at(&bic, 4, 1),
            at(&bil, 4, 1)
        );
        assert_ne!(near, bil);
        assert_ne!(bil, bic);
    }

    /// 缩小:最近邻保留块状原值,双线性/双三次用加宽的核预滤波(得到中间灰)。
    #[test]
    fn minification_prefilters_with_bilinear_and_bicubic() {
        use crate::scene::ImageQuality;
        // 8×8 棋盘格 → 1×1。
        let px: Vec<u8> = (0..64u32)
            .flat_map(|i| {
                let v = if (i % 8 + i / 8) % 2 == 0 { 0u8 } else { 255 };
                [v, v, v, 255]
            })
            .collect();
        let img = crate::Pixmap::from_rgba8(8, 8, px).unwrap();
        let render = |q: ImageQuality| {
            let scene_img = crate::SceneImage::from_pixmap(img.clone())
                .with_object_fit(crate::ObjectFit::Fill)
                .with_quality(q);
            let mut r = VelloPixmapRenderer::new(1, 1);
            pixel_at(
                &r.render_scene_to_pixmap(&image_scene(scene_img, Rect::new(0.0, 0.0, 1.0, 1.0))),
                0,
                0,
            )
            .0
        };
        let near = render(ImageQuality::Nearest);
        assert!(near == 0 || near == 255, "最近邻应保留原值: {near}");
        let bil = render(ImageQuality::Bilinear);
        assert!((100..=155).contains(&bil), "双线性应预滤波成中灰: {bil}");
        let bic = render(ImageQuality::Bicubic);
        assert!((90..=165).contains(&bic), "双三次应预滤波成中灰: {bic}");
    }

    /// `ObjectFit::Tile`:按原始像素尺寸在 frame 内重复(4×4 的图 → 每 4px 一轮)。
    #[test]
    fn tile_object_fit_repeats_the_image() {
        let img =
            crate::SceneImage::from_pixmap(quad_pixmap()).with_object_fit(crate::ObjectFit::Tile);
        let mut r = VelloPixmapRenderer::new(8, 8);
        let pix = r.render_scene_to_pixmap(&image_scene(img, Rect::new(0.0, 0.0, 8.0, 8.0)));
        assert_eq!(pixel_at(&pix, 0, 0), (255, 0, 0, 255));
        assert_eq!(pixel_at(&pix, 3, 3), (255, 255, 255, 255));
        // 第二轮的同一相位颜色相同。
        assert_eq!(pixel_at(&pix, 4, 4), (255, 0, 0, 255));
        assert_eq!(pixel_at(&pix, 7, 7), (255, 255, 255, 255));
    }

    /// `Fill::Image`:用图片做填充,按 tile 网格在形状内重复。
    #[test]
    fn image_fill_tiles_inside_the_shape() {
        let mut scene = Scene::new(8.0, 8.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 8.0, 8.0),
            FillStrokeStyle::fill_gradient(crate::scene::ImageFill::natural(
                quad_pixmap(),
                Point::new(0.0, 0.0),
            )),
        ));
        let mut r = VelloPixmapRenderer::new(8, 8);
        let pix = r.render_scene_to_pixmap(&scene);
        assert_eq!(pixel_at(&pix, 0, 0), (255, 0, 0, 255));
        assert_eq!(pixel_at(&pix, 3, 3), (255, 255, 255, 255));
        assert_eq!(pixel_at(&pix, 4, 4), (255, 0, 0, 255), "第二块应重复");
    }

    /// 抗锯齿开关:关闭后边缘像素变为二值(不再有半覆盖的灰),开启时是灰。
    #[test]
    fn antialias_off_gives_binary_edges() {
        let scene_with = |aa: bool| {
            let mut s = Scene::new(20.0, 20.0);
            // 右边缘落在 10.5 → 像素 x=10 被覆盖 50%。
            s.push(
                SceneNode::new(Element::rect(
                    Rect::new(0.0, 0.0, 10.5, 10.0),
                    FillStrokeStyle::fill(Color::BLACK),
                ))
                .with_antialias(aa),
            );
            s
        };
        let mut ra = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let aa = pixel_at(&ra.render_scene_to_pixmap(&scene_with(true)), 10, 5);
        let mut rn = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let crisp = pixel_at(&rn.render_scene_to_pixmap(&scene_with(false)), 10, 5);
        assert!(aa.0 > 0 && aa.0 < 255, "开启时应有半覆盖的灰: {aa:?}");
        assert!(
            crisp.0 <= 20,
            "关闭后覆盖率 > 0 即应填满(纯黑): {crisp:?}"
        );
    }

    /// 色彩矩阵(方案 B:烘进 paint):灰度把红填充变成等亮度灰(0.213 × 255 ≈ 54)。
    #[test]
    fn color_matrix_bakes_into_paints() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_color_matrix(ColorMatrix::grayscale()),
        );
        let mut r = VelloPixmapRenderer::new(20, 20);
        let pix = r.render_scene_to_pixmap(&scene);
        let (pr, pg, pb, _) = pixel_at(&pix, 10, 10);
        assert!(
            pr.abs_diff(54) <= 1 && pr == pg && pg == pb,
            "灰度应为 ~54, got ({pr},{pg},{pb})"
        );
    }

    /// 嵌套色彩矩阵:子节点灰化 + 父容器增亮 0.5 → 54 × 0.5 = 27(与 SVG 后端一致)。
    #[test]
    fn nested_color_matrices_compose() {
        let child = SceneNode::new(Element::rect(
            Rect::new(0.0, 0.0, 20.0, 20.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ))
        .with_color_matrix(ColorMatrix::grayscale());
        let group = SceneNode::group(vec![child]).with_color_matrix(ColorMatrix::brightness(0.5));
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(group);
        let mut r = VelloPixmapRenderer::new(20, 20);
        let pix = r.render_scene_to_pixmap(&scene);
        let (pr, pg, pb, _) = pixel_at(&pix, 10, 10);
        assert!(
            pr.abs_diff(27) <= 1 && pr == pg && pg == pb,
            "组合后应为 ~27, got ({pr},{pg},{pb})"
        );
    }

    /// BlendMode:Multiply 把不透明灰 (128) 叠在不透明灰 (128) 上 ≈ 64(Normal 则为 128)。
    #[test]
    fn blend_mode_multiply_darkens() {
        let gray = Color::rgb(0x80, 0x80, 0x80);
        let mut scene = Scene::new(20.0, 20.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 20.0, 20.0),
            FillStrokeStyle::fill(gray),
        ));
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(gray),
            ))
            .with_blend_mode(BlendMode::Multiply),
        );
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (pr, pg, pb, _) = pixel_at(&pix, 10, 10);
        // multiply(0.502, 0.502) = 0.252 → ≈64;Normal 会得到 128。
        assert!(
            (60..=68).contains(&pr) && (60..=68).contains(&pg) && (60..=68).contains(&pb),
            "multiply 应使 128 灰变暗到 ~64, got ({pr},{pg},{pb})"
        );
    }

    /// Porter-Duff:`DestOut` 在源覆盖处擦除目标、其余保留(raster-only)。
    #[test]
    fn porter_duff_dest_out_erases_within_source() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 10.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_blend_mode(BlendMode::DestOut),
        );
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (_, _, _, ca) = pixel_at(&pix, 5, 10);
        let (wr, _, _, wa) = pixel_at(&pix, 15, 10);
        assert_eq!(ca, 0, "DestOut 应在源覆盖处擦除目标");
        assert!(wa == 255 && wr == 255, "源之外应保留白底, a={wa} r={wr}");
    }

    /// Porter-Duff:`Plus` 为可加混合(源 + 目标,饱和到白)。
    #[test]
    fn porter_duff_plus_adds() {
        let gray = Color::rgb(0x80, 0x80, 0x80);
        let mut scene = Scene::new(20.0, 20.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 20.0, 20.0),
            FillStrokeStyle::fill(gray),
        ));
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(gray),
            ))
            .with_blend_mode(BlendMode::Plus),
        );
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (pr, _, _, _) = pixel_at(&pix, 10, 10);
        assert!(pr > 250, "Plus 应叠加 128+128 到白, got {pr}");
    }

    /// Mask:线性渐变遮罩(左不透明 → 右透明)在不透明红矩形上产生平滑淡出。
    #[test]
    fn gradient_mask_fades_alpha() {
        let mask = crate::scene::Mask::new(Clip::Rect(Rect::new(0.0, 0.0, 20.0, 20.0))).with_fill(
            LinearGradient::new(
                Point::new(0.0, 0.0),
                Point::new(20.0, 0.0),
                vec![
                    GradientStop {
                        offset: 0.0,
                        color: Color::WHITE,
                    },
                    GradientStop {
                        offset: 1.0,
                        color: Color::rgba(0xff, 0xff, 0xff, 0),
                    },
                ],
            ),
        );
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_mask(mask),
        );
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (lr, lg, lb, _) = pixel_at(&pix, 2, 10);
        let (rr, rg, rb, _) = pixel_at(&pix, 18, 10);
        assert!(
            lr > 200 && lg < 90 && lb < 90,
            "左侧应保留红色, got ({lr},{lg},{lb})"
        );
        assert!(
            rr > 200 && rg > 200 && rb > 200,
            "右侧应被遮罩淡出为白, got ({rr},{rg},{rb})"
        );
    }

    /// Filter:高斯模糊让矩形边缘之外也变暗(无滤镜时该点为纯白背景)。
    #[test]
    fn blur_filter_softens_edges() {
        let rect = Element::rect(
            Rect::new(0.0, 0.0, 10.0, 20.0),
            FillStrokeStyle::fill(Color::BLACK),
        );
        let mut plain = Scene::new(20.0, 20.0);
        plain.push(rect.clone());
        let mut blurred = Scene::new(20.0, 20.0);
        blurred.push_node(SceneNode::new(rect).with_filter(Filter::blur(2.0)));

        let mut rp = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let mut rb = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pp = rp.render_scene_to_pixmap(&plain);
        let pb = rb.render_scene_to_pixmap(&blurred);
        let plain_px = pixel_at(&pp, 11, 10).0;
        let blur_px = pixel_at(&pb, 11, 10).0;
        assert_eq!(plain_px, 255, "无滤镜时边界外应为纯白");
        assert!(
            (20..250).contains(&blur_px),
            "模糊应使边界外变暗, got {blur_px}"
        );
    }

    /// Filter:投影在矩形外的偏移方向产生非白像素(无滤镜时为白背景)。
    #[test]
    fn drop_shadow_filter_adds_shadow() {
        let rect = Element::rect(
            Rect::new(2.0, 2.0, 8.0, 8.0),
            FillStrokeStyle::fill(Color::BLACK),
        );
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(SceneNode::new(rect).with_filter(Filter::drop_shadow(
            4.0,
            4.0,
            1.5,
            Color::BLACK,
        )));
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        // 投影中心 ≈ (2,2)+(4,4) + 半尺寸 → (6,6)+... 取 (10,10) 处应有阴影。
        let (pr, _, _, _) = pixel_at(&pix, 10, 10);
        assert!(pr < 250, "投影应在偏移位置产生非白像素, got {pr}");
    }

    /// 节点 visible=false:整棵子树跳过,不产生像素。
    #[test]
    fn visibility_skips_pixels() {
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 20.0, 20.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_visible(false),
        );
        let mut r = VelloPixmapRenderer::new(20, 20);
        let pix = r.render_scene_to_pixmap(&scene);
        // 背景为透明 → 红色像素数应为 0。
        assert_eq!(
            count_color(&pix, (0xff, 0x00, 0x00), 20),
            0,
            "隐藏节点不应渲染"
        );
    }

    /// 图层层序:顶层覆盖底层。交换层序后遮挡关系反转。
    #[test]
    fn layer_order_pixels() {
        use crate::scene::Layer;
        let mut scene = Scene::new(40.0, 40.0);
        let bottom = Layer::new("bottom").with_nodes(vec![SceneNode::new(Element::rect(
            Rect::new(0.0, 0.0, 40.0, 40.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ))]);
        let top = Layer::new("top").with_nodes(vec![SceneNode::new(Element::rect(
            Rect::new(10.0, 10.0, 30.0, 30.0),
            FillStrokeStyle::fill(Color::rgb(0x00, 0x00, 0xff)),
        ))]);
        scene.push_layer(bottom);
        scene.push_layer(top);
        let mut r = VelloPixmapRenderer::new(40, 40);
        let pix = r.render_scene_to_pixmap(&scene);
        // 中心 (20,20) 在顶层蓝矩形内 → 蓝色。
        let (r_, g, b, _) = pixel_at(&pix, 20, 20);
        assert!(
            b > 200 && r_ < 100 && g < 100,
            "中心应为顶层蓝色, got ({r_},{g},{b})"
        );
        // 角落 (2,2) 在底层红矩形内 → 红色。
        let (r2, g2, b2, _) = pixel_at(&pix, 2, 2);
        assert!(
            r2 > 200 && g2 < 100 && b2 < 100,
            "角落应为底层红色, got ({r2},{g2},{b2})"
        );
    }

    /// 文本字形渲染:黑字在白色背景上产生非白像素。
    #[test]
    fn text_glyphs_render() {
        let style = TextStyle::new(Color::rgb(0, 0, 0), 24.0, "sans-serif");
        let mut scene = Scene::new(200.0, 60.0);
        scene.push(Element::text("Hello", Point::new(10.0, 40.0), style));
        let mut r = VelloPixmapRenderer::new(200, 60).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let non_white = pix
            .pixels()
            .as_chunks::<4>()
            .0
            .iter()
            .filter(|p| p[0] < 250 || p[1] < 250 || p[2] < 250)
            .count();
        assert!(non_white > 20, "字形应产生非白像素, got {non_white}");
    }

    /// 文本旋转回归:块变换必须作用于**整个 glyph run**(scene transform),
    /// 而非逐字形的 `glyph_transform`。
    ///
    /// 表现:旋转 90° 的宽字符串,墨迹包围盒应呈"竖窄"(绕锚点整体旋转);
    /// 修复前每个字符绕自身位置旋转、字符间相对位置不旋转,墨迹仍是"横宽",
    /// 与 SVG `<text transform="rotate(...)">` 的整体旋转不一致。
    #[test]
    fn text_rotation_rotates_whole_run() {
        use crate::text::TextAlign;
        use crate::text::TextBaseline;

        /// 非白像素的墨迹包围盒 (min_x, min_y, max_x, max_y);无墨迹返回 None。
        fn ink_bbox(pix: &Pixmap) -> Option<(f64, f64, f64, f64)> {
            let (w, h) = (pix.width(), pix.height());
            let mut bbox: Option<(u32, u32, u32, u32)> = None;
            for y in 0..h {
                for x in 0..w {
                    let p = pixel_at(pix, x, y);
                    if p.0 < 250 || p.1 < 250 || p.2 < 250 {
                        bbox = Some(match bbox {
                            None => (x, y, x, y),
                            Some((x0, y0, x1, y1)) => (x0.min(x), y0.min(y), x1.max(x), y1.max(y)),
                        });
                    }
                }
            }
            bbox.map(|(x0, y0, x1, y1)| {
                (f64::from(x0), f64::from(y0), f64::from(x1), f64::from(y1))
            })
        }

        let anchor = Point::new(40.0, 160.0);
        let style = TextStyle::new(Color::BLACK, 24.0, "sans-serif")
            .with_align(TextAlign::Left)
            .with_baseline(TextBaseline::Top)
            .with_rotation(std::f64::consts::FRAC_PI_2);
        let mut scene = Scene::new(200.0, 200.0);
        scene.push(Element::text("MMMMM", anchor, style));
        let mut r = VelloPixmapRenderer::new(200, 200).with_background(Color::WHITE);
        let bbox = ink_bbox(&r.render_scene_to_pixmap(&scene)).expect("旋转文本应产生墨迹");
        let (w, h) = (bbox.2 - bbox.0, bbox.3 - bbox.1);
        assert!(
            h > w,
            "90° 旋转的宽字符串墨迹应为竖窄(整体旋转),got bbox w={w} h={h}"
        );
        // 绕锚点旋转:墨迹应贴近锚点列(x≈40),而非沿基线横向铺开。
        assert!(
            (bbox.0 + bbox.2) / 2.0 - anchor.x < 24.0,
            "墨迹应贴近锚点 x={},got center_x={}",
            anchor.x,
            (bbox.0 + bbox.2) / 2.0
        );
    }

    /// 预排版 layout 与自动排版渲染结果一致(同一 TLS 上下文)。
    #[test]
    fn prelaid_layout_renders_same_as_auto() {
        use crate::text::RichSpan;
        use crate::text::measure_text;
        let style = TextStyle::new(Color::BLACK, 24.0, "sans-serif");
        let m = measure_text(
            std::slice::from_ref(&RichSpan::new("Hello", style.clone())),
            None,
        );
        // 自动排版
        let mut a = Scene::new(200.0, 60.0);
        a.push(Element::text(
            "Hello",
            Point::new(10.0, 40.0),
            style.clone(),
        ));
        // 预排版
        let mut b = Scene::new(200.0, 60.0);
        b.push(Element::Text {
            spans: vec![RichSpan::new("Hello", style.clone())],
            position: Point::new(10.0, 40.0),
            style,
            layout: Some(m.layout),
        });
        let mut ra = VelloPixmapRenderer::new(200, 60).with_background(Color::WHITE);
        let mut rb = VelloPixmapRenderer::new(200, 60).with_background(Color::WHITE);
        let da = pixels(&ra.render_scene_to_pixmap(&a));
        let db = pixels(&rb.render_scene_to_pixmap(&b));
        let diff = da.iter().zip(db.iter()).filter(|(x, y)| x != y).count();
        assert!(
            diff < da.len() / 1000,
            "预排版与自动排版应一致, 差异 {diff} 字节"
        );
    }

    /// clip:把大红矩形裁到中心小圆内 → 圆心是红、四角是背景(非红)。
    #[test]
    fn clip_restricts_pixels_to_shape() {
        use crate::scene::Clip;
        let mut scene = Scene::new(100.0, 100.0);
        // 全幅红色矩形,裁到中心半径 20 的圆。
        scene.push_node(
            SceneNode::new(Element::rect(
                Rect::new(0.0, 0.0, 100.0, 100.0),
                FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
            ))
            .with_clip(Clip::circle(Point::new(50.0, 50.0), 20.0)),
        );
        let mut r = VelloPixmapRenderer::new(100, 100).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        // 圆心 (50,50) 应在圆内 → 红色。
        let (cr, cg, cb, ca) = pixel_at(&pix, 50, 50);
        assert!(
            cr > 200 && cg < 60 && cb < 60 && ca > 200,
            "圆心应为红, got ({cr},{cg},{cb},{ca})"
        );
        // 角落 (5,5) 在圆外 → 白色背景(红色不应出现)。
        let (lr, lg, lb, _) = pixel_at(&pix, 5, 5);
        assert!(
            lr > 240 && lg > 240 && lb > 240,
            "角落应为白, got ({lr},{lg},{lb})"
        );
    }

    /// Bug 回归:PNG 输出必须是 **非预乘** alpha。
    ///
    /// vello 的 Pixmap 保存预乘像素,直接写入 PNG 会让所有 alpha<255 的像素
    /// (抗锯齿边缘 / 半透明填充 / 文字边缘)整体偏暗。
    #[test]
    fn png_output_is_unpremultiplied() {
        let mut scene = Scene::new(4.0, 4.0).with_background(Color::TRANSPARENT);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 4.0, 4.0),
            FillStrokeStyle::fill(Color::rgba(0xff, 0x00, 0x00, 128)),
        ));
        let mut r = VelloPixmapRenderer::new(4, 4);
        let (w, h, data) = render_png_pixels(&mut r, &scene);
        assert_eq!((w, h), (4, 4));
        let i = ((2 * w + 2) * 4) as usize;
        let (pr, pg, pb, pa) = (data[i], data[i + 1], data[i + 2], data[i + 3]);
        assert!(
            pr > 240 && pg < 20 && pb < 20 && pa.abs_diff(128) <= 2,
            "50% 红应输出非预乘的 (255,0,0,128), got ({pr},{pg},{pb},{pa})"
        );
    }

    /// Bug 回归:图片的最终透明度 = 图片自身 opacity × 节点 / 图层 opacity。
    #[test]
    fn image_opacity_composes_with_node_opacity() {
        // 4×4 不透明白图,节点 opacity = 0.5,画在黑底上 → 中灰。
        let img = crate::SceneImage::from_rgba8(4, 4, vec![0xffu8; 4 * 4 * 4]).unwrap();
        let mut scene = Scene::new(20.0, 20.0);
        scene.push_node(
            SceneNode::new(Element::image(img, Rect::new(0.0, 0.0, 20.0, 20.0))).with_opacity(0.5),
        );
        let mut r = VelloPixmapRenderer::new(20, 20).with_background(Color::BLACK);
        let (w, _, data) = render_png_pixels(&mut r, &scene);
        let i = ((10 * w + 10) * 4) as usize;
        let (pr, pg, pb, _) = (data[i], data[i + 1], data[i + 2], data[i + 3]);
        let mid = |c: u8| (100..=160).contains(&c);
        assert!(
            mid(pr) && mid(pg) && mid(pb),
            "半透明白图叠黑底应为中灰, got ({pr},{pg},{pb})"
        );
    }

    /// 契约锁定:输出画布 = 构造时给定的尺寸,`scene.scale` **不参与**光栅画布计算。
    ///
    /// 下游(liepress)把场景按最终像素尺寸构造(`scene.width = page_w * (dpi/72)`)并
    /// 记录 `scene.scale = dpi/72` 作为元数据,再把 `scene.width` 直接传进来;若这里再乘
    /// 一次 scale,输出会被二次放大(dpi=144 时面积 ×4)。像素密度由调用方通过构造器
    /// 决定。
    #[test]
    fn renderer_size_defines_output_canvas_regardless_of_scene_scale() {
        let mut scene = Scene::new(100.0, 100.0).with_scale(2.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ));
        let mut r = VelloPixmapRenderer::new(100, 100).with_background(Color::WHITE);
        let (w, h, _) = render_png_pixels(&mut r, &scene);
        assert_eq!(
            (w, h),
            (100, 100),
            "scene.scale=2 时输出画布仍应为 100×100(scale 是密度而非放大)"
        );
    }

    /// 契约锁定(跨后端):`scale` 是**密度**,两个后端语义完全一致。
    ///
    /// 场景坐标 = 输出尺寸 / scale。故"场景 100×100 + scale=2"分别用
    /// `new(200,200)`(vello)与 `new(200.0,200.0)`(SVG)渲染时,内容都应占满整块画布,
    /// 且输出尺寸都是 200×200 —— 而不是 100×100 或 400×400。
    #[test]
    fn scale_is_density_identical_on_both_backends() {
        let mut scene = Scene::new(100.0, 100.0).with_scale(2.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 100.0, 100.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ));

        // 光栅端:输出 200×200,内容铺满(scene 100 → 视口 100 → ×2)。
        let mut r = VelloPixmapRenderer::new(200, 200).with_background(Color::WHITE);
        let (w, h, data) = render_png_pixels(&mut r, &scene);
        assert_eq!((w, h), (200, 200));
        for (x, y) in [(5u32, 5u32), (195, 195), (100, 100)] {
            let i = ((y * w + x) * 4) as usize;
            assert!(
                data[i] > 200 && data[i + 1] < 60 && data[i + 2] < 60,
                "({x},{y}) 应为红(内容铺满画布), got {:?}",
                &data[i..i + 4]
            );
        }

        // SVG 端:同样的构造尺寸 → 同样的输出尺寸与用户坐标系。
        let mut svg = crate::render::SvgRenderer::new(200.0, 200.0);
        scene.render(&mut svg);
        let out = svg.into_string();
        assert!(
            out.contains(r#"width="200.00" height="200.00" viewBox="0 0 100.00 100.00""#),
            "SVG 端应与光栅端一致, 实际: {out}"
        );
    }

    /// 契约锁定:构造尺寸 == 场景尺寸时(下游 liepress 的用法),两个后端都是 1:1 铺满,
    /// 不受 `scene.scale` 影响(liepress 已把坐标乘过 scale 了)。
    #[test]
    fn preset_output_size_with_density_scale_maps_one_to_one() {
        // liepress 形态:场景坐标已是最终像素(= 逻辑尺寸 × scale),scale=2 仅作元数据。
        let mut scene = Scene::new(200.0, 100.0).with_scale(2.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 200.0, 100.0),
            FillStrokeStyle::fill(Color::rgb(0x00, 0x00, 0xff)),
        ));
        let mut r = VelloPixmapRenderer::new(200, 100).with_background(Color::WHITE);
        let (w, h, data) = render_png_pixels(&mut r, &scene);
        assert_eq!((w, h), (200, 100), "构造尺寸即输出尺寸");
        let i = ((50 * w + 100) * 4) as usize;
        assert!(
            data[i] < 60 && data[i + 2] > 200,
            "内容应 1:1 铺满画布, got {:?}",
            &data[i..i + 4]
        );
    }

    /// Bug 回归:画布与场景长宽比不一致时,按 SVG 默认的
    /// `preserveAspectRatio="xMidYMid meet"` 等比缩放并居中(此前只按宽度缩放,
    /// 纵向会溢出/裁切,与 SVG 输出不一致)。
    #[test]
    fn aspect_mismatch_uses_meet_and_centers() {
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::rect(
            Rect::new(0.0, 0.0, 50.0, 50.0),
            FillStrokeStyle::fill(Color::rgb(0xff, 0x00, 0x00)),
        ));
        // 画布 200×100、场景 100×100 → meet 取 s=1,水平居中 → 方块占 x∈[50,100]。
        let mut r = VelloPixmapRenderer::new(200, 100).with_background(Color::WHITE);
        let pix = r.render_scene_to_pixmap(&scene);
        let (cr, cg, cb, _) = pixel_at(&pix, 60, 25);
        assert!(
            cr > 200 && cg < 60 && cb < 60,
            "居中后的方块内应为红, got ({cr},{cg},{cb})"
        );
        // 居中留白区(x=10)与纵向(y=75,场景外)应为白。
        let (lr, lg, lb, _) = pixel_at(&pix, 10, 25);
        assert!(
            lr > 240 && lg > 240 && lb > 240,
            "左侧留白应为白, got ({lr},{lg},{lb})"
        );
        let (br, bg, bb, _) = pixel_at(&pix, 60, 75);
        assert!(
            br > 240 && bg > 240 && bb > 240,
            "纵向未裁切区应为白, got ({br},{bg},{bb})"
        );
    }

    /// 极端 frame 不应导致超大中间位图分配(降采样后仍能画出图片)。
    #[test]
    fn huge_image_frame_is_downscaled() {
        // 1×1 的图 + Cover + 巨大 frame:放大倍数极高,必须被像素上限压住。
        let img = crate::SceneImage::from_rgba8(1, 1, vec![0xffu8; 4])
            .unwrap()
            .with_object_fit(crate::ObjectFit::Cover);
        let mut scene = Scene::new(40.0, 40.0);
        scene.push(Element::image(img, Rect::new(0.0, 0.0, 50000.0, 50000.0)));
        let mut r = VelloPixmapRenderer::new(40, 40).with_background(Color::BLACK);
        let pix = r.render_scene_to_pixmap(&scene);
        let (cr, cg, cb, _) = pixel_at(&pix, 20, 20);
        assert!(
            cr > 200 && cg > 200 && cb > 200,
            "放大后的白色图片应铺满画布, got ({cr},{cg},{cb})"
        );
    }

    /// 画布之外的图片应被直接剔除(不产生任何像素)。
    #[test]
    fn offscreen_image_is_culled() {
        let img = crate::SceneImage::from_rgba8(4, 4, vec![0xffu8; 4 * 4 * 4]).unwrap();
        let mut scene = Scene::new(100.0, 100.0);
        scene.push(Element::image(img, Rect::new(500.0, 500.0, 600.0, 600.0)));
        let mut r = VelloPixmapRenderer::new(100, 100).with_background(Color::BLACK);
        let pix = r.render_scene_to_pixmap(&scene);
        let white = pixels(&pix)
            .as_chunks::<4>()
            .0
            .iter()
            .filter(|p| p[0] > 200 && p[1] > 200 && p[2] > 200)
            .count();
        assert_eq!(white, 0, "画布外图片不应产生像素");
    }
}