sim-engine 0.4.2

A validated high-performance visualization engine for simulations
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
use std::{
    error::Error,
    fmt,
    mem::size_of,
    panic::{AssertUnwindSafe, catch_unwind, resume_unwind},
};

use crate::{Color, LogicalScreenPosition, LogicalScreenVector, Rect, Vec2};

mod styles;
pub use styles::{
    Fill, LinearGradient, RadialGradient, Shadow, ShapeStyle, Stroke, StrokeCap2d,
    StrokeDashPattern2d, StrokeJoin2d, StrokeMarker2d, StrokeMarkerAnchor2d, StrokeStyle2d,
    StrokeStyleError, StrokeWidthMode2d,
};

pub(crate) const CIRCLE_SEGMENTS: usize = 64;
pub(crate) const ROUND_CAP_SEGMENTS: usize = 16;
pub(crate) const CORNER_SEGMENTS: usize = 12;
pub(crate) const TESSELLATED_VERTEX_BYTES: usize = 20 * size_of::<f32>();
const MIN_STROKE_TURN_SINE: f64 = 0.000_1;
/// Maximum visible dash pieces one command may request from tessellation.
pub const MAX_STROKE_DASH_SUBSEGMENTS: usize = 1_000_000;

/// Primitive category attached to structured scene validation errors.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScenePrimitive {
    /// Circle geometry or style.
    Circle,
    /// Rectangle geometry or style.
    Rect,
    /// Single line geometry or stroke.
    Line,
    /// Connected polyline geometry or stroke.
    Polyline,
}

/// Work category constrained by a [`SceneBudget`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SceneBudgetResource {
    /// Accepted scene commands.
    Commands,
    /// Points retained by polyline commands.
    Points,
    /// Conservative upper bound for generated triangle-list vertices.
    TessellatedVertices,
    /// Command payload bytes retained by the scene.
    RetainedBytes,
    /// Committed command-vector and owned polyline allocation bytes.
    AllocationBytes,
    /// Bytes uploaded for generated scene vertices.
    UploadBytes,
    /// Draw batches caused by ordering and clip changes.
    DrawBatches,
}

/// Explicit upper bounds for engine-owned ordinary-scene work.
///
/// Limits may be zero to construct a background-only scene. Retained bytes
/// count logical command values and owned polyline storage. Allocation bytes
/// additionally bound committed spare command-vector capacity; allocator
/// bookkeeping and transactional replacement overlap are excluded. Vertex and
/// upload limits use the renderer's conservative
/// triangle-list estimate, which is checked again after tessellation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SceneBudget {
    max_commands: usize,
    max_points: usize,
    max_tessellated_vertices: usize,
    max_retained_bytes: usize,
    max_allocation_bytes: usize,
    max_upload_bytes: usize,
    max_draw_batches: usize,
}

impl SceneBudget {
    /// Builds a complete budget for ordinary scene construction and rendering.
    pub const fn new(
        max_commands: usize,
        max_points: usize,
        max_tessellated_vertices: usize,
        max_retained_bytes: usize,
        max_allocation_bytes: usize,
        max_upload_bytes: usize,
        max_draw_batches: usize,
    ) -> Self {
        Self {
            max_commands,
            max_points,
            max_tessellated_vertices,
            max_retained_bytes,
            max_allocation_bytes,
            max_upload_bytes,
            max_draw_batches,
        }
    }

    /// Returns the maximum accepted command count.
    pub const fn max_commands(self) -> usize {
        self.max_commands
    }

    /// Returns the maximum retained polyline point count.
    pub const fn max_points(self) -> usize {
        self.max_points
    }

    /// Returns the maximum conservatively estimated vertex count.
    pub const fn max_tessellated_vertices(self) -> usize {
        self.max_tessellated_vertices
    }

    /// Returns the maximum retained command payload bytes.
    pub const fn max_retained_bytes(self) -> usize {
        self.max_retained_bytes
    }

    /// Returns the maximum committed command and polyline allocation bytes.
    pub const fn max_allocation_bytes(self) -> usize {
        self.max_allocation_bytes
    }

    /// Returns the maximum generated vertex upload bytes.
    pub const fn max_upload_bytes(self) -> usize {
        self.max_upload_bytes
    }

    /// Returns the maximum draw-batch count.
    pub const fn max_draw_batches(self) -> usize {
        self.max_draw_batches
    }
}

/// Construction and conservative rendering work accumulated by a scene.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SceneStatistics {
    requested_commands: usize,
    accepted_commands: usize,
    rejected_commands: usize,
    requested_by_primitive: PrimitiveCommandCounts,
    accepted_by_primitive: PrimitiveCommandCounts,
    rejected_by_primitive: PrimitiveCommandCounts,
    retained_points: usize,
    estimated_tessellated_vertices: usize,
    retained_bytes: usize,
    estimated_upload_bytes: usize,
    estimated_draw_batches: usize,
}

impl SceneStatistics {
    /// Returns all insertion attempts, including invalid and over-budget work.
    pub const fn requested_commands(self) -> usize {
        self.requested_commands
    }

    /// Returns commands currently retained by the scene.
    pub const fn accepted_commands(self) -> usize {
        self.accepted_commands
    }

    /// Returns insertion attempts rejected by validation, budget, or allocation.
    pub const fn rejected_commands(self) -> usize {
        self.rejected_commands
    }

    /// Returns insertion attempts grouped by primitive category.
    pub const fn requested_by_primitive(self) -> PrimitiveCommandCounts {
        self.requested_by_primitive
    }

    /// Returns currently retained commands grouped by primitive category.
    pub const fn accepted_by_primitive(self) -> PrimitiveCommandCounts {
        self.accepted_by_primitive
    }

    /// Returns rejected insertion attempts grouped by primitive category.
    pub const fn rejected_by_primitive(self) -> PrimitiveCommandCounts {
        self.rejected_by_primitive
    }

    /// Returns points retained by accepted polyline commands.
    pub const fn retained_points(self) -> usize {
        self.retained_points
    }

    /// Returns the conservative upper bound for tessellated vertices.
    pub const fn estimated_tessellated_vertices(self) -> usize {
        self.estimated_tessellated_vertices
    }

    /// Returns tracked command and owned polyline payload bytes.
    pub const fn retained_bytes(self) -> usize {
        self.retained_bytes
    }

    /// Returns estimated bytes uploaded for generated vertices.
    pub const fn estimated_upload_bytes(self) -> usize {
        self.estimated_upload_bytes
    }

    /// Returns the conservative draw-batch upper bound.
    pub const fn estimated_draw_batches(self) -> usize {
        self.estimated_draw_batches
    }

    fn with_command(mut self, command: &DrawCommand) -> Self {
        let vertices = command.estimated_tessellated_vertices();
        self.accepted_commands = self.accepted_commands.saturating_add(1);
        self.accepted_by_primitive.increment(command.primitive());
        self.retained_points = self
            .retained_points
            .saturating_add(command.retained_point_count());
        self.estimated_tessellated_vertices =
            self.estimated_tessellated_vertices.saturating_add(vertices);
        self.retained_bytes = self.retained_bytes.saturating_add(command.retained_bytes());
        self.estimated_upload_bytes = self
            .estimated_upload_bytes
            .saturating_add(vertices.saturating_mul(TESSELLATED_VERTEX_BYTES));
        self.estimated_draw_batches = self.estimated_draw_batches.saturating_add(1);
        self
    }
}

/// Command counters grouped by ordinary 2D primitive category.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct PrimitiveCommandCounts {
    circles: usize,
    rectangles: usize,
    lines: usize,
    polylines: usize,
}

impl PrimitiveCommandCounts {
    /// Returns circle command count.
    pub const fn circles(self) -> usize {
        self.circles
    }

    /// Returns rectangle command count.
    pub const fn rectangles(self) -> usize {
        self.rectangles
    }

    /// Returns single-line command count.
    pub const fn lines(self) -> usize {
        self.lines
    }

    /// Returns connected-polyline command count.
    pub const fn polylines(self) -> usize {
        self.polylines
    }

