euv-core 0.52.1

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

/// Default neutral vertex positioned at origin with `+Y` normal, `+X` tangent, and white vertex color.
impl Default for Vertex3D {
    /// Returns a default 64-byte `Vertex3D`.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `Vertex3D`.
    fn default() -> Self {
        Self::from_pos_normal(Vec3::zero(), Vec3::new(0.0, 1.0, 0.0))
    }
}

/// Compact and full attribute constructors for `Vertex3D`.
impl Vertex3D {
    /// Constructs a `Vertex3D` from `position` and `normal` with identity tangent, zero UVs, and opaque white color.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Local-space 3D position.
    /// - `Vec3` - Local-space unit surface normal.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed 64-byte vertex.
    #[must_use]
    pub const fn new(position: Vec3, normal: Vec3) -> Self {
        Self::from_pos_normal(position, normal)
    }

    /// Constructs a `Vertex3D` from `position` and `normal` with default tangent, UV, and color attributes.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Local-space 3D position.
    /// - `Vec3` - Local-space unit surface normal.
    ///
    /// # Returns
    ///
    /// - `Self` - Constructed 64-byte vertex.
    #[must_use]
    pub const fn from_pos_normal(position: Vec3, normal: Vec3) -> Self {
        Self {
            position,
            normal,
            tangent: [1.0, 0.0, 0.0, 1.0],
            uv0: [0.0, 0.0],
            uv1: [0.0, 0.0],
            color0: [255, 255, 255, 255],
            flags: 0,
        }
    }

    /// Constructs a fully populated 64-byte `Vertex3D` with tangent, dual UVs, vertex color, and attribute flags.
    ///
    /// # Arguments
    ///
    /// - `Vec3` - Local-space 3D position.
    /// - `Vec3` - Local-space unit surface normal.
    /// - `[f32; 4]` - Tangent vector `(tx, ty, tz, handedness_sign)`.
    /// - `[f32; 2]` - Primary UV coordinate (`TEXCOORD_0`).
    /// - `[f32; 2]` - Secondary UV coordinate (`TEXCOORD_1`).
    /// - `[u8; 4]` - Packed UNORM8 RGBA vertex color (`COLOR_0`).
    /// - `u32` - Attribute bitmask flags.
    ///
    /// # Returns
    ///
    /// - `Self` - Fully populated 64-byte vertex.
    #[must_use]
    pub const fn from_full(
        position: Vec3,
        normal: Vec3,
        tangent: [f32; 4],
        uv0: [f32; 2],
        uv1: [f32; 2],
        color0: [u8; 4],
        flags: u32,
    ) -> Self {
        Self {
            position,
            normal,
            tangent,
            uv0,
            uv1,
            color0,
            flags,
        }
    }
}

/// Default neutral matte PBR material.
impl Default for PbrMaterial {
    /// Returns a mid-gray dielectric PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Default `PbrMaterial`.
    fn default() -> Self {
        Self {
            base_color: Vec3::new(0.72, 0.75, 0.80),
            metallic: 0.1,
            roughness: 0.55,
            emissive: Vec3::zero(),
            reflectivity: 0.12,
            surface_detail: SurfaceDetailMode::None,
        }
    }
}

/// Material presets and fluent builders for metallic conductors, dielectrics, architectural glass, and neon signage.
impl PbrMaterial {
    /// Creates a PBR material from an sRGB `Color`, `metallic`, `roughness`, and `reflectivity`.
    ///
    /// # Arguments
    ///
    /// - `Color` - Base albedo color.
    /// - `f32` - Metallic scalar `[0.0, 1.0]`.
    /// - `f32` - Roughness scalar `[0.04, 1.0]`.
    /// - `f32` - Ray-traced reflectivity weight `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured PBR material.
    #[must_use]
    pub fn pbr(color: Color, metallic: f32, roughness: f32, reflectivity: f32) -> Self {
        Self {
            base_color: Vec3::from_color(color),
            metallic: metallic.clamp(0.0, 1.0),
            roughness: roughness.clamp(0.04, 1.0),
            emissive: Vec3::zero(),
            reflectivity: reflectivity.clamp(0.0, 1.0),
            surface_detail: SurfaceDetailMode::None,
        }
    }

    /// Creates a metallic conductor PBR material (chrome, painted car body, brushed steel).
    ///
    /// # Arguments
    ///
    /// - `Color` - Base metallic reflectance color.
    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Conductor PBR material.
    #[must_use]
    pub fn metallic(color: Color, roughness: f32) -> Self {
        let red_val: f32 = roughness.clamp(0.04, 1.0);
        Self::pbr(
            color,
            0.92,
            red_val,
            (1.0 - red_val * 0.8).clamp(0.15, 0.96),
        )
    }

    /// Creates a non-metallic dielectric PBR material (asphalt, concrete, matte plastic, cloth).
    ///
    /// # Arguments
    ///
    /// - `Color` - Base diffuse albedo color.
    /// - `f32` - Surface roughness in `[0.04, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Dielectric PBR material.
    #[must_use]
    pub fn dielectric(color: Color, roughness: f32) -> Self {
        let red_val: f32 = roughness.clamp(0.04, 1.0);
        Self::pbr(
            color,
            0.04,
            red_val,
            (0.35 * (1.0 - red_val)).clamp(0.04, 0.35),
        )
    }

    /// Creates a highly reflective architectural glass PBR material.
    ///
    /// # Arguments
    ///
    /// - `Color` - Subtle glass tint color.
    /// - `f32` - Surface roughness in `[0.04, 0.4]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Reflective glass PBR material.
    #[must_use]
    pub fn glass(color: Color, roughness: f32) -> Self {
        let red_val: f32 = roughness.clamp(0.04, 0.4);
        Self::pbr(color, 0.12, red_val, 0.88)
    }

    /// Creates an emissive neon PBR material for city signage, vehicle tail-lights, and beacons.
    ///
    /// # Arguments
    ///
    /// - `Color` - Base and emissive neon color.
    /// - `f32` - Emissive intensity multiplier.
    ///
    /// # Returns
    ///
    /// - `Self` - Emissive PBR material.
    #[must_use]
    pub fn neon(color: Color, intensity: f32) -> Self {
        let rgb: Vec3 = Vec3::from_color(color);
        Self {
            base_color: rgb,
            metallic: 0.2,
            roughness: 0.2,
            emissive: rgb.scale(intensity.max(0.2)),
            reflectivity: 0.3,
            surface_detail: SurfaceDetailMode::None,
        }
    }

    /// Returns a copy of this material with custom linear HDR emissive radiance.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base material.
    /// - `Vec3` - Emissive HDR RGB radiance.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated material.
    #[must_use]
    pub fn with_emissive(mut self, emissive: Vec3) -> Self {
        self.set_emissive(emissive);
        self
    }

    /// Returns a copy of this material with adjusted surface roughness.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base material.
    /// - `f32` - Surface roughness clamped to `[0.04, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated material.
    #[must_use]
    pub fn with_roughness(mut self, roughness: f32) -> Self {
        self.set_roughness(roughness.clamp(0.04, 1.0));
        self
    }

    /// Returns a copy of this material with adjusted metallic factor.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base material.
    /// - `f32` - Metallic factor clamped to `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated material.
    #[must_use]
    pub fn with_metallic(mut self, metallic: f32) -> Self {
        self.set_metallic(metallic.clamp(0.0, 1.0));
        self
    }

    /// Returns a copy of this material with adjusted ray-traced reflectivity.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base material.
    /// - `f32` - Reflectivity weight clamped to `[0.0, 1.0]`.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated material.
    #[must_use]
    pub fn with_reflectivity(mut self, reflectivity: f32) -> Self {
        self.set_reflectivity(reflectivity.clamp(0.0, 1.0));
        self
    }

    /// Returns a copy of this material with the requested procedural surface detail overlay.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base material.
    /// - `SurfaceDetailMode` - Procedural surface detail mode.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated material.
    #[must_use]
    pub fn with_surface_detail(mut self, mode: SurfaceDetailMode) -> Self {
        self.set_surface_detail(mode);
        self
    }
}

/// Fluent constructors for `BoxMeshDesc`.
impl BoxMeshDesc {
    /// Creates a box mesh descriptor with default ground pivot and neutral PBR material.
    ///
    /// # Arguments
    ///
    /// - `&str` - Asset name.
    /// - `Vec3` - Box extents `(width, height, depth)`.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready descriptor.
    #[must_use]
    pub fn new(name: &str, size: Vec3) -> Self {
        Self {
            name: name.to_string(),
            size,
            ground_pivot: true,
            material: PbrMaterial::default(),
        }
    }

    /// Sets whether the box rests on `y = 0` or is centered at the origin.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base descriptor.
    /// - `bool` - Ground pivot toggle.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated descriptor.
    #[must_use]
    pub fn with_ground_pivot(mut self, ground_pivot: bool) -> Self {
        self.set_ground_pivot(ground_pivot);
        self
    }

    /// Assigns the PBR material for the generated box mesh.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base descriptor.
    /// - `PbrMaterial` - Surface material.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated descriptor.
    #[must_use]
    pub fn with_material(mut self, material: PbrMaterial) -> Self {
        self.set_material(material);
        self
    }
}

/// Fluent constructors for `GroundPlaneDesc`.
impl GroundPlaneDesc {
    /// Creates a ground plane descriptor with default subdivisions and neutral PBR material.
    ///
    /// # Arguments
    ///
    /// - `&str` - Asset name.
    /// - `f32` - Width along X.
    /// - `f32` - Depth along Z.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready descriptor.
    #[must_use]
    pub fn new(name: &str, width: f32, depth: f32) -> Self {
        Self {
            name: name.to_string(),
            width,
            depth,
            subdivisions: 8,
            material: PbrMaterial::default(),
        }
    }

    /// Sets the grid subdivision count along each axis.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base descriptor.
    /// - `usize` - Subdivision count.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated descriptor.
    #[must_use]
    pub fn with_subdivisions(mut self, subdivisions: usize) -> Self {
        self.set_subdivisions(subdivisions);
        self
    }

    /// Assigns the PBR material for the generated ground plane.
    ///
    /// # Arguments
    ///
    /// - `Self` - Base descriptor.
    /// - `PbrMaterial` - Surface material.
    ///
    /// # Returns
    ///
    /// - `Self` - Updated descriptor.
    #[must_use]
    pub fn with_material(mut self, material: PbrMaterial) -> Self {
        self.set_material(material);
        self
    }
}

