crcbl-ui 0.2.1

Crucible immediate-mode GUI
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
//! Draw list: a sequence of UI draw commands queued for rendering.
//!
//! Each frame the UI code produces a [`DrawList`] — an ordered list of
//! commands (rectangles, pictures, text spans) that a render backend then
//! processes into GPU draw calls. The draw list is the only interface between
//! the immediate-mode UI and the renderer.
//!
//! # Every primitive is one kind of quad
//!
//! Solid rectangles, strokes, bitmap glyphs, [`glyph runs`](DrawList::glyphs)
//! from a parsed font, [`image`](DrawList::image) quads and
//! [`rounded rectangles`](DrawList::rounded_rect) all expand to the same
//! [`Vertex2d`], which says which of them it belongs to in
//! [`Vertex2d::shape`]. `crcbl-render`'s UI pass draws the whole list with one
//! pipeline and one draw a half, so a menu frame, the text on it and a rounded
//! panel beside it never break a batch.
//!
//! **A [`texture`](DrawList::texture) rectangle is the one exception**, and it
//! breaks the batch on purpose: it samples a picture the renderer drew — a
//! second camera's view — which is bound to a set of its own per draw, because
//! the portable targets have no array of textures to index instead. The
//! expansion reports each run of such quads as a [`TextureRun`], and everything
//! between two runs is still one draw.
//!
//! # Clip rectangles travel on the vertex
//!
//! [`push_clip`](DrawList::push_clip) narrows everything pushed after it until
//! the matching [`pop_clip`](DrawList::pop_clip), and every vertex a command
//! expands to carries the clip that was current when the command went in. The
//! fragment stage discards outside it. No GPU scissor and no stencil: a scissor
//! is per draw, so a list that clipped two panels differently would be two
//! draws, and the UI's rendering rules (`docs/notes/tooling.md`) keep batching
//! as the reason.
//!
//! # Logical pixels, recorded in window pixels
//!
//! A game can lay its UI out in **logical** pixels — for a reference window,
//! say — and have it drawn at the window's size.
//! [`set_scale`](DrawList::set_scale) says how many window pixels one logical
//! pixel covers, and every push from then on converts as it records: positions,
//! sizes, stroke and border widths, corner radii, clips, text sizes, and a glyph
//! run's origin, size and every pen offset. The list itself only ever holds
//! window pixels, so the renderer, the clip lanes and the overlay cut never
//! see the scale.
//!
//! **At record time, not afterwards.** A glyph run recorded at the scaled size
//! is rasterised at that size, so text stays crisp; scaling the finished
//! vertices in a shader would stretch masks rasterised at the logical size, and
//! rebuilding the finished list at the window's size would cost a second list
//! every frame. A pointer position goes the other way through
//! [`to_logical`](DrawList::to_logical), so hit tests stay in the units the
//! layout was made in. At a scale of one nothing is converted at all.

use crate::font::Font;
use crate::font::atlas::{GlyphAtlas, SUBPIXEL_BINS};
use crate::font::color::ColorGlyphCache;
use crate::font::layout::PositionedGlyph;
use crate::image::{AtlasImage, ImageAtlas, NineSliceImage, TextureId, slice_bands, slice_cuts};
use crate::text::FontAtlas;
use crate::text::GLYPH_HEIGHT;
use crate::widget::SkinInsets;
use core::fmt;
use core::ops::Range;
use glam::Vec2;
use std::sync::Arc;

// ---------------------------------------------------------------------------
// Vertex
// ---------------------------------------------------------------------------

/// A 2D vertex for UI rendering (screen-space, no Z).
///
/// Six lanes, mirrored field for field by `Vertex` in
/// `crates/crcbl-shaders/shaders/ui.slang` and read out of one storage buffer
/// by `crcbl_render::ui_pass`. The first three are what every primitive has
/// always had; the last three are zero for a primitive that does not use them,
/// except [`clip`](Self::clip), which is [`ClipRect::NONE`] when nothing is
/// clipped.
///
/// # Safety
///
/// The fields are all f32 values with no padding, making the struct safe to
/// transmute to/from byte slices.
#[derive(Debug, Clone, Copy, PartialEq)]
#[repr(C)]
pub struct Vertex2d {
    /// Position in screen-space pixels.
    pub pos: Vec2,
    /// UV into the bitmap font for [`Primitive::Glyph`], into a glyph page for
    /// [`Primitive::FontGlyph`], into the image atlas for [`Primitive::Image`]
    /// and into the named texture for [`Primitive::Texture`]; zero for
    /// untextured primitives.
    ///
    /// For [`Primitive::RoundedRect`] it is not a UV at all: it is this vertex's
    /// offset from the rectangle's centre in pixels, which the fragment stage
    /// receives interpolated and measures the rectangle's distance field at.
    pub uv: Vec2,
    /// RGBA colour, each component in `[0, 1]`: the fill, the text colour, or
    /// the tint an image is multiplied by.
    pub color: [f32; 4],
    /// The clip rectangle, `[min.x, min.y, max.x, max.y]` in screen pixels.
    pub clip: [f32; 4],
    /// `[half width, half height, border width, primitive]`: the rounded
    /// rectangle's half extent and border in pixels, and the
    /// [`Primitive`] as a float in the last lane, for every vertex. A
    /// [`Primitive::FontGlyph`] carries its glyph page in the first lane
    /// instead.
    pub shape: [f32; 4],
    /// The rounded rectangle's corner radii in pixels: top-left, top-right,
    /// bottom-right, bottom-left.
    pub radii: [f32; 4],
    /// The rounded rectangle's border colour.
    pub border: [f32; 4],
}

impl Vertex2d {
    /// A vertex of `primitive` with nothing clipped and no rounded-rectangle
    /// lanes — what every primitive but the rounded rectangle is.
    #[must_use]
    pub const fn new(pos: Vec2, uv: Vec2, color: [f32; 4], primitive: Primitive) -> Self {
        Self {
            pos,
            uv,
            color,
            clip: ClipRect::NONE.lane(),
            shape: [0.0, 0.0, 0.0, primitive.lane()],
            radii: [0.0; 4],
            border: [0.0; 4],
        }
    }

    /// Which primitive this vertex belongs to, or `None` for a lane holding no
    /// primitive this crate emits.
    #[must_use]
    pub fn primitive(&self) -> Option<Primitive> {
        Primitive::ALL
            .into_iter()
            .find(|primitive| primitive.lane() == self.shape[3])
    }
}

/// What the fragment stage does with a vertex's lanes.
///
/// Carried as a float in [`Vertex2d::shape`]'s last lane; `ui.slang` spells the
/// same numbers.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Primitive {
    /// The vertex colour, as it is.
    Solid,
    /// The vertex colour, its alpha multiplied by the glyph atlas.
    Glyph,
    /// The image atlas, sampled sharp-bilinear and multiplied by the colour.
    Image,
    /// The analytic rounded rectangle: fill, border and corners evaluated as a
    /// signed distance per fragment.
    RoundedRect,
    /// The vertex colour, its alpha multiplied by a [`GlyphAtlas`] page's
    /// coverage — the page in [`Vertex2d::shape`]'s first lane.
    FontGlyph,
    /// A texture the renderer owns, sampled bilinear and multiplied by the
    /// colour. [`Vertex2d::shape`]'s first lane holds the [`TextureId`], which
    /// the shader never reads: the renderer binds the texture per
    /// [`TextureRun`].
    Texture,
}

impl Primitive {
    /// Every primitive, in lane order.
    pub const ALL: [Self; 6] = [
        Self::Solid,
        Self::Glyph,
        Self::Image,
        Self::RoundedRect,
        Self::FontGlyph,
        Self::Texture,
    ];

