bevy_react_core 0.7.0

The core bridge of bevy-react (drive bevy_ui from React over an embedded V8 runtime). Apps depend on the `bevy-react` crate.
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
//! Render-world half of layer compositing — a custom pass over stock
//! `bevy_ui_render`, public API only (no fork). Mechanism per frame:
//!
//! 1. [`extract_ui_layers`] (`ExtractSchedule`, after
//!    `extract_ui_camera_view`): per promoted layer, maintain a **synthetic
//!    view** (a persistent render entity, see [`LayerEntities`]) whose
//!    `clip_from_view` is an orthographic projection over the layer's capture
//!    rect — the same physical screen space stock UI vertices live in — and
//!    register an empty `TransparentUi` phase for it. Stock extraction / queue
//!    never know it exists. Members of layers served from cache this frame
//!    are then hidden from stock extraction for the rest of the extract
//!    window ([`cached`]) — their items would only be stolen and dropped.
//! 2. [`redistribute_ui_layers`] (`PhaseSort`, before the stock sort): move
//!    the already-queued phase items whose `main_entity` lies in a promoted
//!    subtree, **verbatim**, from the camera's UI phase into their layer's
//!    synthetic phase — stock `prepare_uinodes` (and sibling prepares) iterate
//!    *all* phases, so the moved items are batched by stock code against the
//!    synthetic view's `ViewUniformOffset`. Then inject one composite-quad
//!    item per layer at the position of its first stolen item.
//! 3. [`ui_layer_capture_pass`] (`Core2d`/`Core3d`, before `ui_pass`): render
//!    each synthetic phase into the layer's offscreen texture (cleared
//!    transparent). Straight-alpha blending onto transparent black accumulates
//!    **premultiplied** color, so…
//! 4. …a layer with a `filter` chain then replays its staged filter run
//!    (same graph node, right after that layer's capture): fullscreen passes
//!    capture → ping-pong textures ([`LayerFilterMeta::runs`], staged by
//!    [`prepare_layer_filters`]), all of them or none — an uncompiled pass
//!    pipeline aborts the whole run and [`GateState::output_valid`] stays
//!    false, so the layer restages and retries next frame. And…
//! 5. …a layer with the `TRANSFORM3D` promotion reason replays its staged
//!    mip-downsample chain last in the iteration ([`mips`]) — its sampled
//!    texture (capture, or filter output) carries a full mip chain, rebuilt
//!    only when level 0 was rewritten. Finally…
//! 6. …the composite quad ([`DrawLayerComposite`], drawn inside the stock
//!    `ui_pass` at the subtree's stacking position) samples the capture — or,
//!    for a filtered layer, the final filter pass's output — with
//!    premultiplied blending (`One`/`OneMinusSrcAlpha`) and multiplies rgb
//!    *and* alpha by the group alpha. 3D-transformed quads sample trilinear +
//!    anisotropic over the mip chain (minification shimmer) and feather ~1px
//!    of coverage at their silhouette (`composite.wgsl`'s edge AA — diagonal
//!    edges rasterize without MSAA).
//!
//! Re-verify on Bevy upgrades (spike checklist): `TransparentUi` field set,
//! `SortedRenderPhase::{items, transient_items}` visibility, `prepare_uinodes`
//! iterating all phases, `ViewSortedRenderPhases::prepare_for_new_frame`
//! draining transients, straight `ALPHA_BLENDING` in `UiPipeline`, the
//! `Queue → PhaseSort → PrepareBindGroups` schedule shape, naga_oil NOT
//! re-exporting an import's entry points (the split-stage filter pipelines
//! rely on pass shaders having no vertex entry of their own), naga's namer
//! renaming digit-suffixed identifiers (the `pad_a`/`pad_b` constraint in
//! composable WGSL modules), and wgpu accepting per-stage shader modules in
//! `RenderPipelineDescriptor` (filter vertex stage = prelude module, fragment
//! stage = pass module).

pub mod backdrop;
pub mod cached;
pub mod clip;
pub mod mips;
pub mod morph;
pub mod stock_camera;
pub mod store;
pub mod transform3d;
pub mod warm;

pub use store::*;

use std::ops::Range;

use bevy::asset::{AssetServer, Handle};
use bevy::camera::{Camera, Camera2d, Camera3d};
use bevy::core_pipeline::FullscreenShader;
use bevy::ecs::system::SystemParamItem;
use bevy::ecs::system::lifetimeless::SRes;
use bevy::math::{FloatOrd, Mat4, UVec4};
use bevy::mesh::VertexBufferLayout;
use bevy::platform::collections::{HashMap, HashSet};
use bevy::prelude::*;
use bevy::render::Extract;
use bevy::render::camera::CameraMainPassTextureFormats;
use bevy::render::render_phase::{
    DrawFunctions, PhaseItem, PhaseItemExtraIndex, RenderCommand, RenderCommandResult,
    SetItemPipeline, TrackedRenderPass, ViewSortedRenderPhases,
};
use bevy::render::render_resource::binding_types::{sampler, texture_2d, uniform_buffer};
use bevy::render::render_resource::*;
use bevy::render::renderer::{RenderContext, RenderDevice, RenderQueue, ViewQuery};
use bevy::render::sync_world::{MainEntity, RenderEntity};
use bevy::render::view::{ExtractedView, RetainedViewEntity, ViewUniform};
use bevy::shader::Shader;
use bevy::shader::ShaderCacheError;
use bevy::ui::{ComputedNode, ComputedStackIndex, ComputedUiTargetCamera};
use bevy::ui_render::{SetUiViewBindGroup, TransparentUi, stack_z_offsets};

use super::{LayerCaptureRect, LayerGroupAlpha, LayerMembership, PromotedLayer};
use crate::filters::{MAX_FILTER_PARAM_VECS, ResolvedFilterChain};

/// Matches the private `bevy_ui_render::UI_CAMERA_FAR` (the stock UI ortho
/// far plane / view z) so synthetic views project identically to the stock
/// UI view.
const UI_CAMERA_FAR: f32 = 1000.0;
/// Matches the private `bevy_ui_render::UI_CAMERA_TRANSFORM_OFFSET`.
const UI_CAMERA_TRANSFORM_OFFSET: f32 = -0.1;
/// Stock UI views use subview 1 on the *camera's* main entity; layer capture
/// views key off the *layer root's* main entity, so any constant would be
/// collision-free — a distinct one keeps `RetainedViewEntity` debugging sane.
const UI_LAYER_CAPTURE_SUBVIEW: u32 = 2;
/// Cycle/depth guard for enclosing-chain walks ([`walk_enclosing`] and the
/// capture-order depth computation): `enclosing` is acyclic by construction,
/// so a chain longer than this is a bug, not a real hierarchy — walks stop
/// rather than spin.
const MAX_LAYER_DEPTH: usize = 64;
/// Consecutive gated frames ([`GateState::gated_frames`]) before the stuck
/// composite gate warns about a pipeline that is *still compiling*. A shader
/// that outright FAILED warns immediately (the gate inspects
/// [`CachedPipelineState`] each gated frame), so this threshold only covers
/// the never-completes case; it is deliberately generous because frame count
/// is FPS-relative — at an uncapped 300 fps, startup compiles legitimately
/// take hundreds of gated frames (~2 s here; ~10 s at 60 fps).
const STUCK_GATE_HANG_FRAMES: u32 = 600;

/// A staged run's readiness gate — the filter, backdrop, and morph slots
/// each keep one. Staging a run invalidates its output ([`Self::restage`]);
/// prepare marks it valid again only when the whole run is certain to
/// execute this frame ([`Self::ready`]: every pass pipeline compiled, the
/// source valid). While invalid the composite is withheld — never a flash of
/// unfiltered/unblended content — and a stuck episode warns once
/// ([`Self::on_gated`]).
#[derive(Default, Debug)]
pub struct GateState {
    /// The chain version the last staged run used; `0` = never staged
    /// (versions start at 1).
    pub params_version: u32,
    /// Whether the run's output holds a complete result.
    pub output_valid: bool,
    /// Consecutive frames the composite was withheld; reset when the output
    /// goes valid. A pipeline that never compiles (a user WGSL error) would
    /// otherwise leave the subtree withheld forever with no log.
    pub gated_frames: u32,
    /// Whether this stuck episode already warned (once per episode).
    pub gate_warned: bool,
}

impl GateState {
    /// Stage a run for chain `version`: the output is invalid until
    /// [`Self::ready`]. A CHAIN CHANGE (vs a plain retry) re-arms the
    /// stuck-gate warn — the edit may swap in different shaders, and their
    /// failure deserves its own report.
    pub fn restage(&mut self, version: u32) {
        if self.params_version != version {
            self.gated_frames = 0;
            self.gate_warned = false;
        }
        self.params_version = version;
        self.output_valid = false;
    }

    /// The whole staged run will execute: the output is valid and any stuck
    /// episode ends.
    pub fn ready(&mut self) {
        self.output_valid = true;
        self.gated_frames = 0;
        self.gate_warned = false;
    }

    /// Count one withheld frame and warn once per stuck episode: immediately
    /// when one of the run's `pipelines` failed to compile (naming the
    /// error), else after [`STUCK_GATE_HANG_FRAMES`] — a still-compiling
    /// pipeline is normal startup latency. `what` names the pass family,
    /// `effect` what the user sees meanwhile.
    pub fn on_gated(
        &mut self,
        pipelines: impl IntoIterator<Item = CachedRenderPipelineId>,
        pipeline_cache: &PipelineCache,
        layer: MainEntity,
        what: &str,
        effect: &str,
    ) {
        self.gated_frames = self.gated_frames.saturating_add(1);
        if self.gate_warned {
            return;
        }
        // Only PERMANENT failures warn immediately. `ShaderNotLoaded` /
        // `ShaderImportNotYetAvailable` are transient (the cache re-queues
        // them while an asset-path shader streams in at startup) and fall
        // through to the hang threshold.
        let compile_error = pipelines.into_iter().find_map(|pipeline| {
            match pipeline_cache.get_render_pipeline_state(pipeline) {
                CachedPipelineState::Err(
                    e @ (ShaderCacheError::ProcessShaderError(_)
                    | ShaderCacheError::CreateShaderModule(_)),
                ) => Some(e.to_string()),
                _ => None,
            }
        });
        if let Some(err) = compile_error {
            tracing::warn!(
                "UI layer {layer:?}: {what} shader failed to compile — {effect}. Error: {err}"
            );
            self.gate_warned = true;
        } else if self.gated_frames == STUCK_GATE_HANG_FRAMES {
            tracing::warn!(
                "UI layer {layer:?}: composite withheld for {STUCK_GATE_HANG_FRAMES} \
                 consecutive frames and {what} pipeline is still not ready (no compile \
                 error reported — a hung/queued compile?) — {effect}."
            );
            self.gate_warned = true;
        }
    }
}

/// One filter pass of an extracted chain: the pass shader plus its packed
/// uniform params.
pub struct ExtractedFilterPass {
    /// The pass's fragment shader (the vertex stage is always the prelude's —
    /// see [`LayerFilterPipeline`]).
    pub shader: Handle<Shader>,
    /// The packed params, zero-padded to the full uniform array. A fixed
    /// array rather than the main world's `Vec`: `FilterUniforms.params` is
    /// fixed-size anyway, so padding at extract time makes uniform staging a
    /// plain copy (unused slots are never read by the pass shader).
    pub params: [Vec4; MAX_FILTER_PARAM_VECS],
}

/// A layer's filter chain, extracted from [`ResolvedFilterChain`]. Only the
/// render-side fields cross: `wire_index`/`layout`/`outset_px`/`scale` are
/// main-world concerns (animation metadata, capture sizing) and stay there.
pub struct ExtractedChain {
    pub passes: Vec<ExtractedFilterPass>,
    /// Mirrors [`ResolvedFilterChain::version`] — compared against
    /// [`GateState::params_version`] to detect param changes.
    pub version: u32,
    /// Mirrors [`ResolvedFilterChain::always_dirty`] (time-driven filters
    /// re-run every frame).
    pub always_dirty: bool,
    /// Mirrors [`ResolvedFilterChain::bucketable`] (every pass samples via
    /// the prelude helpers, so padded textures are safe).
    pub bucketable: bool,
}

/// Map a main-world resolved chain into its render-side [`ExtractedChain`].
/// The resolver never attaches an empty chain, but guard anyway — an empty
/// chain must read as "no filter machinery" downstream.
fn extract_chain(chain: Option<&ResolvedFilterChain>) -> Option<ExtractedChain> {
    chain
        .filter(|chain| !chain.passes.is_empty())
        .map(|chain| ExtractedChain {
            passes: chain
                .passes
                .iter()
                .map(|pass| {
                    // The registry rejects over-cap packs at resolve; a
                    // custom `resolve` override that bypassed it would
                    // otherwise be silently truncated here.
                    debug_assert!(
                        pass.params.len() <= MAX_FILTER_PARAM_VECS,
                        "filter pass packs {} vec4s, over MAX_FILTER_PARAM_VECS",
                        pass.params.len()
                    );
                    let mut params = [Vec4::ZERO; MAX_FILTER_PARAM_VECS];
                    for (slot, value) in params.iter_mut().zip(&pass.params) {
                        *slot = *value;
                    }
                    ExtractedFilterPass {
                        shader: pass.shader.clone(),
                        params,
                    }
                })
                .collect(),
            version: chain.version,
            always_dirty: chain.always_dirty,
            bucketable: chain.bucketable,
        })
}