    /// Returns all primitive commands represented by these counters.
    pub const fn total(self) -> usize {
        self.circles
            .saturating_add(self.rectangles)
            .saturating_add(self.lines)
            .saturating_add(self.polylines)
    }

    pub(crate) fn increment(&mut self, primitive: ScenePrimitive) {
        match primitive {
            ScenePrimitive::Circle => self.circles = self.circles.saturating_add(1),
            ScenePrimitive::Rect => self.rectangles = self.rectangles.saturating_add(1),
            ScenePrimitive::Line => self.lines = self.lines.saturating_add(1),
            ScenePrimitive::Polyline => self.polylines = self.polylines.saturating_add(1),
        }
    }

    pub(crate) fn adding(mut self, other: Self) -> Self {
        self.circles = self.circles.saturating_add(other.circles);
        self.rectangles = self.rectangles.saturating_add(other.rectangles);
        self.lines = self.lines.saturating_add(other.lines);
        self.polylines = self.polylines.saturating_add(other.polylines);
        self
    }
}

/// Reason a command or temporary scene state was rejected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SceneError {
    /// Clear color is non-finite or outside normalized RGBA.
    InvalidBackground,
    /// Primitive coordinates contain NaN or infinity.
    NonFiniteGeometry(ScenePrimitive),
    /// Radius, size, corner radius, or stroke width is outside its valid range.
    InvalidDimension(ScenePrimitive),
    /// A line segment, or at least one consecutive polyline segment, is not drawable.
    DegenerateGeometry(ScenePrimitive),
    /// Consecutive polyline segments form a numerically ambiguous continuation or reversal.
    ///
    /// An almost-collinear change of direction cannot select a stable shader
    /// join branch; a retraced centerline also has no interior-disjoint
    /// alpha-blended representation. `vertex_index` identifies the path point.
    DegenerateStrokeTurn {
        /// Primitive containing the ambiguous turn.
        primitive: ScenePrimitive,
        /// Zero-based index of the shared turn point.
        vertex_index: usize,
    },
    /// Shape has no fill, stroke, or shadow.
    MissingStyle(ScenePrimitive),
    /// Fill color or gradient configuration is invalid.
    InvalidFill(ScenePrimitive),
    /// Stroke width or color is invalid.
    InvalidStroke(ScenePrimitive),
    /// A dash pattern would expand into more retained triangle pieces than its
    /// explicit per-command limit.
    StrokeExpansionLimitExceeded {
        /// Primitive whose stroke exceeded the limit.
        primitive: ScenePrimitive,
        /// Configured maximum number of emitted visible subsegments.
        limit: usize,
        /// Minimum visible-subsegment count that proved the limit was exceeded.
        required: usize,
    },
    /// Dash/gap boundaries collapse at the source path's `f32` coordinate scale.
    UnrepresentableStrokePattern(ScenePrimitive),
    /// A tip-anchored arrow was used with dashes or a path containing more than
    /// two points. Exact-vector markers currently require an undashed segment.
    UnsupportedTipMarkerPath(ScenePrimitive),
    /// Shadow offset, spread, or color is invalid.
    InvalidShadow(ScenePrimitive),
    /// Active logical screen clip is non-finite or empty.
    InvalidScreenClip,
    /// Pseudo-depth must be finite.
    NonFiniteDepth,
    /// An accepted command would exceed an explicit scene work limit.
    BudgetExceeded {
        /// Work category whose limit was exceeded.
        resource: SceneBudgetResource,
        /// Configured maximum for the category.
        limit: usize,
        /// Total category usage that the command requested.
        requested: usize,
    },
    /// Engine-owned command storage could not be reserved without mutation.
    AllocationFailed {
        /// Conservative byte estimate associated with the failed reservation.
        ///
        /// Depending on the transactional path, this can describe one
        /// command's retained payload or the total replacement/staging
        /// allocation that could not be reserved. It is diagnostic context,
        /// not a delta suitable for allocator accounting.
        requested_bytes: usize,
    },
}

impl fmt::Display for SceneError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "scene command rejected: {self:?}")
    }
}

impl Error for SceneError {}

/// Ordered list of visual draw commands for a single frame.
///
/// A scene contains renderable primitives only. It does not own simulation
/// entities, domain rules, or time stepping.
#[derive(Debug)]
pub struct Scene {
    background: Color,
    /// Commands stored in draw order.
    commands: Vec<SceneCommand>,
    owned_payload_bytes: usize,
    next_order: u64,
    current_screen_clip: Option<ScreenClipRect>,
    current_depth: f32,
    budget: Option<SceneBudget>,
    statistics: SceneStatistics,
}

impl Clone for Scene {
    fn clone(&self) -> Self {
        let commands = self.commands.clone();
        let owned_payload_bytes = commands
            .iter()
            .map(|command| command.command.owned_allocation_bytes())
            .fold(0usize, usize::saturating_add);
        let mut statistics = self.statistics;
        statistics.retained_bytes = commands
            .len()
            .saturating_mul(size_of::<SceneCommand>())
            .saturating_add(owned_payload_bytes);
        Self {
            background: self.background,
            commands,
            owned_payload_bytes,
            next_order: self.next_order,
            current_screen_clip: self.current_screen_clip,
            current_depth: self.current_depth,
            budget: self.budget,
            statistics,
        }
    }
}

impl Scene {
    /// Creates an empty scene with a normalized linear-RGBA background color.
    ///
    /// This compatibility constructor is intentionally unbounded. Production
    /// hosts handling externally sized visual state should prefer
    /// [`Scene::with_budget`].
    pub fn new(background: Color) -> Result<Self, SceneError> {
        Self::create(background, None)
    }

    /// Creates an empty scene with explicit construction and rendering limits.
    pub fn with_budget(background: Color, budget: SceneBudget) -> Result<Self, SceneError> {
        Self::create(background, Some(budget))
    }

    fn create(background: Color, budget: Option<SceneBudget>) -> Result<Self, SceneError> {
        if !background.is_normalized() {
            return Err(SceneError::InvalidBackground);
        }
        Ok(Self {
            background,
            commands: Vec::new(),
            owned_payload_bytes: 0,
            next_order: 0,
            current_screen_clip: None,
            current_depth: 0.0,
            budget,
            statistics: SceneStatistics::default(),
        })
    }

    /// Returns the normalized clear color used before drawing commands.
    pub fn background(&self) -> Color {
        self.background
    }

    /// Replaces the clear color used before drawing commands.
    pub fn set_background(&mut self, background: Color) -> Result<(), SceneError> {
        if !background.is_normalized() {
            return Err(SceneError::InvalidBackground);
        }
        self.background = background;
        Ok(())
    }

    /// Removes all draw commands and active clipping without changing the background color.
    pub fn clear(&mut self) {
        self.commands.clear();
        self.owned_payload_bytes = 0;
        self.next_order = 0;
        self.current_screen_clip = None;
        self.current_depth = 0.0;
        self.statistics = SceneStatistics::default();
    }

    /// Returns accepted commands in stable layer and insertion order.
    pub fn commands(&self) -> &[SceneCommand] {
        &self.commands
    }

    /// Returns the number of accepted render commands.
    pub fn command_count(&self) -> usize {
        self.commands.len()
    }

    /// Returns CPU allocation bytes currently owned by command and polyline storage.
    ///
    /// Unlike [`SceneStatistics::retained_bytes`], which is the budgeted payload
    /// of accepted commands, this includes spare `Vec` capacity retained for
    /// reuse after insertion or [`Scene::clear`]. Allocator bookkeeping is not
    /// included.
    pub fn allocation_bytes(&self) -> usize {
        self.commands
            .capacity()
            .saturating_mul(size_of::<SceneCommand>())
            .saturating_add(self.owned_payload_bytes)
    }