    /// The value [`Vertex2d::shape`]'s last lane holds for this primitive.
    #[must_use]
    pub const fn lane(self) -> f32 {
        match self {
            Self::Solid => 0.0,
            Self::Glyph => 1.0,
            Self::Image => 2.0,
            Self::RoundedRect => 3.0,
            Self::FontGlyph => 4.0,
            Self::Texture => 5.0,
        }
    }
}

// ---------------------------------------------------------------------------
// Clip rectangles, corner radii, borders
// ---------------------------------------------------------------------------

/// A screen-space rectangle nothing is drawn outside of.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ClipRect {
    /// Top-left corner, in screen pixels.
    pub min: Vec2,
    /// Bottom-right corner, in screen pixels.
    pub max: Vec2,
}

impl ClipRect {
    /// No clip: the whole range of `f32`, which every fragment is inside.
    pub const NONE: Self = Self {
        min: Vec2::splat(f32::MIN),
        max: Vec2::splat(f32::MAX),
    };

    /// The part of `self` that is also inside `other`.
    ///
    /// Two rectangles that do not overlap give an empty one — `max` pulled back
    /// to `min` — which clips away everything rather than turning inside out.
    #[must_use]
    pub fn intersect(self, other: Self) -> Self {
        let min = self.min.max(other.min);
        let max = self.max.min(other.max).max(min);
        Self { min, max }
    }

    /// This clip in window pixels, from logical pixels at `scale`.
    ///
    /// A side at [`NONE`](Self::NONE)'s bound is not a coordinate but "no
    /// bound", and stays one: scaled, it would overflow to infinity or shrink to
    /// a finite edge, and neither is the clip the caller asked for.
    fn scaled(self, scale: f32) -> Self {
        if scale == 1.0 {
            return self;
        }
        let side = |value: f32| {
            if value.abs() == f32::MAX {
                value
            } else {
                value * scale
            }
        };
        Self {
            min: Vec2::new(side(self.min.x), side(self.min.y)),
            max: Vec2::new(side(self.max.x), side(self.max.y)),
        }
    }

    /// The four floats [`Vertex2d::clip`] carries.
    #[must_use]
    pub const fn lane(self) -> [f32; 4] {
        [self.min.x, self.min.y, self.max.x, self.max.y]
    }
}

/// [`DrawList::pop_clip`] was called with no clip pushed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ClipUnderflow;

impl fmt::Display for ClipUnderflow {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("pop_clip was called with no clip rectangle pushed")
    }
}

impl std::error::Error for ClipUnderflow {}

/// A rounded rectangle's four corner radii, in pixels.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct CornerRadii {
    /// The top-left corner.
    pub top_left: f32,
    /// The top-right corner.
    pub top_right: f32,
    /// The bottom-right corner.
    pub bottom_right: f32,
    /// The bottom-left corner.
    pub bottom_left: f32,
}

impl CornerRadii {
    /// The same radius at every corner.
    #[must_use]
    pub const fn uniform(radius: f32) -> Self {
        Self {
            top_left: radius,
            top_right: radius,
            bottom_right: radius,
            bottom_left: radius,
        }
    }

    /// The radii as [`Vertex2d::radii`] carries them, each clamped into
    /// `0..=limit` — so no corner is rounder than half the shorter side, and a
    /// negative or NaN radius is a square corner.
    #[must_use]
    pub fn lane(self, limit: f32) -> [f32; 4] {
        [
            self.top_left,
            self.top_right,
            self.bottom_right,
            self.bottom_left,
        ]
        .map(|radius| radius.max(0.0).min(limit))
    }
}

/// A rounded rectangle's border: drawn inside its edge, following its corners.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Border {
    /// Thickness in pixels.
    pub width: f32,
    /// RGBA colour.
    pub color: [f32; 4],
}

impl Border {
    /// No border at all.
    pub const NONE: Self = Self {
        width: 0.0,
        color: [0.0; 4],
    };
}

// ---------------------------------------------------------------------------
// Draw command
// ---------------------------------------------------------------------------

/// A single draw command in a [`DrawList`].
#[derive(Debug, Clone)]
pub enum DrawCommand {
    /// A filled rectangle.
    Rect {
        /// Top-left corner in screen-space (Y grows downwards).
        min: Vec2,
        /// Bottom-right corner in screen-space (Y grows downwards).
        max: Vec2,
        /// RGBA fill colour.
        color: [f32; 4],
    },
    /// A rectangle outline (border), drawn inside the declared bounds.
    RectOutline {
        /// Top-left corner in screen-space.
        min: Vec2,
        /// Bottom-right corner in screen-space.
        max: Vec2,
        /// Line thickness in pixels. Clamped to half the smaller extent, so an
        /// over-thick border becomes a filled rect rather than self-intersecting
        /// geometry.
        thickness: f32,
        /// RGBA border colour.
        color: [f32; 4],
    },
    /// A straight segment stroked to a given thickness.
    Line {
        /// One end, in screen-space.
        from: Vec2,
        /// The other end, in screen-space.
        to: Vec2,
        /// Stroke width in pixels, centred on the segment.
        thickness: f32,
        /// RGBA stroke colour.
        color: [f32; 4],
    },
    /// A connected run of segments stroked to a given thickness.
    ///
    /// A point that is not finite **breaks** the run rather than being
    /// dropped: joining its neighbours would draw a chord that is not in the
    /// caller's data, which is exactly the artefact a diverging simulation
    /// would hide behind. A broken run is never closed.
    Polyline {
        /// The vertices, in order and in screen-space.
        points: Vec<Vec2>,
        /// Stroke width in pixels, centred on the run.
        thickness: f32,
        /// Whether to stroke the closing segment from the last point back to
        /// the first, joining the seam like any other corner.
        closed: bool,
        /// RGBA stroke colour.
        color: [f32; 4],
    },
    /// A single line of text rendered from the glyph atlas.
    Text {
        /// Top-left anchor of the text's em box — *not* a baseline. The first
        /// line's glyphs occupy `pos.y ..= pos.y + LINE_HEIGHT * scale`.
        pos: Vec2,
        /// The text content.
        text: String,
        /// Text colour.
        color: [f32; 4],
        /// Font size in pixels (height of the em-square).
        size: f32,
    },
    /// A run of glyphs from a parsed font, already laid out — what
    /// [`crate::font::layout::TextLayout`] produces.
    ///
    /// Each glyph is drawn at `origin + offset × scale` with its pen snapped:
    /// the baseline to a whole pixel, the x to a whole pixel plus one of the
    /// glyph atlas's subpixel bins. Its mask is drawn one texel to one pixel.
    Glyphs {
        /// The top-left every glyph's offset is measured from.
        origin: Vec2,
        /// The font.
        font: Font,
        /// Pixels per em.
        size: f32,
        /// Text colour.
        color: [f32; 4],
        /// The glyphs and their pen positions.
        glyphs: Vec<PositionedGlyph>,
        /// The text the glyphs spell, when they were laid out from text —
        /// what a UI tree span displayed, after any `text-overflow` cut — and
        /// `None` for a run built from glyph ids by hand. The renderer never
        /// reads it: it is how a test of a whole frame reads what a
        /// parsed-font run says, as it reads [`DrawCommand::Text`]'s `text`.
        text: Option<Arc<str>>,
    },
    /// A rectangle of the image atlas, stretched to a screen rectangle.
    ///
    /// The UVs are already the atlas's: [`DrawList::image`] and
    /// [`DrawList::nine_slice`] work them out from an
    /// [`AtlasImage`].
    Image {
        /// Top-left corner in screen-space.
        min: Vec2,
        /// Bottom-right corner in screen-space.
        max: Vec2,
        /// Atlas UV drawn at `min`.
        uv_min: Vec2,
        /// Atlas UV drawn at `max`.
        uv_max: Vec2,
        /// Straight-alpha RGBA the sampled texel is multiplied by.
        tint: [f32; 4],
    },
    /// A rectangle of a texture the renderer owns, stretched to a screen
    /// rectangle — see [`TextureId`] and [`DrawList::texture`].
    Texture {
        /// Which texture: the caller's name for it, resolved by the renderer
        /// when the frame is recorded.
        texture: TextureId,
        /// Top-left corner in screen-space.
        min: Vec2,
        /// Bottom-right corner in screen-space.
        max: Vec2,
        /// Texture UV drawn at `min`: `(0, 0)` is the texture's top-left.
        uv_min: Vec2,
        /// Texture UV drawn at `max`: `(1, 1)` is the texture's bottom-right.
        uv_max: Vec2,
        /// Straight-alpha RGBA the sampled texel is multiplied by.
        tint: [f32; 4],
    },
    /// A filled rectangle with rounded corners and an optional border,
    /// evaluated per fragment as a signed distance.
    RoundedRect {
        /// Top-left corner in screen-space.
        min: Vec2,
        /// Bottom-right corner in screen-space.
        max: Vec2,
        /// Corner radii in pixels, each clamped to half the shorter side.
        radii: CornerRadii,
        /// RGBA fill colour.
        color: [f32; 4],
        /// The border inside the edge. Its width is clamped the same way.
        border: Border,
    },
}