/// One promoted layer, as seen by the render world this frame.
pub struct ExtractedLayer {
    /// The layer root's main-world entity (subtree identity).
    pub main_entity: MainEntity,
    /// The synthetic capture view ([`LayerEntities::view`], persistent). Only
    /// meaningful — carries an `ExtractedView` + `ViewUniformOffset` — while
    /// [`Self::needs_capture`], the only time the phase renders against it.
    pub view_entity: Entity,
    /// The synthetic view's phase key.
    pub retained: RetainedViewEntity,
    /// Render-world entity of the composite quad ([`LayerEntities::quad`],
    /// persistent; its [`LayerCompositeBatch`] is rewritten by prepare).
    pub quad_entity: Entity,
    /// Capture anchor: fractional physical px, stock UI view space (top-left
    /// of the node's border box — translation moves it without re-capturing).
    pub min: Vec2,
    /// Capture texture size in whole texels.
    pub size: UVec2,
    /// The screen-space rect the composite quad clamps to (the layer root's
    /// ancestor clipping, applied at composite time instead of capture time —
    /// see [`clip`]). `None` = unclipped.
    pub quad_clip: Option<bevy::math::Rect>,
    /// Composite-time group alpha.
    pub alpha: f32,
    /// Color format of the camera target — capture textures must match, or
    /// the stolen items' pipelines (specialized against the camera's format)
    /// would be invalid for the capture pass.
    pub target_format: TextureFormat,
    /// Whether this layer's capture must re-render this frame. `false` = the
    /// persistent texture in [`LayerTextureStore`] already holds the correct
    /// pixels: the capture pass skips it, its members are hidden from stock
    /// extraction ([`cached`]), and any item still stolen for it is dropped
    /// instead of re-drawn. Decided at extract time (main-world dirt ∪
    /// missing/mismatched slot), then propagated up the enclosing chain — a
    /// re-capturing layer's quad re-draws inside every enclosing capture.
    pub needs_capture: bool,
    /// The layer root's resolved filter chain, if any (always non-empty when
    /// present). Drives [`prepare_layer_filters`]; `None` clears the slot's
    /// filter state (see [`FilterSlot`]).
    pub chain: Option<ExtractedChain>,
    /// The layer root's resolved `backdropFilter` chain, if any (always
    /// non-empty and `always_dirty` when present — the source frame is
    /// live). Drives the backdrop snapshot + filter staging
    /// ([`backdrop::prepare_layer_backdrops`]); `None` clears the slot's
    /// backdrop state.
    pub backdrop_chain: Option<ExtractedChain>,
    /// Render-world entity of the backdrop composite quad (the frosted
    /// underlay drawn one epsilon below the content quad). Present only when
    /// [`Self::backdrop_chain`] is ([`LayerEntities::backdrop_quad`]).
    pub backdrop_quad_entity: Option<Entity>,
    /// The quantized outset margin baked into `min`/`size`
    /// ([`LayerCaptureRect::outset`]). The backdrop quad shrinks by this to
    /// the un-inflated border box — frost must not paint in the outset ring.
    pub outset: u32,
    /// The node's layout-resolved corner radii, `[top_left, top_right,
    /// bottom_right, bottom_left]` physical px (from
    /// `ComputedNode.border_radius` — already clamped per corner to
    /// `0.5 * min(w, h)`, Bevy's rule; matching what bevy_ui paints is the
    /// point). Consumed only by the backdrop quad's uniform push: the frost
    /// is masked to the rounded border box. All-zero = square.
    pub corner_radius: [f32; 4],
    /// The layer's composite-time 3D model matrix (screen-space homography,
    /// from `LayerTransform3dMatrix`). `None` = untransformed (absent style
    /// or identity params) — the quad takes the CPU clip path unchanged.
    pub transform3d: Option<Mat4>,
    /// Whether the layer carries the `TRANSFORM3D` promotion reason — its
    /// sampled texture allocates a mip chain (see [`mips`]). Keyed on the
    /// *reason*, not the matrix value: identity↔non-identity changes must
    /// never realloc/re-capture, and the chain stays warm for the first
    /// animated frame. Trilinear sampling itself engages only when
    /// [`Self::transform3d`] is `Some` AND the chain is valid.
    pub wants_mips: bool,
    /// Whether the layer's textures may be **bucket-allocated** (larger than
    /// the image, see [`store`]): no mip chain (mips downsample the padding
    /// into the image's edge), and every chain that samples them — content,
    /// backdrop, and the morph chain whenever one is resolved (a freeze
    /// steals the capture as the morph's input) — is
    /// [`bucketable`](ExtractedChain::bucketable). A flip reallocates (and
    /// re-captures) like a mip-state flip.
    pub bucketable: bool,
    /// The layer's in-flight morph, if any (an active
    /// [`crate::filters::MorphState`] + a resolved single-pass morph chain).
    /// Drives the freeze/steal in `prepare_layer_textures` and the blend
    /// pass ([`morph::prepare_layer_morphs`]); `None` clears the slot's
    /// morph state. The blend feeds the regular [`Self::chain`] (its pass 0
    /// re-sources) or the composite directly (morph-only layers, gated).
    pub morph: Option<morph::ExtractedMorph>,
    /// The IDLE morph's pass shader (a resolved single-pass morph chain with
    /// no active morph): [`morph::prepare_layer_morphs`] pre-specializes the
    /// blend pipeline from it, so the async compile happens while the morph
    /// is idle instead of on the first key change — where the not-yet-ready
    /// pipeline would gate the composite and blink the subtree out for a few
    /// frames. `None` while a morph is in flight ([`Self::morph`] carries
    /// the shader then).
    pub morph_warm: Option<Handle<Shader>>,
    /// The layer root's own stacking position as a phase sort key — the key
    /// a background quad of the root would have produced
    /// (`stack_z_offsets::BACKGROUND_COLOR` is 0.0). `None` when the root has
    /// no `ComputedStackIndex` yet. Source of [`Self::fallback_sort_key`].
    pub root_sort_key: Option<FloatOrd>,
    /// The root's true `InheritedVisibility` at extract time (read before the
    /// [`cached`] flip). Visibility inherits, so `false` means every member
    /// is invisible too — stock would have queued nothing for the subtree.
    pub root_visible: bool,
}

impl ExtractedLayer {
    /// Composite-quad sort key to fall back on when the subtree stole no
    /// phase items ([`Self::root_sort_key`]), in exactly two cases: a layer
    /// **served from cache** whose members were hidden from extraction
    /// ([`cached`]) — its quad still has to draw, where the subtree's first
    /// pixel would have — provided its root is visible (an invisible root
    /// queues nothing, so it draws no quad, as before the skip); and a layer
    /// with a **morph in flight**: an empty morph carrier (content
    /// mounted/unmounted around the blend) must still draw its blend quad.
    /// `None` everywhere else: idle empty layers draw no quad. Read after
    /// propagation (`needs_capture` must be final).
    pub fn fallback_sort_key(&self) -> Option<FloatOrd> {
        if self.morph.is_some() || (!self.needs_capture && self.root_visible) {
            self.root_sort_key
        } else {
            None
        }
    }
}

/// `bevy_ui_render`'s item-extraction sets (every `RenderUiSystems` set but
/// the camera views) as one set: bevy has no umbrella of its own, and the
/// layer extract-window systems (the clip swap, cached-member hiding) bracket
/// all of them.
#[derive(SystemSet, Debug, Clone, PartialEq, Eq, Hash)]
pub struct ExtractUiItems;

/// Per-frame extraction output. `layers` is index-aligned with
/// [`LayerCompositeMeta::atlas_bind_groups`].
#[derive(Resource, Default)]
pub struct ExtractedUiLayers {
    pub layers: Vec<ExtractedLayer>,
    /// node main entity → index into `layers` (steal routing). Derived from
    /// [`LayerMembership`] + the extraction order; rebuilt only when either
    /// moved (`membership_rebuilds` / `roots`), kept otherwise.
    pub membership: HashMap<MainEntity, usize>,
    /// layer index → index of its enclosing layer (quad routing); `None` =
    /// composite into the stock camera phase. Rebuilt with `membership`.
    pub enclosing: Vec<Option<usize>>,
    /// The `LayerMembership::rebuilds` the two maps above were derived from.
    pub membership_rebuilds: u64,
    /// The layer roots in `layers` order the two maps were derived from — a
    /// changed order re-indexes them.
    pub roots: Vec<Entity>,
    /// The stock UI view's phase key for the target camera.
    pub stock_view: Option<RetainedViewEntity>,
    /// The camera's render-world entity ([`ui_layer_capture_pass`] gates on
    /// the current view being this camera).
    pub camera_render_entity: Option<Entity>,
    /// Non-stock cameras already warned about ([`stock_camera`]): layers
    /// under them are skipped every frame; the warn (and its formatting)
    /// happens once per camera.
    pub warned_cameras: HashSet<Entity>,
    /// Layer indices in capture order: deepest (innermost) first, so an outer
    /// capture's pass samples already-rendered inner captures.
    pub capture_order: Vec<usize>,
}