/// Mesh construction, Nanite-style meshlet clustering, decimation, and procedural asset generators for `Mesh3D`.
impl Mesh3D {
    /// Partitions indexed triangles into Nanite-style `Meshlet3D` clusters with tight axis-aligned bounding boxes and normal cones.
    ///
    /// # Arguments
    ///
    /// - `&[Vertex3D]` - Source vertex buffer.
    /// - `&[[u32; 3]]` - Source triangle indices.
    ///
    /// # Returns
    ///
    /// - `Vec<Meshlet3D>` - Contiguous cluster descriptors covering all triangles.
    #[must_use]
    pub fn build_meshlets_from_parts(
        vertices: &[Vertex3D],
        indices: &[[u32; 3]],
    ) -> Vec<Meshlet3D> {
        if indices.is_empty() {
            return Vec::new();
        }
        let cluster_count: usize = indices.len().div_ceil(MESHLET_MAX_TRIS);
        let mut out: Vec<Meshlet3D> = Vec::with_capacity(cluster_count);
        let mut start: usize = 0;
        while start < indices.len() {
            let end: usize = (start + MESHLET_MAX_TRIS).min(indices.len());
            let mut cluster_box: AxisAlignedBox3D = AxisAlignedBox3D::empty();
            let mut avg_n: Vec3 = Vec3::zero();
            let mut valid_tris: usize = 0;
            for tri in &indices[start..end] {
                let (i0, i1, i2): (usize, usize, usize) =
                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
                    let p0: Vec3 = vertices[i0].get_position();
                    let p1: Vec3 = vertices[i1].get_position();
                    let p2: Vec3 = vertices[i2].get_position();
                    cluster_box.expand_point(p0);
                    cluster_box.expand_point(p1);
                    cluster_box.expand_point(p2);
                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
                    avg_n = avg_n.add(fn_vec);
                    valid_tris += 1;
                }
            }
            if valid_tris == 0 {
                cluster_box = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
            }
            let cone_axis: Vec3 = avg_n.normalize();
            let mut min_dot: f32 = 1.0;
            for tri in &indices[start..end] {
                let (i0, i1, i2): (usize, usize, usize) =
                    (tri[0] as usize, tri[1] as usize, tri[2] as usize);
                if i0 < vertices.len() && i1 < vertices.len() && i2 < vertices.len() {
                    let p0: Vec3 = vertices[i0].get_position();
                    let p1: Vec3 = vertices[i1].get_position();
                    let p2: Vec3 = vertices[i2].get_position();
                    let fn_vec: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
                    min_dot = min_dot.min(fn_vec.dot(cone_axis));
                }
            }
            let radius: f32 = cluster_box.radius().max(0.05);
            let screen_error: f32 = radius / ((end - start).max(1) as f32).sqrt();
            out.push(Meshlet3D::new(
                start as u32,
                (end - start) as u32,
                cluster_box,
                cone_axis,
                min_dot,
                screen_error,
            ));
            start = end;
        }
        out
    }

    /// Constructs a `Mesh3D`, computes its local `AxisAlignedBox3D`, and partitions Nanite-style `Meshlet3D` clusters.
    ///
    /// # Arguments
    ///
    /// - `String` - Asset name.
    /// - `Vec<Vertex3D>` - Vertex list.
    /// - `Vec<[u32; 3]>` - Triangle indices.
    /// - `PbrMaterial` - Default material.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready indexed mesh with meshlets.
    #[must_use]
    pub fn from_parts(
        name: String,
        vertices: Vec<Vertex3D>,
        indices: Vec<[u32; 3]>,
        material: PbrMaterial,
    ) -> Self {
        let mut bounds: AxisAlignedBox3D = AxisAlignedBox3D::empty();
        for item_val in vertices.iter() {
            bounds.expand_point(item_val.get_position());
        }
        if vertices.is_empty() {
            bounds = AxisAlignedBox3D::new(Vec3::zero(), Vec3::zero());
        }
        let meshlets: Vec<Meshlet3D> = Self::build_meshlets_from_parts(&vertices, &indices);
        Self {
            name,
            vertices,
            indices,
            bounds,
            material,
            sub_materials: Vec::new(),
            tri_materials: Vec::new(),
            meshlets,
            skin_influences: Vec::new(),
            morph_targets: Vec::new(),
            material_index: None,
            is_closed: false,
        }
    }

    /// Recomputes area-weighted smooth per-vertex normals across all indexed triangles.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable 3D mesh.
    pub fn compute_smooth_normals(&mut self) {
        let vert_count: usize = self.get_vertices().len();
        if vert_count == 0 {
            return;
        }
        let mut accum: Vec<Vec3> = vec![Vec3::zero(); vert_count];
        let verts: &[Vertex3D] = self.get_vertices().as_slice();
        for tri in self.get_indices().iter() {
            let (i0, i1, i2): (usize, usize, usize) =
                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
            if i0 < vert_count && i1 < vert_count && i2 < vert_count {
                let p0: Vec3 = verts[i0].get_position();
                let p1: Vec3 = verts[i1].get_position();
                let p2: Vec3 = verts[i2].get_position();
                let weighted_n: Vec3 = p1.sub(p0).cross(p2.sub(p0));
                accum[i0] = accum[i0].add(weighted_n);
                accum[i1] = accum[i1].add(weighted_n);
                accum[i2] = accum[i2].add(weighted_n);
            }
        }
        for (idx, vert) in self.get_mut_vertices().iter_mut().enumerate() {
            let sum_n: Vec3 = accum[idx];
            if sum_n.length_sq() > 1e-10 {
                vert.set_normal(sum_n.normalize());
            }
        }
    }

    /// Computes MikkTSpace-compatible Lengyel tangent-space vectors `(tx, ty, tz, handedness)` from positions, normals, and `uv0`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable 3D mesh.
    pub fn compute_lengyel_tangents(&mut self) {
        let vert_count: usize = self.get_vertices().len();
        if vert_count == 0 {
            return;
        }
        let mut tan1: Vec<Vec3> = vec![Vec3::zero(); vert_count];
        let mut tan2: Vec<Vec3> = vec![Vec3::zero(); vert_count];
        let verts: &[Vertex3D] = self.get_vertices().as_slice();
        for tri in self.get_indices().iter() {
            let (i0, i1, i2): (usize, usize, usize) =
                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
            if i0 >= vert_count || i1 >= vert_count || i2 >= vert_count {
                continue;
            }
            let p0: Vec3 = verts[i0].get_position();
            let p1: Vec3 = verts[i1].get_position();
            let p2: Vec3 = verts[i2].get_position();
            let w0: [f32; 2] = verts[i0].get_uv0();
            let w1: [f32; 2] = verts[i1].get_uv0();
            let w2: [f32; 2] = verts[i2].get_uv0();
            let e1: Vec3 = p1.sub(p0);
            let e2: Vec3 = p2.sub(p0);
            let s1: f32 = w1[0] - w0[0];
            let s2: f32 = w2[0] - w0[0];
            let t1: f32 = w1[1] - w0[1];
            let t2: f32 = w2[1] - w0[1];
            let det: f32 = s1 * t2 - s2 * t1;
            if det.abs() < 1e-10 {
                continue;
            }
            let inv_det: f32 = 1.0 / det;
            let sdir: Vec3 = Vec3::new(
                (t2 * e1.get_x() - t1 * e2.get_x()) * inv_det,
                (t2 * e1.get_y() - t1 * e2.get_y()) * inv_det,
                (t2 * e1.get_z() - t1 * e2.get_z()) * inv_det,
            );
            let tdir: Vec3 = Vec3::new(
                (s1 * e2.get_x() - s2 * e1.get_x()) * inv_det,
                (s1 * e2.get_y() - s2 * e1.get_y()) * inv_det,
                (s1 * e2.get_z() - s2 * e1.get_z()) * inv_det,
            );
            tan1[i0] = tan1[i0].add(sdir);
            tan1[i1] = tan1[i1].add(sdir);
            tan1[i2] = tan1[i2].add(sdir);
            tan2[i0] = tan2[i0].add(tdir);
            tan2[i1] = tan2[i1].add(tdir);
            tan2[i2] = tan2[i2].add(tdir);
        }
        for (idx, vert) in self.get_mut_vertices().iter_mut().enumerate() {
            let n: Vec3 = vert.get_normal().normalize();
            let t: Vec3 = tan1[idx];
            let ortho: Vec3 = t.sub(n.scale(n.dot(t)));
            let unit_t: Vec3 = if ortho.length_sq() > 1e-10 {
                ortho.normalize()
            } else {
                let fallback_axis: Vec3 = if n.get_y().abs() < 0.99 {
                    Vec3::new(0.0, 1.0, 0.0)
                } else {
                    Vec3::new(1.0, 0.0, 0.0)
                };
                fallback_axis.cross(n).normalize()
            };
            let handedness: f32 = if n.cross(t).dot(tan2[idx]) < 0.0 {
                -1.0
            } else {
                1.0
            };
            vert.set_tangent([unit_t.get_x(), unit_t.get_y(), unit_t.get_z(), handedness]);
            let next_flags: u32 = vert.get_flags() | 4;
            vert.set_flags(next_flags);
        }
    }

    /// Resolves the effective PBR material and sub-material slot for triangle `tri_index`.
    ///
    /// # Arguments
    ///
    /// - `usize` - Triangle index inside `indices`.
    /// - `PbrMaterial` - Instance primary PBR material used when slot is `0`.
    ///
    /// # Returns
    ///
    /// - `(PbrMaterial, u16)` - Effective PBR material and resolved material slot.
    #[cfg_attr(not(target_arch = "wasm32"), inline)]
    #[must_use]
    pub fn resolve_triangle_material(
        &self,
        tri_index: usize,
        primary_material: PbrMaterial,
    ) -> (PbrMaterial, u16) {
        let Self {
            sub_materials,
            tri_materials,
            ..
        } = self;
        if tri_materials.is_empty() {
            return (primary_material, 0);
        }
        let slot: u16 = tri_materials.get(tri_index).copied().unwrap_or(0);
        if slot == 0 {
            (primary_material, 0)
        } else if let Some(&sub_mat) = sub_materials.get((slot - 1) as usize) {
            (sub_mat, slot)
        } else {
            (primary_material, 0)
        }
    }

    /// Appends a single outward-oriented flat-shaded triangle tagged with `mat_slot`.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
    /// - `(Vec3, Vec3, Vec3)` - Triangle vertices `(vert_a, vert_b, vert_c)` in CCW outward order.
    /// - `u16` - Sub-material slot index (`0` = primary material).
    fn push_flat_tri(
        vertices: &mut Vec<Vertex3D>,
        indices: &mut Vec<[u32; 3]>,
        tri_materials: &mut Vec<u16>,
        corners: (Vec3, Vec3, Vec3),
        mat_slot: u16,
    ) {
        let (vert_a, vert_b, vert_c): (Vec3, Vec3, Vec3) = corners;
        let face_normal: Vec3 = vert_b.sub(vert_a).cross(vert_c.sub(vert_a)).normalize();
        let base_idx: u32 = vertices.len() as u32;
        vertices.push(Vertex3D::new(vert_a, face_normal));
        vertices.push(Vertex3D::new(vert_b, face_normal));
        vertices.push(Vertex3D::new(vert_c, face_normal));
        indices.push([base_idx, base_idx + 1, base_idx + 2]);
        tri_materials.push(mat_slot);
    }

    /// Appends a flat-shaded CCW quad split into two triangles tagged with `mat_slot`.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
    /// - `[Vec3; 4]` - Quad vertices in CCW outward order.
    /// - `u16` - Sub-material slot index.
    fn push_flat_quad(
        vertices: &mut Vec<Vertex3D>,
        indices: &mut Vec<[u32; 3]>,
        tri_materials: &mut Vec<u16>,
        quad: [Vec3; 4],
        mat_slot: u16,
    ) {
        let edge_u: Vec3 = quad[1].sub(quad[0]);
        let edge_v: Vec3 = quad[2].sub(quad[0]);
        let face_normal: Vec3 = edge_u.cross(edge_v).normalize();
        let base_idx: u32 = vertices.len() as u32;
        for corner in quad.into_iter() {
            vertices.push(Vertex3D::new(corner, face_normal));
        }
        indices.push([base_idx, base_idx + 1, base_idx + 2]);
        indices.push([base_idx, base_idx + 2, base_idx + 3]);
        tri_materials.push(mat_slot);
        tri_materials.push(mat_slot);
    }

    /// Appends a closed 6-face tapered frustum/box prism with explicit bottom and top corner quads.
    ///
    /// Bottom corners are ordered `[(-x,+z), (+x,+z), (+x,-z), (-x,-z)]` and top corners match identically.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
    /// - `[Vec3; 4]` - Bottom loop corners `[bl_rear, br_rear, br_front, bl_front]`.
    /// - `[Vec3; 4]` - Top loop corners `[tl_rear, tr_rear, tr_front, tl_front]`.
    /// - `[u16; 6]` - Per-face material slots `[rear(+z), front(-z), right(+x), left(-x), top(+y), bottom(-y)]`.
    fn push_tapered_prism(
        vertices: &mut Vec<Vertex3D>,
        indices: &mut Vec<[u32; 3]>,
        tri_materials: &mut Vec<u16>,
        bottom: [Vec3; 4],
        top: [Vec3; 4],
        face_slots: [u16; 6],
    ) {
        Self::push_flat_quad(
            vertices,
            indices,
            tri_materials,
            [bottom[0], bottom[1], top[1], top[0]],
            face_slots[0],
        );
        Self::push_flat_quad(
            vertices,
            indices,
            tri_materials,
            [bottom[2], bottom[3], top[3], top[2]],
            face_slots[1],
        );
        Self::push_flat_quad(
            vertices,
            indices,
            tri_materials,
            [bottom[1], bottom[2], top[2], top[1]],
            face_slots[2],
        );
        Self::push_flat_quad(
            vertices,
            indices,
            tri_materials,
            [bottom[3], bottom[0], top[0], top[3]],
            face_slots[3],
        );
        Self::push_flat_quad(
            vertices,
            indices,
            tri_materials,
            [top[0], top[1], top[2], top[3]],
            face_slots[4],
        );
        Self::push_flat_quad(
            vertices,
            indices,
            tri_materials,
            [bottom[3], bottom[2], bottom[1], bottom[0]],
            face_slots[5],
        );
    }

    /// Appends an axis-aligned box prism centered at `center` with `(width, height, depth)` tagged uniformly with `mat_slot`.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
    /// - `Vec3` - Box center position.
    /// - `Vec3` - Box extents `(width, height, depth)`.
    /// - `u16` - Sub-material slot applied to all six faces.
    fn push_box_part(
        vertices: &mut Vec<Vertex3D>,
        indices: &mut Vec<[u32; 3]>,
        tri_materials: &mut Vec<u16>,
        center: Vec3,
        size: Vec3,
        mat_slot: u16,
    ) {
        let half_x: f32 = size.get_x() * 0.5;
        let half_y: f32 = size.get_y() * 0.5;
        let half_z: f32 = size.get_z() * 0.5;
        let cx: f32 = center.get_x();
        let cy: f32 = center.get_y();
        let cz: f32 = center.get_z();
        let bottom: [Vec3; 4] = [
            Vec3::new(cx - half_x, cy - half_y, cz + half_z),
            Vec3::new(cx + half_x, cy - half_y, cz + half_z),
            Vec3::new(cx + half_x, cy - half_y, cz - half_z),
            Vec3::new(cx - half_x, cy - half_y, cz - half_z),
        ];
        let top: [Vec3; 4] = [
            Vec3::new(cx - half_x, cy + half_y, cz + half_z),
            Vec3::new(cx + half_x, cy + half_y, cz + half_z),
            Vec3::new(cx + half_x, cy + half_y, cz - half_z),
            Vec3::new(cx - half_x, cy + half_y, cz - half_z),
        ];
        Self::push_tapered_prism(vertices, indices, tri_materials, bottom, top, [mat_slot; 6]);
    }

    /// Appends a closed cylindrical wheel assembly aligned along the X axle with matte rubber tire tread and inset metallic alloy rim face.
    ///
    /// # Arguments
    ///
    /// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
    /// - `&mut Vec<[u32; 3]>` - Destination triangle index buffer.
    /// - `&mut Vec<u16>` - Destination per-triangle material slot table.
    /// - `Vec3` - Wheel hub center `(center_x, center_y, center_z)`.
    /// - `(f32, f32, f32)` - `(tire_radius, rim_radius, tire_width)`.
    /// - `(u16, u16)` - `(tire_slot, rim_slot)` sub-material slots.
    fn push_wheel_assembly(
        vertices: &mut Vec<Vertex3D>,
        indices: &mut Vec<[u32; 3]>,
        tri_materials: &mut Vec<u16>,
        center: Vec3,
        dims: (f32, f32, f32),
        slots: (u16, u16),
    ) {
        let (tire_radius, rim_radius, tire_width): (f32, f32, f32) = dims;
        let (tire_slot, rim_slot): (u16, u16) = slots;
        let half_w: f32 = tire_width * 0.5;
        let cx: f32 = center.get_x();
        let cy: f32 = center.get_y();
        let cz: f32 = center.get_z();
        let x_left: f32 = cx - half_w;
        let x_right: f32 = cx + half_w;
        let left_hub: Vec3 = Vec3::new(x_left, cy, cz);
        let right_hub: Vec3 = Vec3::new(x_right, cy, cz);
        let outer_sign: f32 = if cx >= 0.0 { 1.0 } else { -1.0 };
        let rim_x: f32 = cx + outer_sign * (half_w + 0.014);
        let brake_x: f32 = cx + outer_sign * (half_w + 0.006);
        let rim_hub: Vec3 = Vec3::new(rim_x, cy, cz);
        let brake_hub: Vec3 = Vec3::new(brake_x, cy, cz);
        let step_rad: f32 = (2.0 * PI) / (MESH_CAR_WHEEL_SEGMENTS as f32);
        for seg_idx in 0..MESH_CAR_WHEEL_SEGMENTS {
            let a0: f32 = (seg_idx as f32) * step_rad;
            let a1: f32 = ((seg_idx + 1) as f32) * step_rad;
            let (s0, c0): (f32, f32) = a0.sin_cos();
            let (s1, c1): (f32, f32) = a1.sin_cos();
            let l0: Vec3 = Vec3::new(x_left, cy + s0 * tire_radius, cz + c0 * tire_radius);
            let l1: Vec3 = Vec3::new(x_left, cy + s1 * tire_radius, cz + c1 * tire_radius);
            let r0: Vec3 = Vec3::new(x_right, cy + s0 * tire_radius, cz + c0 * tire_radius);
            let r1: Vec3 = Vec3::new(x_right, cy + s1 * tire_radius, cz + c1 * tire_radius);
            Self::push_flat_quad(
                vertices,
                indices,
                tri_materials,
                [l0, r0, r1, l1],
                tire_slot,
            );
            Self::push_flat_tri(
                vertices,
                indices,
                tri_materials,
                (right_hub, r1, r0),
                tire_slot,
            );
            Self::push_flat_tri(
                vertices,
                indices,
                tri_materials,
                (left_hub, l0, l1),
                tire_slot,
            );
            let bm0: Vec3 = Vec3::new(brake_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
            let bm1: Vec3 = Vec3::new(brake_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
            if outer_sign > 0.0 {
                Self::push_flat_tri(
                    vertices,
                    indices,
                    tri_materials,
                    (brake_hub, bm1, bm0),
                    tire_slot,
                );
            } else {
                Self::push_flat_tri(
                    vertices,
                    indices,
                    tri_materials,
                    (brake_hub, bm0, bm1),
                    tire_slot,
                );
            }
            let lip_in: f32 = rim_radius * 0.78;
            let rm0: Vec3 = Vec3::new(rim_x, cy + s0 * rim_radius, cz + c0 * rim_radius);
            let rm1: Vec3 = Vec3::new(rim_x, cy + s1 * rim_radius, cz + c1 * rim_radius);
            let ri0: Vec3 = Vec3::new(rim_x, cy + s0 * lip_in, cz + c0 * lip_in);
            let ri1: Vec3 = Vec3::new(rim_x, cy + s1 * lip_in, cz + c1 * lip_in);
            if outer_sign > 0.0 {
                Self::push_flat_quad(
                    vertices,
                    indices,
                    tri_materials,
                    [ri0, rm0, rm1, ri1],
                    rim_slot,
                );
            } else {
                Self::push_flat_quad(
                    vertices,
                    indices,
                    tri_materials,
                    [ri1, rm1, rm0, ri0],
                    rim_slot,
                );
            }
            if seg_idx % 2 == 0 {
                let spoke_rad: f32 = rim_radius * 0.84;
                let a_mid: f32 = a0 + step_rad * 0.48;
                let (sm, cm): (f32, f32) = a_mid.sin_cos();
                let sp0: Vec3 = Vec3::new(rim_x, cy + s0 * spoke_rad, cz + c0 * spoke_rad);
                let sp1: Vec3 = Vec3::new(rim_x, cy + sm * spoke_rad, cz + cm * spoke_rad);
                if outer_sign > 0.0 {
                    Self::push_flat_tri(
                        vertices,
                        indices,
                        tri_materials,
                        (rim_hub, sp1, sp0),
                        rim_slot,
                    );
                } else {
                    Self::push_flat_tri(
                        vertices,
                        indices,
                        tri_materials,
                        (rim_hub, sp0, sp1),
                        rim_slot,
                    );
                }
            }
        }
    }

    /// Generates an axis-aligned box mesh of dimensions `(w, h, d)` resting on `y = 0` or centered.
    ///
    /// # Arguments
    ///
    /// - `&str` - Mesh name.
    /// - `f32` - Width along X.
    /// - `f32` - Height along Y.
    /// - `f32` - Depth along Z.
    /// - `bool` - When `true`, base rests on `y = 0`; otherwise centered at origin.
    /// - `PbrMaterial` - Surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Indexed 12-triangle box mesh with crisp flat face normals.
    #[must_use]
    pub fn box_mesh(
        name: &str,
        width_val: f32,
        height_val: f32,
        delta_val: f32,
        ground_pivot: bool,
        material: PbrMaterial,
    ) -> Self {
        let hx: f32 = width_val * 0.5;
        let hz: f32 = delta_val * 0.5;
        let y0: f32 = if ground_pivot { 0.0 } else { -height_val * 0.5 };
        let y1: f32 = if ground_pivot {
            height_val
        } else {
            height_val * 0.5
        };
        let faces: [([Vec3; 4], Vec3); 6] = [
            (
                [
                    Vec3::new(-hx, y0, hz),
                    Vec3::new(hx, y0, hz),
                    Vec3::new(hx, y1, hz),
                    Vec3::new(-hx, y1, hz),
                ],
                Vec3::new(0.0, 0.0, 1.0),
            ),
            (
                [
                    Vec3::new(hx, y0, -hz),
                    Vec3::new(-hx, y0, -hz),
                    Vec3::new(-hx, y1, -hz),
                    Vec3::new(hx, y1, -hz),
                ],
                Vec3::new(0.0, 0.0, -1.0),
            ),
            (
                [
                    Vec3::new(hx, y0, hz),
                    Vec3::new(hx, y0, -hz),
                    Vec3::new(hx, y1, -hz),
                    Vec3::new(hx, y1, hz),
                ],
                Vec3::new(1.0, 0.0, 0.0),
            ),
            (
                [
                    Vec3::new(-hx, y0, -hz),
                    Vec3::new(-hx, y0, hz),
                    Vec3::new(-hx, y1, hz),
                    Vec3::new(-hx, y1, -hz),
                ],
                Vec3::new(-1.0, 0.0, 0.0),
            ),
            (
                [
                    Vec3::new(-hx, y1, hz),
                    Vec3::new(hx, y1, hz),
                    Vec3::new(hx, y1, -hz),
                    Vec3::new(-hx, y1, -hz),
                ],
                Vec3::new(0.0, 1.0, 0.0),
            ),
            (
                [
                    Vec3::new(-hx, y0, -hz),
                    Vec3::new(hx, y0, -hz),
                    Vec3::new(hx, y0, hz),
                    Vec3::new(-hx, y0, hz),
                ],
                Vec3::new(0.0, -1.0, 0.0),
            ),
        ];
        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(24);
        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(12);
        for (quad, item_count) in faces.into_iter() {
            let base: u32 = vertices.len() as u32;
            for point_val in quad.into_iter() {
                vertices.push(Vertex3D::new(point_val, item_count));
            }
            indices.push([base, base + 1, base + 2]);
            indices.push([base, base + 2, base + 3]);
        }
        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
        mesh.set_is_closed(true);
        mesh
    }

    /// Generates a horizontal ground/road quad plane at `y = 0` subdivided for crisp specular/shadow falloff.
    ///
    /// # Arguments
    ///
    /// - `&str` - Mesh name.
    /// - `f32` - Width along X.
    /// - `f32` - Depth along Z.
    /// - `usize` - Grid subdivisions per axis.
    /// - `PbrMaterial` - Surface PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Subdivided ground plane mesh.
    #[must_use]
    pub fn ground_plane(
        name: &str,
        width_val: f32,
        delta_val: f32,
        subdivisions: usize,
        material: PbrMaterial,
    ) -> Self {
        let segs: usize = subdivisions.clamp(1, 16);
        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((segs + 1) * (segs + 1));
        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(segs * segs * 2);
        let up: Vec3 = Vec3::new(0.0, 1.0, 0.0);
        for iz in 0..=segs {
            let vz: f32 = ((iz as f32) / (segs as f32) - 0.5) * delta_val;
            for ix in 0..=segs {
                let vx: f32 = ((ix as f32) / (segs as f32) - 0.5) * width_val;
                vertices.push(Vertex3D::new(Vec3::new(vx, 0.0, vz), up));
            }
        }
        let stride: u32 = (segs + 1) as u32;
        for iz in 0..segs {
            for ix in 0..segs {
                let i0: u32 = (iz as u32) * stride + (ix as u32);
                let i1: u32 = i0 + 1;
                let i2: u32 = i0 + stride;
                let i3: u32 = i2 + 1;
                indices.push([i0, i2, i1]);
                indices.push([i1, i2, i3]);
            }
        }
        Self::from_parts(name.to_string(), vertices, indices, material)
    }

    /// Builds a subdivided coastal ocean water ring mesh spanning `outer_span` while omitting submerged interior quads strictly inside the solid island footprint and grouping triangles into spatially coherent 4x4 blocks for Nanite frustum culling.
    ///
    /// # Arguments
    ///
    /// - `&str` - Mesh asset name.
    /// - `f32` - Total horizontal outer span in meters along X and Z.
    /// - `f32` - Solid island half-width along X in meters.
    /// - `f32` - Solid island half-depth along Z in meters.
    /// - `usize` - Grid subdivisions along each axis (`8..=32`).
    /// - `PbrMaterial` - Ocean water PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Watertight coastal ocean ring mesh with spatial meshlets.
    #[must_use]
    pub fn coastal_ocean_ring(
        name: &str,
        outer_span: f32,
        inner_half_x: f32,
        inner_half_z: f32,
        subdivisions: usize,
        material: PbrMaterial,
    ) -> Self {
        let seg_count: usize = subdivisions.clamp(8, 32);
        let cut_half_x: f32 = (inner_half_x - 2.0).max(0.0);
        let cut_half_z: f32 = (inner_half_z - 2.0).max(0.0);
        let mut vertices: Vec<Vertex3D> = Vec::with_capacity((seg_count + 1) * (seg_count + 1));
        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(seg_count * seg_count * 2);
        let up_normal: Vec3 = Vec3::new(0.0, 1.0, 0.0);
        let inv_segs: f32 = 1.0 / (seg_count as f32);
        for grid_z in 0..=seg_count {
            let pos_z: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
            for grid_x in 0..=seg_count {
                let pos_x: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
                vertices.push(Vertex3D::new(Vec3::new(pos_x, 0.0, pos_z), up_normal));
            }
        }
        let row_stride: u32 = (seg_count + 1) as u32;
        let mut block_z: usize = 0;
        while block_z < seg_count {
            let end_z: usize = (block_z + 4).min(seg_count);
            let mut block_x: usize = 0;
            while block_x < seg_count {
                let end_x: usize = (block_x + 4).min(seg_count);
                for grid_z in block_z..end_z {
                    let quad_z0: f32 = ((grid_z as f32) * inv_segs - 0.5) * outer_span;
                    let quad_z1: f32 = (((grid_z + 1) as f32) * inv_segs - 0.5) * outer_span;
                    for grid_x in block_x..end_x {
                        let quad_x0: f32 = ((grid_x as f32) * inv_segs - 0.5) * outer_span;
                        let quad_x1: f32 = (((grid_x + 1) as f32) * inv_segs - 0.5) * outer_span;
                        let inside_x: bool = quad_x0 >= -cut_half_x && quad_x1 <= cut_half_x;
                        let inside_z: bool = quad_z0 >= -cut_half_z && quad_z1 <= cut_half_z;
                        if inside_x && inside_z {
                            continue;
                        }
                        let idx0: u32 = (grid_z as u32) * row_stride + (grid_x as u32);
                        let idx1: u32 = idx0 + 1;
                        let idx2: u32 = idx0 + row_stride;
                        let idx3: u32 = idx2 + 1;
                        indices.push([idx0, idx2, idx1]);
                        indices.push([idx1, idx2, idx3]);
                    }
                }
                block_x += 4;
            }
            block_z += 4;
        }
        Self::from_parts(name.to_string(), vertices, indices, material)
    }

    /// Builds a sculpted widebody multi-material GT supercar mesh with smoked glass greenhouse, carbon aero splitter/diffuser/wing, crimson LED taillight bar, xenon headlights, dark undercarriage contact shadow, and round cylindrical wheels with metallic alloy rims.
    ///
    /// # Arguments
    ///
    /// - `&str` - Asset name.
    /// - `PbrMaterial` - Primary car body clearcoat paint PBR material.
    ///
    /// # Returns
    ///
    /// - `Self` - Composite multi-material vehicle mesh.
    #[must_use]
    pub fn sports_car(name: &str, material: PbrMaterial) -> Self {
        let sub_materials: Vec<PbrMaterial> = vec![
            PbrMaterial::glass(Color::hex(0x0A101E), 0.05),
            PbrMaterial::dielectric(Color::hex(0x0D1015), 0.90),
            PbrMaterial::metallic(Color::hex(0xDCE6F2), 0.12),
            PbrMaterial::pbr(Color::hex(0x121722), 0.34, 0.32, 0.26),
            PbrMaterial::neon(Color::hex(0xFF1744), 3.8),
            PbrMaterial::neon(Color::hex(0xFFF6DC), 3.6),
            PbrMaterial::dielectric(Color::hex(0x04060A), 0.96),
            PbrMaterial::neon(Color::hex(0xFF9100), 2.2),
        ];
        let slot_body: u16 = 0;
        let slot_glass: u16 = 1;
        let slot_tire: u16 = 2;
        let slot_chrome: u16 = 3;
        let slot_carbon: u16 = 4;
        let slot_taillight: u16 = 5;
        let slot_headlight: u16 = 6;
        let slot_underbody: u16 = 7;
        let slot_amber: u16 = 8;
        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(960);
        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(340);
        let mut tri_materials: Vec<u16> = Vec::with_capacity(340);
        Self::push_box_part(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            Vec3::new(0.0, 0.14, 0.0),
            Vec3::new(2.06, 0.20, 4.46),
            slot_underbody,
        );
        Self::push_box_part(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            Vec3::new(0.0, 0.22, -2.28),
            Vec3::new(2.10, 0.09, 0.36),
            slot_carbon,
        );
        for skirt_side in [-1.0_f32, 1.0_f32] {
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(skirt_side * 1.12, 0.24, 0.02),
                Vec3::new(0.14, 0.14, 2.04),
                slot_carbon,
            );
        }
        let front_bot: [Vec3; 4] = [
            Vec3::new(-1.14, 0.24, -0.78),
            Vec3::new(1.14, 0.24, -0.78),
            Vec3::new(0.98, 0.26, -2.38),
            Vec3::new(-0.98, 0.26, -2.38),
        ];
        let front_top: [Vec3; 4] = [
            Vec3::new(-1.04, 0.90, -0.78),
            Vec3::new(1.04, 0.90, -0.78),
            Vec3::new(0.84, 0.60, -2.32),
            Vec3::new(-0.84, 0.60, -2.32),
        ];
        Self::push_tapered_prism(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            front_bot,
            front_top,
            [
                slot_body,
                slot_body,
                slot_body,
                slot_body,
                slot_body,
                slot_underbody,
            ],
        );
        let mid_bot: [Vec3; 4] = [
            Vec3::new(-1.06, 0.24, 1.04),
            Vec3::new(1.06, 0.24, 1.04),
            Vec3::new(1.04, 0.24, -0.82),
            Vec3::new(-1.04, 0.24, -0.82),
        ];
        let mid_top: [Vec3; 4] = [
            Vec3::new(-1.04, 0.96, 1.04),
            Vec3::new(1.04, 0.96, 1.04),
            Vec3::new(1.00, 0.89, -0.82),
            Vec3::new(-1.00, 0.89, -0.82),
        ];
        Self::push_tapered_prism(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            mid_bot,
            mid_top,
            [
                slot_body,
                slot_body,
                slot_body,
                slot_body,
                slot_body,
                slot_underbody,
            ],
        );
        let rear_bot: [Vec3; 4] = [
            Vec3::new(-1.12, 0.36, 2.34),
            Vec3::new(1.12, 0.36, 2.34),
            Vec3::new(1.18, 0.26, 1.04),
            Vec3::new(-1.18, 0.26, 1.04),
        ];
        let rear_top: [Vec3; 4] = [
            Vec3::new(-1.06, 1.02, 2.24),
            Vec3::new(1.06, 1.02, 2.24),
            Vec3::new(1.14, 0.98, 1.04),
            Vec3::new(-1.14, 0.98, 1.04),
        ];
        Self::push_tapered_prism(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            rear_bot,
            rear_top,
            [
                slot_carbon,
                slot_body,
                slot_body,
                slot_body,
                slot_body,
                slot_underbody,
            ],
        );
        for fender_side in [-1.0_f32, 1.0_f32] {
            for (fender_z, flare_w) in [(-1.42_f32, 1.18_f32), (1.44_f32, 1.24_f32)] {
                let x_in: f32 = fender_side * 0.94;
                let x_out_lo: f32 = fender_side * flare_w;
                let x_out_hi: f32 = fender_side * (flare_w - 0.12);
                let (xa, xb): (f32, f32) = if fender_side > 0.0 {
                    (x_in, x_out_lo)
                } else {
                    (x_out_lo, x_in)
                };
                let (ta, tb): (f32, f32) = if fender_side > 0.0 {
                    (x_in, x_out_hi)
                } else {
                    (x_out_hi, x_in)
                };
                let arch_bot: [Vec3; 4] = [
                    Vec3::new(xa, 0.62, fender_z + 0.56),
                    Vec3::new(xb, 0.62, fender_z + 0.56),
                    Vec3::new(xb, 0.62, fender_z - 0.56),
                    Vec3::new(xa, 0.62, fender_z - 0.56),
                ];
                let arch_top: [Vec3; 4] = [
                    Vec3::new(ta, 0.98, fender_z + 0.42),
                    Vec3::new(tb, 0.98, fender_z + 0.42),
                    Vec3::new(tb, 0.98, fender_z - 0.42),
                    Vec3::new(ta, 0.98, fender_z - 0.42),
                ];
                Self::push_tapered_prism(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    arch_bot,
                    arch_top,
                    [
                        slot_body,
                        slot_body,
                        slot_body,
                        slot_body,
                        slot_body,
                        slot_underbody,
                    ],
                );
                Self::push_box_part(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    Vec3::new(fender_side * 0.92, 0.44, fender_z),
                    Vec3::new(0.28, 0.56, 0.88),
                    slot_underbody,
                );
            }
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(fender_side * 1.02, 1.02, -0.46),
                Vec3::new(0.20, 0.09, 0.16),
                slot_carbon,
            );
        }
        let cabin_bot: [Vec3; 4] = [
            Vec3::new(-0.92, 0.96, 1.56),
            Vec3::new(0.92, 0.96, 1.56),
            Vec3::new(0.90, 0.88, -0.82),
            Vec3::new(-0.90, 0.88, -0.82),
        ];
        let cabin_top: [Vec3; 4] = [
            Vec3::new(-0.68, 1.48, 0.74),
            Vec3::new(0.68, 1.48, 0.74),
            Vec3::new(0.68, 1.45, -0.14),
            Vec3::new(-0.68, 1.45, -0.14),
        ];
        Self::push_tapered_prism(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            cabin_bot,
            cabin_top,
            [
                slot_glass,
                slot_glass,
                slot_glass,
                slot_glass,
                slot_body,
                slot_underbody,
            ],
        );
        let roof_bot: [Vec3; 4] = [
            Vec3::new(-0.66, 1.488, 0.75),
            Vec3::new(0.66, 1.488, 0.75),
            Vec3::new(0.66, 1.458, -0.15),
            Vec3::new(-0.66, 1.458, -0.15),
        ];
        let roof_top: [Vec3; 4] = [
            Vec3::new(-0.56, 1.545, 0.65),
            Vec3::new(0.56, 1.545, 0.65),
            Vec3::new(0.56, 1.525, -0.05),
            Vec3::new(-0.56, 1.525, -0.05),
        ];
        Self::push_tapered_prism(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            roof_bot,
            roof_top,
            [slot_body; 6],
        );
        Self::push_box_part(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            Vec3::new(0.0, 0.78, 2.34),
            Vec3::new(1.94, 0.11, 0.08),
            slot_taillight,
        );
        for tail_side in [-1.0_f32, 1.0_f32] {
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(tail_side * 0.76, 0.78, 2.36),
                Vec3::new(0.42, 0.17, 0.08),
                slot_taillight,
            );
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(tail_side * 0.72, 0.56, -2.35),
                Vec3::new(0.42, 0.13, 0.10),
                slot_headlight,
            );
        }
        Self::push_box_part(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            Vec3::new(0.0, 0.42, -2.36),
            Vec3::new(1.26, 0.18, 0.08),
            slot_carbon,
        );
        Self::push_box_part(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            Vec3::new(0.0, 0.30, 2.32),
            Vec3::new(1.74, 0.24, 0.24),
            slot_carbon,
        );
        for fin_x in [-0.54_f32, -0.18_f32, 0.18_f32, 0.54_f32] {
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(fin_x, 0.28, 2.40),
                Vec3::new(0.06, 0.22, 0.16),
                slot_carbon,
            );
        }
        for pipe_x in [-0.74_f32, -0.56_f32, 0.56_f32, 0.74_f32] {
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(pipe_x, 0.32, 2.40),
                Vec3::new(0.11, 0.11, 0.14),
                slot_chrome,
            );
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(pipe_x, 0.32, 2.46),
                Vec3::new(0.06, 0.06, 0.04),
                slot_amber,
            );
        }
        Self::push_box_part(
            &mut vertices,
            &mut indices,
            &mut tri_materials,
            Vec3::new(0.0, 1.29, 2.12),
            Vec3::new(2.04, 0.06, 0.38),
            slot_carbon,
        );
        for wing_side in [-1.0_f32, 1.0_f32] {
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(wing_side * 1.02, 1.28, 2.12),
                Vec3::new(0.05, 0.14, 0.42),
                slot_carbon,
            );
            Self::push_box_part(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(wing_side * 0.56, 1.14, 2.06),
                Vec3::new(0.05, 0.28, 0.18),
                slot_carbon,
            );
        }
        let wheel_specs: [(f32, f32, f32, f32, f32); 4] = [
            (-1.04, -1.42, 0.35, 0.24, 0.34),
            (1.04, -1.42, 0.35, 0.24, 0.34),
            (-1.06, 1.44, 0.37, 0.25, 0.44),
            (1.06, 1.44, 0.37, 0.25, 0.44),
        ];
        for (wheel_x, wheel_z, tire_r, rim_r, tire_w) in wheel_specs.into_iter() {
            Self::push_wheel_assembly(
                &mut vertices,
                &mut indices,
                &mut tri_materials,
                Vec3::new(wheel_x, tire_r, wheel_z),
                (tire_r, rim_r, tire_w),
                (slot_tire, slot_chrome),
            );
        }
        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, material);
        mesh.set_sub_materials(sub_materials);
        mesh.set_tri_materials(tri_materials);
        mesh.set_is_closed(true);
        mesh
    }

    /// Builds an instanced Vice Boulevard coastal palm tree with a gracefully leaning segmented trunk and seven arching multi-segment tropical fronds.
    ///
    /// # Arguments
    ///
    /// - `&str` - Asset name.
    ///
    /// # Returns
    ///
    /// - `Self` - Multi-material palm tree mesh (`slot 0` warm bark trunk, `slot 1` emerald tropical fronds).
    #[must_use]
    pub fn palm_tree(name: &str) -> Self {
        let bark_mat: PbrMaterial = PbrMaterial::dielectric(Color::hex(0x4E392B), 0.88);
        let frond_top_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x227848), 0.05, 0.56, 0.08);
        let frond_under_mat: PbrMaterial = PbrMaterial::pbr(Color::hex(0x134A2D), 0.04, 0.68, 0.05);
        let sub_materials: Vec<PbrMaterial> = vec![frond_top_mat, frond_under_mat];
        let mut vertices: Vec<Vertex3D> = Vec::with_capacity(520);
        let mut indices: Vec<[u32; 3]> = Vec::with_capacity(260);
        let mut tri_materials: Vec<u16> = Vec::with_capacity(260);
        let ring_specs: [(f32, f32, f32, f32); 5] = [
            (0.0, 0.0, 0.0, 0.30),
            (1.9, 0.14, 0.05, 0.25),
            (3.9, 0.32, 0.08, 0.21),
            (5.8, 0.44, 0.06, 0.17),
            (7.5, 0.48, 0.02, 0.14),
        ];
        let trunk_step: f32 = (2.0 * PI) / (MESH_PALM_TRUNK_SEGMENTS as f32);
        for seg_idx in 0..4usize {
            let (y0, ox0, oz0, r0): (f32, f32, f32, f32) = ring_specs[seg_idx];
            let (y1, ox1, oz1, r1): (f32, f32, f32, f32) = ring_specs[seg_idx + 1];
            for side_idx in 0..MESH_PALM_TRUNK_SEGMENTS {
                let a0: f32 = (side_idx as f32) * trunk_step;
                let a1: f32 = ((side_idx + 1) as f32) * trunk_step;
                let (s0, c0): (f32, f32) = a0.sin_cos();
                let (s1, c1): (f32, f32) = a1.sin_cos();
                let p0: Vec3 = Vec3::new(ox0 + c0 * r0, y0, oz0 + s0 * r0);
                let p1: Vec3 = Vec3::new(ox0 + c1 * r0, y0, oz0 + s1 * r0);
                let p2: Vec3 = Vec3::new(ox1 + c1 * r1, y1, oz1 + s1 * r1);
                let p3: Vec3 = Vec3::new(ox1 + c0 * r1, y1, oz1 + s0 * r1);
                Self::push_flat_quad(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    [p0, p1, p2, p3],
                    0,
                );
            }
        }
        let crown: Vec3 = Vec3::new(0.48, 7.45, 0.02);
        let frond_step: f32 = (2.0 * PI) / (MESH_PALM_FROND_COUNT as f32);
        for tier_idx in 0..2usize {
            let tier_count: usize = if tier_idx == 0 {
                MESH_PALM_FROND_COUNT
            } else {
                5
            };
            let tier_step: f32 = if tier_idx == 0 {
                frond_step
            } else {
                (2.0 * PI) / 5.0
            };
            let tier_yaw_off: f32 = if tier_idx == 0 { 0.25 } else { 0.62 };
            let tier_origin: Vec3 = crown.add(Vec3::new(0.0, (tier_idx as f32) * 0.22, 0.0));
            for frond_idx in 0..tier_count {
                let yaw: f32 = (frond_idx as f32) * tier_step + tier_yaw_off;
                let (sy, cy): (f32, f32) = yaw.sin_cos();
                let dir: Vec3 = Vec3::new(cy, 0.0, sy);
                let right: Vec3 = Vec3::new(-sy, 0.0, cy);
                let reach: f32 = if tier_idx == 0 {
                    if frond_idx % 2 == 0 { 2.85 } else { 2.45 }
                } else {
                    1.85
                };
                let lift: f32 = if tier_idx == 0 { 0.48 } else { 0.92 };
                let drop_tip: f32 = if tier_idx == 0 { -1.18 } else { -0.18 };
                let p_mid: Vec3 = tier_origin
                    .add(dir.scale(reach * 0.44))
                    .add(Vec3::new(0.0, lift, 0.0));
                let p_arch: Vec3 = tier_origin.add(dir.scale(reach * 0.78)).add(Vec3::new(
                    0.0,
                    lift * 0.15 - 0.12,
                    0.0,
                ));
                let p_tip: Vec3 = tier_origin
                    .add(dir.scale(reach))
                    .add(Vec3::new(0.0, drop_tip, 0.0));
                let w_mid: Vec3 = right.scale(if tier_idx == 0 { 0.34 } else { 0.26 });
                let w_arch: Vec3 = right.scale(if tier_idx == 0 { 0.24 } else { 0.18 });
                let sag_mid: Vec3 = Vec3::new(0.0, -0.16, 0.0);
                let sag_arch: Vec3 = Vec3::new(0.0, -0.20, 0.0);
                let mid_l: Vec3 = p_mid.sub(w_mid).add(sag_mid);
                let mid_r: Vec3 = p_mid.add(w_mid).add(sag_mid);
                let arch_l: Vec3 = p_arch.sub(w_arch).add(sag_arch);
                let arch_r: Vec3 = p_arch.add(w_arch).add(sag_arch);
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (tier_origin, p_mid, mid_l),
                    1,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (tier_origin, mid_r, p_mid),
                    1,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (tier_origin, mid_l, p_mid),
                    2,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (tier_origin, p_mid, mid_r),
                    2,
                );
                Self::push_flat_quad(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    [mid_l, p_mid, p_arch, arch_l],
                    1,
                );
                Self::push_flat_quad(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    [p_mid, mid_r, arch_r, p_arch],
                    1,
                );
                Self::push_flat_quad(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    [arch_l, p_arch, p_mid, mid_l],
                    2,
                );
                Self::push_flat_quad(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    [p_arch, arch_r, mid_r, p_mid],
                    2,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (arch_l, p_arch, p_tip),
                    1,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (p_arch, arch_r, p_tip),
                    1,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (p_arch, arch_l, p_tip),
                    2,
                );
                Self::push_flat_tri(
                    &mut vertices,
                    &mut indices,
                    &mut tri_materials,
                    (arch_r, p_arch, p_tip),
                    2,
                );
            }
        }
        let mut mesh: Self = Self::from_parts(name.to_string(), vertices, indices, bark_mat);
        mesh.set_sub_materials(sub_materials);
        mesh.set_tri_materials(tri_materials);
        mesh.set_is_closed(false);
        mesh
    }

    /// Builds a box mesh from a fluent `BoxMeshDesc`.
    ///
    /// # Arguments
    ///
    /// - `&BoxMeshDesc` - Box mesh descriptor.
    ///
    /// # Returns
    ///
    /// - `Self` - Indexed 12-triangle box mesh.
    #[must_use]
    pub fn from_box_desc(desc: &BoxMeshDesc) -> Self {
        let size: Vec3 = desc.get_size();
        Self::box_mesh(
            desc.get_name(),
            size.get_x(),
            size.get_y(),
            size.get_z(),
            desc.get_ground_pivot(),
            desc.get_material(),
        )
    }

    /// Builds a subdivided ground plane from a fluent `GroundPlaneDesc`.
    ///
    /// # Arguments
    ///
    /// - `&GroundPlaneDesc` - Ground plane descriptor.
    ///
    /// # Returns
    ///
    /// - `Self` - Subdivided ground plane mesh.
    #[must_use]
    pub fn from_ground_desc(desc: &GroundPlaneDesc) -> Self {
        Self::ground_plane(
            desc.get_name(),
            desc.get_width(),
            desc.get_depth(),
            desc.get_subdivisions(),
            desc.get_material(),
        )
    }

    /// Builds a simplified proxy mesh enclosing this mesh's axis-aligned bounding box for distant LOD tiers.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Source mesh reference.
    /// - `&str` - LOD suffix label.
    ///
    /// # Returns
    ///
    /// - `Self` - Lightweight 12-triangle LOD proxy mesh.
    #[must_use]
    pub fn build_lod_proxy(&self, suffix: &str) -> Self {
        let blue_val: AxisAlignedBox3D = self.get_bounds();
        let size: Vec3 = blue_val.get_max().sub(blue_val.get_min());
        let center: Vec3 = blue_val.center();
        let mut proxy: Self = Self::box_mesh(
            &format!("{}_{suffix}", self.get_name()),
            size.get_x().max(0.2),
            size.get_y().max(0.2),
            size.get_z().max(0.2),
            false,
            self.get_material(),
        );
        for item_val in proxy.get_mut_vertices().iter_mut() {
            item_val.set_position(item_val.get_position().add(center));
        }
        proxy.set_bounds(blue_val);
        let meshlets: Vec<Meshlet3D> =
            Self::build_meshlets_from_parts(proxy.get_vertices(), proxy.get_indices());
        proxy.set_meshlets(meshlets);
        proxy
    }

    /// Produces a mid-detail decimated mesh by retaining dominant triangles while preserving bounding silhouette.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Source mesh reference.
    /// - `&str` - LOD suffix label.
    ///
    /// # Returns
    ///
    /// - `Self` - Decimated intermediate LOD mesh.
    #[must_use]
    pub fn build_mid_lod(&self, suffix: &str) -> Self {
        let verts: &[Vertex3D] = self.get_vertices().as_slice();
        let tris: &[[u32; 3]] = self.get_indices().as_slice();
        if tris.len() <= 24 {
            return self.build_lod_proxy(suffix);
        }
        let mut scored: Vec<(f32, [u32; 3], u16)> = Vec::with_capacity(tris.len());
        let default_mat: PbrMaterial = self.get_material();
        for (tri_idx, tri) in tris.iter().copied().enumerate() {
            let (i0, i1, i2): (usize, usize, usize) =
                (tri[0] as usize, tri[1] as usize, tri[2] as usize);
            if i0 < verts.len() && i1 < verts.len() && i2 < verts.len() {
                let p0: Vec3 = verts[i0].get_position();
                let p1: Vec3 = verts[i1].get_position();
                let p2: Vec3 = verts[i2].get_position();
                let area2: f32 = p1.sub(p0).cross(p2.sub(p0)).length_sq();
                let (resolved_mat, slot): (PbrMaterial, u16) =
                    self.resolve_triangle_material(tri_idx, default_mat);
                let emissive_boost: f32 = if resolved_mat.get_emissive().length_sq() > 0.25 {
                    8.0
                } else {
                    1.0
                };
                scored.push((area2 * emissive_boost, tri, slot));
            }
        }
        scored.sort_unstable_by(
            |alpha_val: &(f32, [u32; 3], u16), blue_val: &(f32, [u32; 3], u16)| {
                blue_val.0.total_cmp(&alpha_val.0)
            },
        );
        let keep: usize = (scored.len() / 2).max(12);
        let mut reduced: Vec<[u32; 3]> = Vec::with_capacity(keep);
        let mut reduced_slots: Vec<u16> = if self.get_tri_materials().is_empty() {
            Vec::new()
        } else {
            Vec::with_capacity(keep)
        };
        for (_, tri, slot) in scored.into_iter().take(keep) {
            reduced.push(tri);
            if !self.get_tri_materials().is_empty() {
                reduced_slots.push(slot);
            }
        }
        let mut mid_mesh: Self = Self::from_parts(
            format!("{}_{suffix}", self.get_name()),
            self.get_vertices().clone(),
            reduced,
            self.get_material(),
        );
        if !reduced_slots.is_empty() {
            mid_mesh.set_sub_materials(self.get_sub_materials().clone());
            mid_mesh.set_tri_materials(reduced_slots);
        }
        mid_mesh.set_is_closed(self.get_is_closed());
        mid_mesh
    }
}