impl DrawCommand {
    /// This command in window pixels, from logical pixels at `scale`.
    ///
    /// Every length scales — positions, sizes, strokes, radii, the border's
    /// width, a text size, a glyph run's size and each pen offset — and nothing
    /// else does: colours, UVs, the text and the glyph ids are not lengths.
    fn scaled(self, scale: f32) -> Self {
        match self {
            Self::Rect { min, max, color } => Self::Rect {
                min: min * scale,
                max: max * scale,
                color,
            },
            Self::RectOutline {
                min,
                max,
                thickness,
                color,
            } => Self::RectOutline {
                min: min * scale,
                max: max * scale,
                thickness: thickness * scale,
                color,
            },
            Self::Line {
                from,
                to,
                thickness,
                color,
            } => Self::Line {
                from: from * scale,
                to: to * scale,
                thickness: thickness * scale,
                color,
            },
            Self::Polyline {
                mut points,
                thickness,
                closed,
                color,
            } => {
                for point in &mut points {
                    *point *= scale;
                }
                Self::Polyline {
                    points,
                    thickness: thickness * scale,
                    closed,
                    color,
                }
            }
            Self::Text {
                pos,
                text,
                color,
                size,
            } => Self::Text {
                pos: pos * scale,
                text,
                color,
                size: size * scale,
            },
            Self::Glyphs {
                origin,
                font,
                size,
                color,
                mut glyphs,
                text,
            } => {
                for glyph in &mut glyphs {
                    glyph.offset *= scale;
                }
                Self::Glyphs {
                    origin: origin * scale,
                    font,
                    size: size * scale,
                    color,
                    glyphs,
                    text,
                }
            }
            Self::Image {
                min,
                max,
                uv_min,
                uv_max,
                tint,
            } => Self::Image {
                min: min * scale,
                max: max * scale,
                uv_min,
                uv_max,
                tint,
            },
            Self::Texture {
                texture,
                min,
                max,
                uv_min,
                uv_max,
                tint,
            } => Self::Texture {
                texture,
                min: min * scale,
                max: max * scale,
                uv_min,
                uv_max,
                tint,
            },
            Self::RoundedRect {
                min,
                max,
                radii,
                color,
                border,
            } => Self::RoundedRect {
                min: min * scale,
                max: max * scale,
                radii: CornerRadii {
                    top_left: radii.top_left * scale,
                    top_right: radii.top_right * scale,
                    bottom_right: radii.bottom_right * scale,
                    bottom_left: radii.bottom_left * scale,
                },
                color,
                border: Border {
                    width: border.width * scale,
                    color: border.color,
                },
            },
        }
    }
}

// ---------------------------------------------------------------------------
// DrawList
// ---------------------------------------------------------------------------

/// An ordered list of draw commands for one frame.
///
/// Create one per frame, push commands into it, then hand it to the renderer.
///
/// # Two layers, one list
///
/// The list is cut in two by [`begin_overlay`](DrawList::begin_overlay): the
/// commands before the cut are the game's HUD and GUI, the ones after it are
/// what has to stay on top of a menu — the menu itself, the debug overlay and
/// the console. The renderer draws the halves as two passes; a list nobody cut
/// is one layer and draws exactly as it used to.
///
/// # Its scale
///
/// Commands are pushed in logical pixels and held in window pixels, converted
/// at [`scale`](DrawList::scale) as they go in; see the
/// [module docs](self#logical-pixels-recorded-in-window-pixels). A new list is
/// at a scale of one, where the two are the same.
#[derive(Debug, Clone)]
pub struct DrawList {
    commands: Vec<DrawCommand>,
    /// The clip each command was pushed under, one per command.
    clips: Vec<ClipRect>,
    /// The clips pushed and not yet popped, each already intersected with the
    /// one beneath it. Empty means [`ClipRect::NONE`].
    clip_stack: Vec<ClipRect>,
    /// Where [`begin_overlay`](DrawList::begin_overlay) last cut the list.
    ///
    /// `None` on a list nobody cut, which puts every command below the cut.
    overlay_start: Option<usize>,
    /// Window pixels per logical pixel, applied to every command and clip as it
    /// is pushed. Always positive and finite; see [`DrawList::set_scale`].
    scale: f32,
}

impl Default for DrawList {
    fn default() -> Self {
        Self::new()
    }
}

/// A draw list expanded to triangles, with the overlay cut carried through.
///
/// The return of [`DrawList::to_triangles_split`]. One expansion produces both
/// halves' geometry *and* the index the second half starts at, so a renderer
/// that draws them as two passes never triangulates the list twice.
#[derive(Debug, Clone, PartialEq)]
pub struct Triangles {
    /// Every vertex, in command order, shared by both halves.
    pub vertices: Vec<Vertex2d>,
    /// Every index, in command order.
    pub indices: Vec<u32>,
    /// Where the overlay's indices start: `indices[..overlay]` is the HUD half
    /// and `indices[overlay..]` is the overlay half. Equal to `indices.len()`
    /// on a list with no overlay.
    pub overlay: usize,
    /// The indices that sample a renderer-owned texture, in index order: one
    /// run per stretch of consecutive [`DrawCommand::Texture`] quads naming the
    /// same texture. Every other index samples only the atlases. A run never
    /// straddles [`overlay`](Self::overlay): the cut ends one.
    pub textures: Vec<TextureRun>,
}

/// A stretch of [`Triangles::indices`] that samples one renderer-owned texture:
/// what a renderer binds that texture for before drawing it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextureRun {
    /// The texture its quads name.
    pub texture: TextureId,
    /// Its indices, as a range of [`Triangles::indices`].
    pub indices: Range<u32>,
}

impl DrawList {
    /// Create an empty draw list.
    #[must_use]
    pub fn new() -> Self {
        Self {
            commands: Vec::new(),
            clips: Vec::new(),
            clip_stack: Vec::new(),
            overlay_start: None,
            scale: 1.0,
        }
    }

    /// Records everything pushed from here on at `scale` window pixels per
    /// logical pixel — commands and clips alike.
    ///
    /// What is already in the list stays as it was recorded, so one list can
    /// hold a game's UI at one scale and the engine's overlay at another. A
    /// scale that is not a positive finite number records at one: the
    /// conversion means nothing for it, and [`to_logical`](Self::to_logical)
    /// would divide by it.
    ///
    /// [`clear`](Self::clear) keeps the scale — it says where the list is
    /// drawn, not what was drawn in it.
    pub fn set_scale(&mut self, scale: f32) {
        self.scale = if scale.is_finite() && scale > 0.0 {
            scale
        } else {
            1.0
        };
    }

