bevy_ui_render 0.20.0

Provides rendering functionality for Bevy UI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
#![expect(missing_docs, reason = "Not all docs are written yet, see #3492.")]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
    html_logo_url = "https://bevyengine.org/assets/icon.png",
    html_favicon_url = "https://bevyengine.org/assets/icon.png"
)]

//! Provides rendering functionality for `bevy_ui`.

pub mod box_shadow;
pub mod clipping;
mod gradient;
mod image;
pub use image::ImageNodeAssetChangedSystems;
mod pipeline;
pub mod render_pass;
mod text;
pub mod ui_material;
mod ui_material_pipeline;
pub mod ui_texture_slice_pipeline;

#[cfg(feature = "bevy_ui_debug")]
mod debug_overlay;

use bevy_a11y::AccessibilitySystems;
use bevy_camera::visibility::InheritedVisibility;
use bevy_camera::{Camera, Camera2d, Camera3d, RenderTarget};
use bevy_ecs::entity::EntityIndexMap;
use bevy_reflect::prelude::ReflectDefault;
use bevy_reflect::Reflect;
use bevy_render::camera::{extract_cameras, CameraMainPassTextureFormats};
use bevy_render::sync_world::{MainEntityHashMap, MainEntityHashSet};
use bevy_shader::load_shader_library;
use bevy_sprite_render::SpriteAssetEvents;
use bevy_ui::widget::{
    ImageNode, ImageNodeSize, InlineImage, NodeImageMode, Text, TextShadow, ViewportNode,
};
use bevy_ui::{
    BackgroundColor, BackgroundGradient, BorderColor, BorderGradient, BoxShadow, CalculatedClip,
    ComputedNode, ComputedStackIndex, ComputedUiTargetCamera, Display, Node, OuterColor, Outline,
    ResolvedBorderRadius, UiGlobalTransform, UiSystems, VisualBox,
};

use bevy_app::prelude::*;
use bevy_asset::{AssetEvent, AssetEventSystems, AssetId, Assets};
use bevy_color::{Alpha, ColorToComponents, LinearRgba};
use bevy_core_pipeline::schedule::{Core2d, Core2dSystems, Core3d, Core3dSystems};
use bevy_core_pipeline::upscaling::upscaling;
use bevy_ecs::prelude::*;
use bevy_ecs::schedule::IntoScheduleConfigs;
use bevy_ecs::system::SystemParam;
use bevy_image::{prelude::*, TRANSPARENT_IMAGE_HANDLE};
use bevy_math::{proj, Affine2, FloatOrd, Rect, UVec4, Vec2};
use bevy_render::{
    render_asset::RenderAssets,
    render_phase::{
        sort_phase_system, AddRenderCommand, DrawFunctions, PhaseItem, PhaseItemExtraIndex,
        ViewSortedRenderPhases,
    },
    render_resource::*,
    renderer::{RenderDevice, RenderQueue},
    sync_world::{MainEntity, RenderEntity},
    texture::GpuImage,
    view::{ExtractedView, RetainedViewEntity, ViewUniforms},
    Extract, ExtractSchedule, GpuResourceAppExt, Render, RenderApp, RenderStartup, RenderSystems,
};
use bevy_sprite::BorderRect;
#[cfg(feature = "bevy_ui_debug")]
pub use debug_overlay::{GlobalUiDebugOptions, UiDebugOptions};

use gradient::GradientPlugin;

use bevy_platform::collections::{hash_map::Entry, HashMap, HashSet};
use bevy_text::{
    ComputedTextBlock, EditableText, InlineBox, PositionedGlyph, Strikethrough, StrikethroughColor,
    TextBackgroundColor, TextColor, TextCursorStyle, TextLayoutInfo, TextSpan, Underline,
    UnderlineColor,
};
use bevy_transform::components::GlobalTransform;
use box_shadow::BoxShadowPlugin;
use bytemuck::{Pod, Zeroable};
use core::ops::Range;
use std::mem;

pub use pipeline::*;
pub use render_pass::*;
pub use ui_material_pipeline::*;
use ui_texture_slice_pipeline::UiTextureSlicerPlugin;

use crate::clipping::clip_polygon;
use crate::shader_flags::INVERT;
use crate::text::{calculate_text_scroll_clip, extract_preedit_underlines, extract_text_cursor};

pub mod prelude {
    #[cfg(feature = "bevy_ui_debug")]
    pub use crate::debug_overlay::{GlobalUiDebugOptions, UiDebugOptions};

    pub use crate::{
        ui_material::*, ui_material_pipeline::UiMaterialPlugin, BoxShadowSamples, UiAntiAlias,
    };
}

/// Local Z offsets of "extracted nodes" for a given entity. These exist to allow rendering multiple "extracted nodes"
/// for a given source entity (ex: render both a background color _and_ a custom material for a given node).
///
/// When possible these offsets should be defined in _this_ module to ensure z-index coordination across contexts.
/// When this is _not_ possible, pick a suitably unique index unlikely to clash with other things (ex: `0.1826823` not `0.1`).
///
/// Offsets should be unique for a given node entity to avoid z fighting.
/// These should pretty much _always_ be larger than -0.5 and smaller than 0.5 to avoid clipping into nodes
/// above / below the current node in the stack.
///
/// A z-index of 0.0 is the baseline, which is used as the primary "background color" of the node.
///
/// Note that nodes "stack" on each other, so a negative offset on the node above could clip _into_
/// a positive offset on a node below.
pub mod stack_z_offsets {
    pub const BOX_SHADOW: f32 = -0.1;
    pub const BACKGROUND_COLOR: f32 = 0.0;
    pub const BORDER: f32 = 0.01;
    pub const GRADIENT: f32 = 0.02;
    pub const BORDER_GRADIENT: f32 = 0.03;
    pub const IMAGE: f32 = 0.04;
    pub const MATERIAL: f32 = 0.05;
    pub const TEXT_SELECTION: f32 = 0.055;
    pub const TEXT: f32 = 0.06;
    pub const TEXT_STRIKETHROUGH: f32 = 0.07;
    pub const TEXT_CURSOR: f32 = 0.08;
    pub const INLINE_IMAGE: f32 = 0.09;
}

#[derive(Debug, Hash, PartialEq, Eq, Clone, SystemSet)]
pub enum RenderUiSystems {
    ExtractChanges,
    ExtractCameraViews,
    ExtractBoxShadows,
    ExtractBackgrounds,
    ExtractImages,
    ExtractTextureSlice,
    ExtractBorders,
    ExtractViewportNodes,
    ExtractTextBackgrounds,
    ExtractTextShadows,
    ExtractText,
    ExtractCursor,
    ExtractDebug,
    ExtractGradient,
    ExtractInlineImages,
}

/// Marker for controlling whether UI is rendered with or without anti-aliasing
/// in a camera. By default, UI is always anti-aliased.
///
/// **Note:** This does not affect text anti-aliasing. For that, use the `font_smoothing` property of the [`TextFont`](bevy_text::TextFont) component.
///
/// ```
/// use bevy_camera::prelude::*;
/// use bevy_ecs::prelude::*;
/// use bevy_ui::prelude::*;
/// use bevy_ui_render::prelude::*;
///
/// fn spawn_camera(mut commands: Commands) {
///     commands.spawn((
///         Camera2d,
///         // This will cause all UI in this camera to be rendered without
///         // anti-aliasing
///         UiAntiAlias::Off,
///     ));
/// }
/// ```
#[derive(Component, Clone, Copy, Default, Debug, Reflect, Eq, PartialEq)]
#[reflect(Component, Default, PartialEq, Clone)]
pub enum UiAntiAlias {
    /// UI will render with anti-aliasing
    #[default]
    On,
    /// UI will render without anti-aliasing
    Off,
}

/// Number of shadow samples.
/// A larger value will result in higher quality shadows.
/// Default is 4, values higher than ~10 offer diminishing returns.
///
/// ```
/// use bevy_camera::prelude::*;
/// use bevy_ecs::prelude::*;
/// use bevy_ui::prelude::*;
/// use bevy_ui_render::prelude::*;
///
/// fn spawn_camera(mut commands: Commands) {
///     commands.spawn((
///         Camera2d,
///         BoxShadowSamples(6),
///     ));
/// }
/// ```
#[derive(Component, Clone, Copy, Debug, Reflect, Eq, PartialEq)]
#[reflect(Component, Default, PartialEq, Clone)]
pub struct BoxShadowSamples(pub u32);

impl Default for BoxShadowSamples {
    fn default() -> Self {
        Self(4)
    }
}

#[derive(Default)]
pub struct UiRenderPlugin;