    pub(crate) fn preflight_command_storage(
        &self,
        additional_commands: usize,
        additional_owned_bytes: usize,
    ) -> Result<(), SceneError> {
        let Some(budget) = self.budget else {
            return Ok(());
        };
        let retained_bytes = self
            .statistics
            .retained_bytes
            .saturating_add(additional_commands.saturating_mul(size_of::<SceneCommand>()))
            .saturating_add(additional_owned_bytes);
        if retained_bytes > budget.max_retained_bytes {
            return Err(SceneError::BudgetExceeded {
                resource: SceneBudgetResource::RetainedBytes,
                limit: budget.max_retained_bytes,
                requested: retained_bytes,
            });
        }
        let required_len = self.commands.len().saturating_add(additional_commands);
        let owned_payload_bytes = self
            .owned_payload_bytes
            .saturating_add(additional_owned_bytes);
        let capacity = if required_len <= self.commands.capacity() {
            self.commands.capacity()
        } else {
            budgeted_command_capacity(
                budget,
                self.commands.capacity(),
                required_len,
                owned_payload_bytes,
            )?
        };
        validate_scene_allocation_budget(budget, capacity, owned_payload_bytes)
    }

    /// Returns the explicit work budget, or `None` for an unbounded scene.
    pub const fn budget(&self) -> Option<SceneBudget> {
        self.budget
    }

    /// Returns requested, accepted, rejected, and estimated scene work.
    pub const fn statistics(&self) -> SceneStatistics {
        self.statistics
    }

    pub(crate) const fn current_screen_clip(&self) -> Option<ScreenClipRect> {
        self.current_screen_clip
    }

    /// Replaces the screen-space clipping rectangle captured by new commands.
    ///
    /// The rectangle uses logical screen pixels with the origin at the top-left
    /// of the render surface. Existing commands keep the clip they captured when
    /// they were appended. `None` disables clipping for subsequent commands.
    /// The previous clip is returned so callers can restore explicit drawing
    /// state without tracking it separately. Invalid clips are rejected here,
    /// before they can affect a later command insertion.
    pub fn set_screen_clip(
        &mut self,
        screen_clip: Option<ScreenClipRect>,
    ) -> Result<Option<ScreenClipRect>, SceneError> {
        if screen_clip.is_some_and(|clip| !clip.is_valid()) {
            return Err(SceneError::InvalidScreenClip);
        }
        Ok(std::mem::replace(
            &mut self.current_screen_clip,
            screen_clip,
        ))
    }

    /// Appends commands from `draw` using a temporary screen-space clip.
    ///
    /// The rectangle uses logical screen pixels. Nested clips are intersected,
    /// so inner drawing cannot escape an outer clip. The previous clip is
    /// restored after `draw` returns.
    pub fn with_screen_clip<R>(
        &mut self,
        screen_clip: ScreenClipRect,
        draw: impl FnOnce(&mut Self) -> R,
    ) -> Result<R, SceneError> {
        if !screen_clip.is_valid() {
            return Err(SceneError::InvalidScreenClip);
        }
        let previous = self.current_screen_clip;
        let combined = match previous {
            Some(outer) => outer.intersection(screen_clip)?,
            None => screen_clip,
        };
        if !combined.is_valid() {
            return Err(SceneError::InvalidScreenClip);
        }
        self.current_screen_clip = Some(combined);
        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
        self.current_screen_clip = previous;
        match result {
            Ok(result) => Ok(result),
            Err(payload) => resume_unwind(payload),
        }
    }

    /// Replaces the pseudo-depth captured by subsequently appended commands.
    ///
    /// Depth is measured in caller-defined units and converted through
    /// [`crate::Projection2d::depth_scale`]. It affects projection only, not draw
    /// order. Non-finite values return `false` and leave the current depth unchanged.
    pub fn set_depth(&mut self, depth: f32) -> bool {
        self.try_set_depth(depth).is_ok()
    }

    /// Replaces pseudo-depth and reports why invalid input was rejected.
    pub fn try_set_depth(&mut self, depth: f32) -> Result<(), SceneError> {
        if !depth.is_finite() {
            return Err(SceneError::NonFiniteDepth);
        }
        self.current_depth = depth;
        Ok(())
    }

    /// Appends commands with a temporary pseudo-depth value.
    ///
    /// The previous depth is restored after `draw` returns or unwinds. Non-finite
    /// depth returns an error without calling `draw`.
    pub fn with_depth<R>(
        &mut self,
        depth: f32,
        draw: impl FnOnce(&mut Self) -> R,
    ) -> Result<R, SceneError> {
        if !depth.is_finite() {
            return Err(SceneError::NonFiniteDepth);
        }

        let previous = self.current_depth;
        self.current_depth = depth;
        let result = catch_unwind(AssertUnwindSafe(|| draw(self)));
        self.current_depth = previous;
        match result {
            Ok(result) => Ok(result),
            Err(payload) => resume_unwind(payload),
        }
    }

    /// Appends a valid command to the default layer.
    ///
    /// Returns `false` without changing commands, ordering, or retained
    /// allocation when the primitive is invalid. Requested/rejected diagnostic
    /// counters still advance for the attempted command.
    pub fn push(&mut self, command: DrawCommand) -> bool {
        self.try_push(command).is_ok()
    }

    /// Appends a command to the default layer with structured rejection diagnostics.
    pub fn try_push(&mut self, command: DrawCommand) -> Result<(), SceneError> {
        self.try_push_to_layer(Layer::DEFAULT, command)
    }

    /// Appends a command to a layer.
    ///
    /// Lower layer values are drawn first. Commands on the same layer preserve
    /// insertion order.
    /// Returns `false` without changing commands, ordering, or retained
    /// allocation when `command` is invalid. Requested/rejected diagnostic
    /// counters still advance for the attempted command.
    pub fn push_to_layer(&mut self, layer: Layer, command: DrawCommand) -> bool {
        self.try_push_to_layer(layer, command).is_ok()
    }

    /// Appends a command to a layer with structured rejection diagnostics.
    ///
    /// An incoming layer at or above the last layer appends without searching.
    /// Out-of-order layers use stable insertion. Both paths perform the same
    /// validation, budget checks, statistics updates, and capacity reuse.
    pub fn try_push_to_layer(
        &mut self,
        layer: Layer,
        command: DrawCommand,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer_ordered::<true>(layer, command)
    }

    fn try_push_to_layer_ordered<const FAST_APPEND: bool>(
        &mut self,
        layer: Layer,
        command: DrawCommand,
    ) -> Result<(), SceneError> {
        let primitive = command.primitive();
        self.statistics.requested_commands = self.statistics.requested_commands.saturating_add(1);
        self.statistics.requested_by_primitive.increment(primitive);
        let result = self.try_push_to_layer_inner::<FAST_APPEND>(layer, command);
        if result.is_err() {
            self.statistics.rejected_commands = self.statistics.rejected_commands.saturating_add(1);
            self.statistics.rejected_by_primitive.increment(primitive);
        }
        result
    }