    /// Window pixels per logical pixel: what a push is multiplied by.
    #[must_use]
    pub const fn scale(&self) -> f32 {
        self.scale
    }

    /// A point in window pixels — the pointer's, say — in the logical pixels
    /// this list is being pushed in, where hit tests are made.
    #[must_use]
    pub fn to_logical(&self, point: Vec2) -> Vec2 {
        point / self.scale
    }

    /// Appends one command under the current clip and overlay state.
    ///
    /// This supports adapters that transform commands from another list without
    /// losing primitive parameters. The source command's clip and overlay are
    /// not part of the command; restore them with [`Self::push_clip`] and
    /// [`Self::begin_overlay`] before appending it.
    ///
    /// The command is in logical pixels and is scaled like every other push, so
    /// a command copied out of a list at a scale of one lands where it would
    /// have been drawn into this one.
    pub fn push_command(&mut self, command: DrawCommand) {
        self.push(command);
    }

    /// Records `command`, converted to window pixels, under the current clip.
    ///
    /// **Every command goes in through here**, which is what makes the scale
    /// impossible to skip: the list's commands are private, and each public
    /// push forwards to this.
    fn push(&mut self, command: DrawCommand) {
        let command = if self.scale == 1.0 {
            command
        } else {
            command.scaled(self.scale)
        };
        self.commands.push(command);
        self.clips.push(self.clip());
    }

    /// Push a filled rectangle command.
    pub fn rect(&mut self, min: Vec2, max: Vec2, color: [f32; 4]) {
        self.push(DrawCommand::Rect { min, max, color });
    }

    /// Push a rectangle outline command.
    pub fn rect_outline(&mut self, min: Vec2, max: Vec2, thickness: f32, color: [f32; 4]) {
        self.push(DrawCommand::RectOutline {
            min,
            max,
            thickness,
            color,
        });
    }

    /// Push a straight line segment, stroked centred on the segment.
    pub fn line(&mut self, from: Vec2, to: Vec2, thickness: f32, color: [f32; 4]) {
        self.push(DrawCommand::Line {
            from,
            to,
            thickness,
            color,
        });
    }

    /// Push a connected run of segments, stroked centred on the run.
    ///
    /// Corners are bevelled. Set `closed` to stroke the segment from the last
    /// point back to the first as well; see [`DrawCommand::Polyline`] for what
    /// a non-finite point does.
    pub fn polyline(
        &mut self,
        points: impl Into<Vec<Vec2>>,
        thickness: f32,
        closed: bool,
        color: [f32; 4],
    ) {
        self.push(DrawCommand::Polyline {
            points: points.into(),
            thickness,
            closed,
            color,
        });
    }

    /// Push a text command.
    pub fn text(&mut self, pos: Vec2, text: impl Into<String>, color: [f32; 4], size: f32) {
        self.push(DrawCommand::Text {
            pos,
            text: text.into(),
            color,
            size,
        });
    }

    /// Push a run of laid-out glyphs from `font`; see [`DrawCommand::Glyphs`].
    pub fn glyphs(
        &mut self,
        origin: Vec2,
        font: &Font,
        size: f32,
        color: [f32; 4],
        glyphs: impl Into<Vec<PositionedGlyph>>,
    ) {
        self.push(DrawCommand::Glyphs {
            origin,
            font: font.clone(),
            size,
            color,
            glyphs: glyphs.into(),
            text: None,
        });
    }

    /// [`DrawList::glyphs`] for a run laid out from `text`, which the command
    /// carries alongside its glyphs so the frame can be read back as text.
    pub fn text_glyphs(
        &mut self,
        origin: Vec2,
        font: &Font,
        size: f32,
        color: [f32; 4],
        glyphs: impl Into<Vec<PositionedGlyph>>,
        text: &str,
    ) {
        self.push(DrawCommand::Glyphs {
            origin,
            font: font.clone(),
            size,
            color,
            glyphs: glyphs.into(),
            text: Some(Arc::from(text)),
        });
    }

    /// Push a whole registered image, stretched to `min..max` and multiplied by
    /// `tint`.
    pub fn image(&mut self, min: Vec2, max: Vec2, image: &AtlasImage, tint: [f32; 4]) {
        self.push(DrawCommand::Image {
            min,
            max,
            uv_min: image.uv_min(),
            uv_max: image.uv_max(),
            tint,
        });
    }

    /// Push a rectangle of a texture the renderer owns — a view it rendered this
    /// frame, say — stretched to `min..max` and multiplied by `tint`.
    ///
    /// `uv` is the part of the texture drawn, `(0, 0)` its top-left and
    /// `(1, 1)` its bottom-right, so a whole view is `(Vec2::ZERO, Vec2::ONE)`.
    /// The rectangle is clipped and scaled like every other push; which picture
    /// `texture` is gets decided when the renderer records the frame — see
    /// [`TextureId`].
    pub fn texture(
        &mut self,
        min: Vec2,
        max: Vec2,
        texture: TextureId,
        uv: (Vec2, Vec2),
        tint: [f32; 4],
    ) {
        self.push(DrawCommand::Texture {
            texture,
            min,
            max,
            uv_min: uv.0,
            uv_max: uv.1,
            tint,
        });
    }

    /// Push `sliced` drawn into `min..max` as a nine-slice: up to nine
    /// [`DrawCommand::Image`]s, corners fixed, edges and centre stretched.
    ///
    /// `scale` is logical pixels per texel of the fixed bands, so a four-texel
    /// corner at a scale of three is twelve pixels across — before the list's
    /// own [`scale`](Self::scale) converts it like any other length. The stretched bands
    /// take whatever is left.
    ///
    /// # What comes out
    ///
    /// The quads in image order — top row left to right, then the middle, then
    /// the bottom — sharing every cut line as the same `f32`, so no seam can
    /// open between two bands. **An empty band emits nothing**: a three-slice
    /// with no top or bottom inset is three quads, not nine with six of them
    /// zero-sized.
    ///
    /// A target smaller than its corners squashes the corners in proportion
    /// rather than overlapping them; see [`slice_bands`]. A non-finite
    /// rectangle, or a `scale` that is not a positive finite number, draws
    /// nothing.
    pub fn nine_slice(
        &mut self,
        min: Vec2,
        max: Vec2,
        sliced: &NineSliceImage,
        scale: f32,
        tint: [f32; 4],
    ) {
        if !(scale.is_finite() && scale > 0.0) {
            return;
        }
        let insets = sliced.clamped_insets();
        let bands = SkinInsets::new(
            insets.left * scale,
            insets.right * scale,
            insets.top * scale,
            insets.bottom * scale,
        );
        self.nine_slice_bands(min, max, sliced, bands, true, tint);
    }