impl Plugin for UiRenderPlugin {
    fn build(&self, app: &mut App) {
        load_shader_library!(app, "ui.wesl");

        #[cfg(feature = "bevy_ui_debug")]
        app.init_resource::<GlobalUiDebugOptions>();

        app.add_systems(
            PostUpdate,
            (
                image::mark_images_as_changed_if_their_assets_changed,
                image::update_texture_atlas_layout_components,
            )
                .chain()
                .in_set(ImageNodeAssetChangedSystems)
                .after(UiSystems::Content)
                .after(AssetEventSystems)
                .after(AccessibilitySystems::Update),
        );

        let Some(render_app) = app.get_sub_app_mut(RenderApp) else {
            return;
        };

        render_app
            .init_gpu_resource::<SpecializedRenderPipelines<UiPipeline>>()
            .init_gpu_resource::<ImageNodeBindGroups>()
            .init_gpu_resource::<UiMeta>()
            .init_resource::<ExtractedUiNodes>()
            .allow_ambiguous_resource::<ExtractedUiNodes>()
            .init_resource::<DrawFunctions<TransparentUi>>()
            .init_resource::<ViewSortedRenderPhases<TransparentUi>>()
            .allow_ambiguous_resource::<ViewSortedRenderPhases<TransparentUi>>()
            .add_render_command::<TransparentUi, DrawUi>()
            .configure_sets(
                ExtractSchedule,
                (
                    RenderUiSystems::ExtractChanges,
                    RenderUiSystems::ExtractCameraViews,
                    RenderUiSystems::ExtractBoxShadows,
                    RenderUiSystems::ExtractBackgrounds,
                    RenderUiSystems::ExtractViewportNodes,
                    RenderUiSystems::ExtractImages,
                    RenderUiSystems::ExtractTextureSlice,
                    RenderUiSystems::ExtractBorders,
                    RenderUiSystems::ExtractTextBackgrounds,
                    RenderUiSystems::ExtractTextShadows,
                    RenderUiSystems::ExtractText,
                    RenderUiSystems::ExtractCursor,
                    RenderUiSystems::ExtractDebug,
                    RenderUiSystems::ExtractInlineImages,
                )
                    .chain_weak(),
            )
            .add_systems(RenderStartup, init_ui_pipeline)
            .add_systems(
                ExtractSchedule,
                (
                    extract_uinode_changes.in_set(RenderUiSystems::ExtractChanges),
                    extract_ui_camera_view
                        .after(extract_cameras)
                        .in_set(RenderUiSystems::ExtractCameraViews),
                    extract_uinode_background_colors.in_set(RenderUiSystems::ExtractBackgrounds),
                    extract_uinode_images.in_set(RenderUiSystems::ExtractImages),
                    extract_uinode_borders.in_set(RenderUiSystems::ExtractBorders),
                    extract_viewport_nodes.in_set(RenderUiSystems::ExtractViewportNodes),
                    extract_text_decorations.in_set(RenderUiSystems::ExtractTextBackgrounds),
                    extract_text_shadows.in_set(RenderUiSystems::ExtractTextShadows),
                    extract_text_sections.in_set(RenderUiSystems::ExtractText),
                    extract_text_cursor.in_set(RenderUiSystems::ExtractCursor),
                    extract_preedit_underlines.in_set(RenderUiSystems::ExtractCursor),
                    extract_inline_images.in_set(RenderUiSystems::ExtractInlineImages),
                    #[cfg(feature = "bevy_ui_debug")]
                    debug_overlay::extract_debug_overlay.in_set(RenderUiSystems::ExtractDebug),
                ),
            )
            .add_systems(
                Render,
                (
                    queue_uinodes.in_set(RenderSystems::Queue),
                    sort_phase_system::<TransparentUi>.in_set(RenderSystems::PhaseSort),
                    prepare_uinodes.in_set(RenderSystems::PrepareBindGroups),
                    clear_batches.in_set(RenderSystems::Cleanup),
                ),
            )
            .add_systems(
                Core2d,
                ui_pass.after(Core2dSystems::PostProcess).before(upscaling),
            )
            .add_systems(
                Core3d,
                ui_pass.after(Core3dSystems::PostProcess).before(upscaling),
            );

        app.add_plugins(UiTextureSlicerPlugin);
        app.add_plugins(GradientPlugin);
        app.add_plugins(BoxShadowPlugin);
    }
}

#[derive(SystemParam)]
pub struct UiCameraMap<'w, 's> {
    mapping: Query<'w, 's, RenderEntity>,
}

impl<'w, 's> UiCameraMap<'w, 's> {
    /// Creates a [`UiCameraMapper`] for performing repeated camera-to-render-entity lookups.
    ///
    /// The last successful mapping is cached to avoid redundant queries.
    pub fn get_mapper(&'w self) -> UiCameraMapper<'w, 's> {
        UiCameraMapper {
            mapping: &self.mapping,
            camera_entity: None,
            render_entity: None,
        }
    }
}

/// Helper for mapping UI target camera entities to their corresponding render entities,
/// with caching to avoid repeated lookups for the same camera.
pub struct UiCameraMapper<'w, 's> {
    mapping: &'w Query<'w, 's, RenderEntity>,
    /// Cached camera entity from the last successful `map` call.
    camera_entity: Option<Entity>,
    /// Cached camera entity from the last successful `map` call.
    render_entity: Option<Entity>,
}

impl<'w, 's> UiCameraMapper<'w, 's> {
    /// Returns the render entity corresponding to the given [`ComputedUiTargetCamera`]'s camera, or none if no corresponding entity was found.
    pub fn map(&mut self, computed_target: &ComputedUiTargetCamera) -> Option<Entity> {
        let camera_entity = computed_target.get()?;
        if self.camera_entity != Some(camera_entity) {
            let new_render_camera_entity = self.mapping.get(camera_entity).ok()?;
            self.render_entity = Some(new_render_camera_entity);
            self.camera_entity = Some(camera_entity);
        }

        self.render_entity
    }

    /// Returns the cached camera entity from the last successful `map` call.
    pub fn current_camera(&self) -> Option<Entity> {
        self.camera_entity
    }
}

pub struct ExtractedUiNode {
    pub z_order: f32,
    pub image: AssetId<Image>,
    pub clip: Option<CalculatedClip>,
    pub item: ExtractedUiItem,
    pub transform: Affine2,
}

/// The type of UI node.
/// This is used to determine how to render the UI node.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum NodeType {
    Rect,
    Inverted,
    Border(u32), // shader flags
}

pub enum ExtractedUiItem {
    Node {
        color: LinearRgba,
        rect: Rect,
        atlas_scaling: Option<Vec2>,
        flip_x: bool,
        flip_y: bool,
        /// Border radius of the UI node.
        /// Ordering: top left, top right, bottom right, bottom left.
        border_radius: ResolvedBorderRadius,
        /// Border thickness of the UI node.
        /// Ordering: left, top, right, bottom.
        border: BorderRect,
        node_type: NodeType,
    },
    /// A contiguous sequence of text glyphs from the same section
    Glyphs {
        /// The color, position, and UV rect of each glyph.
        glyphs: Vec<ExtractedGlyph>,
    },
}

pub struct ExtractedGlyph {
    pub color: LinearRgba,
    pub translation: Vec2,
    pub rect: Rect,
}

/// The list of UI nodes, as well as the set of nodes that changed.
///
/// This is a two-level data structure so that we can quickly remove all
/// gradients associated with a main-world entity when it changes.
#[derive(Resource, Default)]
pub struct ExtractedUiNodes {
    /// The list of UI nodes grouped by their main-world entity, along with
    /// each group's target camera entity.
    ///
    /// This is a two-level data structure so that we can quickly remove all UI
    /// nodes associated with a main-world entity when it changes.
    pub uinodes: MainEntityHashMap<(Entity, EntityIndexMap<ExtractedUiNode>)>,
    /// UI nodes that changed this frame.
    pub changed: MainEntityHashSet,
}

/// A query filter that matches all UI nodes.
type UiNodeQueryFilter = (
    With<ComputedNode>,
    With<ComputedStackIndex>,
    With<UiGlobalTransform>,
    With<InheritedVisibility>,
    With<ComputedUiTargetCamera>,
);

// Note: Whenever you add a new component that affects UI rendering, make sure
// to add a `Changed` query filter and a reference to the `RemovedComponents`
// resource to `extract_uinode_changes` below.
//
// Note: We don't have to match on `AssetChanged` for images or texture atlas
// layouts because the
// `bevy_ui::widget::mark_images_as_changed_as_their_assets_changed` image marks
// the `ImageNode` for us automatically as changed when those assets change.