    /// Atomically appends many commands and orders the combined scene once.
    ///
    /// This is the bounded high-volume construction path for adversarial or
    /// frequently alternating layers. Validation and budget accounting happen
    /// before the existing command list is changed. On failure, no command from
    /// the batch is retained; request and rejection diagnostics still advance.
    /// The resulting order is stable by layer and by batch insertion order.
    pub fn try_extend_to_layers(
        &mut self,
        commands: impl IntoIterator<Item = (Layer, DrawCommand)>,
    ) -> Result<(), SceneError> {
        let mut staged = Vec::new();
        let mut requested = self.statistics;
        let mut attempted = 0usize;
        let mut attempted_by_primitive = PrimitiveCommandCounts::default();
        let mut next_order = self.next_order;
        let existing_owned_payload_bytes = self.owned_payload_bytes;
        let mut staged_owned_payload_bytes = 0usize;

        for (layer, command) in commands {
            let primitive = command.primitive();
            attempted = attempted.saturating_add(1);
            attempted_by_primitive.increment(primitive);
            requested.requested_commands = requested.requested_commands.saturating_add(1);
            requested.requested_by_primitive.increment(primitive);
            if let Err(error) = command.validate() {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(error);
            }
            if self
                .current_screen_clip
                .is_some_and(|screen_clip| !screen_clip.is_valid())
            {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(SceneError::InvalidScreenClip);
            }

            requested = requested.with_command(&command);
            if let Some(budget) = self.budget
                && let Err(error) = validate_scene_budget(budget, requested)
            {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(error);
            }
            let command_owned_payload_bytes = command.owned_allocation_bytes();
            let prospective_owned_payload_bytes = existing_owned_payload_bytes
                .saturating_add(staged_owned_payload_bytes)
                .saturating_add(command_owned_payload_bytes);
            if let Some(budget) = self.budget {
                let required_total = self
                    .commands
                    .len()
                    .saturating_add(staged.len())
                    .saturating_add(1);
                let final_capacity = if required_total <= self.commands.capacity() {
                    self.commands.capacity()
                } else {
                    match budgeted_command_capacity(
                        budget,
                        self.commands.capacity(),
                        required_total,
                        prospective_owned_payload_bytes,
                    ) {
                        Ok(capacity) => capacity,
                        Err(error) => {
                            self.record_batch_rejection(attempted, attempted_by_primitive);
                            return Err(error);
                        }
                    }
                };
                if let Err(error) = validate_scene_allocation_budget(
                    budget,
                    final_capacity,
                    prospective_owned_payload_bytes,
                ) {
                    self.record_batch_rejection(attempted, attempted_by_primitive);
                    return Err(error);
                }

                if staged.len() == staged.capacity() {
                    let staging_capacity = match budgeted_command_capacity(
                        budget,
                        staged.capacity(),
                        staged.len().saturating_add(1),
                        prospective_owned_payload_bytes,
                    ) {
                        Ok(capacity) => capacity,
                        Err(error) => {
                            self.record_batch_rejection(attempted, attempted_by_primitive);
                            return Err(error);
                        }
                    };
                    let mut replacement = Vec::new();
                    if replacement.try_reserve_exact(staging_capacity).is_err() {
                        self.record_batch_rejection(attempted, attempted_by_primitive);
                        return Err(SceneError::AllocationFailed {
                            requested_bytes: scene_allocation_bytes(
                                staging_capacity,
                                prospective_owned_payload_bytes,
                            ),
                        });
                    }
                    if let Err(error) = validate_scene_allocation_budget(
                        budget,
                        replacement.capacity(),
                        prospective_owned_payload_bytes,
                    ) {
                        self.record_batch_rejection(attempted, attempted_by_primitive);
                        return Err(error);
                    }
                    replacement.append(&mut staged);
                    staged = replacement;
                } else if let Err(error) = validate_scene_allocation_budget(
                    budget,
                    staged.capacity(),
                    prospective_owned_payload_bytes,
                ) {
                    self.record_batch_rejection(attempted, attempted_by_primitive);
                    return Err(error);
                }
            } else if staged.try_reserve(1).is_err() {
                self.record_batch_rejection(attempted, attempted_by_primitive);
                return Err(SceneError::AllocationFailed {
                    requested_bytes: command.retained_bytes(),
                });
            }
            staged.push(SceneCommand {
                layer,
                order: next_order,
                depth: self.current_depth,
                screen_clip: self.current_screen_clip,
                command,
            });
            staged_owned_payload_bytes =
                staged_owned_payload_bytes.saturating_add(command_owned_payload_bytes);
            next_order = next_order.saturating_add(1);
        }

        if staged.is_empty() {
            return Ok(());
        }
        let total = self.commands.len().saturating_add(staged.len());
        let owned_payload_bytes =
            existing_owned_payload_bytes.saturating_add(staged_owned_payload_bytes);
        let requested_capacity = if let Some(budget) = self.budget {
            if total <= self.commands.capacity() {
                self.commands.capacity()
            } else {
                match budgeted_command_capacity(
                    budget,
                    self.commands.capacity(),
                    total,
                    owned_payload_bytes,
                ) {
                    Ok(capacity) => capacity,
                    Err(error) => {
                        self.record_batch_rejection(attempted, attempted_by_primitive);
                        return Err(error);
                    }
                }
            }
        } else {
            total
        };
        if staged.capacity() < requested_capacity
            && staged
                .try_reserve_exact(requested_capacity.saturating_sub(staged.len()))
                .is_err()
        {
            self.record_batch_rejection(attempted, attempted_by_primitive);
            return Err(SceneError::AllocationFailed {
                requested_bytes: scene_allocation_bytes(requested_capacity, owned_payload_bytes),
            });
        }
        if let Some(budget) = self.budget
            && let Err(error) =
                validate_scene_allocation_budget(budget, staged.capacity(), owned_payload_bytes)
        {
            self.record_batch_rejection(attempted, attempted_by_primitive);
            return Err(error);
        }
        staged.append(&mut self.commands);
        staged.sort_unstable_by_key(|command| (command.layer, command.order));
        self.commands = staged;
        self.owned_payload_bytes = owned_payload_bytes;
        self.next_order = next_order;
        self.statistics = requested;
        Ok(())
    }

    fn record_batch_rejection(
        &mut self,
        command_count: usize,
        by_primitive: PrimitiveCommandCounts,
    ) {
        self.statistics.requested_commands = self
            .statistics
            .requested_commands
            .saturating_add(command_count);
        self.statistics.rejected_commands = self
            .statistics
            .rejected_commands
            .saturating_add(command_count);
        self.statistics.requested_by_primitive =
            self.statistics.requested_by_primitive.adding(by_primitive);
        self.statistics.rejected_by_primitive =
            self.statistics.rejected_by_primitive.adding(by_primitive);
    }

    pub(crate) fn record_external_rejection(&mut self, primitive: ScenePrimitive) {
        let mut counts = PrimitiveCommandCounts::default();
        counts.increment(primitive);
        self.record_batch_rejection(1, counts);
    }

    fn try_push_to_layer_inner<const FAST_APPEND: bool>(
        &mut self,
        layer: Layer,
        command: DrawCommand,
    ) -> Result<(), SceneError> {
        command.validate()?;
        if self
            .current_screen_clip
            .is_some_and(|screen_clip| !screen_clip.is_valid())
        {
            return Err(SceneError::InvalidScreenClip);
        }

        let command_retained_bytes = command.retained_bytes();
        let owned_payload_bytes = self
            .owned_payload_bytes
            .saturating_add(command.owned_allocation_bytes());
        let requested = self.statistics.with_command(&command);
        if let Some(budget) = self.budget {
            validate_scene_budget(budget, requested)?;
        }

        let replacement = if self.commands.len() == self.commands.capacity() {
            if let Some(budget) = self.budget {
                let required_len = self.commands.len().saturating_add(1);
                let capacity = budgeted_command_capacity(
                    budget,
                    self.commands.capacity(),
                    required_len,
                    owned_payload_bytes,
                )?;
                let mut replacement = Vec::new();
                replacement.try_reserve_exact(capacity).map_err(|_| {
                    SceneError::AllocationFailed {
                        requested_bytes: scene_allocation_bytes(capacity, owned_payload_bytes),
                    }
                })?;
                validate_scene_allocation_budget(
                    budget,
                    replacement.capacity(),
                    owned_payload_bytes,
                )?;
                Some(replacement)
            } else {
                self.commands
                    .try_reserve(1)
                    .map_err(|_| SceneError::AllocationFailed {
                        requested_bytes: command_retained_bytes,
                    })?;
                None
            }
        } else {
            if let Some(budget) = self.budget {
                validate_scene_allocation_budget(
                    budget,
                    self.commands.capacity(),
                    owned_payload_bytes,
                )?;
            }
            None
        };

        if let Some(mut replacement) = replacement {
            replacement.append(&mut self.commands);
            self.commands = replacement;
        }

        let order = self.next_order;
        let scene_command = SceneCommand {
            layer,
            order,
            depth: self.current_depth,
            screen_clip: self.current_screen_clip,
            command,
        };
        if FAST_APPEND
            && self
                .commands
                .last()
                .is_none_or(|existing| existing.layer <= layer)
        {
            // Orders are monotonic even at saturation, so equal layers can
            // append without disturbing stable painter order.
            self.commands.push(scene_command);
        } else {
            let position = self.commands.partition_point(|existing| {
                existing.layer < scene_command.layer
                    || (existing.layer == scene_command.layer
                        && existing.order <= scene_command.order)
            });
            self.commands.insert(position, scene_command);
        }
        self.owned_payload_bytes = owned_payload_bytes;
        self.next_order = self.next_order.saturating_add(1);
        self.statistics = requested;
        Ok(())
    }