    /// Push `sliced` drawn into `min..max` with each fixed band `bands` pixels
    /// wide, rather than its insets at one scale: what a stylesheet's
    /// `border-image-width` asks for, whose sides need not agree.
    ///
    /// Cut as [`nine_slice`](Self::nine_slice) cuts, which is this with the
    /// insets times the scale; `fill` false leaves out the middle quad, as
    /// CSS's `border-image-slice` does without its `fill` keyword. A band whose
    /// inset is zero texels draws nothing whatever its width, and a non-finite
    /// rectangle or a band that is negative or not finite draws nothing at all.
    pub fn nine_slice_bands(
        &mut self,
        min: Vec2,
        max: Vec2,
        sliced: &NineSliceImage,
        bands: SkinInsets,
        fill: bool,
        tint: [f32; 4],
    ) {
        let widths = [bands.left, bands.right, bands.top, bands.bottom];
        if !(min.is_finite()
            && max.is_finite()
            && widths
                .iter()
                .all(|width| width.is_finite() && *width >= 0.0))
        {
            return;
        }
        let insets = sliced.clamped_insets();
        let size = sliced.image.size();
        let texel_x = [0.0, insets.left, size.x - insets.right, size.x];
        let texel_y = [0.0, insets.top, size.y - insets.bottom, size.y];
        let extent = max - min;
        let xs = slice_cuts(
            min.x,
            slice_bands(bands.left, bands.right, extent.x),
            extent.x,
        );
        let ys = slice_cuts(
            min.y,
            slice_bands(bands.top, bands.bottom, extent.y),
            extent.y,
        );
        for row in 0..3 {
            if texel_y[row] == texel_y[row + 1] || ys[row + 1] <= ys[row] {
                continue;
            }
            for column in 0..3 {
                if texel_x[column] == texel_x[column + 1]
                    || xs[column + 1] <= xs[column]
                    || (!fill && row == 1 && column == 1)
                {
                    continue;
                }
                self.push(DrawCommand::Image {
                    min: Vec2::new(xs[column], ys[row]),
                    max: Vec2::new(xs[column + 1], ys[row + 1]),
                    uv_min: sliced.image.uv(Vec2::new(texel_x[column], texel_y[row])),
                    uv_max: sliced
                        .image
                        .uv(Vec2::new(texel_x[column + 1], texel_y[row + 1])),
                    tint,
                });
            }
        }
    }

    /// Push a filled rectangle with rounded corners and an optional border.
    ///
    /// The corners are a signed distance evaluated per fragment, so they are
    /// smooth with multisampling off and cost no geometry: the command is one
    /// quad whatever its radii. See [`DrawCommand::RoundedRect`].
    pub fn rounded_rect(
        &mut self,
        min: Vec2,
        max: Vec2,
        radii: CornerRadii,
        color: [f32; 4],
        border: Border,
    ) {
        self.push(DrawCommand::RoundedRect {
            min,
            max,
            radii,
            color,
            border,
        });
    }

    /// Narrows the clip to its intersection with `min..max` until the matching
    /// [`pop_clip`](Self::pop_clip).
    ///
    /// Nested clips intersect: a panel inside a scroll view is clipped by both.
    /// `min..max` is in logical pixels, converted at [`scale`](Self::scale)
    /// like a command; a side at [`ClipRect::NONE`]'s bound stays unbounded.
    pub fn push_clip(&mut self, min: Vec2, max: Vec2) {
        let clip = self
            .clip()
            .intersect(ClipRect { min, max }.scaled(self.scale));
        self.clip_stack.push(clip);
    }

    /// Restores the clip that was current before the last
    /// [`push_clip`](Self::push_clip).
    ///
    /// # Errors
    ///
    /// [`ClipUnderflow`] when no clip is pushed, and nothing changes. An error
    /// rather than a panic, as everything else here that a mismatched caller
    /// can reach degrades rather than taking the frame down with it.
    pub fn pop_clip(&mut self) -> Result<(), ClipUnderflow> {
        self.clip_stack.pop().map(|_| ()).ok_or(ClipUnderflow)
    }

    /// The clip a command pushed now would be drawn under, in window pixels.
    #[must_use]
    pub fn clip(&self) -> ClipRect {
        self.clip_stack.last().copied().unwrap_or(ClipRect::NONE)
    }

    /// The clip each command was pushed under, one per
    /// [`commands`](Self::commands) entry.
    #[must_use]
    pub fn clips(&self) -> &[ClipRect] {
        &self.clips
    }

    /// Consume the draw list and return its commands.
    #[must_use]
    pub fn into_commands(self) -> Vec<DrawCommand> {
        self.commands
    }

    /// Borrow the commands.
    #[must_use]
    pub fn commands(&self) -> &[DrawCommand] {
        &self.commands
    }

    /// Cut the list here: everything pushed after this call is **overlay**.
    ///
    /// `crcbl-render`'s UI pass draws the two halves as two render passes, so a
    /// command pushed after this call paints over a pause menu's scrim and one
    /// pushed before it goes under. The engine calls this once a frame — after
    /// the game has drawn its HUD, before the menu, the debug overlay and the
    /// console go in.
    ///
    /// **The last call wins.** A second call moves the cut down to the new
    /// length rather than being refused, which is the only answer that keeps
    /// the engine's overlays on top: a game that marked a boundary of its own
    /// during `draw` marked an earlier one, and the engine's comes after it.
    ///
    /// **The cut also drops every pushed clip.** The overlay is the engine's,
    /// and a clip a game pushed and forgot to pop would otherwise cut the debug
    /// panel and the console down to that game's scroll view.
    ///
    /// [`clear`](Self::clear) drops the cut along with the commands.
    pub fn begin_overlay(&mut self) {
        self.overlay_start = Some(self.commands.len());
        self.clip_stack.clear();
    }

    /// The commands below the cut — the game's HUD and GUI.
    ///
    /// The whole list on a frame where
    /// [`begin_overlay`](Self::begin_overlay) was never called.
    #[must_use]
    pub fn base_commands(&self) -> &[DrawCommand] {
        &self.commands[..self.overlay_start()]
    }

    /// The commands above the cut — what must stay on top of a menu.
    ///
    /// Empty on a frame where [`begin_overlay`](Self::begin_overlay) was never
    /// called.
    #[must_use]
    pub fn overlay_commands(&self) -> &[DrawCommand] {
        &self.commands[self.overlay_start()..]
    }

    /// Where the overlay starts, clamped into the list.
    ///
    /// The clamp is what makes the two slicings above infallible rather than
    /// merely unreachable: `begin_overlay` records a length and the list only
    /// grows until it is cleared, and a cut that somehow outran the commands
    /// would lose the split rather than panic the frame.
    fn overlay_start(&self) -> usize {
        self.overlay_start
            .unwrap_or(self.commands.len())
            .min(self.commands.len())
    }

    /// Number of commands in the list.
    #[must_use]
    pub fn len(&self) -> usize {
        self.commands.len()
    }