/// A render-world system that scans for any UI nodes that have changed and
/// removes the render world data associated with them.
pub fn extract_uinode_changes(
    mut commands: Commands,
    mut extracted_uinodes: ResMut<ExtractedUiNodes>,
    all_uinodes_query: Extract<Query<Entity, UiNodeQueryFilter>>,
    changed_uinodes_query: Extract<
        Query<
            Entity,
            (
                UiNodeQueryFilter,
                Or<(
                    Or<(
                        Changed<ComputedNode>,
                        Changed<ComputedStackIndex>,
                        Changed<UiGlobalTransform>,
                        Changed<InheritedVisibility>,
                        Changed<CalculatedClip>,
                        Changed<ComputedUiTargetCamera>,
                        Changed<BackgroundColor>,
                        Changed<OuterColor>,
                    )>,
                    Or<(
                        Changed<ImageNode>,
                        Changed<ImageNodeSize>,
                        Changed<BorderColor>,
                        Changed<Outline>,
                        Changed<ViewportNode>,
                        Changed<ComputedTextBlock>,
                        Changed<TextColor>,
                        Changed<TextLayoutInfo>,
                    )>,
                    Or<(
                        Changed<TextCursorStyle>,
                        Changed<TextShadow>,
                        Changed<BackgroundGradient>,
                        Changed<BorderGradient>,
                        Changed<BoxShadow>,
                        Changed<EditableText>,
                        Changed<Underline>,
                        Changed<Strikethrough>,
                    )>,
                    Or<(Changed<StrikethroughColor>, Changed<UnderlineColor>)>,
                )>,
            ),
        >,
    >,
    #[cfg(feature = "bevy_ui_debug")] changed_debug_options_query: Extract<
        Query<Entity, (UiNodeQueryFilter, Changed<UiDebugOptions>)>,
    >,
    text_span_query: Extract<
        Query<
            Entity,
            (
                Or<(With<TextSpan>, With<InlineImage>)>,
                Or<(
                    Changed<InlineImage>,
                    Changed<TextColor>,
                    Changed<TextBackgroundColor>,
                    Changed<Underline>,
                    Changed<Strikethrough>,
                    Changed<StrikethroughColor>,
                    Changed<UnderlineColor>,
                )>,
            ),
        >,
    >,
    text_span_parent_query: Extract<Query<&ChildOf, Or<(With<TextSpan>, With<InlineBox>)>>>,
    text_query: Extract<Query<Entity, With<Text>>>,
    (
        mut removed_computed_node_query,
        mut removed_computed_stack_index_query,
        mut removed_ui_global_transform_query,
        mut removed_inherited_visibility_query,
        mut removed_calculated_clip_query,
        mut removed_computed_ui_target_camera_query,
        mut removed_background_color_query,
        mut removed_outer_color_query,
    ): (
        Extract<RemovedComponents<ComputedNode>>,
        Extract<RemovedComponents<ComputedStackIndex>>,
        Extract<RemovedComponents<UiGlobalTransform>>,
        Extract<RemovedComponents<InheritedVisibility>>,
        Extract<RemovedComponents<CalculatedClip>>,
        Extract<RemovedComponents<ComputedUiTargetCamera>>,
        Extract<RemovedComponents<BackgroundColor>>,
        Extract<RemovedComponents<OuterColor>>,
    ),
    (
        mut removed_image_node_query,
        mut removed_image_node_size_query,
        mut removed_border_color_query,
        mut removed_outline_query,
        mut removed_viewport_node_query,
        mut removed_computed_text_block_query,
        mut removed_text_color_query,
        mut removed_text_layout_info_query,
    ): (
        Extract<RemovedComponents<ImageNode>>,
        Extract<RemovedComponents<ImageNodeSize>>,
        Extract<RemovedComponents<BorderColor>>,
        Extract<RemovedComponents<Outline>>,
        Extract<RemovedComponents<ViewportNode>>,
        Extract<RemovedComponents<ComputedTextBlock>>,
        Extract<RemovedComponents<TextColor>>,
        Extract<RemovedComponents<TextLayoutInfo>>,
    ),
    (
        mut removed_text_cursor_style_query,
        mut removed_text_shadow_query,
        mut removed_background_gradient_query,
        mut removed_border_gradient_query,
        mut removed_box_shadow_query,
        mut removed_editable_text_query,
        mut removed_underline_query,
        mut removed_strikethrough_query,
    ): (
        Extract<RemovedComponents<TextCursorStyle>>,
        Extract<RemovedComponents<TextShadow>>,
        Extract<RemovedComponents<BackgroundGradient>>,
        Extract<RemovedComponents<BorderGradient>>,
        Extract<RemovedComponents<BoxShadow>>,
        Extract<RemovedComponents<EditableText>>,
        Extract<RemovedComponents<Underline>>,
        Extract<RemovedComponents<Strikethrough>>,
    ),
    (
        mut removed_strikethrough_color_query,
        mut removed_underline_color_query,
        mut removed_inline_image_query,
    ): (
        Extract<RemovedComponents<StrikethroughColor>>,
        Extract<RemovedComponents<UnderlineColor>>,
        Extract<RemovedComponents<InlineImage>>,
    ),
    #[cfg(feature = "bevy_ui_debug")] mut removed_debug_options_query: Extract<
        RemovedComponents<UiDebugOptions>,
    >,
    #[cfg(feature = "bevy_ui_debug")] global_ui_debug_options: Extract<Res<GlobalUiDebugOptions>>,
    mut extra_nodes_to_invalidate: Local<MainEntityHashSet>,
) {
    extracted_uinodes.changed.clear();

    // If the debug options changed, we wipe everything.
    // That's a bit coarse-grained, but having the debug options change is rare
    // and should only happen in, well, debugging.
    #[cfg(feature = "bevy_ui_debug")]
    let must_wipe_all_nodes = global_ui_debug_options.is_changed();
    #[cfg(not(feature = "bevy_ui_debug"))]
    let must_wipe_all_nodes = false;

    if must_wipe_all_nodes {
        for main_entity in &all_uinodes_query {
            process_changed_entity(
                main_entity.into(),
                &mut commands,
                &text_span_parent_query,
                &text_query,
                &mut extracted_uinodes,
                Some(&mut extra_nodes_to_invalidate),
            );
        }
    } else {
        // Go through all nodes that have changed and invalidate any render world
        // data associated with them.
        for main_entity in changed_uinodes_query
            .iter()
            .chain(text_span_query.iter())
            .chain(removed_computed_node_query.read())
            .chain(removed_computed_stack_index_query.read())
            .chain(removed_ui_global_transform_query.read())
            .chain(removed_inherited_visibility_query.read())
            .chain(removed_calculated_clip_query.read())
            .chain(removed_computed_ui_target_camera_query.read())
            .chain(removed_background_color_query.read())
            .chain(removed_outer_color_query.read())
            .chain(removed_image_node_query.read())
            .chain(removed_image_node_size_query.read())
            .chain(removed_border_color_query.read())
            .chain(removed_outline_query.read())
            .chain(removed_viewport_node_query.read())
            .chain(removed_computed_text_block_query.read())
            .chain(removed_text_color_query.read())
            .chain(removed_text_layout_info_query.read())
            .chain(removed_text_cursor_style_query.read())
            .chain(removed_text_shadow_query.read())
            .chain(removed_background_gradient_query.read())
            .chain(removed_border_gradient_query.read())
            .chain(removed_box_shadow_query.read())
            .chain(removed_editable_text_query.read())
            .chain(removed_underline_query.read())
            .chain(removed_strikethrough_query.read())
            .chain(removed_strikethrough_color_query.read())
            .chain(removed_underline_color_query.read())
            .chain(removed_inline_image_query.read())
        {
            process_changed_entity(
                main_entity.into(),
                &mut commands,
                &text_span_parent_query,
                &text_query,
                &mut extracted_uinodes,
                Some(&mut extra_nodes_to_invalidate),
            );
        }

        // Process nodes that have changed debug options too, if that feature is
        // enabled.
        #[cfg(feature = "bevy_ui_debug")]
        for main_entity in changed_debug_options_query
            .iter()
            .chain(removed_debug_options_query.read())
        {
            process_changed_entity(
                main_entity.into(),
                &mut commands,
                &text_span_parent_query,
                &text_query,
                &mut extracted_uinodes,
                Some(&mut extra_nodes_to_invalidate),
            );
        }
    }

    for main_entity in extra_nodes_to_invalidate.drain() {
        process_changed_entity(
            main_entity,
            &mut commands,
            &text_span_parent_query,
            &text_query,
            &mut extracted_uinodes,
            None,
        );
    }

    fn process_changed_entity(
        mut main_entity: MainEntity,
        commands: &mut Commands,
        text_span_parent_query: &Query<&ChildOf, Or<(With<TextSpan>, With<InlineBox>)>>,
        text_query: &Query<Entity, With<Text>>,
        extracted_uinodes: &mut ExtractedUiNodes,
        maybe_extra_nodes_to_invalidate: Option<&mut MainEntityHashSet>,
    ) {
        // Mark the node as changed so that the other `extract_` systems will
        // know to process it.
        extracted_uinodes.changed.insert(main_entity);

        if let Some((_, mut render_entities)) = extracted_uinodes.uinodes.remove(&main_entity) {
            for (render_entity, _) in render_entities.drain(..) {
                commands.entity(render_entity).despawn();
            }
        }

        // If this node is a `TextSpan`, then we need to invalidate the ancestor
        // `Text` node too. This is because `extract_text_decorations` only
        // looks at the `text_background_colors_query` for the text spans if the
        // `uinode_query` that it's iterating over matched the ancestor `Text`
        // node.
        if let Some(extra_nodes_to_invalidate) = maybe_extra_nodes_to_invalidate
            && let Ok(parent) = text_span_parent_query.get(main_entity.entity())
        {
            main_entity = parent.parent().into();
            loop {
                if text_query.contains(main_entity.entity()) {
                    extra_nodes_to_invalidate.insert(main_entity);
                    break;
                }
                match text_span_parent_query.get(main_entity.entity()) {
                    Ok(parent) => main_entity = parent.parent().into(),
                    Err(_) => break,
                }
            }
        }
    }
}