    /// Appends a circle in world coordinates.
    ///
    /// `radius` is in world units. Returns `false` for non-positive or non-finite
    /// radius, non-finite center, or invalid style values.
    pub fn circle(&mut self, center: Vec2, radius: f32, style: ShapeStyle) -> bool {
        self.try_circle(center, radius, style).is_ok()
    }

    /// Appends a circle and returns a structured validation error on rejection.
    pub fn try_circle(
        &mut self,
        center: Vec2,
        radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_circle_on_layer(Layer::DEFAULT, center, radius, style)
    }

    /// Appends a circle in world coordinates to a layer.
    ///
    /// `radius` is in world units. Returns `false` for non-positive or non-finite
    /// radius, non-finite center, or invalid style values.
    pub fn circle_on_layer(
        &mut self,
        layer: Layer,
        center: Vec2,
        radius: f32,
        style: ShapeStyle,
    ) -> bool {
        self.try_circle_on_layer(layer, center, radius, style)
            .is_ok()
    }

    /// Appends a circle to a layer with structured rejection diagnostics.
    pub fn try_circle_on_layer(
        &mut self,
        layer: Layer,
        center: Vec2,
        radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(
            layer,
            DrawCommand::Circle(Circle {
                center,
                radius,
                style,
            }),
        )
    }

    /// Appends an axis-aligned rectangle in world coordinates.
    ///
    /// `corner_radius` is in world units and renderers clamp it to half the
    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
    /// `false` without adding a command.
    pub fn rect(&mut self, rect: Rect, corner_radius: f32, style: ShapeStyle) -> bool {
        self.try_rect(rect, corner_radius, style).is_ok()
    }

    /// Appends a rectangle and returns a structured validation error on rejection.
    pub fn try_rect(
        &mut self,
        rect: Rect,
        corner_radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_rect_on_layer(Layer::DEFAULT, rect, corner_radius, style)
    }

    /// Appends an axis-aligned rectangle in world coordinates to a layer.
    ///
    /// `corner_radius` is in world units and renderers clamp it to half the
    /// rectangle size. Invalid bounds, negative radius, and invalid styles return
    /// `false` without adding a command.
    pub fn rect_on_layer(
        &mut self,
        layer: Layer,
        rect: Rect,
        corner_radius: f32,
        style: ShapeStyle,
    ) -> bool {
        self.try_rect_on_layer(layer, rect, corner_radius, style)
            .is_ok()
    }

    /// Appends a rectangle to a layer with structured rejection diagnostics.
    pub fn try_rect_on_layer(
        &mut self,
        layer: Layer,
        rect: Rect,
        corner_radius: f32,
        style: ShapeStyle,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(
            layer,
            DrawCommand::Rect(RectShape {
                rect,
                corner_radius,
                style,
            }),
        )
    }

    /// Appends a stroked line between world-space points.
    ///
    /// `width` is in logical screen pixels so line thickness stays readable while the
    /// camera zooms. Degenerate geometry and invalid width or color return
    /// `false`.
    pub fn line(&mut self, from: Vec2, to: Vec2, width: f32, color: Color) -> bool {
        self.try_line(from, to, width, color).is_ok()
    }

    /// Appends a line and returns a structured validation error on rejection.
    pub fn try_line(
        &mut self,
        from: Vec2,
        to: Vec2,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_line(from, to, StrokeStyle2d::new(width, color))
    }

    /// Appends a stroked line between world-space points to a layer.
    ///
    /// `width` is in logical screen pixels so line thickness stays readable while the
    /// camera zooms. Degenerate geometry and invalid width or color return
    /// `false`.
    pub fn line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        width: f32,
        color: Color,
    ) -> bool {
        self.try_line_on_layer(layer, from, to, width, color)
            .is_ok()
    }

    /// Appends a line to a layer with structured rejection diagnostics.
    pub fn try_line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_line_on_layer(layer, from, to, StrokeStyle2d::new(width, color))
    }

    /// Appends a line with explicit width units, caps, joins, dashes, and markers.
    pub fn styled_line(&mut self, from: Vec2, to: Vec2, style: StrokeStyle2d) -> bool {
        self.try_styled_line(from, to, style).is_ok()
    }

    /// Appends an explicitly styled line with structured rejection diagnostics.
    pub fn try_styled_line(
        &mut self,
        from: Vec2,
        to: Vec2,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_styled_line_on_layer(Layer::DEFAULT, from, to, style)
    }

    /// Appends an explicitly styled line to a shared draw layer.
    pub fn styled_line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        style: StrokeStyle2d,
    ) -> bool {
        self.try_styled_line_on_layer(layer, from, to, style)
            .is_ok()
    }

    /// Appends an explicitly styled line to a layer with structured rejection.
    pub fn try_styled_line_on_layer(
        &mut self,
        layer: Layer,
        from: Vec2,
        to: Vec2,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(layer, DrawCommand::Line(Line { from, to, style }))
    }

    /// Appends connected stroked segments through world-space points.
    ///
    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
    /// without adding a command; every consecutive segment must be drawable.
    pub fn polyline(&mut self, points: Vec<Vec2>, width: f32, color: Color) -> bool {
        self.try_polyline(points, width, color).is_ok()
    }

    /// Appends a polyline and returns a structured validation error on rejection.
    pub fn try_polyline(
        &mut self,
        points: Vec<Vec2>,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_polyline(points, StrokeStyle2d::new(width, color))
    }

    /// Appends connected stroked segments through world-space points to a layer.
    ///
    /// `width` is in logical screen pixels. Empty, single-point, non-finite,
    /// repeated-adjacent, or numerically ambiguous turn input returns `false`
    /// without adding a command; every consecutive segment must be drawable.
    pub fn polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        width: f32,
        color: Color,
    ) -> bool {
        self.try_polyline_on_layer(layer, points, width, color)
            .is_ok()
    }

    /// Appends a polyline to a layer with structured rejection diagnostics.
    pub fn try_polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        width: f32,
        color: Color,
    ) -> Result<(), SceneError> {
        self.try_styled_polyline_on_layer(layer, points, StrokeStyle2d::new(width, color))
    }

    /// Appends a connected path with explicit width, caps, joins, dashes, and markers.
    pub fn styled_polyline(&mut self, points: Vec<Vec2>, style: StrokeStyle2d) -> bool {
        self.try_styled_polyline(points, style).is_ok()
    }

    /// Appends an explicitly styled path with structured rejection diagnostics.
    pub fn try_styled_polyline(
        &mut self,
        points: Vec<Vec2>,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_styled_polyline_on_layer(Layer::DEFAULT, points, style)
    }

    /// Appends an explicitly styled path to a shared draw layer.
    pub fn styled_polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        style: StrokeStyle2d,
    ) -> bool {
        self.try_styled_polyline_on_layer(layer, points, style)
            .is_ok()
    }

    /// Appends an explicitly styled path to a layer with structured rejection.
    pub fn try_styled_polyline_on_layer(
        &mut self,
        layer: Layer,
        points: Vec<Vec2>,
        style: StrokeStyle2d,
    ) -> Result<(), SceneError> {
        self.try_push_to_layer(layer, DrawCommand::Polyline(Polyline { points, style }))
    }
}

/// Draw layer used to order scene commands.
///
/// Lower values are drawn first. Higher values appear above lower layers.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Layer {
    order: i32,
}

impl Layer {
    /// Default layer used by convenience drawing methods.
    pub const DEFAULT: Self = Self::new(0);
    /// Conventional layer for background guides or grids.
    pub const BACKGROUND: Self = Self::new(-100);
    /// Conventional layer for foreground annotations or overlays.
    pub const FOREGROUND: Self = Self::new(100);

    /// Builds a layer from an order value.
    pub const fn new(order: i32) -> Self {
        Self { order }
    }

    /// Returns the order value used for sorting.
    pub const fn order(self) -> i32 {
        self.order
    }
}