    /// Whether the list is empty.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.commands.is_empty()
    }

    /// Clear all commands, every pushed clip and the overlay cut (reuse the
    /// allocation across frames).
    ///
    /// The cut goes with them: a frame that kept the previous frame's cut would
    /// put its first few commands above a menu for no reason anyone wrote down.
    pub fn clear(&mut self) {
        self.commands.clear();
        self.clips.clear();
        self.clip_stack.clear();
        self.overlay_start = None;
    }

    /// Swaps every colour glyph in the list's glyph runs for an image quad of
    /// it, rasterised into `images` through `cache` — see
    /// [`crate::font::color`]. **`crcbl-frame`'s UI pass does this itself**,
    /// as it tessellates (see [`DrawList::to_triangles_with_colors`]); this is
    /// for a renderer of its own that draws from `images`, which calls it once
    /// a frame, after [`ColorGlyphCache::begin_frame`]. Without either a colour
    /// glyph draws as its outline, which for a bitmap-only font is nothing.
    ///
    /// Each quad follows its run, under the run's clip and on the run's side
    /// of the overlay cut, where [`DrawList::to_triangles_with_colors`] puts
    /// it for the same `scale`; see [`ColorGlyphs`]. The run itself stays even
    /// when every glyph left it, so the text it carries can still be read back.
    pub fn resolve_color_glyphs(
        &mut self,
        cache: &mut ColorGlyphCache,
        images: &mut ImageAtlas,
        scale: f32,
    ) {
        let mut colors = ColorGlyphs { cache, images };
        let cut = self.overlay_start.map(|_| self.overlay_start());
        let mut commands = Vec::with_capacity(self.commands.len());
        let mut clips = Vec::with_capacity(self.clips.len());
        let mut overlay = None;
        for (index, (mut command, clip)) in core::mem::take(&mut self.commands)
            .into_iter()
            .zip(core::mem::take(&mut self.clips))
            .enumerate()
        {
            if Some(index) == cut {
                overlay = Some(commands.len());
            }
            let quads = match &mut command {
                DrawCommand::Glyphs {
                    origin,
                    font,
                    size,
                    color,
                    glyphs,
                    ..
                } => match colors.split((*origin, font, *size, *color), glyphs, scale) {
                    Some((outlines, quads)) => {
                        *glyphs = outlines;
                        quads
                    }
                    None => Vec::new(),
                },
                _ => Vec::new(),
            };
            commands.push(command);
            clips.push(clip);
            for quad in quads {
                commands.push(quad);
                clips.push(clip);
            }
        }
        self.commands = commands;
        self.clips = clips;
        self.overlay_start = self
            .overlay_start
            .map(|_| overlay.unwrap_or(self.commands.len()));
    }

    /// Expand every draw command into screen-space triangles.
    ///
    /// [`to_triangles_split`](Self::to_triangles_split) without the overlay cut,
    /// for a caller that draws the whole list as one thing.
    #[must_use]
    pub fn to_triangles(
        &self,
        atlas: Option<&FontAtlas>,
        glyphs: Option<&mut GlyphAtlas>,
        scale: f32,
    ) -> (Vec<Vertex2d>, Vec<u32>) {
        let triangles = self.to_triangles_split(atlas, glyphs, scale);
        (triangles.vertices, triangles.indices)
    }

    /// Expand every draw command into screen-space triangles, both halves in
    /// one pass over the list.
    ///
    /// [`Triangles::overlay`] is where the indices of the commands pushed after
    /// [`begin_overlay`](Self::begin_overlay) start, so a renderer drawing the
    /// halves as two passes gets both ranges out of **one** expansion — running
    /// the tessellation twice would double the work and could disagree with
    /// itself about the glyph layout.
    ///
    /// The vertices and indices are in a format a render backend can upload
    /// directly. Each `Rect`, `Image` and `RoundedRect` becomes one quad (4
    /// vertices, 6 indices). `RectOutline` becomes 4 thin quads — one per side
    /// — forming a hollow border. `Line` and `Polyline` become one quad per
    /// segment plus one bevel triangle per corner. Every vertex carries the clip
    /// its command was pushed under.
    ///
    /// `Text` commands are expanded when `atlas` is `Some`: each glyph becomes
    /// one textured quad with UV coordinates into the atlas. When `atlas` is
    /// `None`, text commands are skipped (the `to_triangles` return from S6).
    ///
    /// `Glyphs` commands are expanded when `glyphs` is `Some`, each glyph
    /// looked up in — and on a miss rasterised into — that atlas, which is why
    /// it is taken mutably. A glyph the atlas defers this frame is left out,
    /// and a list with glyph runs should be expanded once a frame, after
    /// [`GlyphAtlas::begin_frame`]. When `glyphs` is `None` they are skipped.
    ///
    /// `scale` is a multiplier on the font size (1.0 = baked-in 8×13 px) and
    /// on a glyph run's size and offsets.
    ///
    /// The index buffer uses `u32` indices; callers that need `u16` must adapt.
    ///
    /// # Coordinate convention
    ///
    /// Vertex positions are in screen-space pixels, **Y-down**: `(0, 0)` is the
    /// top-left of the framebuffer and Y grows towards the bottom. This is the
    /// convention `shaders/ui.slang` implements
    /// (`ndc.y = 1.0 - (y / viewport.y) * 2.0`) and the one every widget in this
    /// crate lays out in, so `min` really is the visually-upper corner.
    ///
    /// Glyph UVs follow the same convention: `v = 0` is the atlas's top row and
    /// is emitted at the quad's `min.y` vertex, so glyphs render upright.
    #[must_use]
    pub fn to_triangles_split(
        &self,
        atlas: Option<&FontAtlas>,
        glyphs: Option<&mut GlyphAtlas>,
        scale: f32,
    ) -> Triangles {
        self.to_triangles_with_colors(atlas, glyphs, None, scale)
    }

    /// [`DrawList::to_triangles_split`], drawing each colour glyph of a glyph
    /// run as an image quad from `colors` in place of its outline, as
    /// [`DrawList::resolve_color_glyphs`] would have swapped it: what
    /// `crcbl-frame`'s UI pass tessellates with, so every list it draws shows
    /// colour emoji with no call of the caller's. The quads go after the run's
    /// outline glyphs, under its clip and on its side of the overlay cut.
    /// `None` draws every glyph as its outline.
    #[must_use]
    pub fn to_triangles_with_colors(
        &self,
        atlas: Option<&FontAtlas>,
        mut glyphs: Option<&mut GlyphAtlas>,
        mut colors: Option<ColorGlyphs<'_>>,
        scale: f32,
    ) -> Triangles {
        let mut vertices = Vec::new();
        let mut indices = Vec::new();

        let cut = self.overlay_start();
        let mut overlay = 0;
        let mut textures: Vec<TextureRun> = Vec::new();
        for (index, (cmd, clip)) in self.commands.iter().zip(&self.clips).enumerate() {
            if index == cut {
                overlay = indices.len();
            }
            let first = vertices.len();
            let first_index = indices.len() as u32;
            expand(
                cmd,
                (atlas, glyphs.as_deref_mut(), colors.as_mut()),
                scale,
                &mut vertices,
                &mut indices,
            );
            for vertex in &mut vertices[first..] {
                vertex.clip = clip.lane();
            }
            if let DrawCommand::Texture { texture, .. } = cmd {
                let end = indices.len() as u32;
                // Extended only when nothing was drawn in between and the cut
                // does not fall here, so one run is exactly one bind's worth.
                match textures.last_mut() {
                    Some(run)
                        if run.texture == *texture
                            && run.indices.end == first_index
                            && index != cut =>
                    {
                        run.indices.end = end;
                    }
                    _ if end > first_index => textures.push(TextureRun {
                        texture: *texture,
                        indices: first_index..end,
                    }),
                    _ => {}
                }
            }
        }
        if cut == self.commands.len() {
            overlay = indices.len();
        }
        Triangles {
            vertices,
            indices,
            overlay,
            textures,
        }
    }
}

/// Where colour glyphs are drawn from: the cache that rasterises and holds
/// them, and the image atlas it holds them in — what
/// [`DrawList::to_triangles_with_colors`] takes, and
/// [`DrawList::resolve_color_glyphs`] makes of its arguments.
///
/// Both draw a colour glyph the same way, through one function: an image quad
/// at the glyph's pen as the expansion places it for a `scale` — offset
/// scaled, origin not — rounded to whole pixels and moved by the picture's
/// bearing, the size scaled too. **The run's colour does not tint it, but the
/// run's opacity applies**, as a browser draws an emoji. A glyph the cache
/// cannot draw in colour this frame stays an outline glyph.
#[derive(Debug)]
pub struct ColorGlyphs<'a> {
    /// The rasterised colour glyphs.
    pub cache: &'a mut ColorGlyphCache,
    /// The atlas the cache registers them in, which the quads sample.
    pub images: &'a mut ImageAtlas,
}