pub fn extract_uinode_background_colors(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &ComputedStackIndex,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
            &BackgroundColor,
            Option<&OuterColor>,
        )>,
    >,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();

    for (
        entity,
        uinode,
        stack_index,
        transform,
        inherited_visibility,
        clip,
        camera,
        background_color,
        maybe_outer_color,
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip invisible backgrounds
        if !inherited_visibility.get()
            || (background_color.is_fully_transparent()
                && maybe_outer_color.is_none_or(|outer| outer.is_fully_transparent()))
            || uinode.is_empty()
        {
            continue;
        }

        let extracted_sub_uinodes = match extracted_uinodes.uinodes.entry(entity.into()) {
            Entry::Occupied(entry) => &mut entry.into_mut().1,
            Entry::Vacant(entry) => {
                let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
                    continue;
                };
                &mut entry
                    .insert((extracted_camera_entity, Default::default()))
                    .1
            }
        };

        if !background_color.is_fully_transparent() {
            extracted_sub_uinodes.insert(
                commands.spawn_empty().id(),
                ExtractedUiNode {
                    z_order: stack_index.0 as f32 + stack_z_offsets::BACKGROUND_COLOR,
                    clip: clip.cloned(),
                    image: AssetId::default(),
                    transform: transform.into(),
                    item: ExtractedUiItem::Node {
                        color: background_color.0.into(),
                        rect: Rect {
                            min: Vec2::ZERO,
                            max: uinode.size,
                        },
                        atlas_scaling: None,
                        flip_x: false,
                        flip_y: false,
                        border: uinode.border(),
                        border_radius: uinode.border_radius(),
                        node_type: NodeType::Rect,
                    },
                },
            );
        }

        if let Some(outer_color) = maybe_outer_color
            && !outer_color.0.is_fully_transparent()
        {
            extracted_sub_uinodes.insert(
                commands.spawn_empty().id(),
                ExtractedUiNode {
                    z_order: stack_index.0 as f32 + stack_z_offsets::BACKGROUND_COLOR,
                    clip: clip.cloned(),
                    image: AssetId::default(),
                    transform: transform.into(),
                    item: ExtractedUiItem::Node {
                        color: outer_color.0.into(),
                        rect: Rect {
                            min: Vec2::ZERO,
                            max: uinode.size,
                        },
                        atlas_scaling: None,
                        flip_x: false,
                        flip_y: false,
                        border: BorderRect::ZERO,
                        border_radius: uinode.border_radius(),
                        node_type: NodeType::Inverted,
                    },
                },
            );
        }
    }
}

pub fn extract_inline_images(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &TextLayoutInfo,
            &ComputedUiTargetCamera,
            &InheritedVisibility,
            &ComputedStackIndex,
            &UiGlobalTransform,
            Option<&CalculatedClip>,
            &ComputedNode,
        )>,
    >,
    inline_image_query: Extract<Query<&InlineImage, With<InlineBox>>>,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();
    for (entity, text_layout, camera, inherited_visibility, stack_index, transform, clip, uinode) in
        extracted_uinodes
            .changed
            .iter()
            .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip invisible images and empty nodes
        if !inherited_visibility.get() || uinode.is_empty() {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
            continue;
        };

        for (inline_entity, _, rect) in text_layout.inline_boxes.iter() {
            let Ok(image) = inline_image_query.get(*inline_entity) else {
                continue;
            };

            if rect.is_empty()
                || image.color.is_fully_transparent()
                || image.image.id() == TRANSPARENT_IMAGE_HANDLE.id()
            {
                continue;
            }

            extracted_uinodes
                .uinodes
                .entry(entity.into())
                .or_insert_with(|| (extracted_camera_entity, Default::default()))
                .1
                .insert(
                    commands.spawn_empty().id(),
                    ExtractedUiNode {
                        z_order: stack_index.0 as f32 + stack_z_offsets::INLINE_IMAGE,
                        clip: clip.cloned(),
                        image: image.image.id(),
                        transform: Affine2::from(*transform)
                            * Affine2::from_translation(uinode.content_box().min + rect.center()),
                        item: ExtractedUiItem::Node {
                            color: image.color.into(),
                            rect: Rect {
                                min: Vec2::ZERO,
                                max: rect.size(),
                            },
                            atlas_scaling: None,
                            flip_x: image.flip_x,
                            flip_y: image.flip_y,
                            border: BorderRect::ZERO,
                            border_radius: ResolvedBorderRadius::ZERO,
                            node_type: NodeType::Rect,
                        },
                    },
                );
        }
    }
}

pub fn extract_uinode_images(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    texture_atlases: Extract<Res<Assets<TextureAtlasLayout>>>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &ComputedStackIndex,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
            &ImageNode,
            &ImageNodeSize,
        )>,
    >,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();

    for (
        entity,
        uinode,
        stack_index,
        transform,
        inherited_visibility,
        clip,
        camera,
        image,
        image_size,
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        let visual_box = match image.visual_box {
            VisualBox::ContentBox => uinode.content_box(),
            VisualBox::PaddingBox => uinode.padding_box(),
            VisualBox::BorderBox => uinode.border_box(),
        };

        // Skip invisible images
        if !inherited_visibility.get()
            || image.color.is_fully_transparent()
            || image.image.id() == TRANSPARENT_IMAGE_HANDLE.id()
            || image.image_mode.uses_slices()
            || visual_box.size().cmple(Vec2::ZERO).any()
        {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
            continue;
        };

        let size = if matches!(image.image_mode, NodeImageMode::Auto) {
            let source = image_size.size().as_vec2();
            if source.cmple(Vec2::ZERO).any() {
                visual_box.size()
            } else {
                source * (visual_box.size() / source).min_element()
            }
        } else {
            visual_box.size()
        };

        // The node's border radius is subtracted from the visual box target's edge insets
        // and then clamped to get the corner radius for the image. Ideally this should be handled
        // on the GPU, but that might need changes to `ui.wesl`'s UV calculations.
        let mut inset = match image.visual_box {
            VisualBox::ContentBox => uinode.content_inset(),
            VisualBox::PaddingBox => uinode.border(),
            VisualBox::BorderBox => BorderRect::ZERO,
        };
        let image_inset = 0.5 * (visual_box.size() - size);
        inset.min_inset += image_inset;
        inset.max_inset += image_inset;

        let radius = uinode.border_radius();
        let clamped_radius = ResolvedBorderRadius {
            top_left: (radius.top_left - inset.min_inset).clamp(Vec2::ZERO, 0.5 * size),
            top_right: (radius.top_right - Vec2::new(inset.max_inset.x, inset.min_inset.y))
                .clamp(Vec2::ZERO, 0.5 * size),
            bottom_right: (radius.bottom_right - inset.max_inset).clamp(Vec2::ZERO, 0.5 * size),
            bottom_left: (radius.bottom_left - Vec2::new(inset.min_inset.x, inset.max_inset.y))
                .clamp(Vec2::ZERO, 0.5 * size),
        };

        let atlas_rect = image
            .texture_atlas
            .as_ref()
            .and_then(|s| s.texture_rect(&texture_atlases))
            .map(|r| r.as_rect());

        let mut rect = match (atlas_rect, image.rect) {
            (None, None) => Rect {
                min: Vec2::ZERO,
                max: size,
            },
            (None, Some(image_rect)) => image_rect,
            (Some(atlas_rect), None) => atlas_rect,
            (Some(atlas_rect), Some(mut image_rect)) => {
                image_rect.min += atlas_rect.min;
                image_rect.max += atlas_rect.min;
                image_rect
            }
        };

        let atlas_scaling = if atlas_rect.is_some() || image.rect.is_some() {
            let atlas_scaling = size / rect.size();
            rect.min *= atlas_scaling;
            rect.max *= atlas_scaling;
            Some(atlas_scaling)
        } else {
            None
        };

        extracted_uinodes
            .uinodes
            .entry(entity.into())
            .or_insert_with(|| (extracted_camera_entity, Default::default()))
            .1
            .insert(
                commands.spawn_empty().id(),
                ExtractedUiNode {
                    z_order: stack_index.0 as f32 + stack_z_offsets::IMAGE,
                    clip: clip.cloned(),
                    image: image.image.id(),
                    transform: Affine2::from(*transform)
                        * Affine2::from_translation(visual_box.center()),
                    item: ExtractedUiItem::Node {
                        color: image.color.into(),
                        rect,
                        atlas_scaling,
                        flip_x: image.flip_x,
                        flip_y: image.flip_y,
                        border: BorderRect::ZERO,
                        border_radius: clamped_radius,
                        node_type: NodeType::Rect,
                    },
                },
            );
    }
}