/// Multi-level continuous LOD chain creation and screen-error selection for `MeshLodChain`.
impl MeshLodChain {
    /// Builds a continuous 3-tier Nanite-style LOD chain (`LOD0` full -> `LOD1` mid -> `LOD2` proxy) automatically.
    ///
    /// # Arguments
    ///
    /// - `Mesh3D` - Full-resolution `LOD0` mesh.
    ///
    /// # Returns
    ///
    /// - `Self` - Ready LOD chain.
    #[must_use]
    pub fn from_mesh(mesh: Mesh3D) -> Self {
        let tri_count: usize = mesh.get_indices().len();
        if tri_count > 32 {
            let lod1: Mesh3D = mesh.build_mid_lod(MESH_LOD1_SUFFIX);
            let lod2: Mesh3D = mesh.build_lod_proxy(MESH_LOD2_SUFFIX);
            Self {
                levels: vec![mesh, lod1, lod2],
            }
        } else if tri_count > 16 {
            let lod1: Mesh3D = mesh.build_lod_proxy(MESH_LOD1_SUFFIX);
            Self {
                levels: vec![mesh, lod1],
            }
        } else {
            let clone_lod1: Mesh3D = mesh.clone();
            Self {
                levels: vec![mesh, clone_lod1],
            }
        }
    }