impl ColorGlyphs<'_> {
    /// `glyphs` of the run `(origin, font, size, color)` cut into the glyphs
    /// that stay outlines and the image quads of the ones drawn in colour; see
    /// the type's docs. `None` for a font with no colour tables, which keeps
    /// every glyph.
    fn split(
        &mut self,
        (origin, font, size, color): (Vec2, &Font, f32, [f32; 4]),
        glyphs: &[PositionedGlyph],
        scale: f32,
    ) -> Option<(Vec<PositionedGlyph>, Vec<DrawCommand>)> {
        if !font.has_color_tables() {
            return None;
        }
        let mut outlines = Vec::with_capacity(glyphs.len());
        let mut quads = Vec::new();
        for glyph in glyphs {
            let pen = origin + glyph.offset * scale;
            let colour = pen
                .is_finite()
                .then(|| {
                    self.cache
                        .glyph(self.images, font, glyph.glyph, size * scale)
                })
                .flatten();
            let Some(colour) = colour else {
                outlines.push(*glyph);
                continue;
            };
            let min = pen.round() + Vec2::new(colour.left as f32, colour.top as f32);
            quads.push(DrawCommand::Image {
                min,
                max: min + colour.image.size(),
                uv_min: colour.image.uv_min(),
                uv_max: colour.image.uv_max(),
                tint: [1.0, 1.0, 1.0, color[3]],
            });
        }
        Some((outlines, quads))
    }
}

/// Expand one draw command onto the end of `vertices` and `indices`.
///
/// The clip is not this function's: [`DrawList::to_triangles_split`] stamps it
/// onto whatever this pushed, so no primitive below can forget to carry it.
fn expand(
    cmd: &DrawCommand,
    (atlas, glyph_atlas, colors): (
        Option<&FontAtlas>,
        Option<&mut GlyphAtlas>,
        Option<&mut ColorGlyphs<'_>>,
    ),
    scale: f32,
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    match cmd {
        DrawCommand::Rect { min, max, color } => {
            push_quad(
                *min,
                *max,
                (Vec2::ZERO, Vec2::ZERO),
                *color,
                Primitive::Solid,
                vertices,
                indices,
            );
        }
        DrawCommand::RectOutline {
            min,
            max,
            thickness,
            color,
        } => {
            // Four quads: top and bottom span the full width, left and
            // right fill the gap between them. Every corner is covered
            // exactly once, and both ends of each edge are built the
            // same way.
            //
            // The thickness is clamped to half the smaller extent: an
            // unclamped border would invert the inner rect and emit
            // self-intersecting bowties that paint over the whole box.
            let half = (*max - *min) * 0.5;
            let t = thickness.max(0.0).min(half.x.max(0.0)).min(half.y.max(0.0));
            let c = *color;

            let inner_min = Vec2::new(min.x + t, min.y + t);
            let inner_max = Vec2::new(max.x - t, max.y - t);

            let mut edge = |q_min: Vec2, q_max: Vec2| {
                push_quad(
                    q_min,
                    q_max,
                    (Vec2::ZERO, Vec2::ZERO),
                    c,
                    Primitive::Solid,
                    vertices,
                    indices,
                );
            };
            // top (full width, including both corners)
            edge(*min, Vec2::new(max.x, inner_min.y));
            // bottom (full width, including both corners)
            edge(Vec2::new(min.x, inner_max.y), *max);
            // left (between the two horizontal edges)
            edge(
                Vec2::new(min.x, inner_min.y),
                Vec2::new(inner_min.x, inner_max.y),
            );
            // right (between the two horizontal edges)
            edge(
                Vec2::new(inner_max.x, inner_min.y),
                Vec2::new(max.x, inner_max.y),
            );
        }
        DrawCommand::Line {
            from,
            to,
            thickness,
            color,
        } => {
            push_stroke(&[*from, *to], false, *thickness, *color, vertices, indices);
        }
        DrawCommand::Polyline {
            points,
            thickness,
            closed,
            color,
        } => {
            push_stroke(points, *closed, *thickness, *color, vertices, indices);
        }
        DrawCommand::Text {
            pos,
            text,
            color,
            size,
        } => {
            if let Some(atlas) = atlas {
                let layout_scale = (*size / GLYPH_HEIGHT as f32) * scale;
                let glyphs = atlas.glyph_positions(text, *pos, layout_scale);
                for (c, min, max) in glyphs {
                    // v = 0 is the atlas's top row, and `min.y` is the
                    // quad's top edge in the Y-down screen convention.
                    let uv_min = Vec2::new(atlas.glyph_u_min(c), 0.0);
                    let uv_max = Vec2::new(atlas.glyph_u_max(c), 1.0);
                    push_quad(
                        min,
                        max,
                        (uv_min, uv_max),
                        *color,
                        Primitive::Glyph,
                        vertices,
                        indices,
                    );
                }
            }
        }
        DrawCommand::Glyphs {
            origin,
            font,
            size,
            color,
            glyphs,
            text: _,
        } => {
            let split = colors
                .and_then(|colors| colors.split((*origin, font, *size, *color), glyphs, scale));
            let (outlines, quads) = match &split {
                Some((outlines, quads)) => (outlines.as_slice(), quads.as_slice()),
                None => (glyphs.as_slice(), &[][..]),
            };
            if let Some(glyph_atlas) = glyph_atlas {
                push_glyphs(
                    glyph_atlas,
                    (*origin, font, *size * scale, scale),
                    outlines,
                    *color,
                    vertices,
                    indices,
                );
            }
            for quad in quads {
                expand(quad, (None, None, None), scale, vertices, indices);
            }
        }
        DrawCommand::Image {
            min,
            max,
            uv_min,
            uv_max,
            tint,
        } => {
            push_quad(
                *min,
                *max,
                (*uv_min, *uv_max),
                *tint,
                Primitive::Image,
                vertices,
                indices,
            );
        }
        DrawCommand::Texture {
            texture,
            min,
            max,
            uv_min,
            uv_max,
            tint,
        } => {
            let first = vertices.len();
            push_quad(
                *min,
                *max,
                (*uv_min, *uv_max),
                *tint,
                Primitive::Texture,
                vertices,
                indices,
            );
            for vertex in &mut vertices[first..] {
                vertex.shape[0] = texture.index() as f32;
            }
        }
        DrawCommand::RoundedRect {
            min,
            max,
            radii,
            color,
            border,
        } => push_rounded_rect(*min, *max, *radii, *color, *border, vertices, indices),
    }
}

/// Push one quad per inked glyph of a run, each mask one texel to one pixel.
///
/// `(origin, font, pixel_size, scale)` is the run: its top-left, its font, its
/// size already scaled, and the scale its offsets take. Each pen's x is
/// rounded to the nearest [`SUBPIXEL_BINS`]th of a pixel, split into a whole
/// pixel and a bin, and its baseline to a whole pixel, so the quad's corners
/// are whole pixels and a nearest sample at every fragment centre reads
/// exactly one texel.
fn push_glyphs(
    atlas: &mut GlyphAtlas,
    (origin, font, pixel_size, scale): (Vec2, &Font, f32, f32),
    glyphs: &[PositionedGlyph],
    color: [f32; 4],
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    let bins = f32::from(SUBPIXEL_BINS);
    let page = atlas.page_size() as f32;
    for glyph in glyphs {
        let pen = origin + glyph.offset * scale;
        if !pen.is_finite() {
            continue;
        }
        let steps = (pen.x * bins).round();
        let whole = (steps / bins).floor();
        let bin = (steps - whole * bins) as u8;
        let Some(placed) = atlas.glyph(font, glyph.glyph, pixel_size, bin) else {
            continue;
        };
        if placed.is_empty() {
            continue;
        }
        let min = Vec2::new(
            whole + placed.left as f32,
            pen.y.round() + placed.top as f32,
        );
        let extent = Vec2::new(placed.width as f32, placed.height as f32);
        let texel = Vec2::new(placed.x as f32, placed.y as f32);
        let first = vertices.len();
        push_quad(
            min,
            min + extent,
            (texel / page, (texel + extent) / page),
            color,
            Primitive::FontGlyph,
            vertices,
            indices,
        );
        for vertex in &mut vertices[first..] {
            vertex.shape[0] = placed.page as f32;
        }
    }
}