/// Extracts promoted layers into the render world and maintains their
/// persistent render entities ([`LayerEntities`]: synthetic capture view +
/// composite quads). Must run after `extract_ui_camera_view`: that system
/// ends with a `retain` that would drop any phase it didn't create.
#[allow(clippy::type_complexity, clippy::too_many_arguments)]
pub fn extract_ui_layers(
    mut commands: Commands,
    mut views: Query<&mut ExtractedView, With<LayerCaptureView>>,
    mut phases: ResMut<ViewSortedRenderPhases<TransparentUi>>,
    mut extracted: ResMut<ExtractedUiLayers>,
    layers: Extract<
        Query<(
            Entity,
            &LayerCaptureRect,
            &LayerGroupAlpha,
            &ComputedUiTargetCamera,
            Option<&ResolvedFilterChain>,
            Option<&crate::filters::ResolvedBackdropChain>,
            Option<&crate::layer::transform3d::LayerTransform3dMatrix>,
            &PromotedLayer,
            Option<&ComputedNode>,
            Option<&ComputedStackIndex>,
            Option<&crate::filters::MorphState>,
            Option<&crate::filters::ResolvedMorphChain>,
            Option<&InheritedVisibility>,
        )>,
    >,
    membership: Extract<Res<LayerMembership>>,
    repaints: Extract<Res<super::LayerRepaintState>>,
    clips: Extract<Res<crate::layer::clip::LayerClips>>,
    cameras: Extract<
        Query<
            (
                RenderEntity,
                &Camera,
                Option<&bevy::camera::RenderTarget>,
                Has<bevy::ui::IsDefaultUiCamera>,
            ),
            Or<(With<Camera2d>, With<Camera3d>)>,
        >,
    >,
    main_pass_formats: Res<CameraMainPassTextureFormats>,
    mut store: ResMut<LayerTextureStore>,
) {
    // Split borrow: `entities` (maintained here) and `slots` (read for the
    // cache decision) are used together below.
    let store = &mut *store;
    extracted.layers.clear();
    extracted.capture_order.clear();
    extracted.stock_view = None;
    extracted.camera_render_entity = None;

    if layers.is_empty() {
        extracted.membership.clear();
        extracted.enclosing.clear();
        extracted.roots.clear();
        // No layers at all: every persistent entity set is stale.
        for (_, entities) in store.entities.drain() {
            despawn_layer_entities(&mut commands, &entities);
        }
        return;
    }

    // v1: all layers composite on ONE camera — the stock camera picked among
    // the cameras that have layers this frame (default UI camera > window
    // target > first seen, see [`stock_camera`]); a layer under any other
    // camera is skipped below, so it never injects a quad specialized on a
    // foreign target format into the stock phase.
    let camera_of = |target_camera: &ComputedUiTargetCamera| {
        let camera_main = target_camera.get()?;
        let (camera_render, camera, target, is_default_ui) = cameras.get(camera_main).ok()?;
        if !camera.is_active {
            return None;
        }
        let target_format = main_pass_formats.get(&camera_render).copied()?;
        let window_target = matches!(target, Some(bevy::camera::RenderTarget::Window(_)));
        Some((
            stock_camera::CameraCandidate {
                entity: camera_main,
                is_default_ui,
                window_target,
            },
            camera_render,
            target_format,
        ))
    };
    let stock_camera = stock_camera::pick_stock_camera(
        layers
            .iter()
            .filter_map(|l| camera_of(l.3).map(|(candidate, _, _)| candidate)),
    );
    let mut layer_index: HashMap<Entity, usize> = HashMap::default();
    for (
        root,
        rect,
        alpha,
        target_camera,
        filter_chain,
        backdrop,
        transform3d,
        promoted,
        computed,
        stack_index,
        morph_state,
        morph_chain,
        root_visibility,
    ) in layers.iter()
    {
        let Some((candidate, camera_render, target_format)) = camera_of(target_camera) else {
            continue;
        };
        let camera_main = candidate.entity;
        if Some(camera_main) != stock_camera {
            // Non-stock camera: skipped, not extracted (no persistent
            // entities, no membership → its members are neither stolen nor
            // hidden by the cached-member skip; the subtree renders
            // unpromoted in its own camera's phase).
            let stock = stock_camera.expect("a candidate exists, so a stock camera was picked");
            if extracted.warned_cameras.insert(camera_main) {
                stock_camera::warn_skipped(camera_main, stock);
            }
            continue;
        }
        if extracted.stock_view.is_none() {
            extracted.stock_view = Some(RetainedViewEntity::new(
                camera_main.into(),
                None,
                // Stock `UI_CAMERA_SUBVIEW`.
                1,
            ));
            extracted.camera_render_entity = Some(camera_render);
        }

        let (min, size) = (rect.min, rect.size);
        let retained =
            RetainedViewEntity::new(MainEntity::from(root), None, UI_LAYER_CAPTURE_SUBVIEW);
        // The layer's persistent entities: spawned on first sight, kept until
        // the layer stops being extracted (evicted below). The view gets its
        // `ExtractedView` in the sync pass at the end — `needs_capture` is
        // only final after propagation.
        let entities = store
            .entities
            .entry(MainEntity::from(root))
            .or_insert_with(|| LayerEntities {
                view: commands.spawn(LayerCaptureView).id(),
                view_extracted: false,
                quad: commands.spawn(LayerCompositeBatch::default()).id(),
                backdrop_quad: None,
            });
        let view_entity = entities.view;
        let quad_entity = entities.quad;
        phases.prepare_for_new_frame(retained);

        let wants_mips = promoted.reasons.0 & crate::layer::PromotionReasons::TRANSFORM3D != 0;
        let bucketable = !wants_mips
            && filter_chain.is_none_or(|c| c.bucketable)
            && backdrop.is_none_or(|b| b.0.bucketable)
            && morph_chain.is_none_or(|m| m.0.bucketable);
        // Cache decision: re-capture on main-world dirt, or when the persistent
        // slot can't serve (first frame, a size change — the image is
        // re-laid-out even when the allocation still fits —, or a realloc:
        // outgrown allocation, format flip, or a mip-state flip — the fresh
        // texture needs content).
        let cached_ok = store
            .slots
            .get(&MainEntity::from(root))
            .is_some_and(|slot| {
                slot.content_valid
                    && slot.size == size
                    && !slot.needs_realloc(size, target_format, wants_mips, bucketable)
            });
        let needs_capture = !cached_ok || repaints.dirty.contains(&root);

        let chain = extract_chain(filter_chain);
        let backdrop_chain = extract_chain(backdrop.map(|b| &b.0));
        // The backdrop quad follows the chain's presence (spawned when a
        // `backdropFilter` appears, despawned when it goes).
        let backdrop_quad_entity = match (backdrop_chain.is_some(), entities.backdrop_quad) {
            (true, Some(quad)) => Some(quad),
            (true, None) => {
                let quad = commands.spawn(LayerCompositeBatch::default()).id();
                entities.backdrop_quad = Some(quad);
                Some(quad)
            }
            (false, Some(quad)) => {
                commands.entity(quad).despawn();
                entities.backdrop_quad = None;
                None
            }
            (false, None) => None,
        };
        // An in-flight morph: active state + a recorded freeze rect + a
        // resolved single-pass chain (the resolver's cap guarantees one pass;
        // guard anyway — no morph must ever read as a partial one).
        let morph = morph_state.and_then(|state| {
            if !state.active {
                return None;
            }
            let chain = &morph_chain?.0;
            let pass = extract_chain(Some(chain))
                .and_then(|mut c| (c.passes.len() == 1).then(|| c.passes.remove(0)))?;
            Some(morph::ExtractedMorph {
                freeze_seq: state.freeze_seq,
                progress: state.progress,
                version: chain.version,
                pass,
            })
        });
        // Idle morph: carry the resolved pass shader so the blend pipeline
        // pre-compiles before the first key change (no first-morph gate
        // blink).
        let morph_warm = match &morph {
            Some(_) => None,
            None => morph_chain
                .and_then(|c| (c.0.passes.len() == 1).then(|| c.0.passes[0].shader.clone())),
        };

        layer_index.insert(root, extracted.layers.len());
        extracted.layers.push(ExtractedLayer {
            main_entity: MainEntity::from(root),
            view_entity,
            retained,
            quad_entity,
            min,
            size,
            quad_clip: clips.quads.get(&root).copied().flatten(),
            alpha: alpha.0.clamp(0.0, 1.0),
            target_format,
            needs_capture,
            chain,
            backdrop_chain,
            backdrop_quad_entity,
            outset: rect.outset,
            corner_radius: computed.map_or([0.0; 4], |c| c.border_radius.into()),
            // Identity matrices stay `None`: the quad renders exactly like an
            // untransformed layer (CPU clip path), and picking stays inert.
            transform3d: transform3d.filter(|m| !m.identity).map(|m| m.model),
            wants_mips,
            bucketable,
            root_sort_key: stack_index
                .map(|s| FloatOrd(s.0 as f32 + stack_z_offsets::BACKGROUND_COLOR)),
            root_visible: root_visibility.is_some_and(|v| v.get()),
            morph,
            morph_warm,
        });
    }

    // Prune phases of layers that died since last frame: stock `retain` only
    // keeps its own views alive, and ours re-register just above, so any
    // subview-2 phase without a live layer this frame is stale.
    let live: HashSet<RetainedViewEntity> = extracted.layers.iter().map(|l| l.retained).collect();
    phases.retain(|retained, _| {
        retained.subview_index != UI_LAYER_CAPTURE_SUBVIEW || live.contains(retained)
    });
    // Same for the persistent entities: a layer not extracted this frame
    // (demoted, despawned, camera gone inactive) loses its view + quads.
    store.entities.retain(|main, entities| {
        let live = layer_index.contains_key(&main.id());
        if !live {
            despawn_layer_entities(&mut commands, entities);
        }
        live
    });

    // The steal index (node → layer index) and the quad routing derive from
    // main-world membership and this frame's layer order; both are stable
    // across a plain geometry frame, so re-derive only when one moved.
    let roots_changed = extracted.roots.len() != extracted.layers.len()
        || extracted
            .roots
            .iter()
            .zip(&extracted.layers)
            .any(|(root, layer)| *root != layer.main_entity.id());
    if roots_changed || extracted.membership_rebuilds != membership.rebuilds {
        let extracted = &mut *extracted;
        extracted.membership_rebuilds = membership.rebuilds;
        extracted.roots.clear();
        extracted
            .roots
            .extend(extracted.layers.iter().map(|l| l.main_entity.id()));
        extracted.membership.clear();
        for (node, layer_root) in membership.node_to_layer.iter() {
            if let Some(&idx) = layer_index.get(layer_root) {
                extracted.membership.insert(MainEntity::from(*node), idx);
            }
        }
        extracted.enclosing = extracted
            .layers
            .iter()
            .map(|layer| {
                membership
                    .enclosing
                    .get(&layer.main_entity.id())
                    .copied()
                    .flatten()
                    .and_then(|e| layer_index.get(&e).copied())
            })
            .collect();
    }
    // Propagate `needs_capture` outward: a re-capturing inner layer's quad
    // re-draws inside its enclosing captures, so those must re-capture too.
    // (The main-world resolver already propagates its dirt the same way; this
    // pass additionally covers render-side reasons — a missing/realloc'd
    // slot — so redistribute can rely on "outer cached ⇒ inner cached".)
    let extracted = &mut *extracted;
    for i in 0..extracted.layers.len() {
        if extracted.layers[i].needs_capture {
            let layers = &mut extracted.layers;
            walk_enclosing(i, &extracted.enclosing, |outer| {
                if layers[outer].needs_capture {
                    return false; // its own chain is already propagated
                }
                layers[outer].needs_capture = true;
                true
            });
        }
    }
    // A nested backdrop layer's quad holds LIVE screen pixels (the snapshot
    // re-blits every frame), so every enclosing capture containing that quad
    // can never serve from cache — force the chain dirty unconditionally,
    // each frame. The backdrop layer's OWN content capture still caches
    // normally (the frost is a separate quad, not part of its capture).
    // Documented cost: nesting a backdrop defeats ancestor capture caching.
    for i in 0..extracted.layers.len() {
        if extracted.layers[i].backdrop_chain.is_some() {
            let layers = &mut extracted.layers;
            walk_enclosing(i, &extracted.enclosing, |outer| {
                if layers[outer].needs_capture {
                    return false; // already dirty ⇒ its chain already is too
                }
                layers[outer].needs_capture = true;
                true
            });
        }
    }
    // Capture order: innermost first (an outer capture samples its inner
    // quads). depth = length of the enclosing chain.
    let enclosing = extracted.enclosing.clone();
    let depth_of = |mut idx: usize| {
        let mut depth = 0usize;
        while let Some(outer) = enclosing[idx] {
            depth += 1;
            idx = outer;
            if depth > MAX_LAYER_DEPTH {
                break; // cycle guard (impossible by construction)
            }
        }
        depth
    };
    let mut order: Vec<usize> = (0..extracted.layers.len()).collect();
    order.sort_by_key(|&i| std::cmp::Reverse(depth_of(i)));
    extracted.capture_order = order;

    // Sync each layer's synthetic view to its FINAL `needs_capture`: a
    // capturing layer's view carries an `ExtractedView` (inserted on the
    // flip, updated in place — compare-before-write — while it stays), a
    // cached layer's view carries none (removed on the flip), so
    // `prepare_view_uniforms` only ever writes uniforms for views whose
    // phase actually renders this frame.
    for layer in &extracted.layers {
        let Some(entities) = store.entities.get_mut(&layer.main_entity) else {
            continue;
        };
        match (layer.needs_capture, entities.view_extracted) {
            (true, true) => {
                if let Ok(mut view) = views.get_mut(entities.view) {
                    update_capture_view(&mut view, layer);
                }
            }
            (true, false) => {
                commands.entity(entities.view).insert(capture_view(layer));
                entities.view_extracted = true;
            }
            (false, true) => {
                commands.entity(entities.view).remove::<ExtractedView>();
                entities.view_extracted = false;
            }
            (false, false) => {}
        }
    }
}

/// The synthetic capture view for `layer`: an ortho over the capture rect in
/// stock UI view space — vertices keep their physical screen coordinates; the
/// projection alone remaps the rect to the capture target's clip space.
/// Top-left origin like stock. The bounds are fractional — the window tracks
/// the node exactly, so capture content is translation-invariant even
/// subpixel.
fn capture_view(layer: &ExtractedLayer) -> ExtractedView {
    let (min, size) = (layer.min, layer.size);
    ExtractedView {
        retained_view_entity: layer.retained,
        clip_from_view: Mat4::orthographic_rh(
            min.x,
            min.x + size.x as f32,
            min.y + size.y as f32,
            min.y,
            0.0,
            UI_CAMERA_FAR,
        ),
        world_from_view: GlobalTransform::from_xyz(
            0.0,
            0.0,
            UI_CAMERA_FAR + UI_CAMERA_TRANSFORM_OFFSET,
        ),
        clip_from_world: None,
        target_format: layer.target_format,
        viewport: UVec4::new(0, 0, size.x, size.y),
        color_grading: Default::default(),
        invert_culling: false,
    }
}

/// Bring a persistent view up to date with `layer`, touching it only when
/// something moved (a stationary re-capturing layer writes nothing).
fn update_capture_view(view: &mut Mut<ExtractedView>, layer: &ExtractedLayer) {
    let fresh = capture_view(layer);
    if view.clip_from_view != fresh.clip_from_view
        || view.viewport != fresh.viewport
        || view.target_format != fresh.target_format
        || view.retained_view_entity != fresh.retained_view_entity
    {
        **view = fresh;
    }
}

/// Despawn a layer's persistent entity set (the layer left extraction).
fn despawn_layer_entities(commands: &mut Commands, entities: &LayerEntities) {
    commands.entity(entities.view).despawn();
    commands.entity(entities.quad).despawn();
    if let Some(quad) = entities.backdrop_quad {
        commands.entity(quad).despawn();
    }
}