pub fn extract_uinode_borders(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            Option<&Node>,
            &ComputedNode,
            &ComputedStackIndex,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
            AnyOf<(&BorderColor, &Outline)>,
        )>,
    >,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let image = AssetId::<Image>::default();
    let mut camera_mapper = camera_map.get_mapper();

    for (
        entity,
        node,
        computed_node,
        stack_index,
        transform,
        inherited_visibility,
        maybe_clip,
        camera,
        (maybe_border_color, maybe_outline),
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip invisible borders and removed nodes
        if !inherited_visibility.get() || node.is_some_and(|node| node.display == Display::None) {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
            continue;
        };

        // Don't extract borders with zero width along all edges
        if computed_node.border() != BorderRect::ZERO
            && let Some(border_color) = maybe_border_color
        {
            let border_colors = [
                border_color.left.to_linear(),
                border_color.top.to_linear(),
                border_color.right.to_linear(),
                border_color.bottom.to_linear(),
            ];

            const BORDER_FLAGS: [u32; 4] = [
                shader_flags::BORDER_LEFT,
                shader_flags::BORDER_TOP,
                shader_flags::BORDER_RIGHT,
                shader_flags::BORDER_BOTTOM,
            ];
            let mut completed_flags = 0;

            for (i, &color) in border_colors.iter().enumerate() {
                if color.is_fully_transparent() {
                    continue;
                }

                let mut border_flags = BORDER_FLAGS[i];

                if completed_flags & border_flags != 0 {
                    continue;
                }

                for j in i + 1..4 {
                    if color == border_colors[j] {
                        border_flags |= BORDER_FLAGS[j];
                    }
                }
                completed_flags |= border_flags;

                let node = ExtractedUiNode {
                    z_order: stack_index.0 as f32 + stack_z_offsets::BORDER,
                    image,
                    clip: maybe_clip.cloned(),
                    transform: transform.into(),
                    item: ExtractedUiItem::Node {
                        color,
                        rect: Rect {
                            max: computed_node.size(),
                            ..Default::default()
                        },
                        atlas_scaling: None,
                        flip_x: false,
                        flip_y: false,
                        border: computed_node.border(),
                        border_radius: computed_node.border_radius(),
                        node_type: NodeType::Border(border_flags),
                    },
                };

                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(commands.spawn_empty().id(), node);
            }
        }

        if computed_node.outline_width() <= 0. {
            continue;
        }

        if let Some(outline) = maybe_outline.filter(|outline| !outline.color.is_fully_transparent())
        {
            let outline_size = computed_node.outlined_node_size();
            extracted_uinodes
                .uinodes
                .entry(entity.into())
                .or_insert_with(|| (extracted_camera_entity, Default::default()))
                .1
                .insert(
                    commands.spawn_empty().id(),
                    ExtractedUiNode {
                        z_order: stack_index.0 as f32 + stack_z_offsets::BORDER,
                        image,
                        clip: maybe_clip.cloned(),
                        transform: transform.into(),
                        item: ExtractedUiItem::Node {
                            color: outline.color.into(),
                            rect: Rect {
                                max: outline_size,
                                ..Default::default()
                            },
                            atlas_scaling: None,
                            flip_x: false,
                            flip_y: false,
                            border: BorderRect::all(computed_node.outline_width()),
                            border_radius: computed_node.outline_radius(),
                            node_type: NodeType::Border(shader_flags::BORDER_ALL),
                        },
                    },
                );
        }
    }
}

/// The UI camera is "moved back" by this many units (plus the [`UI_CAMERA_TRANSFORM_OFFSET`]) and also has a view
/// distance of this many units. This ensures that with a left-handed projection,
/// as UI elements are "stacked on top of each other", they are within the camera's view
/// and have room to grow.
// TODO: Consider computing this value at runtime based on the maximum z-value.
const UI_CAMERA_FAR: f32 = 1000.0;

// This value is subtracted from the far distance for the camera's z-position to ensure nodes at z == 0.0 are rendered
// TODO: Evaluate if we still need this.
const UI_CAMERA_TRANSFORM_OFFSET: f32 = -0.1;

/// The ID of the subview associated with a camera on which UI is to be drawn.
///
/// When UI is present, cameras extract to two views: the main 2D/3D one and a
/// UI one. The main 2D or 3D camera gets subview 0, and the corresponding UI
/// camera gets this subview, 1.
const UI_CAMERA_SUBVIEW: u32 = 1;

/// A render-world component that lives on the main render target view and
/// specifies the corresponding UI view.
///
/// For example, if UI is being rendered to a 3D camera, this component lives on
/// the 3D camera and contains the entity corresponding to the UI view.
#[derive(Component)]
/// Entity id of the temporary render entity with the corresponding extracted UI view.
pub struct UiCameraView(pub Entity);

/// A render-world component that lives on the UI view and specifies the
/// corresponding main render target view.
///
/// For example, if the UI is being rendered to a 3D camera, this component
/// lives on the UI view and contains the entity corresponding to the 3D camera.
///
/// This is the inverse of [`UiCameraView`].
#[derive(Component)]
pub struct UiViewTarget(pub Entity);

/// Information that [`extract_ui_camera_view`] maintains about each view that
/// it has seen.
pub struct CachedUiViewData {
    /// The render-world [`ExtractedView`].
    extracted_view_entity: Entity,
    /// The unique, stable identifier for the view across frames.
    retained_view_entity: RetainedViewEntity,
}

/// Extracts all UI elements associated with a camera into the render world.
pub fn extract_ui_camera_view(
    mut commands: Commands,
    mut transparent_render_phases: ResMut<ViewSortedRenderPhases<TransparentUi>>,
    query: Extract<
        Query<
            (
                Entity,
                RenderEntity,
                &Camera,
                Option<&UiAntiAlias>,
                Option<&BoxShadowSamples>,
            ),
            Or<(With<Camera2d>, With<Camera3d>)>,
        >,
    >,
    main_pass_formats: Res<CameraMainPassTextureFormats>,
    mut live_entities: Local<HashSet<RetainedViewEntity>>,
    mut cached_ui_view_data: Local<MainEntityHashMap<CachedUiViewData>>,
    mut removed_cameras_query: Extract<RemovedComponents<Camera>>,
    mut cameras_updated_this_frame: Local<MainEntityHashSet>,
) {
    cameras_updated_this_frame.clear();
    for (main_entity, render_entity, camera, ui_anti_alias, shadow_samples) in &query {
        let main_entity = MainEntity::from(main_entity);
        let retained_view_entity = RetainedViewEntity::new(main_entity, None, UI_CAMERA_SUBVIEW);

        // ignore inactive cameras
        if let (Some(physical_viewport_rect), Some(target_size), Some(target_format)) = (
            camera.physical_viewport_rect(),
            camera.physical_target_size(),
            main_pass_formats.get(&render_entity).copied(),
        ) && target_size.x != 0
            && target_size.y != 0
            && camera.physical_viewport_size().is_some()
            && camera.is_active
        {
            cameras_updated_this_frame.insert(main_entity);
            transparent_render_phases.prepare_for_new_frame(retained_view_entity);

            // use a projection matrix with the origin in the top left instead of the bottom left that comes with OrthographicProjection
            let projection_matrix = proj::orthographic(
                0.0,
                physical_viewport_rect.width() as f32,
                physical_viewport_rect.height() as f32,
                0.0,
                0.0,
                UI_CAMERA_FAR,
            );
            // We use `UI_CAMERA_SUBVIEW` here so as not to conflict with the
            // main 3D or 2D camera, which will have subview index 0.
            // Creates the UI view.
            let extracted_view = ExtractedView {
                retained_view_entity,
                clip_from_view: projection_matrix,
                world_from_view: GlobalTransform::from_xyz(
                    0.0,
                    0.0,
                    UI_CAMERA_FAR + UI_CAMERA_TRANSFORM_OFFSET,
                ),
                clip_from_world: None,
                target_format,
                viewport: UVec4::from((physical_viewport_rect.min, physical_viewport_rect.size())),
                color_grading: Default::default(),
                invert_culling: false,
            };
            // Link to the main camera view.
            let ui_view_target_component = UiViewTarget(render_entity);

            let ui_camera_view = match cached_ui_view_data.get(&main_entity) {
                Some(cached_ui_view_data) => commands
                    .entity(cached_ui_view_data.extracted_view_entity)
                    .insert((extracted_view, ui_view_target_component))
                    .id(),
                None => commands
                    .spawn((extracted_view, ui_view_target_component))
                    .id(),
            };

            let mut entity_commands = commands
                .get_entity(render_entity)
                .expect("Camera entity wasn't synced.");
            // Link from the main 2D/3D camera view to the UI view.
            entity_commands.insert(UiCameraView(ui_camera_view));
            if let Some(ui_anti_alias) = ui_anti_alias {
                entity_commands.insert(*ui_anti_alias);
            }
            if let Some(shadow_samples) = shadow_samples {
                entity_commands.insert(*shadow_samples);
            }

            live_entities.insert(retained_view_entity);
            cached_ui_view_data.insert(
                main_entity,
                CachedUiViewData {
                    extracted_view_entity: ui_camera_view,
                    retained_view_entity,
                },
            );
            continue;
        }

        // If we got here, the camera no longer exists or is no longer
        // renderable. Remove its associated render-world data.
        commands
            .get_entity(render_entity)
            .expect("Camera entity wasn't synced.")
            .remove::<(UiCameraView, UiAntiAlias, BoxShadowSamples)>();
        live_entities.remove(&retained_view_entity);
        if let Some(cached_ui_view_data) = cached_ui_view_data.remove(&main_entity) {
            commands
                .entity(cached_ui_view_data.extracted_view_entity)
                .despawn();
        }
    }

    // Only remove the render-world data for a camera if we didn't handle the
    // camera above.
    // It's possible that the `Camera` component was removed and added in the
    // same frame.
    for main_entity in removed_cameras_query.read() {
        let main_entity = MainEntity::from(main_entity);
        if cameras_updated_this_frame.contains(&main_entity) {
            continue;
        }

        if let Some(cached_ui_view_data) = cached_ui_view_data.remove(&main_entity) {
            commands
                .entity(cached_ui_view_data.extracted_view_entity)
                .despawn();
            live_entities.remove(&cached_ui_view_data.retained_view_entity);
        }
    }

    // Clean up render phases belonging to cameras that no longer exist.
    transparent_render_phases.retain(|entity, _| live_entities.contains(entity));
}