/// Push one rounded rectangle: a single quad whose vertices carry the shape.
///
/// The UV lane is each corner's offset from the centre — `-half` at `min`,
/// `+half` at `max` — so the fragment stage receives the offset interpolated
/// and evaluates the distance field there. The radii and the border width are
/// clamped to half the shorter side here rather than in the shader, where a
/// radius past it would bend the corners of a pill into each other.
///
/// A rectangle with no area, or one that is not finite, pushes nothing.
fn push_rounded_rect(
    min: Vec2,
    max: Vec2,
    radii: CornerRadii,
    color: [f32; 4],
    border: Border,
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    if !(min.is_finite() && max.is_finite()) || max.x <= min.x || max.y <= min.y {
        return;
    }
    let half = (max - min) * 0.5;
    let limit = half.x.min(half.y);
    let first = vertices.len();
    push_quad(
        min,
        max,
        (-half, half),
        color,
        Primitive::RoundedRect,
        vertices,
        indices,
    );
    for vertex in &mut vertices[first..] {
        vertex.shape = [
            half.x,
            half.y,
            border.width.max(0.0).min(limit),
            Primitive::RoundedRect.lane(),
        ];
        vertex.radii = radii.lane(limit);
        vertex.border = border.color;
    }
}

/// Stroke a run of points, centred on the path, and push the triangles.
///
/// A point that is not finite splits the run in two rather than being dropped:
/// dropping it would connect its neighbours with a chord the caller never
/// asked for, and a straight line across a discontinuity reads as data. A run
/// that was split is never closed, because its two ends are no longer known to
/// belong together.
///
/// Consecutive points closer together than one representable step are merged,
/// so every segment handed to [`push_run`] has a direction.
fn push_stroke(
    points: &[Vec2],
    closed: bool,
    thickness: f32,
    color: [f32; 4],
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    let half = thickness * 0.5;
    if half.is_nan() || half <= 0.0 || half.is_infinite() {
        return;
    }

    let mut run: Vec<Vec2> = Vec::with_capacity(points.len());
    let mut split = false;
    for &point in points {
        if !point.is_finite() {
            split = true;
            push_run(&run, false, half, color, vertices, indices);
            run.clear();
            continue;
        }
        if run.last().is_none_or(|&last| (point - last).length() > 0.0) {
            run.push(point);
        }
    }
    push_run(&run, closed && !split, half, color, vertices, indices);
}

/// Stroke one unbroken run whose consecutive points are all distinct.
///
/// Each segment becomes a quad offset by `half` along the segment's normal.
/// Corners are bevelled: a single triangle fills the wedge that opens on the
/// outside of the turn, which is where the two quads leave a gap. The inside
/// of the turn needs nothing — the quads already overlap there, and painting
/// it again would blend a translucent stroke against itself.
///
/// Bevel rather than miter deliberately. A miter joint's length grows without
/// bound as the turn sharpens, so it needs a limit and a fallback to this same
/// bevel anyway; going straight to the bevel is one triangle, no division, and
/// no angle at which it degenerates.
fn push_run(
    points: &[Vec2],
    closed: bool,
    half: f32,
    color: [f32; 4],
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    // A closing segment needs a third point to be anything but a retrace of
    // the run, and it needs the two ends to actually differ — a caller that
    // repeated the first point to close the shape has already drawn it.
    let closed =
        closed && points.len() >= 3 && (points[points.len() - 1] - points[0]).length() > 0.0;

    let count = points.len();
    if count < 2 {
        return;
    }
    let segments = if closed { count } else { count - 1 };

    let mut directions: Vec<Vec2> = Vec::with_capacity(segments);
    for index in 0..segments {
        let delta = points[(index + 1) % count] - points[index];
        directions.push(delta / delta.length());
    }

    let normal = |direction: Vec2| Vec2::new(-direction.y, direction.x) * half;

    for index in 0..segments {
        let (a, b) = (points[index], points[(index + 1) % count]);
        let offset = normal(directions[index]);
        push_quad_free(
            a + offset,
            b + offset,
            b - offset,
            a - offset,
            color,
            vertices,
            indices,
        );
    }

    // One joint per interior corner, plus the seam when the run is closed.
    let joints = if closed { segments } else { segments - 1 };
    for index in 0..joints {
        let incoming = directions[index];
        let outgoing = directions[(index + 1) % segments];
        // `perp_dot` is positive when the path turns towards the +normal side,
        // which is the inside of the bend; the gap is on the other one.
        let turn = incoming.perp_dot(outgoing);
        if turn == 0.0 {
            continue;
        }
        let side = if turn > 0.0 { -1.0 } else { 1.0 };
        let corner = points[(index + 1) % count];
        push_triangle(
            corner,
            corner + normal(incoming) * side,
            corner + normal(outgoing) * side,
            color,
            vertices,
            indices,
        );
    }
}

/// Push one quad from four corners in order, for primitives that are not
/// axis-aligned. `p0`..`p3` must wind consistently; the stroke code emits them
/// as (start left, end left, end right, start right).
fn push_quad_free(
    p0: Vec2,
    p1: Vec2,
    p2: Vec2,
    p3: Vec2,
    color: [f32; 4],
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    let base = vertices.len() as u32;
    for pos in [p0, p1, p2, p3] {
        vertices.push(Vertex2d::new(pos, Vec2::ZERO, color, Primitive::Solid));
    }
    indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
}

/// Push one untextured triangle, used for stroke corners.
fn push_triangle(
    p0: Vec2,
    p1: Vec2,
    p2: Vec2,
    color: [f32; 4],
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    let base = vertices.len() as u32;
    for pos in [p0, p1, p2] {
        vertices.push(Vertex2d::new(pos, Vec2::ZERO, color, Primitive::Solid));
    }
    indices.extend_from_slice(&[base, base + 1, base + 2]);
}

/// Push one axis-aligned quad — 4 vertices, 6 indices — for use by
/// [`DrawList::to_triangles`].
///
/// `min`/`max` are the top-left and bottom-right corners in the Y-down screen
/// convention, and `(uv_min, uv_max)` the matching UV corners (both
/// [`Vec2::ZERO`] for untextured primitives). `primitive` is what the fragment
/// stage does with them.
///
/// Vertices are emitted bottom-left, bottom-right, top-right, top-left, which
/// after the shader's Y flip is counter-clockwise in NDC. Nothing depends on
/// that today — `crcbl-render`'s UI pass uses `PrimitiveState::default()` with
/// no face culling — but the order is fixed here rather than per-call-site so
/// there is only one thing to change if it ever does.
fn push_quad(
    min: Vec2,
    max: Vec2,
    (uv_min, uv_max): (Vec2, Vec2),
    color: [f32; 4],
    primitive: Primitive,
    vertices: &mut Vec<Vertex2d>,
    indices: &mut Vec<u32>,
) {
    let base = vertices.len() as u32;
    for (pos, uv) in [
        (Vec2::new(min.x, max.y), Vec2::new(uv_min.x, uv_max.y)),
        (Vec2::new(max.x, max.y), Vec2::new(uv_max.x, uv_max.y)),
        (Vec2::new(max.x, min.y), Vec2::new(uv_max.x, uv_min.y)),
        (Vec2::new(min.x, min.y), Vec2::new(uv_min.x, uv_min.y)),
    ] {
        vertices.push(Vertex2d::new(pos, uv, color, primitive));
    }
    indices.extend_from_slice(&[base, base + 1, base + 2, base, base + 2, base + 3]);
}

// SAFETY: Vertex2d is `#[repr(C)]` with only f32 fields (Vec2 is 2×f32,
// [f32; 4] is 4×f32), every field's alignment is 4, and the fields add to a
// multiple of it. No padding, all bit patterns valid.
unsafe impl bytemuck::Pod for Vertex2d {}
unsafe impl bytemuck::Zeroable for Vertex2d {}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "parsed-font"))]
mod color_tests;
#[cfg(test)]
mod scale_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod texture_tests;