    /// Selects the appropriate `Mesh3D` detail level for `distance` and `lod_bias`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - LOD chain reference.
    /// - `f32` - Camera-to-object distance in meters.
    /// - `f32` - Quality LOD bias multiplier.
    ///
    /// # Returns
    ///
    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
    #[must_use]
    pub fn select(&self, distance: f32, lod_bias: f32) -> (&Mesh3D, usize) {
        let levels: &[Mesh3D] = self.get_levels().as_slice();
        let effective_dist: f32 = distance * lod_bias.max(0.25);
        if levels.len() > 2 && effective_dist > 135.0 {
            (&levels[2], 2)
        } else if levels.len() > 1 && effective_dist > 78.0 {
            (&levels[1], 1)
        } else {
            (&levels[0], 0)
        }
    }

    /// Nanite-style continuous LOD selection driven by projected screen-space pixel coverage.
    ///
    /// # Arguments
    ///
    /// - `&Self` - LOD chain reference.
    /// - `f32` - Camera-to-object distance in meters.
    /// - `f32` - World-space bounding sphere radius in meters.
    /// - `f32` - Projected viewport focal length in pixels (`height / (2 * tan(fov/2))`).
    /// - `f32` - Quality LOD bias multiplier (`< 1.0` higher detail, `> 1.0` aggressive simplification).
    ///
    /// # Returns
    ///
    /// - `(&Mesh3D, usize)` - Selected mesh reference and its LOD tier index.
    #[must_use]
    pub fn select_screen_error(
        &self,
        distance: f32,
        bounds_radius: f32,
        focal_px: f32,
        lod_bias: f32,
    ) -> (&Mesh3D, usize) {
        let levels: &[Mesh3D] = self.get_levels().as_slice();
        let safe_dist: f32 = distance.max(0.5);
        let projected_px: f32 =
            (bounds_radius.max(0.2) * focal_px) / (safe_dist * lod_bias.max(0.25));
        if levels.len() > 2 && projected_px < 22.0 {
            (&levels[2], 2)
        } else if levels.len() > 1 && projected_px < 58.0 {
            (&levels[1], 1)
        } else {
            (&levels[0], 0)
        }
    }
}