/// Axis-aligned clipping rectangle in logical screen pixels.
///
/// The coordinate origin is the top-left of the render surface and positive y
/// points downward. Constructors reject empty and non-finite bounds.
/// Renderers clamp valid clips to the target viewport.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ScreenClipRect {
    rect: Rect,
}

impl ScreenClipRect {
    /// Builds a non-empty clip from two corners in logical screen pixels.
    pub fn new(min: LogicalScreenPosition, max: LogicalScreenPosition) -> Result<Self, SceneError> {
        Self::from_rect(Rect::new(min.to_vec2(), max.to_vec2()))
    }

    /// Builds a clip from its top-left corner and size in logical screen pixels.
    ///
    /// Negative size components are accepted and normalized before validation.
    pub fn from_min_size(
        min: LogicalScreenPosition,
        size: LogicalScreenVector,
    ) -> Result<Self, SceneError> {
        Self::from_rect(Rect::from_min_size(min.to_vec2(), size.to_vec2()))
    }

    fn from_rect(rect: Rect) -> Result<Self, SceneError> {
        let clip = Self { rect };
        clip.is_valid()
            .then_some(clip)
            .ok_or(SceneError::InvalidScreenClip)
    }

    #[cfg(feature = "wgpu")]
    pub(crate) fn rect(self) -> Rect {
        self.rect
    }

    /// Returns the normalized top-left corner in logical screen pixels.
    pub fn min(self) -> LogicalScreenPosition {
        LogicalScreenPosition::from_vec2(self.rect.normalized().min)
    }

    /// Returns the normalized bottom-right corner in logical screen pixels.
    pub fn max(self) -> LogicalScreenPosition {
        LogicalScreenPosition::from_vec2(self.rect.normalized().max)
    }

    /// Returns the overlap between two screen-space clips.
    ///
    /// Disjoint inputs return [`SceneError::InvalidScreenClip`].
    pub fn intersection(self, other: Self) -> Result<Self, SceneError> {
        let first = self.rect.normalized();
        let second = other.rect.normalized();
        let min = Vec2::new(first.min.x.max(second.min.x), first.min.y.max(second.min.y));
        let max = Vec2::new(first.max.x.min(second.max.x), first.max.y.min(second.max.y));

        Self::new(
            LogicalScreenPosition::from_vec2(min),
            LogicalScreenPosition::from_vec2(Vec2::new(max.x.max(min.x), max.y.max(min.y))),
        )
    }

    fn is_valid(self) -> bool {
        if !self.rect.min.is_finite() || !self.rect.max.is_finite() {
            return false;
        }

        let rect = self.rect.normalized();
        rect.width() > 0.0 && rect.height() > 0.0
    }
}

/// Draw command with layer and stable insertion order metadata.
#[derive(Debug, Clone)]
pub struct SceneCommand {
    /// Layer used to sort commands before rendering.
    layer: Layer,
    /// Monotonic insertion order within the scene.
    order: u64,
    /// Caller-defined pseudo-depth used by camera projection.
    depth: f32,
    /// Optional clipping rectangle in logical screen pixels.
    screen_clip: Option<ScreenClipRect>,
    /// Visual primitive to render.
    command: DrawCommand,
}

impl SceneCommand {
    /// Returns the layer used for stable scene ordering.
    pub fn layer(&self) -> Layer {
        self.layer
    }

    /// Returns the insertion order assigned by the scene.
    pub fn order(&self) -> u64 {
        self.order
    }

    /// Returns caller-defined pseudo-depth captured by this command.
    ///
    /// Depth affects camera projection only. Commands on one layer retain their
    /// insertion order regardless of depth.
    pub fn depth(&self) -> f32 {
        self.depth
    }

    /// Returns the optional clip captured when the command was appended.
    pub fn screen_clip(&self) -> Option<ScreenClipRect> {
        self.screen_clip
    }

    /// Returns the visual primitive stored by this command.
    pub fn command(&self) -> &DrawCommand {
        &self.command
    }
}

/// Renderable primitive command.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum DrawCommand {
    /// Filled and/or stroked circle.
    Circle(Circle),
    /// Filled and/or stroked rectangle.
    Rect(RectShape),
    /// Single stroked segment.
    Line(Line),
    /// Connected stroked segments.
    Polyline(Polyline),
}

impl DrawCommand {
    /// Returns the primitive category used by diagnostics and budgets.
    pub const fn primitive(&self) -> ScenePrimitive {
        match self {
            Self::Circle(_) => ScenePrimitive::Circle,
            Self::Rect(_) => ScenePrimitive::Rect,
            Self::Line(_) => ScenePrimitive::Line,
            Self::Polyline(_) => ScenePrimitive::Polyline,
        }
    }

    /// Builds and validates a circle command for batch insertion.
    pub fn circle(center: Vec2, radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
        let command = Self::Circle(Circle {
            center,
            radius,
            style,
        });
        command.validate()?;
        Ok(command)
    }

    /// Builds and validates a rectangle command for batch insertion.
    pub fn rect(rect: Rect, corner_radius: f32, style: ShapeStyle) -> Result<Self, SceneError> {
        let command = Self::Rect(RectShape {
            rect,
            corner_radius,
            style,
        });
        command.validate()?;
        Ok(command)
    }

    /// Builds and validates a single line command for batch insertion.
    pub fn line(from: Vec2, to: Vec2, width: f32, color: Color) -> Result<Self, SceneError> {
        Self::styled_line(from, to, StrokeStyle2d::new(width, color))
    }

    /// Builds and validates an explicitly styled line command.
    pub fn styled_line(from: Vec2, to: Vec2, style: StrokeStyle2d) -> Result<Self, SceneError> {
        let command = Self::Line(Line { from, to, style });
        command.validate()?;
        Ok(command)
    }

    /// Builds and validates a connected polyline command for batch insertion.
    pub fn polyline(points: Vec<Vec2>, width: f32, color: Color) -> Result<Self, SceneError> {
        Self::styled_polyline(points, StrokeStyle2d::new(width, color))
    }

    /// Builds and validates an explicitly styled polyline command.
    pub fn styled_polyline(points: Vec<Vec2>, style: StrokeStyle2d) -> Result<Self, SceneError> {
        let command = Self::Polyline(Polyline { points, style });
        command.validate()?;
        Ok(command)
    }