/// Moves promoted subtrees' phase items from the camera's UI phase into their
/// layer's synthetic phase, then injects one composite quad per layer. Runs
/// after queueing, before the stock sort (which then sorts every phase,
/// stolen items keeping their global stack-index sort keys).
pub fn redistribute_ui_layers(
    extracted: Res<ExtractedUiLayers>,
    mut phases: ResMut<ViewSortedRenderPhases<TransparentUi>>,
    draw_functions: Res<DrawFunctions<TransparentUi>>,
    composite_pipeline: Option<Res<LayerCompositePipeline>>,
    mut specialized: ResMut<SpecializedRenderPipelines<LayerCompositePipeline>>,
    pipeline_cache: Res<PipelineCache>,
) {
    if extracted.layers.is_empty() {
        return;
    }
    let Some(stock_view) = extracted.stock_view else {
        return;
    };
    let Some(composite_pipeline) = composite_pipeline else {
        return;
    };

    // Steal: drain matching items out of the stock phase in one pass…
    let mut stolen: Vec<(usize, (Entity, MainEntity), TransparentUi)> = Vec::new();
    // …tracking each layer's first (lowest-sort-key) stolen item: the
    // composite quad draws exactly where the subtree would have started.
    let mut quad_sort_keys: Vec<Option<FloatOrd>> = vec![None; extracted.layers.len()];
    {
        let Some(stock_phase) = phases.get_mut(&stock_view) else {
            return;
        };
        // One O(n) partition pass (order-preserving): a `shift_remove` per
        // stolen key shifts the IndexMap tail each time — O(n²), ~14ms/frame
        // at 500 stress layers with most of the phase promoted.
        let taken = std::mem::take(&mut stock_phase.items);
        for (key, item) in taken {
            let Some(&idx) = extracted.membership.get(&item.main_entity()) else {
                stock_phase.items.insert(key, item);
                continue;
            };
            let best = &mut quad_sort_keys[idx];
            if best.is_none() || item.sort_key < best.unwrap() {
                *best = Some(item.sort_key);
            }
            stolen.push((idx, key, item));
        }
    }
    // Cached layers' members were hidden from extraction ([`cached`]), so
    // they stole nothing: their quads take the root's own stacking position.
    fill_fallback_sort_keys(
        &mut quad_sort_keys,
        extracted
            .layers
            .iter()
            .map(ExtractedLayer::fallback_sort_key),
    );
    propagate_quad_sort_keys(&mut quad_sort_keys, &extracted.enclosing);
    for (idx, _key, item) in stolen {
        // A cached layer's items (anything an extractor outside the hide
        // window still produced — see [`cached`]'s known gap) are simply
        // dropped: the persistent texture already holds their pixels, so
        // nothing re-draws them (and stock `prepare_uinodes` builds no
        // vertices for them either). The steal keeps them out of the stock
        // phase.
        if !extracted.layers[idx].needs_capture {
            continue;
        }
        if let Some(phase) = phases.get_mut(&extracted.layers[idx].retained) {
            phase.add_transient(item);
        }
    }

    // Inject composite quads — inner layers' quads land in their enclosing
    // layer's phase (they are content of the outer capture); top-level quads
    // land in the camera phase at the subtree's stacking position.
    let draw_function = draw_functions.read().id::<DrawLayerComposite>();
    for (idx, layer) in extracted.layers.iter().enumerate() {
        let Some(sort_key) = quad_sort_keys[idx] else {
            // Nothing of this subtree was queued (hidden/empty): no quad.
            continue;
        };
        let pipeline = specialized.specialize(
            &pipeline_cache,
            &composite_pipeline,
            LayerCompositePipelineKey {
                target_format: layer.target_format,
            },
        );
        let target = match extracted.enclosing[idx] {
            Some(outer) => {
                if !extracted.layers[outer].needs_capture {
                    // The enclosing capture is cached and already contains this
                    // quad's pixels — nothing to draw it into. Propagation
                    // guarantees a re-capturing inner never meets a cached
                    // outer.
                    debug_assert!(
                        !layer.needs_capture,
                        "inner layer re-captures but its enclosing layer is cached"
                    );
                    continue;
                }
                extracted.layers[outer].retained
            }
            None => stock_view,
        };
        if let Some(phase) = phases.get_mut(&target) {
            // The frosted backdrop draws one epsilon UNDER the whole subtree
            // (`BACKGROUND_COLOR` is 0.0 — the content quad sits exactly at
            // the first stolen key, so "under" needs an explicit offset).
            if let Some(backdrop_quad_entity) = layer.backdrop_quad_entity {
                phase.add_transient(TransparentUi {
                    sort_key: FloatOrd(sort_key.0 - backdrop::BACKDROP_UNDERLAY_EPSILON),
                    entity: (backdrop_quad_entity, layer.main_entity),
                    pipeline,
                    draw_function,
                    batch_range: 0..0,
                    extra_index: PhaseItemExtraIndex::None,
                    index: idx,
                    indexed: false,
                });
            }
            phase.add_transient(TransparentUi {
                sort_key: FloatOrd(sort_key.0 + stack_z_offsets::BACKGROUND_COLOR),
                entity: (layer.quad_entity, layer.main_entity),
                pipeline,
                draw_function,
                batch_range: 0..0,
                extra_index: PhaseItemExtraIndex::None,
                index: idx,
                indexed: false,
            });
        }
    }
}

/// One composite-quad vertex: physical screen position (2D — the quad lies in
/// the UI plane, `composite.wgsl` flattens z anyway; the stock UI view
/// projects it), capture UV, and the group alpha. Future composite params
/// (per-rule) extend this struct — the pass stays rule-agnostic.
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub struct LayerCompositeVertex {
    pub position: [f32; 2],
    pub uv: [f32; 2],
    pub alpha: f32,
}

/// Vertex buffer + per-layer capture bind groups for the composite draws.
#[derive(Resource)]
pub struct LayerCompositeMeta {
    /// This frame's staged vertices (CPU side) + the GPU vertex buffer.
    pub vertices: RawBufferVec<LayerCompositeVertex>,
    /// What the GPU buffer currently holds: the staged list is uploaded only
    /// when it differs (a static scene of cached layers re-stages identical
    /// bytes every frame — the upload is skipped, the buffer already matches).
    pub uploaded: Vec<LayerCompositeVertex>,
    pub atlas_bind_groups: Vec<BindGroup>,
}

impl Default for LayerCompositeMeta {
    fn default() -> Self {
        Self {
            vertices: RawBufferVec::new(BufferUsages::VERTEX),
            uploaded: Vec::new(),
            atlas_bind_groups: Vec::new(),
        }
    }
}

/// The composite quad's draw data on its render entity (mirrors `UiBatch`).
/// Always present on a quad entity ([`LayerEntities`]): a quad that staged
/// nothing this frame keeps a stale value, which is never read — its phase
/// item's `batch_range` stays `0..0` and empty ranges are skipped unrendered.
#[derive(Component, Default, Clone)]
pub struct LayerCompositeBatch {
    pub range: Range<u32>,
    /// Index into [`LayerCompositeMeta::atlas_bind_groups`].
    pub atlas: usize,
    /// Dynamic offset of this quad's [`transform3d::CompositeUniforms`] entry.
    pub uniform_offset: u32,
}

/// Edge-AA inflation for 3D-transformed composite quads, in pre-transform
/// local px: the quad grows this much on every side (UVs extended
/// proportionally past `[0, 1]`, clamped by the sampler) so the fragment
/// stage can center a feather of the same width on the true rect edge — the
/// outside half lands on the inflated ring, the inside half on real content.
const EDGE_AA_INFLATE_PX: f32 = 1.0;

/// A quad that staged vertices this frame, pending its
/// [`LayerCompositeBatch`] write once the uniform offsets are known.
struct StagedQuad {
    entity: Entity,
    range: Range<u32>,
    atlas: usize,
    /// Index into [`transform3d::CompositeUniformsMeta::staged`].
    uniform: usize,
}

/// Stage one quad (two triangles, 6 vertices) spanning `min..max` with UVs
/// `uv_min..uv_max` at group alpha `alpha`.
fn push_quad_vertices(
    vertices: &mut RawBufferVec<LayerCompositeVertex>,
    min: Vec2,
    max: Vec2,
    uv_min: Vec2,
    uv_max: Vec2,
    alpha: f32,
) {
    let corners = [
        ([min.x, min.y], [uv_min.x, uv_min.y]),
        ([max.x, min.y], [uv_max.x, uv_min.y]),
        ([max.x, max.y], [uv_max.x, uv_max.y]),
        ([min.x, min.y], [uv_min.x, uv_min.y]),
        ([max.x, max.y], [uv_max.x, uv_max.y]),
        ([min.x, max.y], [uv_min.x, uv_max.y]),
    ];
    for (position, uv) in corners {
        vertices.push(LayerCompositeVertex {
            position,
            uv,
            alpha,
        });
    }
}