pub fn extract_viewport_nodes(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    camera_query: Extract<Query<(&Camera, &RenderTarget)>>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &ComputedStackIndex,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
            &ViewportNode,
        )>,
    >,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();

    for (
        entity,
        uinode,
        stack_index,
        transform,
        inherited_visibility,
        clip,
        camera,
        viewport_node,
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip invisible images
        if !inherited_visibility.get() || uinode.is_empty() {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
            continue;
        };
        let Some(camera_entity) = viewport_node.camera else {
            continue;
        };

        let Some(image) = camera_query
            .get(camera_entity)
            .ok()
            .and_then(|(_, render_target)| render_target.as_image())
        else {
            continue;
        };

        extracted_uinodes
            .uinodes
            .entry(entity.into())
            .or_insert_with(|| (extracted_camera_entity, Default::default()))
            .1
            .insert(
                commands.spawn_empty().id(),
                ExtractedUiNode {
                    z_order: stack_index.0 as f32 + stack_z_offsets::IMAGE,
                    clip: clip.cloned(),
                    image: image.id(),
                    transform: transform.into(),
                    item: ExtractedUiItem::Node {
                        color: LinearRgba::WHITE,
                        rect: Rect {
                            min: Vec2::ZERO,
                            max: uinode.size,
                        },
                        atlas_scaling: None,
                        flip_x: false,
                        flip_y: false,
                        border: uinode.border(),
                        border_radius: uinode.border_radius(),
                        node_type: NodeType::Rect,
                    },
                },
            );
    }
}

pub fn extract_text_sections(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &ComputedStackIndex,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
            &ComputedTextBlock,
            &TextColor,
            &TextLayoutInfo,
            Option<&EditableText>,
            Option<&TextCursorStyle>,
        )>,
    >,
    text_styles: Extract<Query<&TextColor>>,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();

    let mut glyphs = vec![];

    for (
        entity,
        uinode,
        stack_index,
        global_transform,
        inherited_visibility,
        maybe_clip,
        camera,
        computed_block,
        text_color,
        text_layout_info,
        editable_text,
        cursor_style,
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip if not visible or if size is set to zero (e.g. when a parent is set to `Display::None`)
        if !inherited_visibility.get() || uinode.is_empty() {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
            continue;
        };

        let transform = Affine2::from(*global_transform)
            * Affine2::from_translation(
                uinode.content_box().min
                    - editable_text.map_or(Vec2::ZERO, |text| text.viewport.offset),
            );

        let clip = calculate_text_scroll_clip(editable_text, maybe_clip, uinode, global_transform);

        let mut color = text_color.0.to_linear();

        let selected_text_color = cursor_style
            .and_then(|cursor_style| cursor_style.selected_text_color)
            .map(|selected_text_color| selected_text_color.to_linear());

        let mut current_section_index = 0;

        for (
            i,
            PositionedGlyph {
                position,
                atlas_info,
                section_index,
                ..
            },
        ) in text_layout_info.glyphs.iter().enumerate()
        {
            if current_section_index != *section_index
                && let Some(section_entity) = computed_block
                    .entities()
                    .get(*section_index as usize)
                    .map(|t| t.entity)
            {
                color = text_styles
                    .get(section_entity)
                    .map(|text_color| LinearRgba::from(text_color.0))
                    .unwrap_or_default();
                current_section_index = *section_index;
            }

            let color = if !atlas_info.is_alpha_mask {
                LinearRgba::WHITE
            } else if let Some(selected_text_color) = selected_text_color
                && text_layout_info
                    .selection_rects
                    .iter()
                    .any(|selection_rect| {
                        let glyph_rect = Rect::from_center_size(*position, atlas_info.rect.size());
                        selection_rect.contains(glyph_rect.min)
                            && selection_rect.contains(glyph_rect.max)
                    })
            {
                selected_text_color
            } else {
                color
            };

            glyphs.push(ExtractedGlyph {
                color,
                translation: *position,
                rect: atlas_info.rect,
            });

            if text_layout_info
                .glyphs
                .get(i + 1)
                .is_none_or(|info| info.atlas_info.texture != atlas_info.texture)
            {
                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT,
                            image: atlas_info.texture,
                            clip: clip.clone(),
                            item: ExtractedUiItem::Glyphs {
                                glyphs: mem::take(&mut glyphs),
                            },
                            transform,
                        },
                    );
            }
        }
    }
}

pub fn extract_text_shadows(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &ComputedStackIndex,
            &UiGlobalTransform,
            &ComputedUiTargetCamera,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &TextLayoutInfo,
            &TextShadow,
            &ComputedTextBlock,
            Option<&EditableText>,
        )>,
    >,
    text_decoration_query: Extract<Query<(Has<Strikethrough>, Has<Underline>)>>,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();

    let mut glyphs = vec![];

    for (
        entity,
        uinode,
        stack_index,
        global_transform,
        target,
        inherited_visibility,
        maybe_clip,
        text_layout_info,
        shadow,
        computed_block,
        editable_text,
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip if not visible or if size is set to zero (e.g. when a parent is set to `Display::None`)
        if !inherited_visibility.get() || uinode.is_empty() {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(target) else {
            continue;
        };

        let node_transform = Affine2::from(*global_transform)
            * Affine2::from_translation(
                uinode.content_box().min + shadow.offset / uinode.inverse_scale_factor()
                    - editable_text.map_or(Vec2::ZERO, |text| text.viewport.offset),
            );

        let clip = calculate_text_scroll_clip(editable_text, maybe_clip, uinode, global_transform);

        for (
            i,
            PositionedGlyph {
                position,
                atlas_info,
                section_index,
                ..
            },
        ) in text_layout_info.glyphs.iter().enumerate()
        {
            glyphs.push(ExtractedGlyph {
                color: shadow.color.into(),
                translation: *position,
                rect: atlas_info.rect,
            });

            if text_layout_info.glyphs.get(i + 1).is_none_or(|info| {
                info.section_index != *section_index
                    || info.atlas_info.texture != atlas_info.texture
            }) {
                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            transform: node_transform,
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT,
                            image: atlas_info.texture,
                            clip: clip.clone(),
                            item: ExtractedUiItem::Glyphs {
                                glyphs: mem::take(&mut glyphs),
                            },
                        },
                    );
            }
        }

        for run in text_layout_info.run_geometry.iter() {
            let Some(section_entity) = computed_block
                .entities()
                .get(run.section_index as usize)
                .map(|t| t.entity)
            else {
                continue;
            };
            let Ok((has_strikethrough, has_underline)) = text_decoration_query.get(section_entity)
            else {
                continue;
            };

            if has_strikethrough {
                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT,
                            clip: clip.clone(),
                            image: AssetId::default(),
                            transform: node_transform
                                * Affine2::from_translation(run.strikethrough_position()),
                            item: ExtractedUiItem::Node {
                                color: shadow.color.into(),
                                rect: Rect {
                                    min: Vec2::ZERO,
                                    max: run.strikethrough_size(),
                                },
                                atlas_scaling: None,
                                flip_x: false,
                                flip_y: false,
                                border: BorderRect::ZERO,
                                border_radius: ResolvedBorderRadius::ZERO,
                                node_type: NodeType::Rect,
                            },
                        },
                    );
            }

            if has_underline {
                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT,
                            clip: clip.clone(),
                            image: AssetId::default(),
                            transform: node_transform
                                * Affine2::from_translation(run.underline_position()),
                            item: ExtractedUiItem::Node {
                                color: shadow.color.into(),
                                rect: Rect {
                                    min: Vec2::ZERO,
                                    max: run.underline_size(),
                                },
                                atlas_scaling: None,
                                flip_x: false,
                                flip_y: false,
                                border: BorderRect::ZERO,
                                border_radius: ResolvedBorderRadius::ZERO,
                                node_type: NodeType::Rect,
                            },
                        },
                    );
            }
        }
    }
}