    fn validate(&self) -> Result<(), SceneError> {
        match self {
            Self::Circle(circle) => {
                if !circle.center.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
                }
                if !circle.radius.is_finite() || circle.radius <= 0.0 {
                    return Err(SceneError::InvalidDimension(ScenePrimitive::Circle));
                }
                if !(circle.center + Vec2::splat(circle.radius)).is_finite()
                    || !(circle.center - Vec2::splat(circle.radius)).is_finite()
                {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Circle));
                }
                circle.style.validate(ScenePrimitive::Circle)
            }
            Self::Rect(rectangle) => {
                let rect = rectangle.rect.normalized();
                if !rect.min.is_finite() || !rect.max.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
                }
                let width = rect.width();
                let height = rect.height();
                if !width.is_finite() || !height.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Rect));
                }
                if width <= 0.0
                    || height <= 0.0
                    || !rectangle.corner_radius.is_finite()
                    || rectangle.corner_radius < 0.0
                {
                    return Err(SceneError::InvalidDimension(ScenePrimitive::Rect));
                }
                rectangle.style.validate(ScenePrimitive::Rect)
            }
            Self::Line(line) => {
                if !line.from.is_finite() || !line.to.is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
                }
                if !(line.to - line.from).is_finite() {
                    return Err(SceneError::NonFiniteGeometry(ScenePrimitive::Line));
                }
                if !drawable_segment(line.from, line.to) {
                    return Err(SceneError::DegenerateGeometry(ScenePrimitive::Line));
                }
                if !line.style.is_valid() {
                    return Err(SceneError::InvalidStroke(ScenePrimitive::Line));
                }
                validate_stroke_path(&[line.from, line.to], line.style, ScenePrimitive::Line)?;
                Ok(())
            }
            Self::Polyline(polyline) => {
                validate_styled_polyline(polyline.points.iter().copied(), polyline.style)?;
                Ok(())
            }
        }
    }

    fn retained_point_count(&self) -> usize {
        match self {
            Self::Polyline(polyline) => polyline.points.len(),
            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
        }
    }

    fn retained_bytes(&self) -> usize {
        size_of::<SceneCommand>().saturating_add(self.owned_allocation_bytes())
    }

    fn owned_allocation_bytes(&self) -> usize {
        match self {
            Self::Polyline(polyline) => {
                polyline.points.capacity().saturating_mul(size_of::<Vec2>())
            }
            Self::Circle(_) | Self::Rect(_) | Self::Line(_) => 0,
        }
    }

    fn estimated_tessellated_vertices(&self) -> usize {
        match self {
            Self::Circle(circle) => {
                let fill_vertices = CIRCLE_SEGMENTS * 3;
                let stroke_vertices = CIRCLE_SEGMENTS * 6;
                let style = circle.style;
                usize::from(style.fill.is_some()) * fill_vertices
                    + usize::from(style.stroke.is_some()) * stroke_vertices
                    + style.shadow.map_or(0, |shadow| {
                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
                    })
            }
            Self::Rect(rectangle) => {
                let rect = rectangle.rect.normalized();
                let radius = rectangle
                    .corner_radius
                    .max(0.0)
                    .min(rect.width().abs() * 0.5)
                    .min(rect.height().abs() * 0.5);
                let boundary_segments = if radius <= 0.0 {
                    4
                } else {
                    4 * (CORNER_SEGMENTS + 1)
                };
                let fill_vertices = boundary_segments * 3;
                let stroke_vertices = boundary_segments * 6;
                let style = rectangle.style;
                usize::from(style.fill.is_some()) * fill_vertices
                    + usize::from(style.stroke.is_some()) * stroke_vertices
                    + style.shadow.map_or(0, |shadow| {
                        fill_vertices + usize::from(shadow.spread > 0.0) * stroke_vertices
                    })
            }
            Self::Line(line) => estimate_stroke_vertices(&[line.from, line.to], line.style),
            Self::Polyline(polyline) => estimate_stroke_vertices(&polyline.points, polyline.style),
        }
    }
}

fn validate_stroke_path(
    points: &[Vec2],
    style: StrokeStyle2d,
    primitive: ScenePrimitive,
) -> Result<(), SceneError> {
    validate_stroke_path_iter(points.iter().copied(), style, primitive)
}

fn validate_stroke_path_iter<I>(
    points: I,
    style: StrokeStyle2d,
    primitive: ScenePrimitive,
) -> Result<(), SceneError>
where
    I: Iterator<Item = Vec2> + Clone,
{
    if style.has_tip_marker() && (style.dash.is_some() || points.clone().count() != 2) {
        return Err(SceneError::UnsupportedTipMarkerPath(primitive));
    }
    let maximum_offset = f64::from(style.stroke.width) * 0.5 * f64::from(style.miter_limit);
    if !maximum_offset.is_finite() || maximum_offset > f64::from(f32::MAX) {
        return Err(SceneError::InvalidStroke(primitive));
    }
    if style.width_mode == StrokeWidthMode2d::WorldUnits {
        let extent = Vec2::splat(maximum_offset as f32);
        if points
            .clone()
            .any(|point| !(point + extent).is_finite() || !(point - extent).is_finite())
        {
            return Err(SceneError::NonFiniteGeometry(primitive));
        }
    }
    if let Some(dash) = style.dash {
        let required = dash_subsegment_count_iter(points, dash, Some(dash.max_subsegments))
            .ok_or(SceneError::UnrepresentableStrokePattern(primitive))?;
        if required > dash.max_subsegments {
            return Err(SceneError::StrokeExpansionLimitExceeded {
                primitive,
                limit: dash.max_subsegments,
                required,
            });
        }
    }
    Ok(())
}

/// Validates caller-owned polyline coordinates without allocating or copying them.
///
/// Screen-space adapters use this before reserving their converted point buffer,
/// so an invalid leading point or segment cannot force work proportional to the
/// rest of a caller-sized slice.
pub(crate) fn validate_polyline_geometry<I>(points: I) -> Result<(), SceneError>
where
    I: Iterator<Item = Vec2> + Clone,
{
    let primitive = ScenePrimitive::Polyline;
    if !points.clone().all(|point| point.is_finite()) {
        return Err(SceneError::NonFiniteGeometry(primitive));
    }

    let mut deltas = points.clone();
    let Some(mut previous) = deltas.next() else {
        return Err(SceneError::DegenerateGeometry(primitive));
    };
    let mut segment_count = 0usize;
    for point in deltas {
        let delta = point - previous;
        if !delta.is_finite() {
            return Err(SceneError::NonFiniteGeometry(primitive));
        }
        previous = point;
        segment_count = segment_count.saturating_add(1);
    }
    if segment_count == 0 {
        return Err(SceneError::DegenerateGeometry(primitive));
    }

    let mut segments = points.clone();
    let mut previous = segments
        .next()
        .expect("a non-empty path was established above");
    for point in segments {
        if !drawable_segment(previous, point) {
            return Err(SceneError::DegenerateGeometry(primitive));
        }
        previous = point;
    }

    let mut turns = points;
    let mut first = turns
        .next()
        .expect("a drawable segment was established above");
    let mut second = turns
        .next()
        .expect("a drawable segment was established above");
    for (index, third) in turns.enumerate() {
        let incoming = second - first;
        let outgoing = third - second;
        let cross = f64::from(incoming.x) * f64::from(outgoing.y)
            - f64::from(incoming.y) * f64::from(outgoing.x);
        let dot = f64::from(incoming.x) * f64::from(outgoing.x)
            + f64::from(incoming.y) * f64::from(outgoing.y);
        let direction_product = f64::from(incoming.x).hypot(f64::from(incoming.y))
            * f64::from(outgoing.x).hypot(f64::from(outgoing.y));
        let normalized_cross = cross / direction_product;
        if normalized_cross.abs() <= MIN_STROKE_TURN_SINE && (dot < 0.0 || normalized_cross != 0.0)
        {
            return Err(SceneError::DegenerateStrokeTurn {
                primitive,
                vertex_index: index + 1,
            });
        }
        first = second;
        second = third;
    }
    Ok(())
}

/// Validates a complete styled polyline without taking ownership of its points.
pub(crate) fn validate_styled_polyline<I>(points: I, style: StrokeStyle2d) -> Result<(), SceneError>
where
    I: Iterator<Item = Vec2> + Clone,
{
    validate_polyline_geometry(points.clone())?;
    if !style.is_valid() {
        return Err(SceneError::InvalidStroke(ScenePrimitive::Polyline));
    }
    validate_stroke_path_iter(points, style, ScenePrimitive::Polyline)
}

fn estimate_stroke_vertices(points: &[Vec2], style: StrokeStyle2d) -> usize {
    let segment_count = points
        .windows(2)
        .filter(|pair| drawable_segment(pair[0], pair[1]))
        .count();
    if segment_count == 0 {
        return 0;
    }
    let body_count = style.dash.map_or(segment_count, |dash| {
        dash_subsegment_count(points, dash, None)
            .expect("accepted dash paths have representable subsegments")
    });
    // A visible dash may continue across every geometric vertex. Counting all
    // possible joins is conservative without expanding the pattern twice.
    let join_count = segment_count.saturating_sub(1);
    let cap_count = if style.dash.is_some() {
        body_count.saturating_mul(2)
    } else {
        2
    };
    let cap_vertices = match style.cap {
        StrokeCap2d::Round => cap_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
        StrokeCap2d::Butt | StrokeCap2d::Square => 0,
    };
    let join_vertices = match style.join {
        StrokeJoin2d::Bevel => join_count.saturating_mul(6),
        StrokeJoin2d::Miter => join_count.saturating_mul(12),
        // Logical round joins carry one candidate fan for each possible screen
        // orientation; the shader collapses the inactive fan to zero area.
        StrokeJoin2d::Round if style.width_mode == StrokeWidthMode2d::LogicalPixels => {
            join_count.saturating_mul(ROUND_CAP_SEGMENTS * 6)
        }
        StrokeJoin2d::Round => join_count.saturating_mul(ROUND_CAP_SEGMENTS * 3),
    };
    let marker_vertices = (usize::from(style.start_marker.is_some())
        + usize::from(style.end_marker.is_some()))
    .saturating_mul(3);
    body_count
        .saturating_mul(6)
        .saturating_add(cap_vertices)
        .saturating_add(join_vertices)
        .saturating_add(marker_vertices)
}