/// Builds composite-quad vertices + bind groups and writes each quad's
/// [`LayerCompositeBatch`] (through its persistent entity) and vertex range
/// back into its phase item. GPU uploads happen only when the staged data
/// differs from what the buffers hold (see [`LayerCompositeMeta::uploaded`]).
#[allow(clippy::too_many_arguments)]
pub fn prepare_layer_composites(
    extracted: Res<ExtractedUiLayers>,
    mut store: ResMut<LayerTextureStore>,
    mut batches: Query<&mut LayerCompositeBatch>,
    pipeline: Option<Res<LayerCompositePipeline>>,
    pipeline_cache: Res<PipelineCache>,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    mut meta: ResMut<LayerCompositeMeta>,
    mut uniforms_meta: ResMut<transform3d::CompositeUniformsMeta>,
    filter_meta: Res<LayerFilterMeta>,
    backdrop_meta: Res<backdrop::BackdropMeta>,
    morph_meta: Res<morph::MorphMeta>,
    mut phases: ResMut<ViewSortedRenderPhases<TransparentUi>>,
) {
    meta.vertices.clear();
    meta.atlas_bind_groups.clear();
    uniforms_meta.staged.clear();
    let Some(pipeline) = pipeline else {
        return;
    };
    if extracted.layers.is_empty() {
        return;
    }

    // Membership set for the post-sort batch-range pass at the bottom: the
    // render entities of every quad that actually staged vertices this frame.
    let mut drawable: HashSet<Entity> = HashSet::default();
    let mut staged_quads: Vec<StagedQuad> = Vec::new();
    // Filtered layers whose output isn't ready this frame: their quads stay
    // batch-less, so any enclosing capture rendered without them must not be
    // served from cache — see the invalidation loop after this one.
    let mut gated: Vec<usize> = Vec::new();
    for (idx, layer) in extracted.layers.iter().enumerate() {
        let Some(slot) = store.slots.get_mut(&layer.main_entity) else {
            continue;
        };
        // Every texture the quad may sample (capture, filter output, blend)
        // holds the layer's image in its top-left `slot.size` texels.
        let image_size = slot.size.as_vec2();
        // Pick the quad's source: the raw capture, or — for a filtered
        // layer — the final filter pass's ping-pong output.
        let bind_group = if layer.chain.is_some() {
            let Some(filter) = slot.filter.as_mut() else {
                // Allocated by `prepare_layer_textures` whenever a chain is
                // present; a miss means nothing to sample — gate the quad.
                gated.push(idx);
                continue;
            };
            // Readiness gate: chain present but no complete filtered output
            // yet (startup compile, realloc). Skip the batch — the injected
            // item keeps `batch_range 0..0` and draws nothing. Never fall
            // back to the raw capture: a frame of unfiltered content is
            // exactly the flash this gate exists to prevent.
            if !filter.gate.output_valid {
                filter.gate.on_gated(
                    filter_meta
                        .runs
                        .get(idx)
                        .and_then(Option::as_ref)
                        .into_iter()
                        .flat_map(|run| run.passes.iter().map(|pass| pass.pipeline)),
                    &pipeline_cache,
                    layer.main_entity,
                    "a filter pass",
                    "the layer's subtree is invisible (the composite gate never falls back \
                     to unfiltered content) and its filter run restages every frame",
                );
                gated.push(idx);
                continue;
            }
            // Cached until realloc; invalidated when `output_index` flips
            // (pass-count parity change).
            let output = filter.output_index;
            // Trilinear only for a non-identity quad over a valid mip chain;
            // otherwise the bilinear level-0 view (correct, just unmipped —
            // never a gate, never a stale mip).
            if layer.transform3d.is_some() && filter.mips_valid {
                let Some(chain) = &filter.mips[output] else {
                    unreachable!("mips_valid implies a staged chain");
                };
                if !matches!(&filter.composite_bind_group_mips, Some((built, _)) if *built == output)
                {
                    filter.composite_bind_group_mips = Some((
                        output,
                        render_device.create_bind_group(
                            "ui_layer_composite_filtered_mips",
                            &pipeline_cache.get_bind_group_layout(&pipeline.atlas_layout),
                            &BindGroupEntries::sequential((
                                &chain.full_view,
                                &pipeline.sampler_mips,
                            )),
                        ),
                    ));
                }
                let (_, bind_group) = filter.composite_bind_group_mips.as_ref().expect("just set");
                bind_group.clone()
            } else {
                if !matches!(&filter.composite_bind_group, Some((built, _)) if *built == output) {
                    filter.composite_bind_group = Some((
                        output,
                        render_device.create_bind_group(
                            "ui_layer_composite_filtered",
                            &pipeline_cache.get_bind_group_layout(&pipeline.atlas_layout),
                            &BindGroupEntries::sequential((
                                &filter.textures[output].default_view,
                                &pipeline.sampler,
                            )),
                        ),
                    ));
                }
                let (_, bind_group) = filter.composite_bind_group.as_ref().expect("just set");
                bind_group.clone()
            }
        } else if layer.morph.is_some() {
            // Morph-only layer: the quad samples the blend, gated with the
            // content-filter discipline (never a mid-blend flash of raw
            // content). Bilinear only in v1 — the blend carries no mips, so
            // a 3D-transformed morphing quad minifies without them.
            let Some(morph_slot) = slot.morph.as_mut() else {
                gated.push(idx);
                continue;
            };
            let Some(bind_group) = morph::morph_gate(
                idx,
                layer.main_entity,
                morph_slot,
                &morph_meta,
                &pipeline_cache,
                &render_device,
                &pipeline.atlas_layout,
                &pipeline.sampler,
            ) else {
                gated.push(idx);
                continue;
            };
            bind_group
        } else if layer.transform3d.is_some()
            && slot.mips_valid
            && let Some(chain) = &slot.mips
        {
            // Trilinear variant over the capture's full-mip view (same layout
            // slot — any Filtering sampler fits). Lazy like `bind_group`.
            if slot.bind_group_mips.is_none() {
                slot.bind_group_mips = Some(render_device.create_bind_group(
                    "ui_layer_composite_atlas_mips",
                    &pipeline_cache.get_bind_group_layout(&pipeline.atlas_layout),
                    &BindGroupEntries::sequential((&chain.full_view, &pipeline.sampler_mips)),
                ));
            }
            slot.bind_group_mips.clone().expect("just set")
        } else {
            // Reuse the slot's bind group across frames; it dies on realloc.
            if slot.bind_group.is_none() {
                slot.bind_group = Some(render_device.create_bind_group(
                    "ui_layer_composite_atlas",
                    &pipeline_cache.get_bind_group_layout(&pipeline.atlas_layout),
                    &BindGroupEntries::sequential((&slot.texture.default_view, &pipeline.sampler)),
                ));
            }
            slot.bind_group.clone().expect("just set")
        };
        let start = meta.vertices.len() as u32;
        // Fractional quad position (bilinear sampling smooths subpixel motion
        // of a cached capture — the browser tradeoff), clamped to the layer's
        // ancestor clip: the CAPTURE is clip-independent (interior clips
        // only — see `clip::swap_interior_clips_in`), so the quad is where
        // scroll/viewport clipping applies, with UVs shifted proportionally
        // on clamped sides. A fully clipped-away layer draws no quad at all
        // (the item's batch_range stays `0..0`).
        //
        // A 3D-transformed quad can't be CPU-clamped (the clip rect is
        // axis-aligned in screen space; the transformed quad isn't): it keeps
        // its full geometry/UVs — inflated for the edge-AA feather — and the
        // ancestor clip moves into the fragment stage via the per-quad
        // uniform. A "fully clipped away" verdict is likewise unknowable
        // pre-transform, so the transformed path always draws. Untransformed
        // quads keep the CPU path, an open clip sentinel, and a zero feather —
        // the shader stays single-path and pixel-identical for them.
        let (q, model, clip_rect, feather) = match layer.transform3d {
            Some(model) => (
                clip::clip_quad(layer.min, layer.size, -EDGE_AA_INFLATE_PX, None)
                    .expect("a grown quad is never empty"),
                model,
                layer.quad_clip,
                EDGE_AA_INFLATE_PX,
            ),
            None => {
                let Some(q) = clip::clip_quad(layer.min, layer.size, 0.0, layer.quad_clip) else {
                    continue;
                };
                (q, Mat4::IDENTITY, None, 0.0)
            }
        };
        let (min, max) = (q.pos_min, q.pos_max);
        let (uv_min, uv_max) = (q.uv_min, q.uv_max);
        // UVs are quad-relative.
        push_quad_vertices(&mut meta.vertices, min, max, uv_min, uv_max, layer.alpha);
        drawable.insert(layer.quad_entity);
        let atlas_index = meta.atlas_bind_groups.len();
        meta.atlas_bind_groups.push(bind_group);
        let (open_min, open_max) = transform3d::open_clip();
        let uniform = uniforms_meta.staged.len();
        uniforms_meta.staged.push(transform3d::CompositeUniforms {
            model,
            clip_min: clip_rect.map_or(open_min, |r| r.min),
            clip_max: clip_rect.map_or(open_max, |r| r.max),
            edge_feather: feather,
            pad_a: 0.0,
            image_size,
            // Content quads never round: the capture already holds the
            // node's own rounded paint. Zero radii disable the mask.
            radius: Vec4::ZERO,
            box_center: Vec2::ZERO,
            box_size: Vec2::ZERO,
        });
        staged_quads.push(StagedQuad {
            entity: layer.quad_entity,
            range: start..start + 6,
            atlas: atlas_index,
            uniform,
        });
    }
    // Backdrop quads: the frosted underlay, staged after the content quads so
    // both share the vertex buffer + bind-group list. Geometry is the
    // UN-inflated border box (never the outset ring), UVs into the inflated
    // chain output, alpha = group alpha (a fading panel fades its frost),
    // identity model + zero feather + CPU clip clamp (the untransformed path
    // — a backdrop under a 3D-transformed layer stays axis-aligned, the
    // documented v1 limit). A gated backdrop stays batch-less and draws
    // nothing — the region shows the real frame, graceful by construction,
    // and no enclosing invalidation is needed (extraction already forces
    // enclosing re-capture every frame for backdrop layers).
    for (idx, layer) in extracted.layers.iter().enumerate() {
        let Some(backdrop_quad_entity) = layer.backdrop_quad_entity else {
            continue;
        };
        let Some(slot) = store.slots.get_mut(&layer.main_entity) else {
            continue;
        };
        let image_size = slot.size.as_vec2();
        let Some(backdrop_slot) = slot.backdrop.as_mut() else {
            continue;
        };
        let Some(bind_group) = backdrop::backdrop_gate(
            idx,
            layer.main_entity,
            backdrop_slot,
            &backdrop_meta,
            &pipeline_cache,
            &render_device,
            &pipeline.atlas_layout,
            &pipeline.sampler,
        ) else {
            continue;
        };
        let Some(q) = clip::clip_quad(layer.min, layer.size, layer.outset as f32, layer.quad_clip)
        else {
            continue;
        };
        let start = meta.vertices.len() as u32;
        push_quad_vertices(
            &mut meta.vertices,
            q.pos_min,
            q.pos_max,
            q.uv_min,
            q.uv_max,
            layer.alpha,
        );
        drawable.insert(backdrop_quad_entity);
        let atlas_index = meta.atlas_bind_groups.len();
        meta.atlas_bind_groups.push(bind_group);
        // The UNCLIPPED border box (the same shrink the backdrop `clip_quad` inset applies)
        // for the rounded-corner mask: the CPU clip may have clamped the
        // quad's geometry above, but the SDF must measure the true box.
        let box_min = layer.min + Vec2::splat(layer.outset as f32);
        let box_max = layer.min + layer.size.as_vec2() - Vec2::splat(layer.outset as f32);
        let (open_min, open_max) = transform3d::open_clip();
        let uniform = uniforms_meta.staged.len();
        uniforms_meta.staged.push(transform3d::CompositeUniforms {
            model: Mat4::IDENTITY,
            clip_min: open_min,
            clip_max: open_max,
            edge_feather: 0.0,
            pad_a: 0.0,
            image_size,
            // Frost is masked to the node's rounded border box; the radii
            // are the layout-resolved ones bevy_ui paints with, so the
            // frost edge coincides with the panel's own rounded edge.
            radius: Vec4::from(layer.corner_radius),
            box_center: (box_min + box_max) * 0.5,
            box_size: box_max - box_min,
        });
        staged_quads.push(StagedQuad {
            entity: backdrop_quad_entity,
            range: start..start + 6,
            atlas: atlas_index,
            uniform,
        });
    }
    // A gated quad drew nothing into its enclosing captures this frame, yet
    // those captures' `content_valid` was predicted from pipeline readiness
    // alone — an outer capture with a hole where the filtered subtree belongs
    // could otherwise be frozen as "valid". Force the enclosing chain to
    // re-capture until the filtered output exists.
    for idx in gated {
        walk_enclosing(idx, &extracted.enclosing, |outer| {
            if let Some(slot) = store.slots.get_mut(&extracted.layers[outer].main_entity) {
                slot.content_valid = false;
            }
            true
        });
    }
    // Uploads, skipped when nothing changed: both staging lists are rebuilt
    // every frame, but for a still scene (cached layers, nothing moving) they
    // come out byte-identical to what the GPU buffers already hold — no
    // `write_buffer`, and the uniform offsets from that upload stay valid.
    // A never-created buffer always writes.
    {
        let LayerCompositeMeta {
            vertices, uploaded, ..
        } = &mut *meta;
        let staged: &[u8] = bytemuck::cast_slice(vertices.values());
        if vertices.buffer().is_none() || staged != bytemuck::cast_slice::<_, u8>(uploaded) {
            vertices.write_buffer(&render_device, &render_queue);
            uploaded.clear();
            uploaded.extend_from_slice(vertices.values());
        }
    }
    // Composite uniforms: one whole-buffer bind group, per-quad entries
    // selected by dynamic offset. The bind group is rebuilt only when the
    // buffer object changes (a growth realloc) — the `PassBindKey` rule.
    let uniforms_meta = &mut *uniforms_meta;
    if uniforms_meta.uniforms.buffer().is_none() || uniforms_meta.staged != uniforms_meta.uploaded {
        let transform3d::CompositeUniformsMeta {
            uniforms,
            staged,
            uploaded,
            offsets,
            ..
        } = uniforms_meta;
        uniforms.clear();
        offsets.clear();
        offsets.extend(staged.iter().map(|entry| uniforms.push(entry)));
        uniforms.write_buffer(&render_device, &render_queue);
        std::mem::swap(staged, uploaded);
    }
    if let Some(buffer) = uniforms_meta.uniforms.buffer()
        && !matches!(&uniforms_meta.bind_group, Some((id, _)) if *id == buffer.id())
    {
        let binding = uniforms_meta.uniforms.binding().expect("buffer exists");
        uniforms_meta.bind_group = Some((
            buffer.id(),
            render_device.create_bind_group(
                "ui_layer_composite_uniforms",
                &pipeline_cache.get_bind_group_layout(&pipeline.uniform_layout),
                &BindGroupEntries::single(binding),
            ),
        ));
    }
    // Stamp the batches through the quads' persistent entities (no
    // commands: the component is always present, see `LayerCompositeBatch`).
    for staged in staged_quads {
        if let Ok(mut batch) = batches.get_mut(staged.entity) {
            *batch = LayerCompositeBatch {
                range: staged.range,
                atlas: staged.atlas,
                uniform_offset: uniforms_meta.offsets[staged.uniform],
            };
        }
    }

    // Mark the injected quads drawable (post-sort, pre-draw). A phase item's
    // `batch_range` is an *item-skip count* — `SortedRenderPhase::render`
    // advances by `len()` and skips empty ranges entirely — so a standalone
    // quad is exactly `0..1`; its vertex range rides `LayerCompositeBatch`.
    for phase in phases.values_mut() {
        for item in phase.items.values_mut() {
            if drawable.contains(&item.entity()) {
                item.batch_range = 0..1;
            }
        }
    }
}

/// The composite pipeline: group 0 is the stock UI view uniform (so
/// [`SetUiViewBindGroup`] is reused verbatim), group 1 the capture texture.
/// Blending is **premultiplied** (`One`/`OneMinusSrcAlpha`): capture content
/// is premultiplied by construction (straight-alpha blending onto transparent
/// black), and the shader multiplies rgb *and* alpha by the group alpha.
#[derive(Resource)]
pub struct LayerCompositePipeline {
    pub view_layout: BindGroupLayoutDescriptor,
    pub atlas_layout: BindGroupLayoutDescriptor,
    /// Group 2: the per-quad [`transform3d::CompositeUniforms`] (dynamic
    /// offset) — 3D model matrix + fragment clip rect.
    pub uniform_layout: BindGroupLayoutDescriptor,
    pub sampler: Sampler,
    /// Trilinear + anisotropic sampler for non-identity 3D-transformed quads
    /// over a valid mip chain (see [`mips`]) — tilting minifies the capture,
    /// where bilinear-over-level-0 shimmers. Same layout slot as
    /// [`Self::sampler`] (any Filtering sampler fits), selected per quad via
    /// the variant bind groups.
    pub sampler_mips: Sampler,
    pub shader: Handle<Shader>,
}

pub fn init_layer_composite_pipeline(
    mut commands: Commands,
    render_device: Res<RenderDevice>,
    asset_server: Res<AssetServer>,
) {
    let view_layout = BindGroupLayoutDescriptor::new(
        "ui_layer_composite_view_layout",
        &BindGroupLayoutEntries::single(
            ShaderStages::VERTEX_FRAGMENT,
            uniform_buffer::<ViewUniform>(true),
        ),
    );
    let atlas_layout = BindGroupLayoutDescriptor::new(
        "ui_layer_composite_atlas_layout",
        &BindGroupLayoutEntries::sequential(
            ShaderStages::FRAGMENT,
            (
                texture_2d(TextureSampleType::Float { filterable: true }),
                sampler(SamplerBindingType::Filtering),
            ),
        ),
    );
    let uniform_layout = BindGroupLayoutDescriptor::new(
        "ui_layer_composite_uniform_layout",
        &BindGroupLayoutEntries::single(
            ShaderStages::VERTEX_FRAGMENT,
            uniform_buffer::<transform3d::CompositeUniforms>(true),
        ),
    );
    commands.insert_resource(LayerCompositePipeline {
        view_layout,
        atlas_layout,
        uniform_layout,
        sampler: render_device.create_sampler(&SamplerDescriptor {
            label: Some("ui_layer_composite_sampler"),
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            ..Default::default()
        }),
        // Anisotropy needs no wgpu feature; it requires all three filters
        // Linear (which trilinear wants anyway) and a texture that actually
        // has a mip chain — the bind-group selection guarantees that.
        sampler_mips: render_device.create_sampler(&SamplerDescriptor {
            label: Some("ui_layer_composite_sampler_mips"),
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            mipmap_filter: bevy::render::render_resource::MipmapFilterMode::Linear,
            anisotropy_clamp: 8,
            ..Default::default()
        }),
        shader: bevy::asset::load_embedded_asset!(asset_server.as_ref(), "composite.wgsl"),
    });
}

#[derive(Clone, Copy, Hash, PartialEq, Eq)]
pub struct LayerCompositePipelineKey {
    pub target_format: TextureFormat,
}

impl SpecializedRenderPipeline for LayerCompositePipeline {
    type Key = LayerCompositePipelineKey;

    fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
        let vertex_layout = VertexBufferLayout::from_vertex_formats(
            VertexStepMode::Vertex,
            vec![
                // position (2D, UI plane)
                VertexFormat::Float32x2,
                // uv
                VertexFormat::Float32x2,
                // alpha
                VertexFormat::Float32,
            ],
        );
        RenderPipelineDescriptor {
            vertex: VertexState {
                shader: self.shader.clone(),
                buffers: vec![vertex_layout],
                ..Default::default()
            },
            fragment: Some(FragmentState {
                shader: self.shader.clone(),
                targets: vec![Some(ColorTargetState {
                    format: key.target_format,
                    blend: Some(BlendState::PREMULTIPLIED_ALPHA_BLENDING),
                    write_mask: ColorWrites::ALL,
                })],
                ..Default::default()
            }),
            layout: vec![
                self.view_layout.clone(),
                self.atlas_layout.clone(),
                self.uniform_layout.clone(),
            ],
            label: Some("ui_layer_composite_pipeline".into()),
            ..Default::default()
        }
    }
}

pub struct SetLayerAtlasBindGroup<const I: usize>;
impl<P: PhaseItem, const I: usize> RenderCommand<P> for SetLayerAtlasBindGroup<I> {
    type Param = SRes<LayerCompositeMeta>;
    type ViewQuery = ();
    type ItemQuery = bevy::ecs::system::lifetimeless::Read<LayerCompositeBatch>;

    #[inline]
    fn render<'w>(
        _item: &P,
        _view: (),
        batch: Option<&'w LayerCompositeBatch>,
        meta: SystemParamItem<'w, '_, Self::Param>,
        pass: &mut TrackedRenderPass<'w>,
    ) -> RenderCommandResult {
        let Some(batch) = batch else {
            return RenderCommandResult::Skip;
        };
        let Some(bind_group) = meta.into_inner().atlas_bind_groups.get(batch.atlas) else {
            return RenderCommandResult::Failure("layer atlas bind group missing");
        };
        pass.set_bind_group(I, bind_group, &[]);
        RenderCommandResult::Success
    }
}

pub struct DrawLayerQuad;
impl<P: PhaseItem> RenderCommand<P> for DrawLayerQuad {
    type Param = SRes<LayerCompositeMeta>;
    type ViewQuery = ();
    type ItemQuery = bevy::ecs::system::lifetimeless::Read<LayerCompositeBatch>;

    #[inline]
    fn render<'w>(
        _item: &P,
        _view: (),
        batch: Option<&'w LayerCompositeBatch>,
        meta: SystemParamItem<'w, '_, Self::Param>,
        pass: &mut TrackedRenderPass<'w>,
    ) -> RenderCommandResult {
        let Some(batch) = batch else {
            return RenderCommandResult::Skip;
        };
        let Some(vertices) = meta.into_inner().vertices.buffer() else {
            return RenderCommandResult::Failure("layer composite vertices missing");
        };
        pass.set_vertex_buffer(0, vertices.slice(..));
        pass.draw(batch.range.clone(), 0..1);
        RenderCommandResult::Success
    }
}

/// The composite quad's draw stack — view uniform reuse means the quad rides
/// whatever view its phase belongs to (screen, or an outer layer's capture).
pub type DrawLayerComposite = (
    SetItemPipeline,
    SetUiViewBindGroup<0>,
    SetLayerAtlasBindGroup<1>,
    transform3d::SetCompositeUniforms<2>,
    DrawLayerQuad,
);

/// The Rust mirror of the prelude's `FilterUniforms`
/// (`layer/filter_prelude.wgsl`) — one entry per staged filter pass in
/// [`LayerFilterMeta::uniforms`]. The explicit pad fields reproduce the WGSL
/// uniform-address-space layout byte for byte (176 bytes total; asserted by
/// `filter_uniforms_match_the_documented_wgsl_layout`). The digit-free
/// `pad_a`/`pad_b` names are load-bearing on the WGSL side: naga's namer
/// appends `_` to identifiers ending in a digit, which naga_oil rejects in
/// composable modules — and the mirror matches field for field.
#[derive(Clone, Copy, ShaderType)]
pub struct FilterUniforms {
    /// Seconds since startup (render-world `Time`), for `USES_TIME` filters.
    pub time: f32,
    pub pad_a: f32,
    /// The pass target's size in physical px.
    pub resolution: Vec2,
    /// `1.0 / resolution`: one texel step in UV.
    pub texel_size: Vec2,
    /// The capture outset baked into the pass target: physical px of margin
    /// on every side between the target edge and the node's border box
    /// ([`ExtractedLayer::outset`], splatted). Lets a shader anchor geometry
    /// to the node rect (prelude `content_uv`) inside the inflated capture.
    pub content_inset: Vec2,
    /// The image size (physical px) of the texture at binding 3
    /// (`capture_texture`): `resolution` for content and backdrop passes; a
    /// morph pass binds the frozen snapshot there, whose image was captured
    /// at its own size (prelude `from_image_size` — the sampling helpers
    /// remap onto a bucket-allocated texture from it).
    pub from_image_size: Vec2,
    pub pad_b: Vec2,
    /// The packed filter params ([`ExtractedFilterPass::params`]).
    pub params: [Vec4; MAX_FILTER_PARAM_VECS],
}

/// The filter-pass pipeline: ONE bind group layout for every filter — group 0
/// is the source texture (the capture, or the previous pass's ping-pong
/// output), a linear clamp-to-edge sampler, one dynamically-offset
/// [`FilterUniforms`], and the layer's original capture (always bound, so any
/// pass can sample the unfiltered input). The vertex stage of every filter
/// pipeline is bevy's fullscreen triangle ([`FullscreenShader`]); the
/// fragment entry (`fragment`) lives in each pass shader that `#import`s the
/// prelude for bindings/helpers — the cross-stage interface is the prelude's
/// `FullscreenVertexOutput`, bevy's own.
#[derive(Resource)]
pub struct LayerFilterPipeline {
    pub layout: BindGroupLayoutDescriptor,
    pub sampler: Sampler,
    pub fullscreen: FullscreenShader,
}

pub fn init_layer_filter_pipeline(
    mut commands: Commands,
    render_device: Res<RenderDevice>,
    fullscreen: Res<FullscreenShader>,
) {
    let layout = BindGroupLayoutDescriptor::new(
        "ui_layer_filter_layout",
        &BindGroupLayoutEntries::sequential(
            ShaderStages::FRAGMENT,
            (
                texture_2d(TextureSampleType::Float { filterable: true }),
                sampler(SamplerBindingType::Filtering),
                // `uniform_buffer::<T>` sets `min_binding_size` from
                // `T::min_size()` — the 160-byte contract.
                uniform_buffer::<FilterUniforms>(true),
                // The layer's original capture (prelude `capture_texture`).
                texture_2d(TextureSampleType::Float { filterable: true }),
            ),
        ),
    );
    commands.insert_resource(LayerFilterPipeline {
        layout,
        sampler: render_device.create_sampler(&SamplerDescriptor {
            label: Some("ui_layer_filter_sampler"),
            address_mode_u: AddressMode::ClampToEdge,
            address_mode_v: AddressMode::ClampToEdge,
            mag_filter: FilterMode::Linear,
            min_filter: FilterMode::Linear,
            ..Default::default()
        }),
        fullscreen: fullscreen.clone(),
    });
}

/// Specialization key: the pass's fragment shader plus the target format
/// (filter targets ride the capture's format). `Handle<Shader>` hashes by
/// asset id, so it works as a key directly.
#[derive(Clone, Hash, PartialEq, Eq)]
pub struct LayerFilterPipelineKey {
    pub shader: Handle<Shader>,
    pub target_format: TextureFormat,
}

impl SpecializedRenderPipeline for LayerFilterPipeline {
    type Key = LayerFilterPipelineKey;

    fn specialize(&self, key: Self::Key) -> RenderPipelineDescriptor {
        RenderPipelineDescriptor {
            vertex: self.fullscreen.to_vertex_state(),
            fragment: Some(FragmentState {
                shader: key.shader,
                // `filter` is a WGSL reserved word — the prelude's contract
                // names the entry `fragment`.
                entry_point: Some("fragment".into()),
                targets: vec![Some(ColorTargetState {
                    format: key.target_format,
                    // Replace-write, no blending: the prelude documents that
                    // previous target contents are irrelevant and the
                    // fragment's (premultiplied) output lands verbatim.
                    blend: None,
                    write_mask: ColorWrites::ALL,
                })],
                ..Default::default()
            }),
            layout: vec![self.layout.clone()],
            label: Some("ui_layer_filter_pipeline".into()),
            ..Default::default()
        }
    }
}

/// Whether a layer's filter passes must (re-)run this frame: fresh capture
/// content, changed params, a time-driven chain, or an output that was never
/// completed (startup, realloc, or a run whose execution was skipped).
pub const fn needs_filter_run(
    needs_capture: bool,
    chain_version: u32,
    stored_version: u32,
    always_dirty: bool,
    output_valid: bool,
) -> bool {
    needs_capture || chain_version != stored_version || always_dirty || !output_valid
}

/// Walks the enclosing-layer chain upward from `start` (exclusive), calling
/// `visit` with each enclosing ancestor's index. Stops when the chain ends
/// (`enclosing[cur]` is `None`), when `visit` returns `false`, or after
/// [`MAX_LAYER_DEPTH`] ancestors — the shared bounded guard for every
/// enclosing-chain traversal (`enclosing` is acyclic by construction, so the
/// cap only matters for impossible cycles).
fn walk_enclosing(start: usize, enclosing: &[Option<usize>], mut visit: impl FnMut(usize) -> bool) {
    let mut cur = start;
    for _ in 0..MAX_LAYER_DEPTH {
        let Some(outer) = enclosing[cur] else {
            break;
        };
        if !visit(outer) {
            break;
        }
        cur = outer;
    }
}

/// A layer whose subtree stole no items but still needs its composite quad
/// on screen — one served from cache (members hidden from extraction) or a
/// MORPHING empty carrier mid-blend — fills the missing key from the
/// extract-time fallback ([`ExtractedLayer::fallback_sort_key`], the layer
/// root's own stacking position). Runs before propagation so an enclosing
/// layer inherits the filled key like any stolen one. A stolen key always
/// wins; layers without a fallback stay `None`.
fn fill_fallback_sort_keys(
    keys: &mut [Option<FloatOrd>],
    fallbacks: impl IntoIterator<Item = Option<FloatOrd>>,
) {
    for (key, fallback) in keys.iter_mut().zip(fallbacks) {
        if key.is_none() {
            *key = fallback;
        }
    }
}

/// A layer whose every visible descendant lives in NESTED layers steals no
/// items of its own (a bare wrapper around promoted children queues no
/// vertices), so its composite-quad position must come from its inner
/// layers' quads: propagate each recorded key up the enclosing chain,
/// keeping the minimum — the position where the subtree's first pixel would
/// have drawn. Stopping at an ancestor that already holds a `<=` key is
/// safe: that key's own propagation covers the rest of the chain.
fn propagate_quad_sort_keys(keys: &mut [Option<FloatOrd>], enclosing: &[Option<usize>]) {
    for idx in 0..keys.len() {
        let Some(key) = keys[idx] else {
            continue;
        };
        walk_enclosing(idx, enclosing, |outer| match keys[outer] {
            Some(existing) if existing <= key => false,
            _ => {
                keys[outer] = Some(key);
                true
            }
        });
    }
}

/// Ping-pong source for pass `i`: `None` = the layer's capture texture
/// (pass 0), otherwise the index of the previous pass's target.
pub const fn filter_source_index(pass: usize) -> Option<usize> {
    if pass == 0 {
        None
    } else {
        Some((pass - 1) % 2)
    }
}

/// Ping-pong target for pass `i`.
pub const fn filter_target_index(pass: usize) -> usize {
    pass % 2
}

/// Which ping-pong texture holds the final output of a `len`-pass chain
/// (the last pass's target; `len` is at least 1 for any staged run).
pub const fn filter_output_index(len: usize) -> usize {
    (len.saturating_sub(1)) % 2
}

/// One staged filter pass, replayed by [`ui_layer_capture_pass`]: set the
/// pipeline, bind group 0 at the dynamic offset, render 3 vertices into
/// `target`.
pub struct LayerFilterPass {
    pub pipeline: CachedRenderPipelineId,
    pub bind_group: BindGroup,
    pub uniform_offset: u32,
    pub target: TextureView,
}

/// A layer's staged filter run this frame.
pub struct LayerFilterRun {
    pub passes: Vec<LayerFilterPass>,
    /// `Some(image size)` when the pass targets are bucket-allocated (larger
    /// than the image): every pass sets this viewport + scissor so the
    /// fullscreen triangle covers exactly the image and `uv` spans it
    /// ([`LayerSlot::image_viewport`]). `None` = the full target.
    pub viewport: Option<UVec2>,
}

/// Restrict a pass writing a bucket-allocated texture to its top-left
/// `image`-texel sub-rect: the viewport maps clip space onto the image (the
/// fullscreen triangle's `uv` then spans exactly the image), the scissor
/// keeps stray fragments out of the padding.
pub(super) fn set_image_viewport(pass: &mut TrackedRenderPass, image: UVec2) {
    pass.set_viewport(0.0, 0.0, image.x as f32, image.y as f32, 0.0, 1.0);
    pass.set_scissor_rect(0, 0, image.x, image.y);
}