pub fn extract_text_decorations(
    mut commands: Commands,
    extracted_uinodes: ResMut<ExtractedUiNodes>,
    uinode_query: Extract<
        Query<(
            Entity,
            &ComputedNode,
            &ComputedStackIndex,
            &ComputedTextBlock,
            &UiGlobalTransform,
            &InheritedVisibility,
            Option<&CalculatedClip>,
            &ComputedUiTargetCamera,
            &TextLayoutInfo,
            Option<&EditableText>,
        )>,
    >,
    text_background_colors_query: Extract<
        Query<(
            AnyOf<(&TextBackgroundColor, &Strikethrough, &Underline)>,
            &TextColor,
            Option<&StrikethroughColor>,
            Option<&UnderlineColor>,
        )>,
    >,
    camera_map: Extract<UiCameraMap>,
) {
    let extracted_uinodes = extracted_uinodes.into_inner();
    let mut camera_mapper = camera_map.get_mapper();

    for (
        entity,
        uinode,
        stack_index,
        computed_block,
        global_transform,
        inherited_visibility,
        maybe_clip,
        camera,
        text_layout_info,
        editable_text,
    ) in extracted_uinodes
        .changed
        .iter()
        .flat_map(|main_entity| uinode_query.get(main_entity.entity()).ok())
    {
        // Skip if not visible or if size is set to zero (e.g. when a parent is set to `Display::None`)
        if !inherited_visibility.get() || uinode.is_empty() {
            continue;
        }

        let Some(extracted_camera_entity) = camera_mapper.map(camera) else {
            continue;
        };

        let transform = Affine2::from(global_transform)
            * Affine2::from_translation(
                uinode.content_box().min
                    - editable_text.map_or(Vec2::ZERO, |text| text.viewport.offset),
            );

        let clip = calculate_text_scroll_clip(editable_text, maybe_clip, uinode, global_transform);

        for run in text_layout_info.run_geometry.iter() {
            let Some(section_entity) = computed_block
                .entities()
                .get(run.section_index as usize)
                .map(|t| t.entity)
            else {
                continue;
            };
            let Ok((
                (text_background_color, maybe_strikethrough, maybe_underline),
                text_color,
                maybe_strikethrough_color,
                maybe_underline_color,
            )) = text_background_colors_query.get(section_entity)
            else {
                continue;
            };

            if let Some(text_background_color) = text_background_color {
                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT,
                            clip: clip.clone(),
                            image: AssetId::default(),
                            transform: transform * Affine2::from_translation(run.bounds.center()),
                            item: ExtractedUiItem::Node {
                                color: text_background_color.0.to_linear(),
                                rect: Rect {
                                    min: Vec2::ZERO,
                                    max: run.bounds.size(),
                                },
                                atlas_scaling: None,
                                flip_x: false,
                                flip_y: false,
                                border: BorderRect::ZERO,
                                border_radius: ResolvedBorderRadius::ZERO,
                                node_type: NodeType::Rect,
                            },
                        },
                    );
            }

            if maybe_strikethrough.is_some() {
                let color = maybe_strikethrough_color
                    .map(|sc| sc.0)
                    .unwrap_or(text_color.0)
                    .to_linear();

                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT_STRIKETHROUGH,
                            clip: clip.clone(),
                            image: AssetId::default(),
                            transform: transform
                                * Affine2::from_translation(run.strikethrough_position()),
                            item: ExtractedUiItem::Node {
                                color,
                                rect: Rect {
                                    min: Vec2::ZERO,
                                    max: run.strikethrough_size(),
                                },
                                atlas_scaling: None,
                                flip_x: false,
                                flip_y: false,
                                border: BorderRect::ZERO,
                                border_radius: ResolvedBorderRadius::ZERO,
                                node_type: NodeType::Rect,
                            },
                        },
                    );
            }

            if maybe_underline.is_some() {
                let color = maybe_underline_color
                    .map(|uc| uc.0)
                    .unwrap_or(text_color.0)
                    .to_linear();

                extracted_uinodes
                    .uinodes
                    .entry(entity.into())
                    .or_insert_with(|| (extracted_camera_entity, Default::default()))
                    .1
                    .insert(
                        commands.spawn_empty().id(),
                        ExtractedUiNode {
                            z_order: stack_index.0 as f32 + stack_z_offsets::TEXT_STRIKETHROUGH,
                            clip: clip.clone(),
                            image: AssetId::default(),
                            transform: transform
                                * Affine2::from_translation(run.underline_position()),
                            item: ExtractedUiItem::Node {
                                color,
                                rect: Rect {
                                    min: Vec2::ZERO,
                                    max: run.underline_size(),
                                },
                                atlas_scaling: None,
                                flip_x: false,
                                flip_y: false,
                                border: BorderRect::ZERO,
                                border_radius: ResolvedBorderRadius::ZERO,
                                node_type: NodeType::Rect,
                            },
                        },
                    );
            }
        }
    }
}

#[repr(C)]
#[derive(Copy, Clone, Debug, Pod, Zeroable)]
struct UiVertex {
    pub position: [f32; 3],
    pub uv: [f32; 2],
    pub color: [f32; 4],
    /// Shader flags to determine how to render the UI node.
    /// See [`shader_flags`] for possible values.
    pub flags: u32,
    /// Border radius of the UI node.
    /// Ordering: top left, top right, bottom right, bottom left.
    pub radius: [[f32; 4]; 2],
    /// Border thickness of the UI node.
    /// Ordering: left, top, right, bottom.
    pub border: [f32; 4],
    /// Size of the UI node.
    pub size: [f32; 2],
    /// Position relative to the center of the UI node.
    pub point: [f32; 2],
}

#[derive(Resource)]
pub struct UiMeta {
    vertices: RawBufferVec<UiVertex>,
    indices: RawBufferVec<u32>,
    view_bind_group: Option<BindGroup>,
}

impl Default for UiMeta {
    fn default() -> Self {
        Self {
            vertices: RawBufferVec::new(BufferUsages::VERTEX),
            indices: RawBufferVec::new(BufferUsages::INDEX),
            view_bind_group: None,
        }
    }
}

pub(crate) const QUAD_VERTEX_POSITIONS: [Vec2; 4] = [
    Vec2::new(-0.5, -0.5),
    Vec2::new(0.5, -0.5),
    Vec2::new(0.5, 0.5),
    Vec2::new(-0.5, 0.5),
];

#[derive(Component, Debug)]
pub struct UiBatch {
    pub range: Range<u32>,
    pub image: AssetId<Image>,
}

/// The values here should match the values for the constants in `ui.wesl`
pub mod shader_flags {
    /// Texture should be ignored
    pub const UNTEXTURED: u32 = 0;
    /// Textured
    pub const TEXTURED: u32 = 1;
    /// Ordering: top left, top right, bottom right, bottom left.
    pub const CORNERS: [u32; 4] = [0, 2, 2 | 4, 4];
    pub const RADIAL: u32 = 16;
    pub const FILL_START: u32 = 32;
    pub const FILL_END: u32 = 64;
    pub const CONIC: u32 = 128;
    pub const BORDER_LEFT: u32 = 256;
    pub const BORDER_TOP: u32 = 512;
    pub const BORDER_RIGHT: u32 = 1024;
    pub const BORDER_BOTTOM: u32 = 2048;
    pub const BORDER_ALL: u32 = BORDER_LEFT + BORDER_TOP + BORDER_RIGHT + BORDER_BOTTOM;
    pub const INVERT: u32 = 4096;
}

pub fn queue_uinodes(
    extracted_uinodes: Res<ExtractedUiNodes>,
    ui_pipeline: Res<UiPipeline>,
    mut pipelines: ResMut<SpecializedRenderPipelines<UiPipeline>>,
    mut transparent_render_phases: ResMut<ViewSortedRenderPhases<TransparentUi>>,
    render_views: Query<(&UiCameraView, Option<&UiAntiAlias>), With<ExtractedView>>,
    camera_views: Query<&ExtractedView>,
    pipeline_cache: Res<PipelineCache>,
    draw_functions: Res<DrawFunctions<TransparentUi>>,
) {
    let draw_function = draw_functions.read().id::<DrawUi>();
    let mut current_camera_entity = Entity::PLACEHOLDER;
    let mut current_phase = None;

    for (main_entity, (extracted_camera_entity, extracted_sub_uinodes)) in
        extracted_uinodes.uinodes.iter()
    {
        if current_camera_entity != *extracted_camera_entity {
            current_phase = render_views.get(*extracted_camera_entity).ok().and_then(
                |(default_camera_view, ui_anti_alias)| {
                    camera_views
                        .get(default_camera_view.0)
                        .ok()
                        .and_then(|view| {
                            transparent_render_phases
                                .get_mut(&view.retained_view_entity)
                                .map(|transparent_phase| {
                                    let pipeline = pipelines.specialize(
                                        &pipeline_cache,
                                        &ui_pipeline,
                                        UiPipelineKey {
                                            target_format: view.target_format,
                                            anti_alias: matches!(
                                                ui_anti_alias,
                                                None | Some(UiAntiAlias::On)
                                            ),
                                        },
                                    );
                                    (pipeline, transparent_phase)
                                })
                        })
                },
            );
            current_camera_entity = *extracted_camera_entity;
        }

        let Some((pipeline, transparent_phase)) = current_phase.as_mut() else {
            continue;
        };
        for (render_entity, extracted_uinode) in extracted_sub_uinodes.iter() {
            transparent_phase.add_transient(TransparentUi {
                draw_function,
                pipeline: *pipeline,
                entity: (*render_entity, *main_entity),
                sort_key: FloatOrd(extracted_uinode.z_order),
                // batch_range will be calculated in prepare_uinodes
                batch_range: 0..0,
                extra_index: PhaseItemExtraIndex::None,
                indexed: true,
            });
        }
    }
}

#[derive(Resource, Default)]
pub struct ImageNodeBindGroups {
    pub values: HashMap<AssetId<Image>, BindGroup>,
}