/// Native Wavefront `.obj`, Khronos glTF 2.0 `.gltf`/`.glb`, and baked binary model importers for `ModelImporter3D`.
impl ModelImporter3D {
    /// Imports a 3D model from text source in the specified `ModelFormat` and generates LOD chains.
    ///
    /// # Arguments
    ///
    /// - `ModelFormat` - Interchange format (`Obj` or `GltfJson`).
    /// - `&str` - Raw `.obj` or `.gltf` text content.
    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
    ///
    /// # Returns
    ///
    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error diagnostic.
    pub fn import(
        format: ModelFormat,
        source: &str,
        fallback_material: PbrMaterial,
    ) -> Result<ImportedModel3D, String> {
        match format {
            ModelFormat::Obj => Self::parse_obj(source, fallback_material),
            ModelFormat::GltfJson => Self::parse_gltf_json(source, fallback_material),
            ModelFormat::GlbBinary | ModelFormat::Euv3dBinary | ModelFormat::BlendInspect => {
                Err(ERR_TEXT_FORMAT_UNSUPPORTED.to_string())
            }
        }
    }

    /// Imports a 3D model from raw binary or UTF-8 bytes in `Obj`, `GltfJson`, or `GlbBinary` format.
    ///
    /// # Arguments
    ///
    /// - `ModelFormat` - Source interchange format.
    /// - `&[u8]` - Raw file bytes.
    /// - `PbrMaterial` - Fallback PBR material when source omits material definitions.
    ///
    /// # Returns
    ///
    /// - `Result<ImportedModel3D, String>` - Imported model bundle or parse error.
    pub fn import_bytes(
        format: ModelFormat,
        bytes: &[u8],
        fallback_material: PbrMaterial,
    ) -> Result<ImportedModel3D, String> {
        match format {
            ModelFormat::Obj => {
                let text: &str = from_utf8(bytes)
                    .ok()
                    .ok_or_else(|| ERR_OBJ_EMPTY.to_string())?;
                Self::parse_obj(text, fallback_material)
            }
            ModelFormat::GltfJson => {
                let text: &str = from_utf8(bytes)
                    .ok()
                    .ok_or_else(|| ERR_GLTF_EMPTY.to_string())?;
                Self::parse_gltf_json(text, fallback_material)
            }
            ModelFormat::GlbBinary => {
                let scene: ImportedScene3D = parse_glb_bytes(bytes)?;
                if scene.get_meshes().is_empty() {
                    return Err(ERR_GLTF_EMPTY.to_string());
                }
                let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GlbBinary);
                if scene.get_materials().is_empty() {
                    for chain in model.get_mut_meshes().iter_mut() {
                        for lvl in chain.get_mut_levels().iter_mut() {
                            lvl.set_material(fallback_material);
                        }
                    }
                }
                Ok(model)
            }
            ModelFormat::Euv3dBinary => {
                let bundle: BakedAssetBundle3D = Euv3dPackage::decode_bytes(bytes)?;
                if bundle.get_lod_chains().is_empty() {
                    return Err(ERR_GLTF_EMPTY.to_string());
                }
                let total_vertices: usize = bundle
                    .get_lod_chains()
                    .iter()
                    .filter_map(|c: &MeshLodChain| c.get_levels().first())
                    .map(|m: &Mesh3D| m.get_vertices().len())
                    .sum();
                let total_triangles: usize = bundle
                    .get_lod_chains()
                    .iter()
                    .filter_map(|c: &MeshLodChain| c.get_levels().first())
                    .map(|m: &Mesh3D| m.get_indices().len())
                    .sum();
                Ok(ImportedModel3D {
                    name: bundle.get_scene().get_name().clone(),
                    format: ModelFormat::Euv3dBinary,
                    meshes: bundle.get_lod_chains().clone(),
                    total_vertices,
                    total_triangles,
                })
            }
            ModelFormat::BlendInspect => Err(ERR_BINARY_FORMAT_UNSUPPORTED.to_string()),
        }
    }

    /// Resolves a signed 1-based Wavefront OBJ index (positive or negative relative to `len`) into a 0-based index.
    ///
    /// # Arguments
    ///
    /// - `i32` - Signed 1-based OBJ index.
    /// - `usize` - Current length of the corresponding attribute array.
    ///
    /// # Returns
    ///
    /// - `Option<usize>` - Resolved 0-based index if in bounds.
    #[must_use]
    fn resolve_obj_index(raw: i32, len: usize) -> Option<usize> {
        if raw > 0 {
            let idx: usize = (raw - 1) as usize;
            if idx < len { Some(idx) } else { None }
        } else if raw < 0 {
            let idx: isize = (len as isize) + (raw as isize);
            if idx >= 0 && (idx as usize) < len {
                Some(idx as usize)
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Parses a Wavefront `.mtl` material library into a named `PbrMaterial` map (`Kd`, `Ke`, `Ns`, `Pm`, `Pr`).
    ///
    /// # Arguments
    ///
    /// - `&str` - Raw `.mtl` ASCII text.
    /// - `PbrMaterial` - Base fallback material template.
    ///
    /// # Returns
    ///
    /// - `HashMap<String, PbrMaterial>` - Parsed material table keyed by `newmtl` identifier.
    #[must_use]
    pub fn parse_mtl(mtl_source: &str, fallback: PbrMaterial) -> HashMap<String, PbrMaterial> {
        let mut table: HashMap<String, PbrMaterial> = HashMap::new();
        let mut active_name: Option<String> = None;
        let mut active_mat: PbrMaterial = fallback;
        for raw_line in mtl_source.lines() {
            let line: &str = raw_line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.is_empty() {
                continue;
            }
            if parts[0] == MTL_DIRECTIVE_NEWMTL && parts.len() >= 2 {
                if let Some(prev_name) = active_name.take() {
                    let _: Option<PbrMaterial> = table.insert(prev_name, active_mat);
                }
                active_name = Some(parts[1].to_string());
                active_mat = fallback;
            } else if parts[0] == "Kd" && parts.len() >= 4 {
                let r: f32 = parts[1].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
                let g: f32 = parts[2].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
                let b: f32 = parts[3].parse::<f32>().unwrap_or(0.8).clamp(0.0, 1.0);
                active_mat.set_base_color(Vec3::new(r, g, b));
            } else if parts[0] == "Ke" && parts.len() >= 4 {
                let r: f32 = parts[1].parse::<f32>().unwrap_or(0.0).max(0.0);
                let g: f32 = parts[2].parse::<f32>().unwrap_or(0.0).max(0.0);
                let b: f32 = parts[3].parse::<f32>().unwrap_or(0.0).max(0.0);
                active_mat.set_emissive(Vec3::new(r, g, b));
            } else if parts[0] == "Pm" && parts.len() >= 2 {
                let metal: f32 = parts[1].parse::<f32>().unwrap_or(0.0).clamp(0.0, 1.0);
                active_mat.set_metallic(metal);
            } else if parts[0] == "Pr" && parts.len() >= 2 {
                let rough: f32 = parts[1].parse::<f32>().unwrap_or(0.5).clamp(0.04, 1.0);
                active_mat.set_roughness(rough);
                active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
            } else if parts[0] == "Ns" && parts.len() >= 2 {
                let ns: f32 = parts[1].parse::<f32>().unwrap_or(64.0).clamp(0.0, 1000.0);
                let rough: f32 = (1.0 - (ns / 1000.0).sqrt()).clamp(0.04, 1.0);
                active_mat.set_roughness(rough);
                active_mat.set_reflectivity((1.0 - rough).clamp(0.05, 0.95));
            }
        }
        if let Some(last_name) = active_name {
            let _: Option<PbrMaterial> = table.insert(last_name, active_mat);
        }
        table
    }

    /// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f`, `mtllib`, `usemtl`) with optional `.mtl` library, negative index support, vertex deduplication, and Lengyel tangents.
    ///
    /// # Arguments
    ///
    /// - `&str` - Raw `.obj` ASCII text.
    /// - `Option<&str>` - Optional companion `.mtl` ASCII text.
    /// - `PbrMaterial` - Fallback PBR material.
    ///
    /// # Returns
    ///
    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
    pub fn parse_obj_with_mtl(
        source: &str,
        mtl_source: Option<&str>,
        material: PbrMaterial,
    ) -> Result<ImportedModel3D, String> {
        let mtl_table: HashMap<String, PbrMaterial> = mtl_source
            .map(|text: &str| Self::parse_mtl(text, material))
            .unwrap_or_default();
        let mut positions: Vec<Vec3> = Vec::new();
        let mut uvs: Vec<[f32; 2]> = Vec::new();
        let mut normals: Vec<Vec3> = Vec::new();
        let mut vertices: Vec<Vertex3D> = Vec::new();
        let mut indices: Vec<[u32; 3]> = Vec::new();
        let mut dedup: HashMap<(usize, Option<usize>, Option<usize>), u32> = HashMap::new();
        let mut sub_materials: Vec<PbrMaterial> = Vec::new();
        let mut sub_mat_slots: HashMap<String, u16> = HashMap::new();
        let mut tri_materials: Vec<u16> = Vec::new();
        let mut active_slot: u16 = 0;
        let mut model_name: String = MESH_OBJ_DEFAULT_NAME.to_string();
        let mut saw_any_uv: bool = false;
        let mut saw_any_normal: bool = false;
        for raw_line in source.lines() {
            let line: &str = raw_line.trim();
            if line.is_empty() || line.starts_with('#') {
                continue;
            }
            let parts: Vec<&str> = line.split_whitespace().collect();
            if parts.is_empty() {
                continue;
            }
            match parts[0] {
                "o" | "g" if parts.len() >= 2 => {
                    model_name = parts[1].to_string();
                }
                token if token == OBJ_DIRECTIVE_MTLLIB => {}
                token if token == OBJ_DIRECTIVE_USEMTL && parts.len() >= 2 => {
                    let mat_name: &str = parts[1];
                    if let Some(&slot) = sub_mat_slots.get(mat_name) {
                        active_slot = slot;
                    } else if let Some(&parsed_mat) = mtl_table.get(mat_name) {
                        sub_materials.push(parsed_mat);
                        let new_slot: u16 = sub_materials.len() as u16;
                        let _: Option<u16> = sub_mat_slots.insert(mat_name.to_string(), new_slot);
                        active_slot = new_slot;
                    } else {
                        active_slot = 0;
                    }
                }
                "v" if parts.len() >= 4 => {
                    let pos_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
                    let pos_y: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
                    let pos_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
                    positions.push(Vec3::new(pos_x, pos_y, pos_z));
                }
                "vt" if parts.len() >= 3 => {
                    let coord_u: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
                    let coord_v: f32 = parts[2].parse::<f32>().unwrap_or(0.0);
                    uvs.push([coord_u, coord_v]);
                    saw_any_uv = true;
                }
                "vn" if parts.len() >= 4 => {
                    let coord_x: f32 = parts[1].parse::<f32>().unwrap_or(0.0);
                    let coord_y: f32 = parts[2].parse::<f32>().unwrap_or(1.0);
                    let coord_z: f32 = parts[3].parse::<f32>().unwrap_or(0.0);
                    normals.push(Vec3::new(coord_x, coord_y, coord_z).normalize());
                    saw_any_normal = true;
                }
                "f" if parts.len() >= 4 => {
                    let mut face_refs: Vec<(usize, Option<usize>, Option<usize>)> =
                        Vec::with_capacity(parts.len() - 1);
                    for token in parts.iter().skip(1) {
                        let comps: Vec<&str> = token.split('/').collect();
                        let v_raw: i32 = comps
                            .first()
                            .and_then(|s: &&str| s.parse::<i32>().ok())
                            .unwrap_or(0);
                        let Some(v_idx) = Self::resolve_obj_index(v_raw, positions.len()) else {
                            continue;
                        };
                        let vt_idx: Option<usize> = comps
                            .get(1)
                            .and_then(|s: &&str| s.parse::<i32>().ok())
                            .and_then(|raw: i32| Self::resolve_obj_index(raw, uvs.len()));
                        let vn_idx: Option<usize> = comps
                            .get(2)
                            .and_then(|s: &&str| s.parse::<i32>().ok())
                            .and_then(|raw: i32| Self::resolve_obj_index(raw, normals.len()));
                        face_refs.push((v_idx, vt_idx, vn_idx));
                    }
                    if face_refs.len() >= 3 {
                        for entry_index in 1..(face_refs.len() - 1) {
                            let tri_keys: [(usize, Option<usize>, Option<usize>); 3] = [
                                face_refs[0],
                                face_refs[entry_index],
                                face_refs[entry_index + 1],
                            ];
                            let p0: Vec3 = positions[tri_keys[0].0];
                            let p1: Vec3 = positions[tri_keys[1].0];
                            let p2: Vec3 = positions[tri_keys[2].0];
                            let face_n: Vec3 = p1.sub(p0).cross(p2.sub(p0)).normalize();
                            let mut out_tri: [u32; 3] = [0u32; 3];
                            for lane in 0..3usize {
                                let key: (usize, Option<usize>, Option<usize>) = tri_keys[lane];
                                let vert_id: u32 = if key.2.is_some() {
                                    if let Some(&existing) = dedup.get(&key) {
                                        existing
                                    } else {
                                        let id: u32 = vertices.len() as u32;
                                        let mut v: Vertex3D = Vertex3D::new(
                                            positions[key.0],
                                            key.2
                                                .and_then(|ni: usize| normals.get(ni).copied())
                                                .unwrap_or(face_n),
                                        );
                                        if let Some(ti) = key.1
                                            && let Some(&uv_pair) = uvs.get(ti)
                                        {
                                            v.set_uv0(uv_pair);
                                            v.set_flags(1);
                                        }
                                        vertices.push(v);
                                        let _: Option<u32> = dedup.insert(key, id);
                                        id
                                    }
                                } else {
                                    let id: u32 = vertices.len() as u32;
                                    let mut v: Vertex3D = Vertex3D::new(positions[key.0], face_n);
                                    if let Some(ti) = key.1
                                        && let Some(&uv_pair) = uvs.get(ti)
                                    {
                                        v.set_uv0(uv_pair);
                                        v.set_flags(1);
                                    }
                                    vertices.push(v);
                                    id
                                };
                                out_tri[lane] = vert_id;
                            }
                            indices.push(out_tri);
                            if !sub_materials.is_empty() {
                                tri_materials.push(active_slot);
                            }
                        }
                    }
                }
                _ => {}
            }
        }
        if indices.is_empty() {
            return Err(ERR_OBJ_EMPTY.to_string());
        }
        let mut mesh: Mesh3D = Mesh3D::from_parts(model_name.clone(), vertices, indices, material);
        if !sub_materials.is_empty() {
            if tri_materials.len() < mesh.get_indices().len() {
                tri_materials.resize(mesh.get_indices().len(), 0);
            }
            mesh.set_sub_materials(sub_materials);
            mesh.set_tri_materials(tri_materials);
        }
        if !saw_any_normal && dedup.len() < mesh.get_vertices().len() {
            mesh.compute_smooth_normals();
        }
        if saw_any_uv {
            mesh.compute_lengyel_tangents();
        }
        let total_vertices: usize = mesh.get_vertices().len();
        let total_triangles: usize = mesh.get_indices().len();
        Ok(ImportedModel3D {
            name: model_name,
            format: ModelFormat::Obj,
            meshes: vec![MeshLodChain::from_mesh(mesh)],
            total_vertices,
            total_triangles,
        })
    }

    /// Parses a Wavefront `.obj` mesh (`o`, `g`, `v`, `vt`, `vn`, `f` with n-gon fan triangulation, negative indices, and auto-normals).
    ///
    /// # Arguments
    ///
    /// - `&str` - Raw `.obj` ASCII text.
    /// - `PbrMaterial` - Material assigned to the parsed mesh.
    ///
    /// # Returns
    ///
    /// - `Result<ImportedModel3D, String>` - Parsed model or error string.
    pub fn parse_obj(source: &str, material: PbrMaterial) -> Result<ImportedModel3D, String> {
        Self::parse_obj_with_mtl(source, None, material)
    }

    /// Parses a Khronos glTF 2.0 JSON asset (full buffers/bufferViews/accessors/Principled BSDF plus legacy inline geometry fallback).
    ///
    /// # Arguments
    ///
    /// - `&str` - Raw `.gltf` JSON string.
    /// - `PbrMaterial` - Fallback PBR material when JSON omits `materials`.
    ///
    /// # Returns
    ///
    /// - `Result<ImportedModel3D, String>` - Parsed model bundle or validation error.
    pub fn parse_gltf_json(
        source: &str,
        fallback_material: PbrMaterial,
    ) -> Result<ImportedModel3D, String> {
        let scene: ImportedScene3D = parse_gltf_document(source, None, None)?;
        if scene.get_meshes().is_empty() {
            return Err(ERR_GLTF_EMPTY.to_string());
        }
        let mut model: ImportedModel3D = scene.to_imported_model(ModelFormat::GltfJson);
        if scene.get_materials().is_empty() {
            for chain in model.get_mut_meshes().iter_mut() {
                for lvl in chain.get_mut_levels().iter_mut() {
                    lvl.set_material(fallback_material);
                }
            }
        }
        Ok(model)
    }
}