/// Begin a pass writing `target`, cleared to transparent — every layer pass
/// replace-writes the texels it keeps, so `Clear` vs `Load` is
/// content-equivalent and `Clear` skips loading stale contents on tiled
/// GPUs. `viewport` restricts it to a bucket-allocated target's image
/// ([`set_image_viewport`]).
pub(super) fn clear_pass<'a>(
    ctx: &'a mut RenderContext,
    label: &'static str,
    target: &TextureView,
    viewport: Option<UVec2>,
) -> TrackedRenderPass<'a> {
    let mut pass = ctx.begin_tracked_render_pass(RenderPassDescriptor {
        label: Some(label),
        color_attachments: &[Some(RenderPassColorAttachment {
            view: target,
            depth_slice: None,
            resolve_target: None,
            ops: Operations {
                load: LoadOp::Clear(LinearRgba::NONE.into()),
                store: StoreOp::Store,
            },
        })],
        depth_stencil_attachment: None,
        timestamp_writes: None,
        occlusion_query_set: None,
        multiview_mask: None,
    });
    if let Some(image) = viewport {
        set_image_viewport(&mut pass, image);
    }
    pass
}

/// One fullscreen-triangle pass: `pipeline` with `bind_group` (and its
/// dynamic `offsets`) over a [`clear_pass`] into `target`.
pub(super) fn fullscreen_pass(
    ctx: &mut RenderContext,
    label: &'static str,
    target: &TextureView,
    viewport: Option<UVec2>,
    pipeline: &RenderPipeline,
    bind_group: &BindGroup,
    offsets: &[u32],
) {
    let mut pass = clear_pass(ctx, label, target, viewport);
    pass.set_render_pipeline(pipeline);
    pass.set_bind_group(0, bind_group, offsets);
    pass.draw(0..3, 0..1);
}

/// Every pass pipeline of a staged run, or `None` while any is still
/// compiling: a run executes whole or not at all, never a partial chain
/// (its gate's `output_valid` stayed false at prepare, so the composite is
/// gated this frame and the layer restages + retries next frame).
pub(super) fn run_pipelines<'a>(
    run: &LayerFilterRun,
    pipeline_cache: &'a PipelineCache,
) -> Option<Vec<&'a RenderPipeline>> {
    run.passes
        .iter()
        .map(|pass| pipeline_cache.get_render_pipeline(pass.pipeline))
        .collect()
}

/// Execute a staged run's passes in order, with the pipelines
/// [`run_pipelines`] resolved.
pub(super) fn replay_run(
    ctx: &mut RenderContext,
    label: &'static str,
    run: &LayerFilterRun,
    pipelines: Vec<&RenderPipeline>,
) {
    for (pass, pipeline) in run.passes.iter().zip(pipelines) {
        fullscreen_pass(
            ctx,
            label,
            &pass.target,
            run.viewport,
            pipeline,
            &pass.bind_group,
            &[pass.uniform_offset],
        );
    }
}

/// Per-frame filter staging: the uniform buffer (one entry per staged pass)
/// and the replay list, index-aligned with [`ExtractedUiLayers::layers`].
/// `runs[idx] = None` means "no filter work this frame" — either the layer
/// has no chain, or its cached output is still valid (the composite samples
/// `FilterSlot.textures[output_index]` either way).
#[derive(Resource)]
pub struct LayerFilterMeta {
    pub uniforms: DynamicUniformBuffer<FilterUniforms>,
    pub runs: Vec<Option<LayerFilterRun>>,
}

impl Default for LayerFilterMeta {
    fn default() -> Self {
        let mut uniforms = DynamicUniformBuffer::default();
        uniforms.set_label(Some("ui_layer_filter_uniforms"));
        Self {
            uniforms,
            runs: Vec::new(),
        }
    }
}

/// Stages every resource a layer's filter passes need this frame: pipeline
/// specialization, one uniform entry per pass, and per-pass bind groups over
/// the capture/ping-pong textures. Execution happens in
/// [`ui_layer_capture_pass`], which replays [`LayerFilterMeta::runs`] right
/// after each layer's capture; this system also *predicts* that execution
/// (phase 3) and writes [`GateState::output_valid`] accordingly, so the
/// downstream [`prepare_layer_composites`] gate is same-frame accurate.
#[allow(clippy::too_many_arguments)]
pub fn prepare_layer_filters(
    extracted: Res<ExtractedUiLayers>,
    mut store: ResMut<LayerTextureStore>,
    pipeline: Option<Res<LayerFilterPipeline>>,
    mut specialized: ResMut<SpecializedRenderPipelines<LayerFilterPipeline>>,
    pipeline_cache: Res<PipelineCache>,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    time: Res<Time>,
    mut meta: ResMut<LayerFilterMeta>,
) {
    let LayerFilterMeta { uniforms, runs } = &mut *meta;
    uniforms.clear();
    runs.clear();
    runs.resize_with(extracted.layers.len(), || None);
    let Some(pipeline) = pipeline else {
        return;
    };

    // Phase 1: decide, specialize, and stage uniforms. Bind groups wait for
    // phase 2 — they must reference the uniform buffer *after* `write_buffer`
    // (which may reallocate it).
    struct StagedPass {
        pipeline: CachedRenderPipelineId,
        uniform_offset: u32,
    }
    let mut staged: Vec<(usize, Vec<StagedPass>)> = Vec::new();
    for (idx, layer) in extracted.layers.iter().enumerate() {
        let Some(chain) = &layer.chain else {
            continue;
        };
        let Some(slot) = store.slots.get_mut(&layer.main_entity) else {
            continue;
        };
        // Uniforms describe the IMAGE the pass targets share with the
        // capture (`resolution`); the targets themselves may be larger.
        let size = slot.size;
        let Some(filter) = slot.filter.as_mut() else {
            continue;
        };
        // An in-flight morph re-blends every frame (progress moves), and the
        // regular chain sources the blend — so it must re-run every frame
        // too, regardless of its own version bookkeeping.
        if !needs_filter_run(
            layer.needs_capture,
            chain.version,
            filter.gate.params_version,
            chain.always_dirty,
            filter.gate.output_valid,
        ) && layer.morph.is_none()
        {
            continue;
        }
        // The staged run supersedes whatever the output textures hold; phase 3
        // below marks the output valid again iff the passes will execute.
        filter.gate.restage(chain.version);
        // The run rewrites the output's level 0 — its mip chain goes stale
        // until `prepare_layer_mips` (ordered after this system) restages it.
        filter.mips_valid = false;
        filter.output_index = filter_output_index(chain.passes.len());

        let resolution = size.as_vec2();
        let texel_size = Vec2::ONE / resolution;
        let mut passes = Vec::with_capacity(chain.passes.len());
        for pass in &chain.passes {
            let id = specialized.specialize(
                &pipeline_cache,
                &pipeline,
                LayerFilterPipelineKey {
                    shader: pass.shader.clone(),
                    target_format: layer.target_format,
                },
            );
            let uniform_offset = uniforms.push(&FilterUniforms {
                time: time.elapsed_secs(),
                pad_a: 0.0,
                resolution,
                texel_size,
                content_inset: Vec2::splat(layer.outset as f32),
                // Binding 3 is the capture (or the blend), same image.
                from_image_size: resolution,
                pad_b: Vec2::ZERO,
                params: pass.params,
            });
            passes.push(StagedPass {
                pipeline: id,
                uniform_offset,
            });
        }
        staged.push((idx, passes));
    }
    if staged.is_empty() {
        return;
    }

    // Phase 2: write the uniforms, then build the per-pass bind groups
    // against the (possibly fresh) buffer.
    uniforms.write_buffer(&render_device, &render_queue);
    let (Some(uniform_binding), Some(uniform_buffer)) = (uniforms.binding(), uniforms.buffer())
    else {
        return;
    };
    let layout = pipeline_cache.get_bind_group_layout(&pipeline.layout);
    for (idx, staged_passes) in staged {
        let layer = &extracted.layers[idx];
        let Some(slot) = store.slots.get_mut(&layer.main_entity) else {
            continue;
        };
        // A morphing layer's chain filters the BLEND (the morph pass's
        // output — "morph first, then filters"), both as pass-0 source and
        // as the binding-3 `capture_texture`: the blend IS the effective
        // capture of a morphing layer, so combine-style passes (bloom) stay
        // correct mid-morph.
        let effective_capture = slot
            .morph
            .as_ref()
            .map_or(&slot.texture.default_view, |m| &m.blend.default_view);
        let viewport = slot.image_viewport();
        let Some(filter) = slot.filter.as_mut() else {
            continue;
        };
        // Bind groups are cached per pass and reused while their inputs
        // (views + uniform buffer) are the same objects — a restaging chain
        // (animated params) pays nothing here after its first frame.
        filter.pass_bind_groups.truncate(staged_passes.len());
        let passes = staged_passes
            .into_iter()
            .enumerate()
            .map(|(i, pass)| {
                let source = match filter_source_index(i) {
                    None => effective_capture,
                    Some(ping) => &filter.textures[ping].default_view,
                };
                let key = PassBindKey {
                    source: source.id(),
                    capture: effective_capture.id(),
                    uniforms: uniform_buffer.id(),
                };
                let bind_group = filter.pass_bind_groups.get_or_create(i, key, || {
                    render_device.create_bind_group(
                        "ui_layer_filter",
                        &layout,
                        &BindGroupEntries::sequential((
                            source,
                            &pipeline.sampler,
                            uniform_binding.clone(),
                            effective_capture,
                        )),
                    )
                });
                LayerFilterPass {
                    pipeline: pass.pipeline,
                    bind_group,
                    uniform_offset: pass.uniform_offset,
                    target: filter.textures[filter_target_index(i)].default_view.clone(),
                }
            })
            .collect();
        runs[idx] = Some(LayerFilterRun { passes, viewport });
    }

    // Phase 3: predict execution and mark outputs valid. Mirrors the
    // `content_valid` discipline in `prepare_layer_textures`: a pipeline that
    // `get_render_pipeline` resolves *now* is guaranteed to resolve in the
    // graph node too (compiled pipelines never regress within a frame), so
    // marking valid here is safe — and a still-compiling pipeline (prediction
    // false) leaves `output_valid` false, which both gates the composite quad
    // (no partial/unfiltered flash) and forces a restage + retry next frame.
    // The source capture must be valid too ([`LayerSlot::content_valid`]):
    // filtering a blank/partial capture would freeze garbage on screen.
    for (idx, run) in runs.iter().enumerate() {
        let Some(run) = run else {
            continue;
        };
        let Some(slot) = store.slots.get_mut(&extracted.layers[idx].main_entity) else {
            continue;
        };
        let ready = run
            .passes
            .iter()
            .all(|pass| pipeline_cache.get_render_pipeline(pass.pipeline).is_some());
        // A morphing layer's chain sources the blend, so its output is only
        // as valid as the morph pass that writes it (`prepare_layer_morphs`
        // runs before this system and decided already).
        let morph_ok = slot.morph.as_ref().is_none_or(|m| m.gate.output_valid);
        if ready
            && slot.content_valid
            && morph_ok
            && let Some(filter) = slot.filter.as_mut()
        {
            filter.gate.ready();
        }
    }
}