fn dash_subsegment_count(
    points: &[Vec2],
    dash: StrokeDashPattern2d,
    stop_after: Option<usize>,
) -> Option<usize> {
    dash_subsegment_count_iter(points.iter().copied(), dash, stop_after)
}

fn dash_subsegment_count_iter<I>(
    points: I,
    dash: StrokeDashPattern2d,
    stop_after: Option<usize>,
) -> Option<usize>
where
    I: Iterator<Item = Vec2>,
{
    let lengths = dash.lengths();
    let total: f64 = lengths.iter().map(|length| f64::from(*length)).sum();
    let mut phase = f64::from(dash.phase).rem_euclid(total);
    let mut pattern_index = 0usize;
    while phase >= f64::from(lengths[pattern_index]) {
        phase -= f64::from(lengths[pattern_index]);
        pattern_index = (pattern_index + 1) % lengths.len();
    }
    let mut pattern_remaining = f64::from(lengths[pattern_index]) - phase;
    let mut count = 0usize;

    let mut points = points;
    let mut previous = points.next()?;
    for point in points {
        let delta = point - previous;
        let segment_length = f64::from(delta.x).hypot(f64::from(delta.y));
        let mut segment_remaining = segment_length;
        while segment_remaining > 0.0 {
            let consumed = segment_remaining.min(pattern_remaining);
            if pattern_index.is_multiple_of(2) && consumed > 0.0 {
                count = count.saturating_add(1);
                if stop_after.is_some_and(|limit| count > limit) {
                    return Some(count);
                }
            }
            let next_remaining = segment_remaining - consumed;
            if next_remaining >= segment_remaining {
                return None;
            }
            let amount_start = 1.0 - segment_remaining / segment_length;
            let amount_end = 1.0 - next_remaining / segment_length;
            if dash_segment_point(previous, point, amount_start)
                == dash_segment_point(previous, point, amount_end)
            {
                return None;
            }
            segment_remaining = next_remaining;
            pattern_remaining -= consumed;
            if pattern_remaining <= 0.0 {
                pattern_index = (pattern_index + 1) % lengths.len();
                pattern_remaining = f64::from(lengths[pattern_index]);
            }
        }
        previous = point;
    }
    Some(count)
}

fn dash_segment_point(from: Vec2, to: Vec2, amount: f64) -> Vec2 {
    Vec2::new(
        (f64::from(from.x) * (1.0 - amount) + f64::from(to.x) * amount) as f32,
        (f64::from(from.y) * (1.0 - amount) + f64::from(to.y) * amount) as f32,
    )
}

fn validate_scene_budget(
    budget: SceneBudget,
    requested: SceneStatistics,
) -> Result<(), SceneError> {
    let limits = [
        (
            SceneBudgetResource::Commands,
            budget.max_commands,
            requested.accepted_commands,
        ),
        (
            SceneBudgetResource::Points,
            budget.max_points,
            requested.retained_points,
        ),
        (
            SceneBudgetResource::TessellatedVertices,
            budget.max_tessellated_vertices,
            requested.estimated_tessellated_vertices,
        ),
        (
            SceneBudgetResource::RetainedBytes,
            budget.max_retained_bytes,
            requested.retained_bytes,
        ),
        // Actual allocation capacity is validated transactionally at the
        // insertion boundary, once the prospective Vec capacity is known.
        (
            SceneBudgetResource::UploadBytes,
            budget.max_upload_bytes,
            requested.estimated_upload_bytes,
        ),
        (
            SceneBudgetResource::DrawBatches,
            budget.max_draw_batches,
            requested.estimated_draw_batches,
        ),
    ];
    for (resource, limit, requested) in limits {
        if requested > limit {
            return Err(SceneError::BudgetExceeded {
                resource,
                limit,
                requested,
            });
        }
    }
    Ok(())
}

fn scene_allocation_bytes(command_capacity: usize, owned_payload_bytes: usize) -> usize {
    command_capacity
        .saturating_mul(size_of::<SceneCommand>())
        .saturating_add(owned_payload_bytes)
}

fn validate_scene_allocation_budget(
    budget: SceneBudget,
    command_capacity: usize,
    owned_payload_bytes: usize,
) -> Result<(), SceneError> {
    let requested = scene_allocation_bytes(command_capacity, owned_payload_bytes);
    if requested > budget.max_allocation_bytes {
        return Err(SceneError::BudgetExceeded {
            resource: SceneBudgetResource::AllocationBytes,
            limit: budget.max_allocation_bytes,
            requested,
        });
    }
    Ok(())
}

fn budgeted_command_capacity(
    budget: SceneBudget,
    current_capacity: usize,
    required_len: usize,
    owned_payload_bytes: usize,
) -> Result<usize, SceneError> {
    let available = budget
        .max_allocation_bytes
        .saturating_sub(owned_payload_bytes);
    let maximum_capacity = available / size_of::<SceneCommand>();
    if required_len > maximum_capacity {
        return Err(SceneError::BudgetExceeded {
            resource: SceneBudgetResource::AllocationBytes,
            limit: budget.max_allocation_bytes,
            requested: scene_allocation_bytes(required_len, owned_payload_bytes),
        });
    }
    Ok(current_capacity
        .max(1)
        .saturating_mul(2)
        .max(required_len)
        .min(maximum_capacity))
}

fn drawable_segment(from: Vec2, to: Vec2) -> bool {
    let delta = to - from;
    delta.is_finite() && (delta.x != 0.0 || delta.y != 0.0)
}

/// Circle primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct Circle {
    center: Vec2,
    radius: f32,
    style: ShapeStyle,
}

impl Circle {
    /// Returns the center in world coordinates.
    pub const fn center(&self) -> Vec2 {
        self.center
    }
    /// Returns the radius in world units.
    pub const fn radius(&self) -> f32 {
        self.radius
    }
    /// Returns fill, stroke, and shadow styling.
    pub const fn style(&self) -> ShapeStyle {
        self.style
    }
}

/// Axis-aligned rectangle primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct RectShape {
    rect: Rect,
    corner_radius: f32,
    style: ShapeStyle,
}

impl RectShape {
    /// Returns rectangle bounds in world coordinates.
    pub const fn rect(&self) -> Rect {
        self.rect
    }
    /// Returns corner radius in world units.
    pub const fn corner_radius(&self) -> f32 {
        self.corner_radius
    }
    /// Returns fill, stroke, and shadow styling.
    pub const fn style(&self) -> ShapeStyle {
        self.style
    }
}

/// Stroked line primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct Line {
    from: Vec2,
    to: Vec2,
    style: StrokeStyle2d,
}

impl Line {
    /// Returns the start point in world coordinates.
    pub const fn from(&self) -> Vec2 {
        self.from
    }
    /// Returns the end point in world coordinates.
    pub const fn to(&self) -> Vec2 {
        self.to
    }
    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
    pub const fn stroke(&self) -> Stroke {
        self.style.stroke
    }
    /// Returns the complete cap, join, dash, marker, and width-mode style.
    pub const fn stroke_style(&self) -> StrokeStyle2d {
        self.style
    }
}

/// Connected line-strip primitive in world coordinates.
#[derive(Debug, Clone)]
pub struct Polyline {
    points: Vec<Vec2>,
    style: StrokeStyle2d,
}

impl Polyline {
    /// Returns connected points in world coordinates.
    pub fn points(&self) -> &[Vec2] {
        &self.points
    }
    /// Returns color and scalar width; inspect [`Self::stroke_style`] for units.
    pub const fn stroke(&self) -> Stroke {
        self.style.stroke
    }
    /// Returns the complete cap, join, dash, marker, and width-mode style.
    pub const fn stroke_style(&self) -> StrokeStyle2d {
        self.style
    }
}

#[cfg(test)]
mod tests;