pub fn prepare_uinodes(
    mut commands: Commands,
    render_device: Res<RenderDevice>,
    render_queue: Res<RenderQueue>,
    pipeline_cache: Res<PipelineCache>,
    mut ui_meta: ResMut<UiMeta>,
    extracted_uinodes: Res<ExtractedUiNodes>,
    view_uniforms: Res<ViewUniforms>,
    ui_pipeline: Res<UiPipeline>,
    mut image_bind_groups: ResMut<ImageNodeBindGroups>,
    gpu_images: Res<RenderAssets<GpuImage>>,
    mut phases: ResMut<ViewSortedRenderPhases<TransparentUi>>,
    events: Res<SpriteAssetEvents>,
    mut previous_len: Local<usize>,
) {
    // If an image has changed, the GpuImage has (probably) changed
    for event in &events.images {
        match event {
            AssetEvent::Added { .. } |
            AssetEvent::Unused { .. } |
            // Images don't have dependencies
            AssetEvent::LoadedWithDependencies { .. } => {}
            AssetEvent::Modified { id } | AssetEvent::Removed { id } => {
                image_bind_groups.values.remove(id);
            }
        };
    }

    if let Some(view_binding) = view_uniforms.uniforms.binding() {
        let mut batches: Vec<(Entity, UiBatch)> = Vec::with_capacity(*previous_len);

        ui_meta.vertices.clear();
        ui_meta.indices.clear();
        ui_meta.view_bind_group = Some(render_device.create_bind_group(
            "ui_view_bind_group",
            &pipeline_cache.get_bind_group_layout(&ui_pipeline.view_layout),
            &BindGroupEntries::single(view_binding),
        ));

        // Buffer indexes
        let mut vertices_index = 0;
        let mut indices_index = 0;

        for ui_phase in phases.values_mut() {
            let mut batch_item_index = 0;
            let mut batch_image_handle = None;

            for item_index in 0..ui_phase.items.len() {
                let item = &mut ui_phase.items[item_index];
                let Some(extracted_uinode) = extracted_uinodes
                    .uinodes
                    .get(&item.main_entity())
                    .and_then(|(_, sub_uinodes)| sub_uinodes.get(&item.entity()))
                else {
                    batch_image_handle = None;
                    continue;
                };

                // Initialize the batch range to be zero-length initially.
                // We'll extend it as we accumulate items into this batch.
                item.batch_range = (item_index as u32)..(item_index as u32);

                let mut existing_batch = batches.last_mut();

                if batch_image_handle.is_none()
                    || existing_batch.is_none()
                    || (batch_image_handle != Some(AssetId::default())
                        && extracted_uinode.image != AssetId::default()
                        && batch_image_handle != Some(extracted_uinode.image))
                {
                    if let Some(gpu_image) = gpu_images.get(extracted_uinode.image) {
                        batch_item_index = item_index;
                        batch_image_handle = Some(extracted_uinode.image);

                        let new_batch = UiBatch {
                            range: vertices_index..vertices_index,
                            image: extracted_uinode.image,
                        };
                        batches.push((item.entity(), new_batch));

                        image_bind_groups
                            .values
                            .entry(extracted_uinode.image)
                            .or_insert_with(|| {
                                render_device.create_bind_group(
                                    "ui_material_bind_group",
                                    &pipeline_cache
                                        .get_bind_group_layout(&ui_pipeline.image_layout),
                                    &BindGroupEntries::sequential((
                                        &gpu_image.texture_view,
                                        &gpu_image.sampler,
                                    )),
                                )
                            });

                        existing_batch = batches.last_mut();
                    } else {
                        continue;
                    }
                } else if batch_image_handle == Some(AssetId::default())
                    && extracted_uinode.image != AssetId::default()
                {
                    if let Some(ref mut existing_batch) = existing_batch
                        && let Some(gpu_image) = gpu_images.get(extracted_uinode.image)
                    {
                        batch_image_handle = Some(extracted_uinode.image);
                        existing_batch.1.image = extracted_uinode.image;

                        image_bind_groups
                            .values
                            .entry(extracted_uinode.image)
                            .or_insert_with(|| {
                                render_device.create_bind_group(
                                    "ui_material_bind_group",
                                    &pipeline_cache
                                        .get_bind_group_layout(&ui_pipeline.image_layout),
                                    &BindGroupEntries::sequential((
                                        &gpu_image.texture_view,
                                        &gpu_image.sampler,
                                    )),
                                )
                            });
                    } else {
                        continue;
                    }
                }
                match &extracted_uinode.item {
                    ExtractedUiItem::Node {
                        atlas_scaling,
                        flip_x,
                        flip_y,
                        border_radius,
                        border,
                        node_type,
                        rect,
                        color,
                    } => {
                        let mut flags = if extracted_uinode.image != AssetId::default() {
                            shader_flags::TEXTURED
                        } else {
                            shader_flags::UNTEXTURED
                        };

                        let rect_size = rect.size();

                        let transform = extracted_uinode.transform;

                        // Specify the corners of the node
                        let points = QUAD_VERTEX_POSITIONS.map(|pos| pos * rect_size);
                        let positions = points.map(|pos| transform.transform_point2(pos));

                        let uvs = if flags == shader_flags::UNTEXTURED {
                            [Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::Y]
                        } else {
                            let mut uinode_rect = *rect;
                            let image = gpu_images
                                .get(extracted_uinode.image)
                                .expect("Image was checked during batching and should still exist");
                            // Rescale atlases. This is done here because we need texture data that might not be available in Extract.
                            let atlas_extent = atlas_scaling
                                .map(|scaling| image.size_2d().as_vec2() * scaling)
                                .unwrap_or(uinode_rect.max);
                            if *flip_x {
                                mem::swap(&mut uinode_rect.max.x, &mut uinode_rect.min.x);
                            }
                            if *flip_y {
                                mem::swap(&mut uinode_rect.max.y, &mut uinode_rect.min.y);
                            }
                            [
                                Vec2::new(uinode_rect.min.x, uinode_rect.min.y),
                                Vec2::new(uinode_rect.max.x, uinode_rect.min.y),
                                Vec2::new(uinode_rect.max.x, uinode_rect.max.y),
                                Vec2::new(uinode_rect.min.x, uinode_rect.max.y),
                            ]
                            .map(|pos| pos / atlas_extent)
                        };

                        let color = color.to_f32_array();
                        match *node_type {
                            NodeType::Border(border_flags) => {
                                flags |= border_flags;
                            }
                            NodeType::Inverted => {
                                flags |= INVERT;
                            }
                            _ => {}
                        }

                        let vertices = clip_polygon(
                            extracted_uinode.clip.as_ref(),
                            &[
                                (positions[0], (uvs[0], points[0])),
                                (positions[1], (uvs[1], points[1])),
                                (positions[2], (uvs[2], points[2])),
                                (positions[3], (uvs[3], points[3])),
                            ],
                            |a, b, t| (a.0.lerp(b.0, t), a.1.lerp(b.1, t)),
                        );
                        if vertices.is_empty() {
                            continue;
                        }

                        for &(position, (uv, point)) in &vertices {
                            ui_meta.vertices.push(UiVertex {
                                position: position.extend(0.).into(),
                                uv: uv.into(),
                                color,
                                flags,
                                radius: (*border_radius).into(),
                                border: [
                                    border.min_inset.x,
                                    border.min_inset.y,
                                    border.max_inset.x,
                                    border.max_inset.y,
                                ],
                                size: rect_size.into(),
                                point: point.into(),
                            });
                        }

                        for i in 1..vertices.len() as u32 - 1 {
                            ui_meta.indices.push(indices_index);
                            ui_meta.indices.push(indices_index + i);
                            ui_meta.indices.push(indices_index + i + 1);
                        }

                        vertices_index += 3 * (vertices.len() as u32 - 2);
                        indices_index += vertices.len() as u32;
                    }
                    ExtractedUiItem::Glyphs { glyphs } => {
                        let image = gpu_images
                            .get(extracted_uinode.image)
                            .expect("Image was checked during batching and should still exist");

                        let atlas_extent = image.size_2d().as_vec2();

                        for glyph in glyphs {
                            let color = glyph.color.to_f32_array();
                            let glyph_rect = glyph.rect;
                            let rect_size = glyph_rect.size();

                            // Specify the corners of the glyph
                            let positions = QUAD_VERTEX_POSITIONS.map(|pos| {
                                extracted_uinode
                                    .transform
                                    .transform_point2(glyph.translation + pos * glyph_rect.size())
                            });

                            let vertices = clip_polygon(
                                extracted_uinode.clip.as_ref(),
                                &[
                                    (
                                        positions[0],
                                        Vec2::new(glyph.rect.min.x, glyph.rect.min.y)
                                            / atlas_extent,
                                    ),
                                    (
                                        positions[1],
                                        Vec2::new(glyph.rect.max.x, glyph.rect.min.y)
                                            / atlas_extent,
                                    ),
                                    (
                                        positions[2],
                                        Vec2::new(glyph.rect.max.x, glyph.rect.max.y)
                                            / atlas_extent,
                                    ),
                                    (
                                        positions[3],
                                        Vec2::new(glyph.rect.min.x, glyph.rect.max.y)
                                            / atlas_extent,
                                    ),
                                ],
                                Vec2::lerp,
                            );
                            if vertices.is_empty() {
                                continue;
                            }

                            for vertex in &vertices {
                                ui_meta.vertices.push(UiVertex {
                                    position: vertex.0.extend(0.).into(),
                                    uv: vertex.1.into(),
                                    color,
                                    flags: shader_flags::TEXTURED,
                                    radius: [[0.0; 4]; 2],
                                    border: [0.0; 4],
                                    size: rect_size.into(),
                                    point: [0.0; 2],
                                });
                            }

                            for i in 1..vertices.len() as u32 - 1 {
                                ui_meta.indices.push(indices_index);
                                ui_meta.indices.push(indices_index + i);
                                ui_meta.indices.push(indices_index + i + 1);
                            }

                            vertices_index += 3 * (vertices.len() as u32 - 2);
                            indices_index += vertices.len() as u32;
                        }
                    }
                }
                existing_batch.unwrap().1.range.end = vertices_index;
                ui_phase.items[batch_item_index].batch_range_mut().end += 1;
            }
        }

        ui_meta.vertices.write_buffer(&render_device, &render_queue);
        ui_meta.indices.write_buffer(&render_device, &render_queue);
        *previous_len = batches.len();
        commands.try_insert_batch(batches);
    }
}

/// A render-world system that removes all [`UiBatch`] components.
///
/// They're currently rebuilt from scratch every frame, so we have to remove
/// them.
///
/// This is run during the render cleanup phase.
pub fn clear_batches(mut commands: Commands, batches_query: Query<Entity, With<UiBatch>>) {
    for entity in &batches_query {
        commands.entity(entity).remove::<UiBatch>();
    }
}