/// Renders each layer's synthetic phase into its capture texture, then
/// replays the layer's staged filter run (if any) capture → ping-pong
/// textures. Runs in the camera's schedule right before the stock `ui_pass`
/// consumes the composite quads.
#[allow(clippy::too_many_arguments)]
pub fn ui_layer_capture_pass(
    world: &World,
    view: ViewQuery<Entity>,
    extracted: Res<ExtractedUiLayers>,
    store: Res<LayerTextureStore>,
    phases: Res<ViewSortedRenderPhases<TransparentUi>>,
    filter_meta: Res<LayerFilterMeta>,
    mip_meta: Res<mips::LayerMipMeta>,
    backdrop_meta: Res<backdrop::BackdropMeta>,
    morph_meta: Res<morph::MorphMeta>,
    blit_pipeline: Option<Res<backdrop::BackdropBlitPipeline>>,
    pipeline_cache: Res<PipelineCache>,
    mut ctx: RenderContext,
) {
    if extracted.camera_render_entity != Some(view.into_inner()) {
        return;
    }
    // The camera's CURRENT main texture — post-PostProcess, pre-`ui_pass`:
    // the tonemapped 3D frame with no UI on it, the v1 backdrop source.
    // Fetched here (not prepare) because the a/b buffer selection flips
    // during PostProcess.
    let main_texture = backdrop::camera_main_texture(world, extracted.camera_render_entity);
    // Innermost first ([`ExtractedUiLayers::capture_order`]): a quad sampling
    // layer B's capture (or B's filtered output) must draw — inside some
    // outer capture or the screen — only after B's capture *and filter*
    // passes ran; passes execute in encoder order, and B's filter replay sits
    // in B's loop iteration, before any enclosing layer's capture.
    for &idx in &extracted.capture_order {
        let layer = &extracted.layers[idx];
        // Backdrop first: blit the frame region into the snapshot, then run
        // the backdrop chain. Independent of the content capture below (the
        // source is the pre-UI frame, static across this whole loop in v1).
        if let Some(main_texture) = &main_texture {
            backdrop::run_backdrop_passes(
                idx,
                &backdrop_meta,
                blit_pipeline.as_deref(),
                main_texture,
                &pipeline_cache,
                &mut ctx,
            );
        }
        // Capture. Skipped when cached (`!needs_capture`): the persistent
        // texture already holds the pixels — and skipping keeps the
        // `LoadOp::Clear` from wiping them.
        // An EMPTY phase still captures: the clear-only pass leaves a valid
        // transparent texture — the correct content of a subtree that paints
        // nothing (an empty morph carrier freezes from / blends to it).
        if layer.needs_capture
            && let Some(slot) = store.slots.get(&layer.main_entity)
            && let Some(phase) = phases.get(&layer.retained)
        {
            // A bucket-allocated texture: the synthetic view's ortho maps the
            // capture rect onto clip space, so the viewport places the image
            // 1:1 in the texture's top-left `size` texels (the clear still
            // wipes the whole attachment — the padding stays transparent).
            let mut pass = clear_pass(
                &mut ctx,
                "ui_layer_capture",
                &slot.texture.default_view,
                slot.image_viewport(),
            );
            if let Err(err) = phase.render(&mut pass, world, layer.view_entity) {
                tracing::error!("layer capture pass failed: {err:?}");
            }
        }

        // Morph replay — capture + snapshot → blend. Before the filter
        // replay: a regular chain on a morphing layer sources the blend.
        morph::run_morph_passes(idx, &morph_meta, &pipeline_cache, &mut ctx);

        // Filter replay — also when the capture above was skipped as cached:
        // a staged run over a clean capture is a params-only change (slider
        // move, time tick) re-filtering last frame's pixels.
        if let Some(run) = filter_meta.runs.get(idx).and_then(Option::as_ref)
            && let Some(pipelines) = run_pipelines(run, &pipeline_cache)
        {
            replay_run(&mut ctx, "ui_layer_filter", run, pipelines);
        }

        // Mip downsample replay — after capture AND filter, so the chain
        // reads this frame's level 0 (of whichever texture the composite
        // samples). Staged only when stale (`mips_valid` — a cached capture
        // keeps last frame's mips and stages nothing); the pipeline was
        // verified compiled at staging, so a `None` here is unreachable-in-
        // practice and simply skips.
        if let Some(run) = mip_meta.runs.get(idx).and_then(Option::as_ref)
            && let Some(pipeline) = pipeline_cache.get_render_pipeline(run.pipeline)
        {
            for level in &run.levels {
                fullscreen_pass(
                    &mut ctx,
                    "ui_layer_mip_blit",
                    &level.target,
                    None,
                    pipeline,
                    &level.bind_group,
                    &[],
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use bevy::render::render_resource::encase::UniformBuffer;

    fn f32_at(bytes: &[u8], offset: usize) -> f32 {
        f32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap())
    }

    /// The Rust mirror must reproduce the prelude's documented 176-byte
    /// uniform layout exactly (`layer/filter_prelude.wgsl`): time@0,
    /// resolution@8, texel_size@16, content_inset@24, from_image_size@32,
    /// pad_b@40, params@48 (stride 16), total 176.
    #[test]
    fn filter_uniforms_match_the_documented_wgsl_layout() {
        assert_eq!(FilterUniforms::min_size().get(), 176);

        let mut params = [Vec4::ZERO; MAX_FILTER_PARAM_VECS];
        params[0] = Vec4::new(1.0, 2.0, 3.0, 4.0);
        params[7] = Vec4::new(5.0, 6.0, 7.0, 8.0);
        let value = FilterUniforms {
            time: 1.5,
            pad_a: 0.0,
            resolution: Vec2::new(320.0, 240.0),
            texel_size: Vec2::new(0.5, 0.25),
            content_inset: Vec2::new(9.0, 9.5),
            from_image_size: Vec2::new(300.0, 200.0),
            pad_b: Vec2::ZERO,
            params,
        };
        let mut buffer = UniformBuffer::new(Vec::<u8>::new());
        buffer.write(&value).expect("uniform write");
        let bytes = buffer.into_inner();
        assert_eq!(bytes.len(), 176);
        // Per-field offsets, per the prelude's comment block.
        assert_eq!(f32_at(&bytes, 0), 1.5); // time
        assert_eq!(f32_at(&bytes, 8), 320.0); // resolution.x
        assert_eq!(f32_at(&bytes, 12), 240.0); // resolution.y
        assert_eq!(f32_at(&bytes, 16), 0.5); // texel_size.x
        assert_eq!(f32_at(&bytes, 20), 0.25); // texel_size.y
        assert_eq!(f32_at(&bytes, 24), 9.0); // content_inset.x
        assert_eq!(f32_at(&bytes, 28), 9.5); // content_inset.y
        assert_eq!(f32_at(&bytes, 32), 300.0); // from_image_size.x
        assert_eq!(f32_at(&bytes, 36), 200.0); // from_image_size.y
        assert_eq!(f32_at(&bytes, 48), 1.0); // params[0].x
        assert_eq!(f32_at(&bytes, 60), 4.0); // params[0].w
        assert_eq!(f32_at(&bytes, 48 + 7 * 16), 5.0); // params[7].x
        assert_eq!(f32_at(&bytes, 48 + 7 * 16 + 12), 8.0); // params[7].w
    }

    /// The re-run decision, exhaustively: any of "capture re-rendered",
    /// "params changed", "time-driven", or "output never completed" forces a
    /// run; only a fully clean layer skips.
    #[test]
    fn needs_filter_run_decision_table() {
        // (needs_capture, chain_version, stored_version, always_dirty,
        //  output_valid) -> expected
        let cases = [
            // Fully clean: same version, valid output, static chain.
            (false, 3, 3, false, true, false),
            // Fresh capture content must re-filter.
            (true, 3, 3, false, true, true),
            // Param change (version bump).
            (false, 4, 3, false, true, true),
            // Version restart collision guard: a *lower* version differs too.
            (false, 1, 3, false, true, true),
            // Time-driven chains never settle.
            (false, 3, 3, true, true, true),
            // Output never completed (startup, realloc, skipped execution).
            (false, 3, 3, false, false, true),
            // Never staged (params_version 0 vs first real version 1).
            (false, 1, 0, false, false, true),
        ];
        for (capture, chain_v, stored_v, dirty, valid, expected) in cases {
            assert_eq!(
                needs_filter_run(capture, chain_v, stored_v, dirty, valid),
                expected,
                "needs_capture={capture} chain={chain_v} stored={stored_v} \
                 always_dirty={dirty} output_valid={valid}"
            );
        }
    }

    /// Ping-pong plumbing: pass 0 reads the capture and writes texture 0;
    /// each later pass reads the previous target and writes the other
    /// texture; the final output is the last pass's target.
    #[test]
    fn filter_ping_pong_indices() {
        assert_eq!(filter_source_index(0), None);
        assert_eq!(filter_target_index(0), 0);
        assert_eq!(filter_source_index(1), Some(0));
        assert_eq!(filter_target_index(1), 1);
        assert_eq!(filter_source_index(2), Some(1));
        assert_eq!(filter_target_index(2), 0);
        assert_eq!(filter_source_index(3), Some(0));
        assert_eq!(filter_target_index(3), 1);
        // Every pass reads what the previous one wrote…
        for pass in 1..8 {
            assert_eq!(
                filter_source_index(pass),
                Some(filter_target_index(pass - 1)),
                "pass {pass} must read pass {}'s target",
                pass - 1
            );
            // …and never its own target.
            assert_ne!(filter_source_index(pass), Some(filter_target_index(pass)));
        }
        // The chain's output is the last pass's target.
        for len in 1..8 {
            assert_eq!(filter_output_index(len), filter_target_index(len - 1));
        }
        assert_eq!(filter_output_index(1), 0);
        assert_eq!(filter_output_index(2), 1);
        assert_eq!(filter_output_index(3), 0);
    }

    /// An enclosing layer with no directly-stolen items (all visible content
    /// in nested layers) inherits its quad position from its inner layers'
    /// keys — minimum wins, whole chains fill in, unrelated roots stay
    /// `None` (no phantom quads for truly empty layers).
    #[test]
    fn quad_sort_keys_propagate_to_bare_enclosing_layers() {
        let key = |v: f32| Some(FloatOrd(v));

        // wrapper(0) ← card(1) ← tile(2); wrapper is a bare node: only the
        // innermost layers stole items.
        let enclosing = [None, Some(0), Some(1)];
        let mut keys = [None, key(5.0), key(7.0)];
        propagate_quad_sort_keys(&mut keys, &enclosing);
        assert_eq!(keys, [key(5.0), key(5.0), key(7.0)]);

        // Minimum wins over an existing larger key; an existing smaller key
        // is kept.
        let enclosing = [None, Some(0), Some(0)];
        let mut keys = [key(9.0), key(3.0), key(12.0)];
        propagate_quad_sort_keys(&mut keys, &enclosing);
        assert_eq!(keys, [key(3.0), key(3.0), key(12.0)]);

        // A fully empty chain stays empty — no quads invented.
        let enclosing = [None, Some(0)];
        let mut keys: [Option<FloatOrd>; 2] = [None, None];
        propagate_quad_sort_keys(&mut keys, &enclosing);
        assert_eq!(keys, [None, None]);
    }

    /// A morphing layer with no stolen items (empty carrier mid-blend) takes
    /// its extract-time fallback key; stolen keys always win; layers without
    /// a fallback (idle/non-morph) stay `None`. Filled keys propagate to
    /// enclosing layers like stolen ones.
    #[test]
    fn fallback_sort_keys_fill_morphing_empty_layers() {
        let key = |v: f32| Some(FloatOrd(v));

        // Stolen key wins over fallback; fallback fills a keyless morpher;
        // no fallback stays None.
        let mut keys = [key(5.0), None, None];
        fill_fallback_sort_keys(&mut keys, [key(1.0), key(4.0), None]);
        assert_eq!(keys, [key(5.0), key(4.0), None]);

        // Fill-then-propagate: an empty morphing layer nested in a bare
        // enclosing layer hands its filled key outward.
        let enclosing = [None, Some(0)];
        let mut keys = [None, None];
        fill_fallback_sort_keys(&mut keys, [None, key(6.0)]);
        propagate_quad_sort_keys(&mut keys, &enclosing);
        assert_eq!(keys, [key(6.0), key(6.0)]);
    }

    /// The shared enclosing-chain walk: visits ancestors bottom-up
    /// (exclusive of the start), stops at the chain end or the `visit`
    /// veto, and never exceeds [`MAX_LAYER_DEPTH`] steps even on a
    /// (construction-impossible) cycle.
    #[test]
    fn walk_enclosing_table() {
        let visited = |start: usize, enclosing: &[Option<usize>]| {
            let mut seen = Vec::new();
            walk_enclosing(start, enclosing, |outer| {
                seen.push(outer);
                true
            });
            seen
        };

        // Simple chain: 2 → 1 → 0 → (root).
        let chain = [None, Some(0), Some(1)];
        assert_eq!(visited(2, &chain), vec![1, 0]);
        assert_eq!(visited(1, &chain), vec![0]);

        // `None` stops immediately: a root layer visits nothing.
        assert_eq!(visited(0, &chain), Vec::<usize>::new());

        // A chain longer than MAX_LAYER_DEPTH truncates at the cap.
        let long: Vec<Option<usize>> = (0..MAX_LAYER_DEPTH + 10)
            .map(|i| i.checked_sub(1))
            .collect();
        let seen = visited(long.len() - 1, &long);
        assert_eq!(seen.len(), MAX_LAYER_DEPTH);
        assert_eq!(seen[0], long.len() - 2);
        assert_eq!(seen[MAX_LAYER_DEPTH - 1], long.len() - 1 - MAX_LAYER_DEPTH);

        // A self-cycle terminates (bounded), visiting the cycle node
        // MAX_LAYER_DEPTH times.
        let cycle = [Some(0)];
        assert_eq!(visited(0, &cycle), vec![0; MAX_LAYER_DEPTH]);

        // A two-node cycle terminates too.
        let cycle2 = [Some(1), Some(0)];
        assert_eq!(visited(0, &cycle2).len(), MAX_LAYER_DEPTH);

        // `visit` returning false stops the walk (the needs_capture
        // propagation's "already propagated" early-out).
        let mut seen = Vec::new();
        walk_enclosing(2, &chain, |outer| {
            seen.push(outer);
            false
        });
        assert_eq!(seen, vec![1]);
    }

    /// The edge-AA inflation grows the quad symmetrically and extends UVs so
    /// `uv ∈ [0, 1]` still maps exactly the true rect; a degenerate size
    /// doesn't divide by zero.
    #[test]
    fn grown_transform_quad_extends_uvs_proportionally() {
        let q = clip::clip_quad(Vec2::new(100.0, 50.0), UVec2::new(200, 100), -1.0, None).unwrap();
        assert_eq!(q.pos_min, Vec2::new(99.0, 49.0));
        assert_eq!(q.pos_max, Vec2::new(301.0, 151.0));
        assert_eq!(q.uv_min, Vec2::new(-1.0 / 200.0, -1.0 / 100.0));
        let uv_max = Vec2::new(1.0 + 1.0 / 200.0, 1.0 + 1.0 / 100.0);
        assert!(q.uv_max.abs_diff_eq(uv_max, 1e-6));
        // uv=0 must still land on the true rect min: interpolating position
        // by the uv fraction of the true edge recovers `min`.
        let span = q.pos_max - q.pos_min;
        let uv_span = q.uv_max - q.uv_min;
        let at_uv_zero = q.pos_min + span * (Vec2::ZERO - q.uv_min) / uv_span;
        assert!(at_uv_zero.abs_diff_eq(Vec2::new(100.0, 50.0), 1e-4));

        let degenerate = clip::clip_quad(Vec2::ZERO, UVec2::ZERO, -1.0, None).unwrap();
        assert!(degenerate.uv_min.is_finite());
    }
}