euv-core 0.57.0

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
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
use super::*;

/// Computes the shortest-arc unit quaternion rotating unit vector `from` onto unit vector `to`.
///
/// # Arguments
///
/// - `Vec3` - Starting unit direction vector.
/// - `Vec3` - Destination unit direction vector.
///
/// # Returns
///
/// - `Quat` - Shortest-arc unit quaternion rotation.
#[must_use]
pub(crate) fn quat_between_unit_vectors(from: Vec3, to: Vec3) -> Quat {
    let f: Vec3 = if from.length_sq() > 1.0e-8 {
        from.normalize()
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    };
    let t: Vec3 = if to.length_sq() > 1.0e-8 {
        to.normalize()
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    };
    let dot_val: f32 = f.dot(t).clamp(-1.0, 1.0);
    if dot_val > 0.9999 {
        return Quat::identity();
    }
    if dot_val < -0.9999 {
        let ortho: Vec3 = if f.get_x().abs() < 0.9 {
            Vec3::new(1.0, 0.0, 0.0)
        } else {
            Vec3::new(0.0, 0.0, 1.0)
        };
        let axis: Vec3 = f.cross(ortho).normalize();
        return Quat::from_axis_angle(axis, PI);
    }
    let axis: Vec3 = f.cross(t);
    let q: Quat = Quat::from_xyzw(axis.get_x(), axis.get_y(), axis.get_z(), 1.0 + dot_val);
    q.normalize()
}

/// Returns the bone index parent of `bone_idx`, if any.
///
/// # Arguments
///
/// - `usize` - Bone index in `0..JIANLAI_BONE_COUNT`.
///
/// # Returns
///
/// - `Option<usize>` - Parent bone index or `None` for root.
#[must_use]
pub fn jianlai_bone_parent(bone_idx: usize) -> Option<usize> {
    JIANLAI_BONE_PARENTS.get(bone_idx).copied().flatten()
}

/// Computes world-space rest positions for all 27 Jianlai armature bones from `JIANLAI_BONE_LOCAL_REST`.
///
/// # Returns
///
/// - `[Vec3; JIANLAI_BONE_COUNT]` - Bind-pose world-space joint positions in meters.
#[must_use]
pub fn compute_jianlai_rest_world_positions() -> [Vec3; JIANLAI_BONE_COUNT] {
    let mut world_pos: [Vec3; JIANLAI_BONE_COUNT] = [Vec3::zero(); JIANLAI_BONE_COUNT];
    for idx in 0..JIANLAI_BONE_COUNT {
        let local: [f32; 3] = JIANLAI_BONE_LOCAL_REST[idx];
        let offset: Vec3 = Vec3::new(local[0], local[1], local[2]);
        world_pos[idx] = match JIANLAI_BONE_PARENTS[idx] {
            Some(parent_idx) => world_pos[parent_idx].add(offset),
            None => offset,
        };
    }
    world_pos
}

/// Strips degenerate zero-area triangles, recomputes smooth averaged normals, computes Lengyel tangents, and builds meshlets.
///
/// # Arguments
///
/// - `Mesh3D` - Source sculpted mesh.
/// - `&str` - Canonical mesh name.
/// - `PbrMaterial` - Default material assigned to the mesh.
/// - `bool` - Whether the mesh represents a closed outward-wound volume.
///
/// # Returns
///
/// - `Mesh3D` - Clean, non-degenerate mesh with smooth normals, tangents, bounds, and meshlets.
#[must_use]
pub fn finalize_jianlai_mesh(
    mesh: Mesh3D,
    name: &str,
    material: PbrMaterial,
    is_closed: bool,
) -> Mesh3D {
    let verts: Vec<Vertex3D> = mesh.get_vertices().clone();
    let vert_len: usize = verts.len();
    let mut clean_tris: Vec<[u32; 3]> = Vec::with_capacity(mesh.get_indices().len());
    for &[i0, i1, i2] in mesh.get_indices().iter() {
        let u0: usize = i0 as usize;
        let u1: usize = i1 as usize;
        let u2: usize = i2 as usize;
        if u0 >= vert_len || u1 >= vert_len || u2 >= vert_len || u0 == u1 || u1 == u2 || u0 == u2 {
            continue;
        }
        let p0: Vec3 = verts[u0].get_position();
        let p1: Vec3 = verts[u1].get_position();
        let p2: Vec3 = verts[u2].get_position();
        let cross: Vec3 = p1.sub(p0).cross(p2.sub(p0));
        let area2: f32 = cross.length();
        if area2.is_finite() && area2 > JIANLAI_MIN_TRI_DOUBLE_AREA {
            clean_tris.push([i0, i1, i2]);
        }
    }
    let skin_inf: Vec<MeshSkinInfluence3D> = mesh.get_skin_influences().clone();
    let morphs: Vec<MorphTarget3D> = mesh.get_morph_targets().clone();
    let sub_mats: Vec<PbrMaterial> = mesh.get_sub_materials().clone();
    let mut rebuilt: Mesh3D = Mesh3D::from_parts(name.to_string(), verts, clean_tris, material);
    rebuilt.set_is_closed(is_closed);
    if !sub_mats.is_empty() {
        rebuilt.set_sub_materials(sub_mats);
    }
    let smoothed: Mesh3D = recompute_smooth_normals(&rebuilt);
    let mut tangent_ready: Mesh3D = compute_tangents(&smoothed);
    tangent_ready.set_name(name.to_string());
    tangent_ready.set_material(material);
    tangent_ready.set_is_closed(is_closed);
    if skin_inf.len() == tangent_ready.get_vertices().len() {
        tangent_ready.set_skin_influences(skin_inf);
    }
    if !morphs.is_empty() {
        tangent_ready.set_morph_targets(morphs);
    }
    tangent_ready
}

/// Paints a uniform RGBA8 vertex color across every vertex of `mesh` and sets the `COLOR_0` vertex attribute flag.
///
/// # Arguments
///
/// - `&mut Mesh3D` - Target mesh to tint.
/// - `[u8; 4]` - Target UNORM8 RGBA vertex color.
pub(crate) fn tint_mesh_vertices(mesh: &mut Mesh3D, rgba: [u8; 4]) {
    for vert in mesh.get_mut_vertices().iter_mut() {
        vert.set_color0(rgba);
        vert.set_flags(vert.get_flags() | 8);
    }
}

/// Paints a vertical ink-wash gradient across `mesh` vertices from `bottom_rgba` at `y_min` to `top_rgba` at `y_max`.
///
/// # Arguments
///
/// - `&mut Mesh3D` - Target mesh to colorize.
/// - `f32` - Bottom Y coordinate of the gradient ramp.
/// - `f32` - Top Y coordinate of the gradient ramp.
/// - `[u8; 4]` - Bottom RGBA8 color.
/// - `[u8; 4]` - Top RGBA8 color.
pub(crate) fn gradient_tint_mesh_y(
    mesh: &mut Mesh3D,
    y_min: f32,
    y_max: f32,
    bottom_rgba: [u8; 4],
    top_rgba: [u8; 4],
) {
    let span: f32 = (y_max - y_min).max(1.0e-4);
    for vert in mesh.get_mut_vertices().iter_mut() {
        let t: f32 = ((vert.get_position().get_y() - y_min) / span).clamp(0.0, 1.0);
        let quantized: f32 = ((t * 4.0).floor() / 4.0) * 0.45 + t * 0.55;
        let mut out: [u8; 4] = [255; 4];
        for c in 0..4 {
            let a: f32 = f32::from(bottom_rgba[c]);
            let b: f32 = f32::from(top_rgba[c]);
            out[c] = (a + (b - a) * quantized).clamp(0.0, 255.0) as u8;
        }
        vert.set_color0(out);
        vert.set_flags(vert.get_flags() | 8);
    }
}

/// Builds a closed elliptic 3D ring centered at `center` with semi-axes `(rx, rz)` and optional vertical dip/wave.
///
/// # Arguments
///
/// - `Vec3` - Ring center in local space.
/// - `f32` - Semi-axis radius along X.
/// - `f32` - Semi-axis radius along Z.
/// - `usize` - Number of vertices around the ring (`>= 6`).
/// - `f32` - Subtle pleat/fold amplitude modulated around the perimeter.
/// - `f32` - Pleat lobe frequency count.
///
/// # Returns
///
/// - `Vec<Vec3>` - Ordered 3D perimeter points for `loft_profiles`.
#[must_use]
pub(crate) fn build_elliptic_ring(
    center: Vec3,
    rx: f32,
    rz: f32,
    segs: usize,
    pleat_amp: f32,
    pleat_freq: f32,
) -> Vec<Vec3> {
    let count: usize = segs.max(6);
    let mut ring: Vec<Vec3> = Vec::with_capacity(count);
    for i in 0..count {
        let theta: f32 = ((i as f32) / (count as f32)) * TAU;
        let fold: f32 = 1.0 + pleat_amp * (theta * pleat_freq).cos();
        let px: f32 = center.get_x() + rx * fold * theta.cos();
        let pz: f32 = center.get_z() + rz * fold * theta.sin();
        ring.push(Vec3::new(px, center.get_y(), pz));
    }
    ring
}

/// Builds a 2D closed circular/elliptic cross-section profile for `sweep_along_spline`.
///
/// # Arguments
///
/// - `f32` - Horizontal half-width.
/// - `f32` - Vertical half-height.
/// - `usize` - Number of radial vertices (`>= 5`).
///
/// # Returns
///
/// - `Vec<Vec2>` - Counter-clockwise 2D cross-section ring.
#[must_use]
pub(crate) fn build_profile_ellipse_2d(rx: f32, ry: f32, segs: usize) -> Vec<Vec2> {
    let count: usize = segs.max(5);
    let mut pts: Vec<Vec2> = Vec::with_capacity(count);
    for i in 0..count {
        let a: f32 = ((i as f32) / (count as f32)) * TAU;
        pts.push(Vec2::new(rx * a.cos(), ry * a.sin()));
    }
    pts
}

/// Computes an ink-wash deterministic value noise sample in `[0.0, 1.0]` for procedural Xuan-paper textures.
///
/// # Arguments
///
/// - `f32` - Horizontal sample coordinate.
/// - `f32` - Vertical sample coordinate.
/// - `u32` - Seed offset.
///
/// # Returns
///
/// - `f32` - Smoothly interpolated pseudo-noise in `[0.0, 1.0]`.
#[must_use]
pub(crate) fn ink_tex_noise(x: f32, y: f32, seed: u32) -> f32 {
    let ix: i32 = x.floor() as i32;
    let iy: i32 = y.floor() as i32;
    let fx: f32 = x - (ix as f32);
    let fy: f32 = y - (iy as f32);
    let sx: f32 = fx * fx * (3.0 - 2.0 * fx);
    let sy: f32 = fy * fy * (3.0 - 2.0 * fy);
    let hash_pt: fn(i32, i32, u32) -> f32 = |px: i32, py: i32, s: u32| -> f32 {
        let mut h: u32 = (px.wrapping_mul(374_761_393) as u32)
            .wrapping_add(py.wrapping_mul(668_265_263) as u32)
            .wrapping_add(s.wrapping_mul(2_246_822_519));
        h = (h ^ (h >> 13)).wrapping_mul(1_274_126_177);
        ((h ^ (h >> 16)) & 0xFFFF) as f32 / 65_535.0
    };
    let n00: f32 = hash_pt(ix, iy, seed);
    let n10: f32 = hash_pt(ix + 1, iy, seed);
    let n01: f32 = hash_pt(ix, iy + 1, seed);
    let n11: f32 = hash_pt(ix + 1, iy + 1, seed);
    let nx0: f32 = n00 + (n10 - n00) * sx;
    let nx1: f32 = n01 + (n11 - n01) * sx;
    nx0 + (nx1 - nx0) * sy
}

/// Generates a procedural Chinese ink-wash `Texture2D3D` for the Jianlai swordsman robes (Xuan-paper white to cyan-jade ink mountain wash).
///
/// # Returns
///
/// - `Texture2D3D` - Mipmapped 128x128 sRGB robe ink-wash texture.
#[must_use]
pub fn build_jianlai_robe_ink_texture() -> Texture2D3D {
    let sz: u32 = JIANLAI_TEX_SIZE;
    let mut pixels: Vec<u8> = Vec::with_capacity((sz as usize) * (sz as usize) * 4);
    for py in 0..sz {
        let v: f32 = (py as f32) / ((sz - 1) as f32);
        for px in 0..sz {
            let u: f32 = (px as f32) / ((sz - 1) as f32);
            let paper: f32 = ink_tex_noise(u * 18.0, v * 18.0, 11) * 0.08;
            let wave: f32 =
                (u * TAU * 2.0 + ink_tex_noise(u * 5.0, v * 5.0, 23) * 1.4).sin() * 0.09 + 0.32;
            let ink_band: f32 = ((wave - v) * 6.5).clamp(0.0, 1.0);
            let cel_ink: f32 = ((ink_band * 3.0).floor() / 3.0) * 0.6 + ink_band * 0.4;
            let collar_trim: f32 = if (u - 0.5).abs() < 0.045 && v > 0.62 {
                1.0
            } else {
                0.0
            };
            let base_r: f32 = 0.90 - cel_ink * 0.68 - paper - collar_trim * 0.72;
            let base_g: f32 = 0.91 - cel_ink * 0.46 - paper * 0.8 - collar_trim * 0.62;
            let base_b: f32 = 0.87 - cel_ink * 0.34 - paper * 0.7 - collar_trim * 0.52;
            pixels.push((base_r.clamp(0.04, 0.98) * 255.0) as u8);
            pixels.push((base_g.clamp(0.05, 0.98) * 255.0) as u8);
            pixels.push((base_b.clamp(0.07, 0.98) * 255.0) as u8);
            pixels.push(255);
        }
    }
    Texture2D3D::from_rgba8(
        MAT_NAME_INK_ROBE,
        sz,
        sz,
        pixels,
        TextureColorSpace::Srgb,
        true,
    )
    .unwrap_or_default()
}

/// Generates a procedural Guilin / Mount Lu blue-green ink-wash axe-cut cliff strata texture.
///
/// # Returns
///
/// - `Texture2D3D` - Mipmapped 128x128 sRGB karst cliff ink texture.
#[must_use]
pub fn build_jianlai_cliff_ink_texture() -> Texture2D3D {
    let sz: u32 = JIANLAI_TEX_SIZE;
    let mut pixels: Vec<u8> = Vec::with_capacity((sz as usize) * (sz as usize) * 4);
    for py in 0..sz {
        let v: f32 = (py as f32) / ((sz - 1) as f32);
        for px in 0..sz {
            let u: f32 = (px as f32) / ((sz - 1) as f32);
            let strata: f32 = ink_tex_noise(u * 22.0, v * 5.0, 41);
            let detail: f32 = ink_tex_noise(u * 10.0, v * 16.0, 73);
            let mist_fade: f32 = (1.0 - v * 1.35).clamp(0.0, 1.0);
            let band: f32 = (((strata * 0.65 + detail * 0.35) * 4.0).floor() / 4.0).clamp(0.0, 1.0);
            let r: f32 = (0.14 + band * 0.24) * (1.0 - mist_fade * 0.7) + 0.88 * mist_fade * 0.7;
            let g: f32 = (0.26 + band * 0.34) * (1.0 - mist_fade * 0.7) + 0.91 * mist_fade * 0.7;
            let b: f32 = (0.29 + band * 0.30) * (1.0 - mist_fade * 0.7) + 0.89 * mist_fade * 0.7;
            pixels.push((r.clamp(0.05, 0.96) * 255.0) as u8);
            pixels.push((g.clamp(0.08, 0.97) * 255.0) as u8);
            pixels.push((b.clamp(0.10, 0.97) * 255.0) as u8);
            pixels.push(255);
        }
    }
    Texture2D3D::from_rgba8(
        MAT_NAME_INK_CLIFF,
        sz,
        sz,
        pixels,
        TextureColorSpace::Srgb,
        true,
    )
    .unwrap_or_default()
}

/// Generates a procedural carved blue-stone Bagua / sword-array terrace texture with inlaid golden calligraphy rings.
///
/// # Returns
///
/// - `Texture2D3D` - Mipmapped 128x128 sRGB Bagua terrace texture.
#[must_use]
pub fn build_jianlai_bagua_terrace_texture() -> Texture2D3D {
    let sz: u32 = JIANLAI_TEX_SIZE;
    let mut pixels: Vec<u8> = Vec::with_capacity((sz as usize) * (sz as usize) * 4);
    for py in 0..sz {
        let dy: f32 = (py as f32) / ((sz - 1) as f32) * 2.0 - 1.0;
        for px in 0..sz {
            let dx: f32 = (px as f32) / ((sz - 1) as f32) * 2.0 - 1.0;
            let rad: f32 = (dx * dx + dy * dy).sqrt();
            let ang: f32 = dy.atan2(dx) + PI;
            let stone_grain: f32 = ink_tex_noise((dx + 1.0) * 14.0, (dy + 1.0) * 14.0, 97) * 0.12;
            let ring_outer: bool = (rad - 0.82).abs() < 0.025 || (rad - 0.56).abs() < 0.02;
            let ring_inner: bool = (rad - 0.28).abs() < 0.018;
            let trigram_spoke: bool =
                rad > 0.56 && rad < 0.82 && ((ang * 8.0 / TAU).fract() - 0.5).abs() < 0.06;
            let is_gold: bool = (ring_outer || ring_inner) || trigram_spoke;
            let (r, g, b): (f32, f32, f32) = if is_gold {
                (0.86, 0.72, 0.34)
            } else {
                (0.28 + stone_grain, 0.34 + stone_grain, 0.37 + stone_grain)
            };
            pixels.push((r.clamp(0.0, 1.0) * 255.0) as u8);
            pixels.push((g.clamp(0.0, 1.0) * 255.0) as u8);
            pixels.push((b.clamp(0.0, 1.0) * 255.0) as u8);
            pixels.push(255);
        }
    }
    Texture2D3D::from_rgba8(
        MAT_NAME_INK_TERRACE,
        sz,
        sz,
        pixels,
        TextureColorSpace::Srgb,
        true,
    )
    .unwrap_or_default()
}

/// Generates a procedural spirit sword Damascus ink-steel texture with glowing cyan-gold central rune inlays.
///
/// # Returns
///
/// - `Texture2D3D` - Mipmapped 128x128 sRGB blade texture.
#[must_use]
pub fn build_jianlai_blade_rune_texture() -> Texture2D3D {
    let sz: u32 = JIANLAI_TEX_SIZE;
    let mut pixels: Vec<u8> = Vec::with_capacity((sz as usize) * (sz as usize) * 4);
    for py in 0..sz {
        let v: f32 = (py as f32) / ((sz - 1) as f32);
        for px in 0..sz {
            let u: f32 = (px as f32) / ((sz - 1) as f32);
            let ripple: f32 = ((u * 24.0 + (v * 18.0).sin() * 2.0).sin() * 0.5 + 0.5) * 0.14;
            let center_dist: f32 = (u - 0.5).abs();
            let rune_pulse: f32 = ((v * 28.0).sin() * 0.5 + 0.5).powf(3.0);
            let is_rune: bool = center_dist < 0.08 && rune_pulse > 0.55 && v > 0.12 && v < 0.88;
            let (r, g, b): (f32, f32, f32) = if is_rune {
                (0.45, 0.94, 0.98)
            } else {
                (0.68 + ripple, 0.76 + ripple, 0.82 + ripple)
            };
            pixels.push((r.clamp(0.0, 1.0) * 255.0) as u8);
            pixels.push((g.clamp(0.0, 1.0) * 255.0) as u8);
            pixels.push((b.clamp(0.0, 1.0) * 255.0) as u8);
            pixels.push(255);
        }
    }
    Texture2D3D::from_rgba8(
        MAT_NAME_INK_BLADE,
        sz,
        sz,
        pixels,
        TextureColorSpace::Srgb,
        true,
    )
    .unwrap_or_default()
}

/// Appends `part` into a merged vertex, index, and skin-influence buffer while tagging every vertex with `skin_influence`.
///
/// # Arguments
///
/// - `&Mesh3D` - Sculpted body part mesh.
/// - `MeshSkinInfluence3D` - Skeletal joint weights applied to every vertex of `part`.
/// - `&mut Vec<Vertex3D>` - Destination vertex accumulator.
/// - `&mut Vec<[u32; 3]>` - Destination triangle index accumulator.
/// - `&mut Vec<MeshSkinInfluence3D>` - Destination per-vertex skin influence accumulator.
pub(crate) fn append_rigged_part(
    part: &Mesh3D,
    skin_influence: MeshSkinInfluence3D,
    out_verts: &mut Vec<Vertex3D>,
    out_tris: &mut Vec<[u32; 3]>,
    out_skins: &mut Vec<MeshSkinInfluence3D>,
) {
    let base: u32 = out_verts.len() as u32;
    out_verts.extend_from_slice(part.get_vertices().as_slice());
    out_skins.resize(out_verts.len(), skin_influence);
    for &[i0, i1, i2] in part.get_indices().iter() {
        out_tris.push([base + i0, base + i1, base + i2]);
    }
}

/// Computes smooth multi-bone skeletal weights for a hero vertex based on its primary and optional secondary bone.
///
/// # Arguments
///
/// - `u16` - Primary bone index owning this anatomical part.
/// - `Option<u16>` - Secondary neighbor bone for smooth joint blending.
/// - `f32` - Blend weight toward the secondary bone in `[0.0, 0.5]`.
///
/// # Returns
///
/// - `MeshSkinInfluence3D` - Normalized 4-slot skin influence record.
#[must_use]
pub(crate) fn make_blended_skin_influence(
    primary: u16,
    secondary: Option<u16>,
    secondary_weight: f32,
) -> MeshSkinInfluence3D {
    let w2: f32 = if secondary.is_some() {
        secondary_weight.clamp(0.0, 0.48)
    } else {
        0.0
    };
    let w1: f32 = 1.0 - w2;
    let j2: u16 = secondary.unwrap_or(primary);
    MeshSkinInfluence3D::new([primary, j2, 0, 0], [w1, w2, 0.0, 0.0], [0; 4], [0.0; 4])
}

/// Appends `part` with per-vertex vertical blend weights transitioning smoothly across `bones` over `y_span`.
///
/// # Arguments
///
/// - `&Mesh3D` - Sculpted organic mesh segment.
/// - `(u16, u16)` - Lower and upper bone indices.
/// - `(f32, f32)` - Lower and upper Y bounds.
/// - `&mut Vec<Vertex3D>` - Destination vertex buffer.
/// - `&mut Vec<[u32; 3]>` - Destination triangle buffer.
/// - `&mut Vec<MeshSkinInfluence3D>` - Destination skin influence buffer.
pub(crate) fn append_blended_y_part(
    part: &Mesh3D,
    bones: (u16, u16),
    y_span: (f32, f32),
    out_verts: &mut Vec<Vertex3D>,
    out_tris: &mut Vec<[u32; 3]>,
    out_skins: &mut Vec<MeshSkinInfluence3D>,
) {
    let base: u32 = out_verts.len() as u32;
    let span: f32 = (y_span.1 - y_span.0).max(1.0e-4);
    for vert in part.get_vertices().iter() {
        let t: f32 = ((vert.get_position().get_y() - y_span.0) / span).clamp(0.0, 1.0);
        let w_high: f32 = t;
        let w_low: f32 = 1.0 - t;
        out_verts.push(*vert);
        out_skins.push(MeshSkinInfluence3D::new(
            [bones.0, bones.1, 0, 0],
            [w_low, w_high, 0.0, 0.0],
            [0; 4],
            [0.0; 4],
        ));
    }
    for &[i0, i1, i2] in part.get_indices().iter() {
        out_tris.push([base + i0, base + i1, base + i2]);
    }
}

/// Builds the complete sculpted multi-part Jianlai Chinese ink-wash swordsman hero mesh with 27-bone skinning and two Shape Keys.
///
/// # Returns
///
/// - `Mesh3D` - High-detail organic sculpted humanoid swordsman mesh (zero cubes) with `skin_influences` and `morph_targets`.
#[must_use]
pub fn build_jianlai_hero_mesh() -> Mesh3D {
    let mut verts: Vec<Vertex3D> = Vec::with_capacity(4096);
    let mut tris: Vec<[u32; 3]> = Vec::with_capacity(6144);
    let mut skins: Vec<MeshSkinInfluence3D> = Vec::with_capacity(4096);
    // Sculpted layered wide-sleeved cross-lapel torso & waist sash (y = 0.92..1.58).
    let torso_rings: Vec<Vec<Vec3>> = vec![
        build_elliptic_ring(Vec3::new(0.0, 0.92, 0.0), 0.21, 0.16, 16, 0.05, 6.0),
        build_elliptic_ring(Vec3::new(0.0, 1.04, 0.01), 0.17, 0.13, 16, 0.03, 4.0),
        build_elliptic_ring(Vec3::new(0.0, 1.20, 0.01), 0.21, 0.15, 16, 0.04, 4.0),
        build_elliptic_ring(Vec3::new(0.0, 1.38, 0.01), 0.25, 0.16, 16, 0.04, 2.0),
        build_elliptic_ring(Vec3::new(0.0, 1.50, 0.0), 0.23, 0.14, 16, 0.03, 2.0),
        build_elliptic_ring(Vec3::new(0.0, 1.56, 0.0), 0.09, 0.08, 14, 0.0, 1.0),
    ];
    let mut torso_mesh: Mesh3D = loft_profiles(&torso_rings, false);
    gradient_tint_mesh_y(
        &mut torso_mesh,
        0.92,
        1.56,
        [46, 86, 108, 255],
        [236, 238, 232, 255],
    );
    append_blended_y_part(
        &torso_mesh,
        (BONE_PELVIS as u16, BONE_CHEST as u16),
        (0.92, 1.52),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    // Cross-lapel collar trim and draped shoulder mantle.
    let collar_spline: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(-0.14, 1.50, 0.08),
            Vec3::new(-0.07, 1.34, 0.16),
            Vec3::new(0.02, 1.18, 0.17),
            Vec3::new(0.11, 1.35, 0.16),
            Vec3::new(0.14, 1.50, 0.07),
        ],
        false,
    );
    let collar_prof: Vec<Vec2> = build_profile_ellipse_2d(0.032, 0.018, 8);
    let mut collar_mesh: Mesh3D =
        sweep_along_spline(&collar_prof, &collar_spline, 14, &[1.0, 1.1, 1.0]);
    tint_mesh_vertices(&mut collar_mesh, [32, 54, 68, 255]);
    append_rigged_part(
        &collar_mesh,
        make_blended_skin_influence(BONE_CHEST as u16, Some(BONE_SPINE as u16), 0.25),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    // Cinched brocade waist sash and sculpted hanging celadon jade pendant.
    let sash_rings: Vec<Vec<Vec3>> = vec![
        build_elliptic_ring(Vec3::new(0.0, 0.96, 0.01), 0.195, 0.155, 16, 0.02, 4.0),
        build_elliptic_ring(Vec3::new(0.0, 1.03, 0.01), 0.192, 0.150, 16, 0.02, 4.0),
        build_elliptic_ring(Vec3::new(0.0, 1.09, 0.01), 0.195, 0.155, 16, 0.02, 4.0),
    ];
    let mut sash_mesh: Mesh3D = loft_profiles(&sash_rings, false);
    tint_mesh_vertices(&mut sash_mesh, [30, 36, 46, 255]);
    append_rigged_part(
        &sash_mesh,
        make_blended_skin_influence(BONE_PELVIS as u16, Some(BONE_SPINE as u16), 0.35),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    let jade_disc: Mesh3D = transform_mesh(
        &torus(0.048, 0.014, 14, 8),
        &Transform3D::new(Vec3::new(-0.18, 0.88, 0.11), 0.45, Vec3::splat(1.0)).to_mat4(),
    );
    let mut jade_colored: Mesh3D = jade_disc;
    tint_mesh_vertices(&mut jade_colored, [98, 212, 182, 255]);
    append_rigged_part(
        &jade_colored,
        make_blended_skin_influence(BONE_HEM_LEFT as u16, Some(BONE_PELVIS as u16), 0.4),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    // Four split flowing robe hem panels.
    let hem_specs: [(Vec3, Vec3, u16); 4] = [
        (
            Vec3::new(0.0, 0.96, 0.13),
            Vec3::new(0.0, 0.16, 0.25),
            BONE_HEM_FRONT as u16,
        ),
        (
            Vec3::new(0.0, 0.96, -0.14),
            Vec3::new(0.0, 0.12, -0.30),
            BONE_HEM_BACK as u16,
        ),
        (
            Vec3::new(-0.16, 0.96, 0.0),
            Vec3::new(-0.30, 0.18, -0.02),
            BONE_HEM_LEFT as u16,
        ),
        (
            Vec3::new(0.16, 0.96, 0.0),
            Vec3::new(0.30, 0.18, -0.02),
            BONE_HEM_RIGHT as u16,
        ),
    ];
    for (top_c, bot_c, bone_id) in hem_specs {
        let mid_c: Vec3 = top_c.lerp(bot_c, 0.52);
        let is_fb: bool = bone_id == BONE_HEM_FRONT as u16 || bone_id == BONE_HEM_BACK as u16;
        let (rx0, rz0): (f32, f32) = if is_fb { (0.16, 0.036) } else { (0.042, 0.16) };
        let (rx1, rz1): (f32, f32) = if is_fb { (0.24, 0.042) } else { (0.048, 0.23) };
        let (rx2, rz2): (f32, f32) = if is_fb { (0.31, 0.032) } else { (0.038, 0.29) };
        let hem_rings: Vec<Vec<Vec3>> = vec![
            build_elliptic_ring(top_c, rx0, rz0, 12, 0.08, 4.0),
            build_elliptic_ring(mid_c, rx1, rz1, 12, 0.12, 5.0),
            build_elliptic_ring(bot_c, rx2, rz2, 12, 0.15, 6.0),
        ];
        let mut hem_mesh: Mesh3D = loft_profiles(&hem_rings, false);
        gradient_tint_mesh_y(
            &mut hem_mesh,
            0.12,
            0.96,
            [28, 66, 86, 255],
            [218, 228, 226, 255],
        );
        append_blended_y_part(
            &hem_mesh,
            (bone_id, BONE_PELVIS as u16),
            (0.12, 0.96),
            &mut verts,
            &mut tris,
            &mut skins,
        );
    }
    // Neck, organic contoured head, topknot hair bun, jade hairpin, and dual flowing ink hair ribbons.
    let mut neck_mesh: Mesh3D = transform_mesh(
        &cylinder(0.062, 0.056, 0.14, 12, true),
        &Transform3D::new(Vec3::new(0.0, 1.59, 0.0), 0.0, Vec3::splat(1.0)).to_mat4(),
    );
    tint_mesh_vertices(&mut neck_mesh, [242, 224, 210, 255]);
    append_rigged_part(
        &neck_mesh,
        make_blended_skin_influence(BONE_NECK as u16, Some(BONE_CHEST as u16), 0.3),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    let head_rings: Vec<Vec<Vec3>> = vec![
        build_elliptic_ring(Vec3::new(0.0, 1.62, 0.02), 0.052, 0.065, 14, 0.0, 1.0),
        build_elliptic_ring(Vec3::new(0.0, 1.68, 0.025), 0.088, 0.104, 14, 0.02, 2.0),
        build_elliptic_ring(Vec3::new(0.0, 1.75, 0.015), 0.098, 0.112, 14, 0.01, 2.0),
        build_elliptic_ring(Vec3::new(0.0, 1.82, 0.0), 0.088, 0.102, 14, 0.0, 1.0),
        build_elliptic_ring(Vec3::new(0.0, 1.87, -0.01), 0.045, 0.052, 14, 0.0, 1.0),
    ];
    let mut head_mesh: Mesh3D = loft_profiles(&head_rings, false);
    tint_mesh_vertices(&mut head_mesh, [245, 228, 214, 255]);
    append_rigged_part(
        &head_mesh,
        make_blended_skin_influence(BONE_HEAD as u16, Some(BONE_NECK as u16), 0.12),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    let hair_bun_profile: Vec<Vec2> = vec![
        Vec2::new(0.0, 1.74),
        Vec2::new(0.106, 1.76),
        Vec2::new(0.104, 1.84),
        Vec2::new(0.062, 1.89),
        Vec2::new(0.048, 1.92),
        Vec2::new(0.056, 1.96),
        Vec2::new(0.036, 1.99),
        Vec2::new(0.0, 2.00),
    ];
    let mut hair_crown: Mesh3D = transform_mesh(
        &lathe_revolve(&hair_bun_profile, 14, TAU),
        &Transform3D::new(Vec3::new(0.0, 0.0, -0.015), 0.0, Vec3::splat(1.0)).to_mat4(),
    );
    tint_mesh_vertices(&mut hair_crown, [22, 26, 34, 255]);
    append_rigged_part(
        &hair_crown,
        make_blended_skin_influence(BONE_HEAD as u16, None, 0.0),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    let hairpin_spline: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(-0.14, 1.93, -0.02),
            Vec3::new(0.0, 1.95, -0.02),
            Vec3::new(0.15, 1.96, -0.02),
        ],
        false,
    );
    let mut hairpin_mesh: Mesh3D = sweep_along_spline(
        &build_profile_ellipse_2d(0.011, 0.011, 6),
        &hairpin_spline,
        8,
        &[0.5, 1.0, 1.25],
    );
    tint_mesh_vertices(&mut hairpin_mesh, [110, 224, 192, 255]);
    append_rigged_part(
        &hairpin_mesh,
        make_blended_skin_influence(BONE_HEAD as u16, None, 0.0),
        &mut verts,
        &mut tris,
        &mut skins,
    );
    for (side_sign, ribbon_bone) in [(-1.0f32, BONE_HAIR_L as u16), (1.0f32, BONE_HAIR_R as u16)] {
        let rib_spline: Spline3D = Spline3D::catmull_rom(
            vec![
                Vec3::new(side_sign * 0.05, 1.90, -0.08),
                Vec3::new(side_sign * 0.14, 1.66, -0.18),
                Vec3::new(side_sign * 0.22, 1.34, -0.28),
                Vec3::new(side_sign * 0.28, 1.04, -0.36),
            ],
            false,
        );
        let mut rib_mesh: Mesh3D = sweep_along_spline(
            &build_profile_ellipse_2d(0.036, 0.008, 6),
            &rib_spline,
            12,
            &[0.65, 1.0, 1.15, 0.45],
        );
        gradient_tint_mesh_y(
            &mut rib_mesh,
            1.04,
            1.90,
            [36, 98, 128, 255],
            [24, 28, 38, 255],
        );
        append_blended_y_part(
            &rib_mesh,
            (ribbon_bone, BONE_HEAD as u16),
            (1.04, 1.90),
            &mut verts,
            &mut tris,
            &mut skins,
        );
    }
    // Articulated shoulders, arms, dramatic wide flared Hanfu sleeves, and hands.
    let arm_sides: [(f32, u16, u16, u16, u16); 2] = [
        (
            -1.0,
            BONE_SHOULDER_L as u16,
            BONE_UPPER_ARM_L as u16,
            BONE_FOREARM_L as u16,
            BONE_HAND_L as u16,
        ),
        (
            1.0,
            BONE_SHOULDER_R as u16,
            BONE_UPPER_ARM_R as u16,
            BONE_FOREARM_R as u16,
            BONE_HAND_R as u16,
        ),
    ];
    for (s, b_sh, b_up, b_fa, b_ha) in arm_sides {
        let upper_spline: Spline3D = Spline3D::catmull_rom(
            vec![
                Vec3::new(s * 0.18, 1.48, 0.0),
                Vec3::new(s * 0.30, 1.40, 0.02),
                Vec3::new(s * 0.42, 1.28, 0.04),
            ],
            false,
        );
        let mut upper_mesh: Mesh3D = sweep_along_spline(
            &build_profile_ellipse_2d(0.088, 0.115, 10),
            &upper_spline,
            8,
            &[1.0, 1.12, 1.35],
        );
        tint_mesh_vertices(&mut upper_mesh, [224, 232, 230, 255]);
        append_rigged_part(
            &upper_mesh,
            make_blended_skin_influence(b_up, Some(b_sh), 0.35),
            &mut verts,
            &mut tris,
            &mut skins,
        );
        // Wide flared drooping ink-wash sleeve.
        let sleeve_rings: Vec<Vec<Vec3>> = vec![
            build_elliptic_ring(Vec3::new(s * 0.42, 1.26, 0.04), 0.085, 0.105, 12, 0.04, 3.0),
            build_elliptic_ring(Vec3::new(s * 0.54, 1.14, 0.07), 0.12, 0.18, 12, 0.08, 4.0),
            build_elliptic_ring(Vec3::new(s * 0.64, 0.98, 0.09), 0.15, 0.24, 12, 0.12, 5.0),
        ];
        let mut sleeve_mesh: Mesh3D = loft_profiles(&sleeve_rings, false);
        gradient_tint_mesh_y(
            &mut sleeve_mesh,
            0.96,
            1.28,
            [38, 88, 114, 255],
            [228, 234, 232, 255],
        );
        append_rigged_part(
            &sleeve_mesh,
            make_blended_skin_influence(b_fa, Some(b_up), 0.3),
            &mut verts,
            &mut tris,
            &mut skins,
        );
        let mut hand_mesh: Mesh3D = transform_mesh(
            &capsule(0.036, 0.09, 10),
            &Transform3D::from_trs(
                Vec3::new(s * 0.68, 1.09, 0.10),
                Quat::from_euler_yxz(0.0, 0.35, -s * 0.72),
                Vec3::splat(1.0),
            )
            .to_mat4(),
        );
        tint_mesh_vertices(&mut hand_mesh, [242, 224, 210, 255]);
        append_rigged_part(
            &hand_mesh,
            make_blended_skin_influence(b_ha, Some(b_fa), 0.25),
            &mut verts,
            &mut tris,
            &mut skins,
        );
    }
    // Articulated legs & traditional upturned-toe cloth boots.
    let leg_sides: [(f32, u16, u16, u16); 2] = [
        (
            -1.0,
            BONE_THIGH_L as u16,
            BONE_SHIN_L as u16,
            BONE_FOOT_L as u16,
        ),
        (
            1.0,
            BONE_THIGH_R as u16,
            BONE_SHIN_R as u16,
            BONE_FOOT_R as u16,
        ),
    ];
    for (s, b_th, b_sh, b_ft) in leg_sides {
        let leg_rings: Vec<Vec<Vec3>> = vec![
            build_elliptic_ring(Vec3::new(s * 0.11, 0.90, 0.0), 0.092, 0.095, 10, 0.0, 1.0),
            build_elliptic_ring(Vec3::new(s * 0.11, 0.48, 0.01), 0.072, 0.078, 10, 0.0, 1.0),
            build_elliptic_ring(Vec3::new(s * 0.11, 0.10, 0.01), 0.056, 0.062, 10, 0.0, 1.0),
        ];
        let mut leg_mesh: Mesh3D = loft_profiles(&leg_rings, false);
        tint_mesh_vertices(&mut leg_mesh, [36, 44, 54, 255]);
        append_blended_y_part(
            &leg_mesh,
            (b_sh, b_th),
            (0.10, 0.90),
            &mut verts,
            &mut tris,
            &mut skins,
        );
        let boot_spline: Spline3D = Spline3D::catmull_rom(
            vec![
                Vec3::new(s * 0.11, 0.06, -0.05),
                Vec3::new(s * 0.11, 0.045, 0.06),
                Vec3::new(s * 0.11, 0.065, 0.17),
            ],
            false,
        );
        let mut boot_mesh: Mesh3D = sweep_along_spline(
            &build_profile_ellipse_2d(0.054, 0.044, 8),
            &boot_spline,
            8,
            &[1.0, 1.05, 0.65],
        );
        tint_mesh_vertices(&mut boot_mesh, [24, 28, 36, 255]);
        append_rigged_part(
            &boot_mesh,
            make_blended_skin_influence(b_ft, Some(b_sh), 0.2),
            &mut verts,
            &mut tris,
            &mut skins,
        );
    }
    // Build two real Blender Shape Keys (`SwordQi_BattleAura` & `Robe_WindBillow`) over the final vertex buffer.
    let mut aura_pos: Vec<[f32; 3]> = Vec::with_capacity(verts.len());
    let mut aura_norm: Vec<[f32; 3]> = Vec::with_capacity(verts.len());
    let mut wind_pos: Vec<[f32; 3]> = Vec::with_capacity(verts.len());
    let mut wind_norm: Vec<[f32; 3]> = Vec::with_capacity(verts.len());
    for vert in verts.iter() {
        let p: Vec3 = vert.get_position();
        let n: Vec3 = vert.get_normal();
        let y: f32 = p.get_y();
        let radial: Vec3 = Vec3::new(p.get_x(), 0.0, p.get_z());
        let r_len: f32 = radial.length();
        let rad_dir: Vec3 = if r_len > 1.0e-4 {
            radial.scale(1.0 / r_len)
        } else {
            Vec3::new(0.0, 0.0, 1.0)
        };
        let lower_factor: f32 = ((1.32 - y) / 1.2).clamp(0.0, 1.0);
        let sleeve_factor: f32 = ((p.get_x().abs() - 0.34) / 0.35).clamp(0.0, 1.0);
        let billow: f32 = 0.055 * lower_factor + 0.08 * sleeve_factor;
        let crest_lift: f32 = if y > 1.72 {
            0.045
        } else {
            0.025 * lower_factor
        };
        aura_pos.push([
            rad_dir.get_x() * billow + n.get_x() * 0.018,
            crest_lift + 0.03 * sleeve_factor,
            rad_dir.get_z() * billow - 0.04 * lower_factor,
        ]);
        aura_norm.push([rad_dir.get_x() * 0.15, 0.08, rad_dir.get_z() * 0.15]);
        let sweep_z: f32 = -0.14 * lower_factor - 0.08 * sleeve_factor;
        let sweep_x: f32 = (y * 6.0).sin() * 0.05 * (lower_factor + sleeve_factor);
        wind_pos.push([sweep_x, 0.04 * lower_factor, sweep_z]);
        wind_norm.push([0.0, 0.05, -0.12 * lower_factor]);
    }
    let morph_aura: MorphTarget3D = MorphTarget3D {
        name: MORPH_NAME_BATTLE_AURA.to_string(),
        delta_positions: aura_pos,
        delta_normals: aura_norm,
        delta_tangents: Vec::new(),
    };
    let morph_wind: MorphTarget3D = MorphTarget3D {
        name: MORPH_NAME_WIND_BILLOW.to_string(),
        delta_positions: wind_pos,
        delta_normals: wind_norm,
        delta_tangents: Vec::new(),
    };
    let mut base_mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = base_mat
        .set_base_color(Vec3::new(0.86, 0.90, 0.89))
        .set_metallic(0.08)
        .set_roughness(0.58);
    let mut raw: Mesh3D = Mesh3D::from_parts(MESH_NAME_HERO.to_string(), verts, tris, base_mat);
    raw.set_skin_influences(skins);
    raw.set_morph_targets(vec![morph_aura, morph_wind]);
    finalize_jianlai_mesh(raw, MESH_NAME_HERO, base_mat, true)
}

/// Builds the sculpted ancient Jianlai Spirit Sword with tapered leaf blade, central fuller ridge, ornate curved bronze guard, wrapped hilt, lotus pommel, and flowing cinnabar tassel.
///
/// # Returns
///
/// - `Mesh3D` - High-detail sculpted spirit sword oriented along `+Y` (`y = -0.26..+1.18`).
#[must_use]
pub fn build_jianlai_spirit_sword_mesh() -> Mesh3D {
    let mut parts: Vec<Mesh3D> = Vec::with_capacity(5);
    // Double-edged diamond cross-section tapered leaf blade with central ridge.
    let blade_stations: [(f32, f32, f32); 7] = [
        (0.04, 0.036, 0.011),
        (0.24, 0.032, 0.010),
        (0.52, 0.029, 0.009),
        (0.78, 0.034, 0.0095),
        (0.96, 0.027, 0.008),
        (1.10, 0.014, 0.005),
        (1.18, 0.002, 0.002),
    ];
    let mut blade_rings: Vec<Vec<Vec3>> = Vec::with_capacity(blade_stations.len());
    for (y, hw, ht) in blade_stations {
        blade_rings.push(vec![
            Vec3::new(hw, y, 0.0),
            Vec3::new(hw * 0.45, y, ht * 0.72),
            Vec3::new(0.0, y, ht),
            Vec3::new(-hw * 0.45, y, ht * 0.72),
            Vec3::new(-hw, y, 0.0),
            Vec3::new(-hw * 0.45, y, -ht * 0.72),
            Vec3::new(0.0, y, -ht),
            Vec3::new(hw * 0.45, y, -ht * 0.72),
        ]);
    }
    let mut blade: Mesh3D = loft_profiles(&blade_rings, false);
    gradient_tint_mesh_y(
        &mut blade,
        0.04,
        1.18,
        [152, 205, 224, 255],
        [238, 252, 255, 255],
    );
    parts.push(blade);
    // Ornate curved wing-shaped bronze-gold handguard.
    let guard_profile: Vec<Vec2> = vec![
        Vec2::new(-0.12, 0.028),
        Vec2::new(-0.07, 0.056),
        Vec2::new(0.0, 0.072),
        Vec2::new(0.07, 0.056),
        Vec2::new(0.12, 0.028),
        Vec2::new(0.085, -0.016),
        Vec2::new(0.0, 0.008),
        Vec2::new(-0.085, -0.016),
    ];
    let mut guard: Mesh3D = extrude_profile(&guard_profile, 0.038, 0.006, 2);
    tint_mesh_vertices(&mut guard, [218, 178, 86, 255]);
    parts.push(guard);
    // Wrapped tapered hilt and lotus-bud bronze pommel.
    let hilt_profile: Vec<Vec2> = vec![
        Vec2::new(0.0, -0.26),
        Vec2::new(0.028, -0.24),
        Vec2::new(0.036, -0.21),
        Vec2::new(0.018, -0.18),
        Vec2::new(0.016, -0.09),
        Vec2::new(0.019, -0.01),
        Vec2::new(0.0, 0.0),
    ];
    let mut hilt: Mesh3D = lathe_revolve(&hilt_profile, 12, TAU);
    tint_mesh_vertices(&mut hilt, [44, 52, 64, 255]);
    parts.push(hilt);
    // Flowing cinnabar silk pommel tassel.
    let tassel_spline: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(0.0, -0.25, 0.0),
            Vec3::new(-0.04, -0.36, -0.03),
            Vec3::new(0.02, -0.49, -0.06),
            Vec3::new(-0.03, -0.60, -0.04),
        ],
        false,
    );
    let mut tassel: Mesh3D = sweep_along_spline(
        &build_profile_ellipse_2d(0.012, 0.012, 6),
        &tassel_spline,
        8,
        &[0.5, 1.15, 1.35, 0.35],
    );
    tint_mesh_vertices(&mut tassel, [206, 54, 48, 255]);
    parts.push(tassel);
    let mut blade_mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = blade_mat
        .set_base_color(Vec3::new(0.76, 0.88, 0.94))
        .set_metallic(0.92)
        .set_roughness(0.16)
        .set_emissive(Vec3::new(0.18, 0.52, 0.62));
    let merged: Mesh3D = merge_meshes(&parts, MESH_NAME_SPIRIT_SWORD);
    finalize_jianlai_mesh(merged, MESH_NAME_SPIRIT_SWORD, blade_mat, true)
}

/// Builds the floating carved bronze-and-jade spirit sword scabbard hovering behind the hero.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted tapered hexagonal-curved sword scabbard mesh.
#[must_use]
pub fn build_jianlai_scabbard_mesh() -> Mesh3D {
    let rings: Vec<Vec<Vec3>> = vec![
        build_elliptic_ring(Vec3::new(0.0, -0.58, 0.0), 0.042, 0.026, 10, 0.06, 2.0),
        build_elliptic_ring(Vec3::new(0.0, -0.20, 0.0), 0.056, 0.032, 10, 0.04, 2.0),
        build_elliptic_ring(Vec3::new(0.0, 0.25, 0.0), 0.064, 0.036, 10, 0.04, 2.0),
        build_elliptic_ring(Vec3::new(0.0, 0.56, 0.0), 0.072, 0.042, 10, 0.08, 4.0),
    ];
    let mut body: Mesh3D = loft_profiles(&rings, false);
    gradient_tint_mesh_y(
        &mut body,
        -0.58,
        0.56,
        [48, 62, 68, 255],
        [182, 152, 84, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.32, 0.38, 0.40))
        .set_metallic(0.68)
        .set_roughness(0.34);
    finalize_jianlai_mesh(body, MESH_NAME_SCABBARD, mat, true)
}

/// Builds the carved circular multi-tier stone Bagua sword terrace resting with top surface at `y = 0.0`.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted circular stone terrace with stepped lotus rim and planar top UVs.
#[must_use]
pub fn build_jianlai_bagua_terrace_mesh() -> Mesh3D {
    let profile: Vec<Vec2> = vec![
        Vec2::new(0.0, -0.78),
        Vec2::new(5.35, -0.78),
        Vec2::new(5.15, -0.44),
        Vec2::new(4.92, -0.42),
        Vec2::new(4.78, -0.18),
        Vec2::new(4.56, -0.16),
        Vec2::new(4.46, 0.0),
        Vec2::new(3.20, 0.005),
        Vec2::new(1.50, 0.008),
        Vec2::new(0.0, 0.01),
    ];
    let mut terrace: Mesh3D = lathe_revolve(&profile, 36, TAU);
    for vert in terrace.get_mut_vertices().iter_mut() {
        let p: Vec3 = vert.get_position();
        vert.set_uv0([p.get_x() / 9.2 + 0.5, p.get_z() / 9.2 + 0.5]);
    }
    gradient_tint_mesh_y(
        &mut terrace,
        -0.78,
        0.01,
        [68, 86, 94, 255],
        [162, 178, 182, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.42, 0.48, 0.50))
        .set_metallic(0.12)
        .set_roughness(0.68);
    finalize_jianlai_mesh(terrace, MESH_NAME_TERRACE, mat, true)
}

/// Builds the sculpted double-tier upturned flying-eave Chinese pavilion roof with golden gourd finial.
///
/// # Returns
///
/// - `Mesh3D` - Sweeping octagonal concave upturned flying-eave roof mesh.
#[must_use]
pub fn build_jianlai_pavilion_roof_mesh() -> Mesh3D {
    let build_tier: fn(f32, f32, f32, f32) -> Mesh3D =
        |base_y: f32, outer_r: f32, top_r: f32, height: f32| -> Mesh3D {
            let stations: [(f32, f32, f32); 5] = [
                (0.0, outer_r * 1.04, 0.24),
                (0.18, outer_r * 0.88, 0.14),
                (0.48, outer_r * 0.64, 0.06),
                (0.78, outer_r * 0.36 + top_r * 0.5, 0.02),
                (1.0, top_r, 0.0),
            ];
            let mut rings: Vec<Vec<Vec3>> = Vec::with_capacity(stations.len());
            for (t, rad, corner_lift) in stations {
                let mut ring: Vec<Vec3> = Vec::with_capacity(16);
                for i in 0..16 {
                    let ang: f32 = ((i as f32) / 16.0) * TAU;
                    let is_corner: bool = i % 2 == 0;
                    let r_eff: f32 = if is_corner { rad * 1.14 } else { rad * 0.92 };
                    let lift: f32 = if is_corner { corner_lift } else { 0.0 };
                    ring.push(Vec3::new(
                        r_eff * ang.cos(),
                        base_y + t * height + lift,
                        r_eff * ang.sin(),
                    ));
                }
                rings.push(ring);
            }
            loft_profiles(&rings, false)
        };
    let lower_eave: Mesh3D = build_tier(2.85, 3.15, 1.35, 1.15);
    let upper_eave: Mesh3D = build_tier(4.10, 2.25, 0.16, 1.35);
    let finial_profile: Vec<Vec2> = vec![
        Vec2::new(0.0, 5.40),
        Vec2::new(0.24, 5.45),
        Vec2::new(0.16, 5.64),
        Vec2::new(0.20, 5.82),
        Vec2::new(0.08, 6.08),
        Vec2::new(0.0, 6.26),
    ];
    let mut finial: Mesh3D = lathe_revolve(&finial_profile, 12, TAU);
    tint_mesh_vertices(&mut finial, [232, 192, 88, 255]);
    let mut lower_c: Mesh3D = lower_eave;
    let mut upper_c: Mesh3D = upper_eave;
    gradient_tint_mesh_y(
        &mut lower_c,
        2.85,
        4.05,
        [34, 58, 72, 255],
        [52, 82, 96, 255],
    );
    gradient_tint_mesh_y(
        &mut upper_c,
        4.10,
        5.50,
        [30, 52, 66, 255],
        [58, 92, 108, 255],
    );
    let merged: Mesh3D = merge_meshes(&[lower_c, upper_c, finial], MESH_NAME_PAVILION_ROOF);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.18, 0.28, 0.34))
        .set_metallic(0.24)
        .set_roughness(0.36);
    finalize_jianlai_mesh(merged, MESH_NAME_PAVILION_ROOF, mat, true)
}

/// Builds the octagonal pavilion stone plinth, eight round vermilion columns with carved stone drum bases, and carved stone balustrades.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted pavilion colonnade and carved stone balustrade assembly.
#[must_use]
pub fn build_jianlai_pavilion_pillars_mesh() -> Mesh3D {
    let mut parts: Vec<Mesh3D> = Vec::with_capacity(20);
    let plinth_prof: Vec<Vec2> = vec![
        Vec2::new(0.0, -0.50),
        Vec2::new(2.85, -0.50),
        Vec2::new(2.70, -0.22),
        Vec2::new(2.50, -0.20),
        Vec2::new(2.40, 0.08),
        Vec2::new(0.0, 0.08),
    ];
    let mut plinth: Mesh3D = lathe_revolve(&plinth_prof, 8, TAU);
    tint_mesh_vertices(&mut plinth, [176, 184, 184, 255]);
    parts.push(plinth);
    let col_prof: Vec<Vec2> = vec![
        Vec2::new(0.0, 0.08),
        Vec2::new(0.20, 0.08),
        Vec2::new(0.18, 0.24),
        Vec2::new(0.135, 0.30),
        Vec2::new(0.125, 2.86),
        Vec2::new(0.175, 2.94),
        Vec2::new(0.0, 2.98),
    ];
    let col_base: Mesh3D = lathe_revolve(&col_prof, 12, TAU);
    let rail_prof: Vec<Vec2> = build_profile_ellipse_2d(0.045, 0.06, 6);
    for i in 0..8usize {
        let ang: f32 = ((i as f32) / 8.0) * TAU + PI / 8.0;
        let next_ang: f32 = (((i + 1) as f32) / 8.0) * TAU + PI / 8.0;
        let p0: Vec3 = Vec3::new(2.08 * ang.cos(), 0.0, 2.08 * ang.sin());
        let p1: Vec3 = Vec3::new(2.08 * next_ang.cos(), 0.0, 2.08 * next_ang.sin());
        let mut col: Mesh3D = transform_mesh(
            &col_base,
            &Transform3D::new(p0, 0.0, Vec3::splat(1.0)).to_mat4(),
        );
        tint_mesh_vertices(&mut col, [156, 46, 42, 255]);
        parts.push(col);
        if i != 0 {
            let rail_spline: Spline3D = Spline3D::catmull_rom(
                vec![
                    p0.add(Vec3::new(0.0, 0.72, 0.0)),
                    p0.lerp(p1, 0.5).add(Vec3::new(0.0, 0.75, 0.0)),
                    p1.add(Vec3::new(0.0, 0.72, 0.0)),
                ],
                false,
            );
            let mut rail: Mesh3D = sweep_along_spline(&rail_prof, &rail_spline, 6, &[1.0, 1.0]);
            tint_mesh_vertices(&mut rail, [212, 214, 208, 255]);
            parts.push(rail);
        }
    }
    let mut ring_beam: Mesh3D = transform_mesh(
        &torus(2.08, 0.12, 16, 8),
        &Transform3D::new(Vec3::new(0.0, 2.86, 0.0), 0.0, Vec3::splat(1.0)).to_mat4(),
    );
    tint_mesh_vertices(&mut ring_beam, [142, 42, 38, 255]);
    parts.push(ring_beam);
    let merged: Mesh3D = merge_meshes(&parts, MESH_NAME_PAVILION_PILLARS);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.66, 0.22, 0.19))
        .set_metallic(0.14)
        .set_roughness(0.44);
    finalize_jianlai_mesh(merged, MESH_NAME_PAVILION_PILLARS, mat, true)
}

/// Builds a ribbed glowing Chinese palace paper lantern via lathe revolution.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted glowing palace lantern mesh.
#[must_use]
pub fn build_jianlai_lantern_mesh() -> Mesh3D {
    let profile: Vec<Vec2> = vec![
        Vec2::new(0.0, -0.34),
        Vec2::new(0.04, -0.26),
        Vec2::new(0.14, -0.18),
        Vec2::new(0.22, -0.06),
        Vec2::new(0.23, 0.06),
        Vec2::new(0.16, 0.18),
        Vec2::new(0.08, 0.24),
        Vec2::new(0.0, 0.28),
    ];
    let mut lantern: Mesh3D = lathe_revolve(&profile, 14, TAU);
    gradient_tint_mesh_y(
        &mut lantern,
        -0.34,
        0.28,
        [232, 92, 46, 255],
        [255, 224, 142, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.98, 0.68, 0.34))
        .set_metallic(0.05)
        .set_roughness(0.45)
        .set_emissive(Vec3::new(1.85, 0.92, 0.32));
    finalize_jianlai_mesh(lantern, MESH_NAME_LANTERN, mat, true)
}

/// Builds the eroded Guilin / Mount Lu ink-wash karst cliff terrain using `HeightfieldTerrain` with hydraulic/thermal erosion and strata terracing.
///
/// # Returns
///
/// - `Mesh3D` - Eroded cliff promontory terrain surrounding the sword terrace.
#[must_use]
pub fn build_jianlai_cliff_terrain_mesh() -> Mesh3D {
    let mut cfg: TerrainConfig = TerrainConfig::alpine(77_009);
    let _: &mut TerrainConfig = cfg
        .set_grid_x(37)
        .set_grid_z(37)
        .set_world_size_x(44.0)
        .set_world_size_z(44.0)
        .set_height_scale(9.5)
        .set_ridged_weight(0.68)
        .set_canyon_weight(0.38)
        .set_terrace_steps(5)
        .set_terrace_strength(0.45)
        .set_hydraulic_droplets(360)
        .set_thermal_iterations(5);
    let terrain: HeightfieldTerrain = HeightfieldTerrain::generate(&cfg);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.26, 0.42, 0.44))
        .set_metallic(0.04)
        .set_roughness(0.84);
    let mut mesh: Mesh3D = terrain.to_mesh3d(MESH_NAME_CLIFF_TERRAIN, mat);
    for vert in mesh.get_mut_vertices().iter_mut() {
        let p: Vec3 = vert.get_position();
        let dist: f32 = (p.get_x() * p.get_x() + p.get_z() * p.get_z()).sqrt();
        let sculpted_y: f32 = if dist < 6.4 {
            -0.78 - (dist / 6.4) * 0.25
        } else if dist < 11.5 {
            let abyss_t: f32 = (dist - 6.4) / 5.1;
            -1.03 - abyss_t * 3.8 + p.get_y() * 0.12
        } else {
            let rim_t: f32 = ((dist - 11.5) / 10.5).clamp(0.0, 1.0);
            -4.8 + p.get_y() * (0.45 + rim_t * 1.15)
        };
        vert.set_position(Vec3::new(p.get_x(), sculpted_y, p.get_z()));
    }
    gradient_tint_mesh_y(
        &mut mesh,
        -5.0,
        7.5,
        [220, 228, 224, 255],
        [34, 68, 78, 255],
    );
    finalize_jianlai_mesh(mesh, MESH_NAME_CLIFF_TERRAIN, mat, false)
}

/// Builds a towering jagged Guilin ink-wash karst mountain peak spire via asymmetric ridged `loft_profiles`.
///
/// # Arguments
///
/// - `f32` - Base radius in meters.
/// - `f32` - Peak summit height in meters.
/// - `f32` - Deterministic angular ridge phase offset in radians.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted jagged karst mountain spire mesh.
#[must_use]
pub fn build_jianlai_karst_spire_mesh(base_radius: f32, height: f32, phase: f32) -> Mesh3D {
    let levels: [(f32, f32, f32); 6] = [
        (0.0, 1.0, 0.16),
        (0.22, 0.82, 0.20),
        (0.46, 0.64, 0.24),
        (0.70, 0.46, 0.22),
        (0.90, 0.24, 0.18),
        (1.0, 0.05, 0.08),
    ];
    let mut rings: Vec<Vec<Vec3>> = Vec::with_capacity(levels.len());
    for (t, r_scale, ridge_amp) in levels {
        let lean_x: f32 = (phase.cos() * 0.9) * t * t;
        let lean_z: f32 = (phase.sin() * 0.9) * t * t;
        let mut ring: Vec<Vec3> = Vec::with_capacity(14);
        for i in 0..14 {
            let ang: f32 = ((i as f32) / 14.0) * TAU + phase;
            let facet: f32 = 1.0
                + ridge_amp * (ang * 3.0 + t * 2.2).cos()
                + (ridge_amp * 0.5) * (ang * 5.0).sin();
            let rad: f32 = base_radius * r_scale * facet;
            ring.push(Vec3::new(
                lean_x + rad * ang.cos(),
                t * height,
                lean_z + rad * ang.sin(),
            ));
        }
        rings.push(ring);
    }
    let mut spire: Mesh3D = loft_profiles(&rings, false);
    gradient_tint_mesh_y(
        &mut spire,
        0.0,
        height,
        [224, 232, 228, 255],
        [28, 56, 68, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.22, 0.36, 0.40))
        .set_metallic(0.05)
        .set_roughness(0.86);
    finalize_jianlai_mesh(spire, MESH_NAME_KARST_SPIRE, mat, true)
}

/// Builds the gnarled cliffside Chinese ink-pine tree combining twisted spline branches and layered L-system pine canopies.
///
/// # Returns
///
/// - `(Mesh3D, Mesh3D)` - `(trunk_and_limbs_mesh, layered_needle_canopy_mesh)`.
#[must_use]
pub fn build_jianlai_cliff_pine_meshes() -> (Mesh3D, Mesh3D) {
    let trunk_spline: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(0.0, -0.45, 0.0),
            Vec3::new(-0.35, 0.55, 0.15),
            Vec3::new(-0.92, 1.55, 0.42),
            Vec3::new(-1.35, 2.48, 0.25),
            Vec3::new(-1.10, 3.32, -0.10),
        ],
        false,
    );
    let limb_a: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(-0.88, 1.52, 0.40),
            Vec3::new(-1.75, 1.72, 0.92),
            Vec3::new(-2.45, 1.82, 1.18),
        ],
        false,
    );
    let limb_b: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(-1.30, 2.40, 0.24),
            Vec3::new(-0.48, 2.75, 0.88),
            Vec3::new(0.18, 2.92, 1.05),
        ],
        false,
    );
    let bark_prof: Vec<Vec2> = build_profile_ellipse_2d(0.24, 0.22, 8);
    let t_mesh: Mesh3D = sweep_along_spline(
        &bark_prof,
        &trunk_spline,
        14,
        &[1.25, 0.95, 0.72, 0.48, 0.22],
    );
    let la_mesh: Mesh3D = sweep_along_spline(&bark_prof, &limb_a, 8, &[0.48, 0.30, 0.12]);
    let lb_mesh: Mesh3D = sweep_along_spline(&bark_prof, &limb_b, 8, &[0.42, 0.26, 0.10]);
    let mut pine_cfg: ProceduralTreeConfig = ProceduralTreeConfig::pine();
    let _: &mut ProceduralTreeConfig = pine_cfg
        .set_iterations(2)
        .set_trunk_radius(0.10)
        .set_segment_length(0.55)
        .set_radial_segments(6)
        .set_leaf_cluster_size(0.68);
    let proc_pine: ProceduralTreeResult = generate_procedural_tree(&pine_cfg, 2026);
    let shifted_proc_branch: Mesh3D = transform_mesh(
        proc_pine.get_branch_mesh(),
        &Transform3D::new(Vec3::new(-1.08, 2.85, -0.08), 0.4, Vec3::splat(0.75)).to_mat4(),
    );
    let mut trunk_merged: Mesh3D = merge_meshes(
        &[t_mesh, la_mesh, lb_mesh, shifted_proc_branch],
        MESH_NAME_PINE_TRUNK,
    );
    tint_mesh_vertices(&mut trunk_merged, [58, 48, 42, 255]);
    let pad_specs: [(Vec3, Vec3); 5] = [
        (Vec3::new(-2.40, 1.94, 1.16), Vec3::new(1.18, 0.28, 0.94)),
        (Vec3::new(-1.55, 2.55, 0.45), Vec3::new(1.05, 0.26, 0.88)),
        (Vec3::new(0.14, 3.04, 1.02), Vec3::new(0.96, 0.24, 0.84)),
        (Vec3::new(-1.12, 3.46, -0.10), Vec3::new(1.25, 0.32, 1.06)),
        (Vec3::new(-0.65, 3.88, -0.15), Vec3::new(0.84, 0.24, 0.76)),
    ];
    let mut canopy_parts: Vec<Mesh3D> = Vec::with_capacity(6);
    let base_pad: Mesh3D = icosphere(1.0, 2);
    for (center, scale_v) in pad_specs {
        let pad: Mesh3D =
            transform_mesh(&base_pad, &Transform3D::new(center, 0.3, scale_v).to_mat4());
        canopy_parts.push(pad);
    }
    let proc_leaves: Mesh3D = transform_mesh(
        proc_pine.get_foliage_mesh(),
        &Transform3D::new(Vec3::new(-1.08, 2.85, -0.08), 0.4, Vec3::splat(0.75)).to_mat4(),
    );
    canopy_parts.push(proc_leaves);
    let mut canopy_merged: Mesh3D = merge_meshes(&canopy_parts, MESH_NAME_PINE_CANOPY);
    gradient_tint_mesh_y(
        &mut canopy_merged,
        1.70,
        4.10,
        [24, 62, 54, 255],
        [52, 118, 92, 255],
    );
    let mut bark_mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = bark_mat
        .set_base_color(Vec3::new(0.24, 0.20, 0.18))
        .set_metallic(0.02)
        .set_roughness(0.90);
    let mut leaf_mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = leaf_mat
        .set_base_color(Vec3::new(0.16, 0.38, 0.30))
        .set_metallic(0.02)
        .set_roughness(0.76);
    (
        finalize_jianlai_mesh(trunk_merged, MESH_NAME_PINE_TRUNK, bark_mat, true),
        finalize_jianlai_mesh(canopy_merged, MESH_NAME_PINE_CANOPY, leaf_mat, true),
    )
}

/// Builds a sinuous drifting Xuan-paper ink-cloud mist ribbon via spline sweep.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted organic horizontal mist ribbon mesh.
#[must_use]
pub fn build_jianlai_cloud_ribbon_mesh() -> Mesh3D {
    let spline: Spline3D = Spline3D::catmull_rom(
        vec![
            Vec3::new(-4.5, 0.0, -0.6),
            Vec3::new(-2.1, 0.28, 0.85),
            Vec3::new(0.2, -0.12, -0.45),
            Vec3::new(2.5, 0.22, 0.72),
            Vec3::new(4.8, 0.0, -0.35),
        ],
        false,
    );
    let profile: Vec<Vec2> = build_profile_ellipse_2d(0.55, 0.08, 8);
    let mut ribbon: Mesh3D =
        sweep_along_spline(&profile, &spline, 18, &[0.15, 0.85, 1.0, 0.82, 0.12]);
    tint_mesh_vertices(&mut ribbon, [242, 246, 244, 210]);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.92, 0.94, 0.92))
        .set_metallic(0.0)
        .set_roughness(0.95)
        .set_emissive(Vec3::new(0.18, 0.22, 0.24));
    finalize_jianlai_mesh(ribbon, MESH_NAME_CLOUD_RIBBON, mat, true)
}

/// Builds the colossal Sky-Cleaving crescent sword-qi energy wave via tapered curved lofting.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted razor-edged sweeping 7m crescent energy wave mesh.
#[must_use]
pub fn build_jianlai_crescent_qi_mesh() -> Mesh3D {
    let mut rings: Vec<Vec<Vec3>> = Vec::with_capacity(15);
    for i in 0..=14usize {
        let t: f32 = (i as f32) / 14.0;
        let ang: f32 = (t - 0.5) * 2.15;
        let taper: f32 = (t * PI).sin().powf(0.72).max(0.04);
        let arc_r: f32 = 3.6;
        let cx: f32 = arc_r * (ang.cos() - 1.0) * 0.65;
        let cy: f32 = arc_r * ang.sin();
        let depth: f32 = 1.45 * taper;
        let thick: f32 = 0.14 * taper;
        rings.push(vec![
            Vec3::new(cx, cy, depth),
            Vec3::new(cx + thick, cy, depth * 0.15),
            Vec3::new(cx + thick * 0.35, cy, -depth * 0.65),
            Vec3::new(cx - thick * 0.35, cy, -depth * 0.65),
            Vec3::new(cx - thick, cy, depth * 0.15),
        ]);
    }
    let mut wave: Mesh3D = loft_profiles(&rings, false);
    gradient_tint_mesh_y(
        &mut wave,
        -3.5,
        3.5,
        [255, 198, 68, 255],
        [118, 244, 248, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(1.0, 0.84, 0.36))
        .set_metallic(0.2)
        .set_roughness(0.18)
        .set_emissive(Vec3::new(2.4, 1.55, 0.42));
    finalize_jianlai_mesh(wave, MESH_NAME_CRESCENT_QI, mat, true)
}

/// Builds the calligraphic ink-splash shockwave ring expanding along the terrace during ultimates.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted undulating lotus-ink shockwave ring mesh.
#[must_use]
pub fn build_jianlai_shockwave_ring_mesh() -> Mesh3D {
    let mut ring_mesh: Mesh3D = torus(1.45, 0.12, 32, 8);
    for vert in ring_mesh.get_mut_vertices().iter_mut() {
        let p: Vec3 = vert.get_position();
        let ang: f32 = p.get_z().atan2(p.get_x());
        let splash: f32 = 1.0 + 0.18 * (ang * 7.0).sin() + 0.10 * (ang * 13.0).cos();
        vert.set_position(Vec3::new(
            p.get_x() * splash,
            p.get_y() * (0.65 + 0.55 * (ang * 5.0).cos().abs()),
            p.get_z() * splash,
        ));
    }
    tint_mesh_vertices(&mut ring_mesh, [58, 212, 224, 240]);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.14, 0.22, 0.28))
        .set_metallic(0.15)
        .set_roughness(0.32)
        .set_emissive(Vec3::new(0.45, 1.45, 1.65));
    finalize_jianlai_mesh(ring_mesh, MESH_NAME_SHOCKWAVE_RING, mat, true)
}

/// Builds the sweeping cyan-ink sword-arc motion trail ribbon orbiting around the blade path.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted curved motion-blur slash arc ribbon mesh.
#[must_use]
pub fn build_jianlai_sword_trail_mesh() -> Mesh3D {
    let mut rings: Vec<Vec<Vec3>> = Vec::with_capacity(13);
    for i in 0..=12usize {
        let t: f32 = (i as f32) / 12.0;
        let ang: f32 = t * PI * 1.35;
        let taper: f32 = (t * PI).sin().max(0.05);
        let r_inner: f32 = 0.85;
        let r_outer: f32 = 0.85 + 0.88 * taper;
        let y_wave: f32 = (t * PI * 2.0).sin() * 0.28;
        let c: f32 = ang.cos();
        let s: f32 = ang.sin();
        rings.push(vec![
            Vec3::new(r_inner * c, y_wave, r_inner * s),
            Vec3::new(
                (r_inner + r_outer) * 0.5 * c,
                y_wave + 0.04 * taper,
                (r_inner + r_outer) * 0.5 * s,
            ),
            Vec3::new(r_outer * c, y_wave, r_outer * s),
            Vec3::new(
                (r_inner + r_outer) * 0.5 * c,
                y_wave - 0.04 * taper,
                (r_inner + r_outer) * 0.5 * s,
            ),
        ]);
    }
    let mut trail: Mesh3D = loft_profiles(&rings, false);
    tint_mesh_vertices(&mut trail, [82, 232, 238, 235]);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.32, 0.92, 0.96))
        .set_metallic(0.1)
        .set_roughness(0.22)
        .set_emissive(Vec3::new(0.45, 1.85, 2.05));
    finalize_jianlai_mesh(trail, MESH_NAME_SWORD_TRAIL, mat, true)
}

/// Builds a Blender-style octahedral armature bone prism extending from `y = 0.0` (head joint) to `y = 1.0` (tail joint).
///
/// # Returns
///
/// - `Mesh3D` - Unit-length sculpted octahedral Blender armature bone mesh.
#[must_use]
pub fn build_octahedral_bone_mesh() -> Mesh3D {
    let rings: Vec<Vec<Vec3>> = vec![
        vec![
            Vec3::new(0.014, 0.0, 0.0),
            Vec3::new(0.0, 0.0, 0.014),
            Vec3::new(-0.014, 0.0, 0.0),
            Vec3::new(0.0, 0.0, -0.014),
        ],
        vec![
            Vec3::new(0.095, 0.22, 0.0),
            Vec3::new(0.0, 0.22, 0.095),
            Vec3::new(-0.095, 0.22, 0.0),
            Vec3::new(0.0, 0.22, -0.095),
        ],
        vec![
            Vec3::new(0.010, 1.0, 0.0),
            Vec3::new(0.0, 1.0, 0.010),
            Vec3::new(-0.010, 1.0, 0.0),
            Vec3::new(0.0, 1.0, -0.010),
        ],
    ];
    let mut bone: Mesh3D = loft_profiles(&rings, false);
    tint_mesh_vertices(&mut bone, [84, 242, 224, 255]);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.28, 0.96, 0.88))
        .set_metallic(0.15)
        .set_roughness(0.25)
        .set_emissive(Vec3::new(0.45, 1.35, 1.25));
    finalize_jianlai_mesh(bone, MESH_NAME_BONE_PRISM, mat, true)
}

/// Builds an inverted-hull Freestyle calligraphy ink outline mesh from `source`, preserving `skin_influences` and `morph_targets`.
///
/// # Arguments
///
/// - `&Mesh3D` - Source sculpted mesh.
/// - `f32` - Normal extrusion thickness in meters.
/// - `&str` - Name for the generated outline mesh.
///
/// # Returns
///
/// - `Mesh3D` - Reversed-winding dark sumi-ink silhouette hull mesh.
#[must_use]
pub fn build_freestyle_outline_mesh(source: &Mesh3D, thickness: f32, name: &str) -> Mesh3D {
    let thick: f32 = thickness.abs().clamp(0.002, 0.15);
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(source.get_vertices().len());
    for vert in source.get_vertices().iter() {
        let mut v: Vertex3D = *vert;
        let n: Vec3 = vert.get_normal();
        let unit_n: Vec3 = if n.length_sq() > 1.0e-8 {
            n.normalize()
        } else {
            Vec3::new(0.0, 1.0, 0.0)
        };
        v.set_position(vert.get_position().add(unit_n.scale(thick)));
        v.set_normal(unit_n.scale(-1.0));
        v.set_color0([16, 20, 28, 255]);
        v.set_flags(v.get_flags() | 8);
        out_verts.push(v);
    }
    let mut rev_tris: Vec<[u32; 3]> = Vec::with_capacity(source.get_indices().len());
    for &[i0, i1, i2] in source.get_indices().iter() {
        rev_tris.push([i0, i2, i1]);
    }
    let mut ink_mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = ink_mat
        .set_base_color(Vec3::new(0.03, 0.035, 0.05))
        .set_metallic(0.0)
        .set_roughness(1.0);
    let mut outline: Mesh3D = Mesh3D::from_parts(name.to_string(), out_verts, rev_tris, ink_mat);
    outline.set_is_closed(true);
    if !source.get_skin_influences().is_empty() {
        outline.set_skin_influences(source.get_skin_influences().clone());
    }
    if !source.get_morph_targets().is_empty() {
        outline.set_morph_targets(source.get_morph_targets().clone());
    }
    outline
}

/// Builds a sculpted topological wireframe cage mesh by emitting thin 3-sided edge struts along sampled unique edges of `source`.
///
/// # Arguments
///
/// - `&Mesh3D` - Source mesh whose topology is inspected.
/// - `f32` - Edge strut radius in meters.
/// - `usize` - Maximum number of unique edges emitted to keep wireframe fast on WASM/mobile.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted wireframe topology inspection mesh.
#[must_use]
pub fn build_wireframe_cage_mesh(source: &Mesh3D, edge_radius: f32, max_edges: usize) -> Mesh3D {
    let src_verts: &[Vertex3D] = source.get_vertices().as_slice();
    let src_tris: &[[u32; 3]] = source.get_indices().as_slice();
    let stride: usize = (src_tris.len().saturating_mul(3) / max_edges.max(1)).max(1);
    let mut seen: HashSet<(u32, u32)> = HashSet::with_capacity(max_edges.min(1024));
    let mut out_verts: Vec<Vertex3D> = Vec::with_capacity(max_edges.min(1024) * 6);
    let mut out_tris: Vec<[u32; 3]> = Vec::with_capacity(max_edges.min(1024) * 6);
    let r: f32 = edge_radius.abs().clamp(0.002, 0.04);
    let mut edge_counter: usize = 0;
    for &[i0, i1, i2] in src_tris.iter() {
        for (a, b) in [(i0, i1), (i1, i2), (i2, i0)] {
            edge_counter = edge_counter.saturating_add(1);
            if !edge_counter.is_multiple_of(stride) {
                continue;
            }
            if seen.len() >= max_edges {
                break;
            }
            let key: (u32, u32) = if a < b { (a, b) } else { (b, a) };
            if !seen.insert(key) {
                continue;
            }
            let (Some(va), Some(vb)) = (src_verts.get(a as usize), src_verts.get(b as usize))
            else {
                continue;
            };
            let pa: Vec3 = va.get_position();
            let pb: Vec3 = vb.get_position();
            let dir: Vec3 = pb.sub(pa);
            let len: f32 = dir.length();
            if len < 1.0e-4 {
                continue;
            }
            let axis: Vec3 = dir.scale(1.0 / len);
            let up_ref: Vec3 = if axis.get_y().abs() > 0.9 {
                Vec3::new(1.0, 0.0, 0.0)
            } else {
                Vec3::new(0.0, 1.0, 0.0)
            };
            let u_vec: Vec3 = axis.cross(up_ref).normalize().scale(r);
            let v_vec: Vec3 = axis.cross(u_vec).normalize().scale(r);
            let base_v: u32 = out_verts.len() as u32;
            let ring_offsets: [Vec3; 3] = [
                u_vec,
                u_vec.scale(-0.5).add(v_vec.scale(0.866)),
                u_vec.scale(-0.5).add(v_vec.scale(-0.866)),
            ];
            for off in ring_offsets {
                let n: Vec3 = off.normalize();
                out_verts.push(Vertex3D::new(pa.add(off), n));
            }
            for off in ring_offsets {
                let n: Vec3 = off.normalize();
                out_verts.push(Vertex3D::new(pb.add(off), n));
            }
            for k in 0..3u32 {
                let kn: u32 = (k + 1) % 3;
                out_tris.push([base_v + k, base_v + kn, base_v + 3 + kn]);
                out_tris.push([base_v + k, base_v + 3 + kn, base_v + 3 + k]);
            }
        }
    }
    let mut wire_mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = wire_mat
        .set_base_color(Vec3::new(0.32, 0.86, 0.95))
        .set_metallic(0.1)
        .set_roughness(0.35)
        .set_emissive(Vec3::new(0.24, 0.68, 0.78));
    finalize_jianlai_mesh(
        Mesh3D::from_parts(
            MESH_NAME_WIREFRAME_CAGE.to_string(),
            out_verts,
            out_tris,
            wire_mat,
        ),
        MESH_NAME_WIREFRAME_CAGE,
        wire_mat,
        false,
    )
}

/// Builds a sculpted carved celadon jade talisman tablet for the 256-entity celestial sword-vortex stress lab.
///
/// # Returns
///
/// - `Mesh3D` - Beveled curved jade talisman tablet mesh (zero simple cubes).
#[must_use]
pub fn build_jianlai_jade_talisman_mesh() -> Mesh3D {
    let profile: Vec<Vec2> = vec![
        Vec2::new(0.0, 0.58),
        Vec2::new(0.20, 0.44),
        Vec2::new(0.24, 0.14),
        Vec2::new(0.22, -0.36),
        Vec2::new(0.10, -0.54),
        Vec2::new(0.0, -0.58),
        Vec2::new(-0.10, -0.54),
        Vec2::new(-0.22, -0.36),
        Vec2::new(-0.24, 0.14),
        Vec2::new(-0.20, 0.44),
    ];
    let mut talisman: Mesh3D = extrude_profile(&profile, 0.08, 0.018, 2);
    gradient_tint_mesh_y(
        &mut talisman,
        -0.58,
        0.58,
        [52, 168, 146, 255],
        [148, 242, 214, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.36, 0.82, 0.72))
        .set_metallic(0.28)
        .set_roughness(0.22)
        .set_emissive(Vec3::new(0.12, 0.42, 0.36));
    finalize_jianlai_mesh(talisman, MESH_NAME_JADE_TALISMAN, mat, true)
}

/// Builds a sculpted fluted sword-tomb monolith spire for the 256-entity celestial sword-vortex stress lab.
///
/// # Returns
///
/// - `Mesh3D` - Tapered octagonal fluted stone monolith spire mesh (zero simple cubes).
#[must_use]
pub fn build_jianlai_monolith_spire_mesh() -> Mesh3D {
    let rings: Vec<Vec<Vec3>> = vec![
        build_elliptic_ring(Vec3::new(0.0, 0.0, 0.0), 0.44, 0.36, 10, 0.10, 5.0),
        build_elliptic_ring(Vec3::new(0.0, 0.55, 0.0), 0.36, 0.28, 10, 0.08, 5.0),
        build_elliptic_ring(Vec3::new(0.0, 1.35, 0.0), 0.28, 0.22, 10, 0.12, 5.0),
        build_elliptic_ring(Vec3::new(0.0, 2.05, 0.0), 0.16, 0.12, 10, 0.10, 5.0),
        build_elliptic_ring(Vec3::new(0.0, 2.38, 0.0), 0.03, 0.03, 10, 0.0, 1.0),
    ];
    let mut spire: Mesh3D = loft_profiles(&rings, false);
    gradient_tint_mesh_y(
        &mut spire,
        0.0,
        2.38,
        [46, 68, 78, 255],
        [176, 194, 198, 255],
    );
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.32, 0.42, 0.46))
        .set_metallic(0.16)
        .set_roughness(0.62);
    finalize_jianlai_mesh(spire, MESH_NAME_MONOLITH_SPIRE, mat, true)
}

/// Builds a carved lotus stone pedestal used to display sculpted spirit swords in the PBR material gallery.
///
/// # Returns
///
/// - `Mesh3D` - Sculpted lathe-revolved lotus stone pedestal mesh.
#[must_use]
pub fn build_jianlai_lotus_pedestal_mesh() -> Mesh3D {
    let profile: Vec<Vec2> = vec![
        Vec2::new(0.0, 0.0),
        Vec2::new(0.62, 0.0),
        Vec2::new(0.56, 0.12),
        Vec2::new(0.42, 0.22),
        Vec2::new(0.34, 0.36),
        Vec2::new(0.48, 0.50),
        Vec2::new(0.52, 0.62),
        Vec2::new(0.38, 0.68),
        Vec2::new(0.0, 0.70),
    ];
    let mut ped: Mesh3D = lathe_revolve(&profile, 20, TAU);
    gradient_tint_mesh_y(&mut ped, 0.0, 0.70, [68, 78, 86, 255], [182, 188, 186, 255]);
    let mut mat: PbrMaterial = PbrMaterial::default();
    let _: &mut PbrMaterial = mat
        .set_base_color(Vec3::new(0.54, 0.58, 0.60))
        .set_metallic(0.12)
        .set_roughness(0.54);
    finalize_jianlai_mesh(ped, MESH_NAME_LOTUS_PEDESTAL, mat, true)
}

/// Appends one rotation keyframe track onto `clip` for `target_node`.
///
/// # Arguments
///
/// - `&mut ImportedAnimationClip3D` - Destination clip being constructed.
/// - `u32` - Scene-graph bone node ID animated by this track.
/// - `&[f32]` - Monotonic keyframe timestamps in seconds.
/// - `&[Quat]` - Unit quaternion orientations aligned with timestamps.
pub(crate) fn push_clip_rot_track(
    clip: &mut ImportedAnimationClip3D,
    target_node: u32,
    timestamps: &[f32],
    rotations: &[Quat],
) {
    let mut values: Vec<f32> = Vec::with_capacity(rotations.len() * 4);
    for q in rotations.iter() {
        let u: Quat = q.normalize();
        values.push(u.get_x());
        values.push(u.get_y());
        values.push(u.get_z());
        values.push(u.get_w());
    }
    let sampler_idx: usize = clip.get_samplers().len();
    clip.get_mut_samplers().push(ImportedAnimationSampler3D {
        timestamps: timestamps.to_vec(),
        values,
        value_stride: 4,
        interpolation: GltfInterpolationMode::Linear,
    });
    clip.get_mut_channels()
        .push(ImportedAnimationChannel3D::new(
            target_node,
            GltfAnimationPath::Rotation,
            sampler_idx,
        ));
}

/// Appends one translation keyframe track onto `clip` for `target_node`.
///
/// # Arguments
///
/// - `&mut ImportedAnimationClip3D` - Destination clip being constructed.
/// - `u32` - Scene-graph bone node ID animated by this track.
/// - `&[f32]` - Monotonic keyframe timestamps in seconds.
/// - `&[Vec3]` - Local translations aligned with timestamps.
pub(crate) fn push_clip_trans_track(
    clip: &mut ImportedAnimationClip3D,
    target_node: u32,
    timestamps: &[f32],
    translations: &[Vec3],
) {
    let mut values: Vec<f32> = Vec::with_capacity(translations.len() * 3);
    for p in translations.iter() {
        values.push(p.get_x());
        values.push(p.get_y());
        values.push(p.get_z());
    }
    let sampler_idx: usize = clip.get_samplers().len();
    clip.get_mut_samplers().push(ImportedAnimationSampler3D {
        timestamps: timestamps.to_vec(),
        values,
        value_stride: 3,
        interpolation: GltfInterpolationMode::Linear,
    });
    clip.get_mut_channels()
        .push(ImportedAnimationChannel3D::new(
            target_node,
            GltfAnimationPath::Translation,
            sampler_idx,
        ));
}

/// Builds all 5 martial arts and ultimate NLA `ImportedAnimationClip3D` actions driving the 27-bone Jianlai armature.
///
/// # Arguments
///
/// - `&[u32; JIANLAI_BONE_COUNT]` - Scene-graph node IDs for all 27 armature joints.
/// - `&[Vec3; JIANLAI_BONE_COUNT]` - Local rest translations for all 27 armature joints.
///
/// # Returns
///
/// - `Vec<ImportedAnimationClip3D>` - Five rich NLA clips (`InkStance`, `FlowingSwordDance`, `MyriadSwordsReturn`, `SkyCleavingSwordQi`, `CloudStepGlide`).
#[must_use]
pub fn build_jianlai_nla_clips(
    bone_nodes: &[u32; JIANLAI_BONE_COUNT],
    rest_trans: &[Vec3; JIANLAI_BONE_COUNT],
) -> Vec<ImportedAnimationClip3D> {
    let mut clips: Vec<ImportedAnimationClip3D> = Vec::with_capacity(JIANLAI_ACTION_COUNT);
    // Clip 0: Ink Stance - poised crane-breath stance, hovering sword, swaying sleeves.
    let mut c0: ImportedAnimationClip3D = ImportedAnimationClip3D {
        name: JIANLAI_ACTION_LABELS[0].to_string(),
        duration_secs: 3.2,
        samplers: Vec::new(),
        channels: Vec::new(),
    };
    let t0: [f32; 5] = [0.0, 0.8, 1.6, 2.4, 3.2];
    let p_rest: Vec3 = rest_trans[BONE_PELVIS];
    push_clip_trans_track(
        &mut c0,
        bone_nodes[BONE_PELVIS],
        &t0,
        &[
            p_rest,
            p_rest.add(Vec3::new(0.0, 0.035, 0.0)),
            p_rest,
            p_rest.add(Vec3::new(0.0, -0.02, 0.0)),
            p_rest,
        ],
    );
    push_clip_rot_track(
        &mut c0,
        bone_nodes[BONE_SPINE],
        &t0,
        &[
            Quat::from_euler_yxz(0.14, 0.04, 0.0),
            Quat::from_euler_yxz(0.20, -0.03, 0.02),
            Quat::from_euler_yxz(0.14, 0.04, 0.0),
            Quat::from_euler_yxz(0.08, 0.06, -0.02),
            Quat::from_euler_yxz(0.14, 0.04, 0.0),
        ],
    );
    push_clip_rot_track(
        &mut c0,
        bone_nodes[BONE_UPPER_ARM_L],
        &t0,
        &[
            Quat::from_euler_yxz(0.28, -0.42, 0.34),
            Quat::from_euler_yxz(0.36, -0.54, 0.42),
            Quat::from_euler_yxz(0.28, -0.42, 0.34),
            Quat::from_euler_yxz(0.22, -0.34, 0.28),
            Quat::from_euler_yxz(0.28, -0.42, 0.34),
        ],
    );
    push_clip_rot_track(
        &mut c0,
        bone_nodes[BONE_UPPER_ARM_R],
        &t0,
        &[
            Quat::from_euler_yxz(-0.24, -0.36, -0.28),
            Quat::from_euler_yxz(-0.32, -0.48, -0.38),
            Quat::from_euler_yxz(-0.24, -0.36, -0.28),
            Quat::from_euler_yxz(-0.18, -0.28, -0.22),
            Quat::from_euler_yxz(-0.24, -0.36, -0.28),
        ],
    );
    push_clip_rot_track(
        &mut c0,
        bone_nodes[BONE_FOREARM_R],
        &t0,
        &[
            Quat::from_euler_yxz(0.18, -0.42, 0.0),
            Quat::from_euler_yxz(0.28, -0.52, 0.08),
            Quat::from_euler_yxz(0.18, -0.42, 0.0),
            Quat::from_euler_yxz(0.10, -0.35, -0.06),
            Quat::from_euler_yxz(0.18, -0.42, 0.0),
        ],
    );
    clips.push(c0);
    // Clip 1: Flowing Sword Dance - spinning figure-eight combo slashes & agile footwork.
    let mut c1: ImportedAnimationClip3D = ImportedAnimationClip3D {
        name: JIANLAI_ACTION_LABELS[1].to_string(),
        duration_secs: 2.8,
        samplers: Vec::new(),
        channels: Vec::new(),
    };
    let t1: [f32; 5] = [0.0, 0.7, 1.4, 2.1, 2.8];
    push_clip_rot_track(
        &mut c1,
        bone_nodes[BONE_ROOT],
        &t1,
        &[
            Quat::from_euler_yxz(0.0, 0.0, 0.0),
            Quat::from_euler_yxz(FRAC_PI_2, 0.0, 0.0),
            Quat::from_euler_yxz(PI, 0.0, 0.0),
            Quat::from_euler_yxz(-FRAC_PI_2, 0.0, 0.0),
            Quat::from_euler_yxz(0.0, 0.0, 0.0),
        ],
    );
    push_clip_trans_track(
        &mut c1,
        bone_nodes[BONE_PELVIS],
        &t1,
        &[
            p_rest,
            p_rest.add(Vec3::new(0.0, 0.14, 0.08)),
            p_rest.add(Vec3::new(0.0, -0.06, -0.04)),
            p_rest.add(Vec3::new(0.0, 0.18, 0.06)),
            p_rest,
        ],
    );
    push_clip_rot_track(
        &mut c1,
        bone_nodes[BONE_UPPER_ARM_R],
        &t1,
        &[
            Quat::from_euler_yxz(-0.55, -0.85, -0.45),
            Quat::from_euler_yxz(0.95, -0.35, -0.82),
            Quat::from_euler_yxz(-0.85, -1.05, -0.25),
            Quat::from_euler_yxz(0.75, -0.62, -0.78),
            Quat::from_euler_yxz(-0.55, -0.85, -0.45),
        ],
    );
    push_clip_rot_track(
        &mut c1,
        bone_nodes[BONE_UPPER_ARM_L],
        &t1,
        &[
            Quat::from_euler_yxz(0.45, -0.65, 0.72),
            Quat::from_euler_yxz(-0.40, -0.95, 0.45),
            Quat::from_euler_yxz(0.62, -0.48, 0.85),
            Quat::from_euler_yxz(-0.25, -0.82, 0.58),
            Quat::from_euler_yxz(0.45, -0.65, 0.72),
        ],
    );
    push_clip_rot_track(
        &mut c1,
        bone_nodes[BONE_THIGH_L],
        &t1,
        &[
            Quat::from_euler_yxz(0.0, -0.22, 0.08),
            Quat::from_euler_yxz(0.0, 0.34, 0.12),
            Quat::from_euler_yxz(0.0, -0.36, 0.05),
            Quat::from_euler_yxz(0.0, 0.28, 0.14),
            Quat::from_euler_yxz(0.0, -0.22, 0.08),
        ],
    );
    push_clip_rot_track(
        &mut c1,
        bone_nodes[BONE_THIGH_R],
        &t1,
        &[
            Quat::from_euler_yxz(0.0, 0.24, -0.08),
            Quat::from_euler_yxz(0.0, -0.34, -0.12),
            Quat::from_euler_yxz(0.0, 0.36, -0.05),
            Quat::from_euler_yxz(0.0, -0.28, -0.14),
            Quat::from_euler_yxz(0.0, 0.24, -0.08),
        ],
    );
    clips.push(c1);
    // Clip 2: Myriad Swords Return - mid-air levitation sword-seal summoning 18-sword Bagua halo.
    let mut c2: ImportedAnimationClip3D = ImportedAnimationClip3D {
        name: JIANLAI_ACTION_LABELS[2].to_string(),
        duration_secs: 4.0,
        samplers: Vec::new(),
        channels: Vec::new(),
    };
    let t2: [f32; 5] = [0.0, 0.9, 2.0, 3.1, 4.0];
    push_clip_trans_track(
        &mut c2,
        bone_nodes[BONE_PELVIS],
        &t2,
        &[
            p_rest,
            p_rest.add(Vec3::new(0.0, 0.72, 0.0)),
            p_rest.add(Vec3::new(0.0, 0.88, -0.06)),
            p_rest.add(Vec3::new(0.0, 0.65, 0.12)),
            p_rest,
        ],
    );
    push_clip_rot_track(
        &mut c2,
        bone_nodes[BONE_CHEST],
        &t2,
        &[
            Quat::from_euler_yxz(0.0, 0.08, 0.0),
            Quat::from_euler_yxz(0.0, -0.18, 0.0),
            Quat::from_euler_yxz(0.0, -0.24, 0.0),
            Quat::from_euler_yxz(0.0, 0.14, 0.0),
            Quat::from_euler_yxz(0.0, 0.08, 0.0),
        ],
    );
    push_clip_rot_track(
        &mut c2,
        bone_nodes[BONE_UPPER_ARM_L],
        &t2,
        &[
            Quat::from_euler_yxz(0.2, -0.3, 0.3),
            Quat::from_euler_yxz(0.75, -1.25, 0.55),
            Quat::from_euler_yxz(0.55, -1.42, 0.25),
            Quat::from_euler_yxz(0.15, -1.10, 0.08),
            Quat::from_euler_yxz(0.2, -0.3, 0.3),
        ],
    );
    push_clip_rot_track(
        &mut c2,
        bone_nodes[BONE_UPPER_ARM_R],
        &t2,
        &[
            Quat::from_euler_yxz(-0.2, -0.3, -0.3),
            Quat::from_euler_yxz(-0.75, -1.25, -0.55),
            Quat::from_euler_yxz(-0.55, -1.42, -0.25),
            Quat::from_euler_yxz(-0.15, -1.10, -0.08),
            Quat::from_euler_yxz(-0.2, -0.3, -0.3),
        ],
    );
    push_clip_rot_track(
        &mut c2,
        bone_nodes[BONE_THIGH_L],
        &t2,
        &[
            Quat::identity(),
            Quat::from_euler_yxz(0.0, -0.45, 0.12),
            Quat::from_euler_yxz(0.0, -0.52, 0.14),
            Quat::from_euler_yxz(0.0, -0.25, 0.08),
            Quat::identity(),
        ],
    );
    push_clip_rot_track(
        &mut c2,
        bone_nodes[BONE_SHIN_L],
        &t2,
        &[
            Quat::identity(),
            Quat::from_euler_yxz(0.0, 0.65, 0.0),
            Quat::from_euler_yxz(0.0, 0.72, 0.0),
            Quat::from_euler_yxz(0.0, 0.32, 0.0),
            Quat::identity(),
        ],
    );
    clips.push(c2);
    // Clip 3: Sky-Cleaving Sword Qi - low crouch charge -> massive overhead vertical cleave!
    let mut c3: ImportedAnimationClip3D = ImportedAnimationClip3D {
        name: JIANLAI_ACTION_LABELS[3].to_string(),
        duration_secs: 3.6,
        samplers: Vec::new(),
        channels: Vec::new(),
    };
    let t3: [f32; 5] = [0.0, 1.0, 1.55, 2.55, 3.6];
    push_clip_trans_track(
        &mut c3,
        bone_nodes[BONE_PELVIS],
        &t3,
        &[
            p_rest,
            p_rest.add(Vec3::new(0.0, -0.24, -0.14)),
            p_rest.add(Vec3::new(0.0, 0.34, 0.24)),
            p_rest.add(Vec3::new(0.0, -0.10, 0.32)),
            p_rest,
        ],
    );
    push_clip_rot_track(
        &mut c3,
        bone_nodes[BONE_SPINE],
        &t3,
        &[
            Quat::identity(),
            Quat::from_euler_yxz(-0.55, 0.38, 0.0),
            Quat::from_euler_yxz(0.68, -0.22, 0.0),
            Quat::from_euler_yxz(0.45, 0.28, 0.0),
            Quat::identity(),
        ],
    );
    push_clip_rot_track(
        &mut c3,
        bone_nodes[BONE_UPPER_ARM_R],
        &t3,
        &[
            Quat::from_euler_yxz(-0.2, -0.35, -0.3),
            Quat::from_euler_yxz(-0.95, -1.95, -0.35),
            Quat::from_euler_yxz(0.85, -0.25, -0.45),
            Quat::from_euler_yxz(0.62, 0.35, -0.25),
            Quat::from_euler_yxz(-0.2, -0.35, -0.3),
        ],
    );
    push_clip_rot_track(
        &mut c3,
        bone_nodes[BONE_UPPER_ARM_L],
        &t3,
        &[
            Quat::from_euler_yxz(0.25, -0.4, 0.35),
            Quat::from_euler_yxz(0.85, -1.45, 0.35),
            Quat::from_euler_yxz(-0.55, -0.2, 0.72),
            Quat::from_euler_yxz(-0.35, 0.15, 0.55),
            Quat::from_euler_yxz(0.25, -0.4, 0.35),
        ],
    );
    push_clip_rot_track(
        &mut c3,
        bone_nodes[BONE_SWORD_SOCKET],
        &t3,
        &[
            Quat::identity(),
            Quat::from_euler_yxz(0.0, -0.65, 0.0),
            Quat::from_euler_yxz(0.0, 0.95, 0.0),
            Quat::from_euler_yxz(0.0, 0.72, 0.0),
            Quat::identity(),
        ],
    );
    clips.push(c3);
    // Clip 4: Cloud-Step Glide - heroic hovering sword-flight glide across the misty peaks.
    let mut c4: ImportedAnimationClip3D = ImportedAnimationClip3D {
        name: JIANLAI_ACTION_LABELS[4].to_string(),
        duration_secs: 3.6,
        samplers: Vec::new(),
        channels: Vec::new(),
    };
    let t4: [f32; 5] = [0.0, 0.9, 1.8, 2.7, 3.6];
    push_clip_trans_track(
        &mut c4,
        bone_nodes[BONE_PELVIS],
        &t4,
        &[
            p_rest.add(Vec3::new(0.0, 0.48, 0.0)),
            p_rest.add(Vec3::new(0.32, 0.64, 0.18)),
            p_rest.add(Vec3::new(0.0, 0.54, 0.34)),
            p_rest.add(Vec3::new(-0.32, 0.68, 0.16)),
            p_rest.add(Vec3::new(0.0, 0.48, 0.0)),
        ],
    );
    push_clip_rot_track(
        &mut c4,
        bone_nodes[BONE_SPINE],
        &t4,
        &[
            Quat::from_euler_yxz(0.28, 0.18, 0.08),
            Quat::from_euler_yxz(0.18, 0.24, -0.14),
            Quat::from_euler_yxz(0.26, 0.20, 0.04),
            Quat::from_euler_yxz(0.36, 0.22, 0.14),
            Quat::from_euler_yxz(0.28, 0.18, 0.08),
        ],
    );
    push_clip_rot_track(
        &mut c4,
        bone_nodes[BONE_UPPER_ARM_L],
        &t4,
        &[
            Quat::from_euler_yxz(0.45, -0.25, 0.85),
            Quat::from_euler_yxz(0.55, -0.35, 0.96),
            Quat::from_euler_yxz(0.45, -0.25, 0.85),
            Quat::from_euler_yxz(0.38, -0.18, 0.78),
            Quat::from_euler_yxz(0.45, -0.25, 0.85),
        ],
    );
    push_clip_rot_track(
        &mut c4,
        bone_nodes[BONE_UPPER_ARM_R],
        &t4,
        &[
            Quat::from_euler_yxz(-0.45, -0.25, -0.85),
            Quat::from_euler_yxz(-0.38, -0.18, -0.76),
            Quat::from_euler_yxz(-0.45, -0.25, -0.85),
            Quat::from_euler_yxz(-0.55, -0.35, -0.96),
            Quat::from_euler_yxz(-0.45, -0.25, -0.85),
        ],
    );
    clips.push(c4);
    clips
}

/// Registers the full suite of ink-wash donghua, PBR, Freestyle, Matcap, Wireframe, Bone, and Shader Debug materials onto `world`.
///
/// # Arguments
///
/// - `&mut World3D` - Target world receiving procedural ink textures and `PrincipledMaterial3D` entries.
///
/// # Returns
///
/// - `JianlaiStyleMaterialIds` - Indexed material slot registry.
pub(crate) fn register_jianlai_materials(world: &mut World3D) -> JianlaiStyleMaterialIds {
    let robe_tex_idx: u32 = world.get_textures().len() as u32;
    world
        .get_mut_textures()
        .push(build_jianlai_robe_ink_texture());
    let cliff_tex_idx: u32 = world.get_textures().len() as u32;
    world
        .get_mut_textures()
        .push(build_jianlai_cliff_ink_texture());
    let terrace_tex_idx: u32 = world.get_textures().len() as u32;
    world
        .get_mut_textures()
        .push(build_jianlai_bagua_terrace_texture());
    let blade_tex_idx: u32 = world.get_textures().len() as u32;
    world
        .get_mut_textures()
        .push(build_jianlai_blade_rune_texture());
    let push_mat: fn(&mut World3D, PrincipledMaterial3D) -> u32 =
        |w: &mut World3D, mat: PrincipledMaterial3D| -> u32 {
            let id: u32 = w.get_principled_materials().len() as u32;
            w.get_mut_principled_materials().push(mat);
            id
        };
    let mut m_robe: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_robe
        .set_name(MAT_NAME_INK_ROBE.to_string())
        .set_base_color_factor([0.96, 0.98, 0.96, 1.0])
        .set_base_color_texture(Some(TextureSlot3D::from_index(robe_tex_idx, 0)))
        .set_metallic_factor(0.04)
        .set_roughness_factor(0.64)
        .set_sheen_color_factor([0.42, 0.78, 0.86])
        .set_sheen_roughness_factor(0.45);
    let ink_robe: u32 = push_mat(world, m_robe);
    let mut m_trim: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_trim
        .set_name(MAT_NAME_INK_TRIM.to_string())
        .set_base_color_factor([0.10, 0.14, 0.19, 1.0])
        .set_metallic_factor(0.12)
        .set_roughness_factor(0.68);
    let ink_trim: u32 = push_mat(world, m_trim);
    let mut m_jade: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_jade
        .set_name(MAT_NAME_INK_JADE.to_string())
        .set_base_color_factor([0.34, 0.82, 0.70, 1.0])
        .set_metallic_factor(0.14)
        .set_roughness_factor(0.18)
        .set_clearcoat_factor(0.85)
        .set_clearcoat_roughness_factor(0.12)
        .set_emissive_factor([0.10, 0.42, 0.36])
        .set_emissive_strength(0.65);
    let ink_jade: u32 = push_mat(world, m_jade);
    let mut m_bronze: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_bronze
        .set_name(MAT_NAME_INK_BRONZE.to_string())
        .set_base_color_factor([0.82, 0.66, 0.32, 1.0])
        .set_metallic_factor(0.88)
        .set_roughness_factor(0.24)
        .set_clearcoat_factor(0.35);
    let ink_bronze: u32 = push_mat(world, m_bronze);
    let mut m_blade: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_blade
        .set_name(MAT_NAME_INK_BLADE.to_string())
        .set_base_color_factor([0.88, 0.95, 0.99, 1.0])
        .set_base_color_texture(Some(TextureSlot3D::from_index(blade_tex_idx, 0)))
        .set_metallic_factor(0.92)
        .set_roughness_factor(0.14)
        .set_clearcoat_factor(0.75)
        .set_emissive_factor([0.24, 0.78, 0.92])
        .set_emissive_strength(0.95);
    let ink_blade: u32 = push_mat(world, m_blade);
    let mut m_cinnabar: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_cinnabar
        .set_name(MAT_NAME_INK_CINNABAR.to_string())
        .set_base_color_factor([0.68, 0.18, 0.16, 1.0])
        .set_metallic_factor(0.12)
        .set_roughness_factor(0.38)
        .set_clearcoat_factor(0.45);
    let ink_cinnabar: u32 = push_mat(world, m_cinnabar);
    let mut m_cliff: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_cliff
        .set_name(MAT_NAME_INK_CLIFF.to_string())
        .set_base_color_factor([0.86, 0.92, 0.90, 1.0])
        .set_base_color_texture(Some(TextureSlot3D::from_index(cliff_tex_idx, 0)))
        .set_metallic_factor(0.02)
        .set_roughness_factor(0.86);
    let ink_cliff: u32 = push_mat(world, m_cliff);
    let mut m_terrace: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_terrace
        .set_name(MAT_NAME_INK_TERRACE.to_string())
        .set_base_color_factor([0.92, 0.94, 0.92, 1.0])
        .set_base_color_texture(Some(TextureSlot3D::from_index(terrace_tex_idx, 0)))
        .set_metallic_factor(0.16)
        .set_roughness_factor(0.58)
        .set_emissive_factor([0.22, 0.18, 0.08])
        .set_emissive_strength(0.28);
    let ink_terrace: u32 = push_mat(world, m_terrace);
    let mut m_roof: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_roof
        .set_name(MAT_NAME_PAVILION_ROOF.to_string())
        .set_base_color_factor([0.16, 0.28, 0.34, 1.0])
        .set_metallic_factor(0.28)
        .set_roughness_factor(0.32)
        .set_clearcoat_factor(0.65);
    let pavilion_roof: u32 = push_mat(world, m_roof);
    let mut m_lantern: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_lantern
        .set_name(MAT_NAME_LANTERN_GLOW.to_string())
        .set_base_color_factor([0.98, 0.72, 0.34, 1.0])
        .set_metallic_factor(0.04)
        .set_roughness_factor(0.45)
        .set_emissive_factor([1.0, 0.56, 0.18])
        .set_emissive_strength(2.4);
    let lantern_glow: u32 = push_mat(world, m_lantern);
    let mut m_bark: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_bark
        .set_name(MAT_NAME_PINE_BARK.to_string())
        .set_base_color_factor([0.22, 0.18, 0.16, 1.0])
        .set_metallic_factor(0.02)
        .set_roughness_factor(0.92);
    let pine_bark: u32 = push_mat(world, m_bark);
    let mut m_needles: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_needles
        .set_name(MAT_NAME_PINE_NEEDLES.to_string())
        .set_base_color_factor([0.16, 0.42, 0.32, 1.0])
        .set_metallic_factor(0.02)
        .set_roughness_factor(0.76);
    let pine_needles: u32 = push_mat(world, m_needles);
    let mut m_cloud: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_cloud
        .set_name(MAT_NAME_INK_CLOUD.to_string())
        .set_base_color_factor([0.94, 0.96, 0.94, 0.78])
        .set_alpha_mode(AlphaMode3D::Blend)
        .set_double_sided(true)
        .set_roughness_factor(0.94)
        .set_emissive_factor([0.36, 0.42, 0.44])
        .set_emissive_strength(0.45);
    let ink_cloud: u32 = push_mat(world, m_cloud);
    let mut m_qi_gold: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_qi_gold
        .set_name(MAT_NAME_QI_GOLD.to_string())
        .set_base_color_factor([1.0, 0.86, 0.38, 0.92])
        .set_double_sided(true)
        .set_metallic_factor(0.25)
        .set_roughness_factor(0.18)
        .set_emissive_factor([1.0, 0.72, 0.22])
        .set_emissive_strength(2.8);
    let qi_gold: u32 = push_mat(world, m_qi_gold);
    let mut m_qi_cyan: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_qi_cyan
        .set_name(MAT_NAME_QI_CYAN.to_string())
        .set_base_color_factor([0.34, 0.94, 0.98, 0.88])
        .set_double_sided(true)
        .set_metallic_factor(0.15)
        .set_roughness_factor(0.20)
        .set_emissive_factor([0.24, 0.92, 0.98])
        .set_emissive_strength(2.35);
    let qi_cyan: u32 = push_mat(world, m_qi_cyan);
    let mut m_freestyle: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_freestyle
        .set_name(MAT_NAME_FREESTYLE_INK.to_string())
        .set_base_color_factor([0.03, 0.035, 0.05, 1.0])
        .set_metallic_factor(0.0)
        .set_roughness_factor(1.0)
        .set_unlit(true);
    let freestyle_ink: u32 = push_mat(world, m_freestyle);
    let mut m_clay: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_clay
        .set_name(MAT_NAME_MATCAP_CLAY.to_string())
        .set_base_color_factor([0.74, 0.52, 0.44, 1.0])
        .set_metallic_factor(0.02)
        .set_roughness_factor(0.62)
        .set_clearcoat_factor(0.12);
    let matcap_clay: u32 = push_mat(world, m_clay);
    let mut m_wire: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_wire
        .set_name(MAT_NAME_WIREFRAME_EDGE.to_string())
        .set_base_color_factor([0.28, 0.86, 0.96, 1.0])
        .set_unlit(true)
        .set_emissive_factor([0.24, 0.82, 0.96])
        .set_emissive_strength(1.6);
    let wireframe_edge: u32 = push_mat(world, m_wire);
    let mut m_bone: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_bone
        .set_name(MAT_NAME_BONE_PRISM.to_string())
        .set_base_color_factor([0.96, 0.78, 0.24, 1.0])
        .set_metallic_factor(0.25)
        .set_roughness_factor(0.22)
        .set_emissive_factor([0.98, 0.68, 0.16])
        .set_emissive_strength(1.85);
    let bone_prism: u32 = push_mat(world, m_bone);
    let mut m_dbg_n: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_dbg_n
        .set_name(MAT_NAME_DBG_NORMALS.to_string())
        .set_base_color_factor([0.52, 0.74, 0.98, 1.0])
        .set_metallic_factor(0.0)
        .set_roughness_factor(0.12)
        .set_emissive_factor([0.22, 0.36, 0.62])
        .set_emissive_strength(0.55);
    let debug_normals: u32 = push_mat(world, m_dbg_n);
    let mut m_dbg_rm: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_dbg_rm
        .set_name(MAT_NAME_DBG_ROUGH_METAL.to_string())
        .set_base_color_factor([0.16, 0.86, 0.64, 1.0])
        .set_metallic_factor(0.85)
        .set_roughness_factor(0.25)
        .set_emissive_factor([0.12, 0.45, 0.34])
        .set_emissive_strength(0.35);
    let debug_rough_metal: u32 = push_mat(world, m_dbg_rm);
    let mut m_dbg_d: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_dbg_d
        .set_name(MAT_NAME_DBG_DEPTH.to_string())
        .set_base_color_factor([0.62, 0.64, 0.68, 1.0])
        .set_metallic_factor(0.0)
        .set_roughness_factor(0.95);
    let debug_depth: u32 = push_mat(world, m_dbg_d);
    let mut m_dbg_paper: PrincipledMaterial3D = PrincipledMaterial3D::default();
    let _: &mut PrincipledMaterial3D = m_dbg_paper
        .set_name(MAT_NAME_DBG_FREESTYLE_PAPER.to_string())
        .set_base_color_factor([0.96, 0.95, 0.91, 1.0])
        .set_metallic_factor(0.0)
        .set_roughness_factor(1.0)
        .set_unlit(true);
    let debug_freestyle_paper: u32 = push_mat(world, m_dbg_paper);
    JianlaiStyleMaterialIds {
        ink_robe,
        ink_trim,
        ink_jade,
        ink_bronze,
        ink_blade,
        ink_cinnabar,
        ink_cliff,
        ink_terrace,
        pavilion_roof,
        lantern_glow,
        pine_bark,
        pine_needles,
        ink_cloud,
        qi_gold,
        qi_cyan,
        freestyle_ink,
        matcap_clay,
        wireframe_edge,
        bone_prism,
        debug_normals,
        debug_rough_metal,
        debug_depth,
        debug_freestyle_paper,
    }
}

/// Spawns a sculpted object into `world` linked to a `SceneNode3D` with collection visibility and a `PrincipledMaterial3D` slot.
///
/// # Arguments
///
/// - `&mut World3D` - Destination world.
/// - `&str` - Human-readable Blender object name.
/// - `usize` - Registered `World3D::mesh_library` index.
/// - `Transform3D` - Initial world-space TRS transform.
/// - `u32` - Principled material index inside `World3D::principled_materials`.
/// - `u64` - Blender Collection bitmask.
/// - `bool` - Whether this object moves dynamically across frames.
///
/// # Returns
///
/// - `(u32, usize)` - `(scene_node_id, world_object_index)`.
pub(crate) fn spawn_jianlai_node_object(
    world: &mut World3D,
    name: &str,
    mesh_id: usize,
    transform: Transform3D,
    principled_mat_id: u32,
    collection_mask: u64,
    is_dynamic: bool,
) -> (u32, usize) {
    let mut node: SceneNode3D = SceneNode3D::from_name(name, None);
    let _: &mut SceneNode3D = node
        .set_local_translation(transform.get_position())
        .set_local_rotation(transform.get_rotation())
        .set_local_scale(transform.get_scale())
        .set_collection_mask(collection_mask)
        .set_mesh_id(Some(mesh_id as u32));
    let node_id: u32 = world.get_mut_scene_graph().add_node(node);
    let legacy: PbrMaterial = world
        .get_principled_materials()
        .get(principled_mat_id as usize)
        .map_or_else(PbrMaterial::default, PrincipledMaterial3D::to_legacy_pbr);
    let obj_idx: usize = world.spawn_object(name, mesh_id, transform, legacy, true);
    if let Some(obj_mut) = world.get_mut_objects().get_mut(obj_idx) {
        let _: &mut SceneObject3D = obj_mut
            .set_node_id(Some(node_id))
            .set_principled_material_id(Some(principled_mat_id));
    }
    if is_dynamic {
        let _: bool = world.set_object_dynamic(obj_idx, true);
    }
    (node_id, obj_idx)
}

/// Builds a `SceneCamera3D` looking from `eye` toward `target` with vertical FOV in degrees.
///
/// # Arguments
///
/// - `&str` - Blender camera name.
/// - `Vec3` - Camera world eye position.
/// - `Vec3` - World look-at target point.
/// - `f32` - Vertical field of view in degrees.
///
/// # Returns
///
/// - `SceneCamera3D` - Configured perspective Blender scene camera.
#[must_use]
pub(crate) fn make_jianlai_camera(
    name: &str,
    eye: Vec3,
    target: Vec3,
    fov_deg: f32,
) -> SceneCamera3D {
    let fwd: Vec3 = target.sub(eye).normalize();
    let back: Vec3 = fwd.scale(-1.0);
    let world_up: Vec3 = if back.get_y().abs() > 0.98 {
        Vec3::new(0.0, 0.0, -1.0)
    } else {
        Vec3::new(0.0, 1.0, 0.0)
    };
    let right: Vec3 = world_up.cross(back).normalize();
    let up: Vec3 = back.cross(right).normalize();
    let rot: Quat = Quat::from_mat3(right, up, back);
    SceneCamera3D {
        name: name.to_string(),
        node_id: None,
        position: eye,
        rotation: rot.normalize(),
        projection: GltfCameraProjection::Perspective {
            yfov_rad: fov_deg.to_radians(),
            aspect_ratio: None,
            znear: 0.08,
            zfar: Some(260.0),
        },
    }
}

/// Builds the complete sculpted Jianlai Ink-Wash Donghua `World3D` and its live `JianlaiSceneController` (zero simple boxes).
///
/// # Returns
///
/// - `(World3D, JianlaiSceneController)` - Ready interactive world and rigging/VFX/render-mode controller.
#[must_use]
pub fn build_jianlai_hero_scene() -> (World3D, JianlaiSceneController) {
    let mut world: World3D = World3D::default();
    world.set_use_agx_tonemap(true);
    let materials: JianlaiStyleMaterialIds = register_jianlai_materials(&mut world);
    let col_hero: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_HERO);
    let col_props: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_PROPS);
    let col_cliff: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_CLIFF);
    let col_vfx: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_VFX);
    let col_outlines: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_OUTLINES);
    let col_armature: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_ARMATURE);
    let hero_mesh: Mesh3D = build_jianlai_hero_mesh();
    let hero_vertices: usize = hero_mesh.get_vertices().len();
    let hero_triangles: usize = hero_mesh.get_indices().len();
    let hero_outline_mesh: Mesh3D = build_freestyle_outline_mesh(
        &hero_mesh,
        JIANLAI_HERO_OUTLINE_THICKNESS,
        MESH_NAME_HERO_OUTLINE,
    );
    let hero_wire_mesh: Mesh3D = build_wireframe_cage_mesh(&hero_mesh, 0.0045, 420);
    let sword_mesh: Mesh3D = build_jianlai_spirit_sword_mesh();
    let sword_outline_mesh: Mesh3D =
        build_freestyle_outline_mesh(&sword_mesh, 0.008, MESH_NAME_SWORD_OUTLINE);
    let scabbard_mesh: Mesh3D = build_jianlai_scabbard_mesh();
    let terrace_mesh: Mesh3D = build_jianlai_bagua_terrace_mesh();
    let pav_roof_mesh: Mesh3D = build_jianlai_pavilion_roof_mesh();
    let pav_roof_outline: Mesh3D = build_freestyle_outline_mesh(
        &pav_roof_mesh,
        JIANLAI_STAGE_OUTLINE_THICKNESS,
        MESH_NAME_PAVILION_ROOF,
    );
    let pav_pillars_mesh: Mesh3D = build_jianlai_pavilion_pillars_mesh();
    let lantern_mesh: Mesh3D = build_jianlai_lantern_mesh();
    let cliff_mesh: Mesh3D = build_jianlai_cliff_terrain_mesh();
    let spire_mesh_a: Mesh3D = build_jianlai_karst_spire_mesh(3.2, 16.5, 0.35);
    let spire_mesh_b: Mesh3D = build_jianlai_karst_spire_mesh(2.6, 13.8, 1.85);
    let (pine_trunk_mesh, pine_canopy_mesh): (Mesh3D, Mesh3D) = build_jianlai_cliff_pine_meshes();
    let cloud_mesh: Mesh3D = build_jianlai_cloud_ribbon_mesh();
    let crescent_mesh: Mesh3D = build_jianlai_crescent_qi_mesh();
    let shockwave_mesh: Mesh3D = build_jianlai_shockwave_ring_mesh();
    let trail_mesh: Mesh3D = build_jianlai_sword_trail_mesh();
    let bone_prism_mesh: Mesh3D = build_octahedral_bone_mesh();
    let stage_triangles: usize = terrace_mesh.get_indices().len()
        + pav_roof_mesh.get_indices().len()
        + pav_pillars_mesh.get_indices().len()
        + cliff_mesh.get_indices().len()
        + spire_mesh_a.get_indices().len() * 4
        + spire_mesh_b.get_indices().len() * 3
        + pine_trunk_mesh.get_indices().len()
        + pine_canopy_mesh.get_indices().len()
        + lantern_mesh.get_indices().len() * 4
        + cloud_mesh.get_indices().len() * 6;
    let vfx_triangles: usize = sword_mesh.get_indices().len() * (JIANLAI_MYRIAD_SWORD_COUNT + 1)
        + scabbard_mesh.get_indices().len()
        + crescent_mesh.get_indices().len()
        + shockwave_mesh.get_indices().len()
        + trail_mesh.get_indices().len();
    let total_triangles: usize = hero_triangles + stage_triangles + vfx_triangles;
    // Register meshes (keep skinned/morphed hero & outline single-LOD so distance never strips skinning!).
    let hero_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(hero_mesh));
    let hero_outline_mesh_id: usize =
        world.register_mesh(MeshLodChain::from_mesh(hero_outline_mesh));
    let hero_wire_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(hero_wire_mesh));
    let sword_mesh_id: usize = world.register_mesh(build_qem_lod_chain(&sword_mesh, 3));
    let sword_outline_mesh_id: usize =
        world.register_mesh(MeshLodChain::from_mesh(sword_outline_mesh));
    let scabbard_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(scabbard_mesh));
    let terrace_mesh_id: usize = world.register_mesh(build_qem_lod_chain(&terrace_mesh, 3));
    let pav_roof_mesh_id: usize = world.register_mesh(build_qem_lod_chain(&pav_roof_mesh, 3));
    let pav_roof_outline_id: usize = world.register_mesh(MeshLodChain::from_mesh(pav_roof_outline));
    let pav_pillars_mesh_id: usize = world.register_mesh(build_qem_lod_chain(&pav_pillars_mesh, 3));
    let lantern_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(lantern_mesh));
    let cliff_mesh_id: usize = world.register_mesh(build_qem_lod_chain(&cliff_mesh, 3));
    let spire_a_id: usize = world.register_mesh(build_qem_lod_chain(&spire_mesh_a, 3));
    let spire_b_id: usize = world.register_mesh(build_qem_lod_chain(&spire_mesh_b, 3));
    let pine_trunk_id: usize = world.register_mesh(build_qem_lod_chain(&pine_trunk_mesh, 3));
    let pine_canopy_id: usize = world.register_mesh(build_qem_lod_chain(&pine_canopy_mesh, 3));
    let cloud_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(cloud_mesh));
    let crescent_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(crescent_mesh));
    let shockwave_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(shockwave_mesh));
    let trail_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(trail_mesh));
    let bone_prism_mesh_id: usize = world.register_mesh(MeshLodChain::from_mesh(bone_prism_mesh));
    // Build the 27-bone hierarchical armature inside `World3D::scene_graph`.
    let rest_world: [Vec3; JIANLAI_BONE_COUNT] = compute_jianlai_rest_world_positions();
    let mut bone_rest_translations: [Vec3; JIANLAI_BONE_COUNT] = [Vec3::zero(); JIANLAI_BONE_COUNT];
    let mut bone_node_ids: [u32; JIANLAI_BONE_COUNT] = [0u32; JIANLAI_BONE_COUNT];
    let mut inv_bind_mats: Vec<Mat4> = Vec::with_capacity(JIANLAI_BONE_COUNT);
    for idx in 0..JIANLAI_BONE_COUNT {
        let local_arr: [f32; 3] = JIANLAI_BONE_LOCAL_REST[idx];
        let local_t: Vec3 = Vec3::new(local_arr[0], local_arr[1], local_arr[2]);
        bone_rest_translations[idx] = local_t;
        let parent_node: Option<u32> = JIANLAI_BONE_PARENTS[idx].map(|p: usize| bone_node_ids[p]);
        let mut b_node: SceneNode3D = SceneNode3D::from_name(JIANLAI_BONE_NAMES[idx], parent_node);
        let _: &mut SceneNode3D = b_node
            .set_local_translation(local_t)
            .set_collection_mask(col_hero);
        let nid: u32 = world.get_mut_scene_graph().add_node(b_node);
        bone_node_ids[idx] = nid;
        let rw: Vec3 = rest_world[idx];
        inv_bind_mats.push(Mat4::from_trs_quat(
            Vec3::new(-rw.get_x(), -rw.get_y(), -rw.get_z()),
            Quat::identity(),
            Vec3::splat(1.0),
        ));
    }
    let _: usize = world.get_mut_scene_graph().propagate_world_matrices();
    let hero_skin_idx: usize = world.get_skins().len();
    let skin: Skin3D = Skin3D::new(
        SKIN_NAME_JIANLAI_ARMATURE,
        bone_node_ids.to_vec(),
        Some(bone_node_ids[BONE_ROOT]),
        inv_bind_mats,
    )
    .with_skinning_mode(SkinningMode::DualQuaternion);
    world.get_mut_skins().push(skin);
    // Register all 5 NLA clips onto `World3D::animation_mixer`.
    let clips: Vec<ImportedAnimationClip3D> =
        build_jianlai_nla_clips(&bone_node_ids, &bone_rest_translations);
    for clip in clips {
        let _: usize = world.get_mut_animation_mixer().add_clip(clip);
    }
    let graph_snap: SceneGraph3D = world.get_scene_graph().clone();
    world
        .get_mut_animation_mixer()
        .capture_rest_pose(&graph_snap);
    let _: usize = world
        .get_mut_animation_mixer()
        .push_layer(NlaLayer3D::new(0));
    let mut scene_material_slots: Vec<(usize, u32)> = Vec::with_capacity(64);
    let mut freestyle_outline_obj_indices: Vec<usize> = Vec::with_capacity(8);
    let mut wireframe_cage_obj_indices: Vec<usize> = Vec::with_capacity(4);
    // Spawn rigged + morphed Hero character and its synchronized Freestyle ink outline hull.
    let (hero_node_id, hero_object_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_HERO,
        hero_mesh_id,
        Transform3D::default(),
        materials.get_ink_robe(),
        col_hero,
        true,
    );
    world
        .get_mut_scene_graph()
        .attach_morph_weights(hero_node_id, &[0.18, 0.22]);
    if let Some(hero_obj) = world.get_mut_objects().get_mut(hero_object_idx) {
        let _: &mut SceneObject3D = hero_obj.set_skin_id(Some(hero_skin_idx as u32));
    }
    scene_material_slots.push((hero_object_idx, materials.get_ink_robe()));
    let (hero_out_node, hero_out_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_HERO_OUTLINE,
        hero_outline_mesh_id,
        Transform3D::default(),
        materials.get_freestyle_ink(),
        col_outlines,
        true,
    );
    world
        .get_mut_scene_graph()
        .attach_morph_weights(hero_out_node, &[0.18, 0.22]);
    if let Some(out_obj) = world.get_mut_objects().get_mut(hero_out_idx) {
        let _: &mut SceneObject3D = out_obj.set_skin_id(Some(hero_skin_idx as u32));
    }
    freestyle_outline_obj_indices.push(hero_out_idx);
    let (_, hero_wire_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_WIREFRAME_CAGE,
        hero_wire_mesh_id,
        Transform3D::default(),
        materials.get_wireframe_edge(),
        col_armature,
        true,
    );
    wireframe_cage_obj_indices.push(hero_wire_idx);
    // Spawn primary Spirit Sword + Freestyle contour + floating carved Scabbard.
    let sword_init: Transform3D = Transform3D::from_trs(
        Vec3::new(0.76, 1.12, 0.22),
        Quat::from_euler_yxz(0.18, 0.65, -0.35),
        Vec3::splat(1.0),
    );
    let (_, sword_obj_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_SPIRIT_SWORD,
        sword_mesh_id,
        sword_init,
        materials.get_ink_blade(),
        col_hero,
        true,
    );
    scene_material_slots.push((sword_obj_idx, materials.get_ink_blade()));
    let (_, sword_out_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_SWORD_OUTLINE,
        sword_outline_mesh_id,
        sword_init,
        materials.get_freestyle_ink(),
        col_outlines,
        true,
    );
    freestyle_outline_obj_indices.push(sword_out_idx);
    let (_, scabbard_obj_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_SCABBARD,
        scabbard_mesh_id,
        Transform3D::from_trs(
            Vec3::new(-0.22, 1.38, -0.34),
            Quat::from_euler_yxz(0.15, 0.08, 0.42),
            Vec3::splat(1.0),
        ),
        materials.get_ink_bronze(),
        col_hero,
        true,
    );
    scene_material_slots.push((scabbard_obj_idx, materials.get_ink_bronze()));
    // Spawn 18 orbiting flying Spirit Swords.
    let mut myriad_sword_obj_indices: Vec<usize> = Vec::with_capacity(JIANLAI_MYRIAD_SWORD_COUNT);
    for idx in 0..JIANLAI_MYRIAD_SWORD_COUNT {
        let ang: f32 = ((idx as f32) / (JIANLAI_MYRIAD_SWORD_COUNT as f32)) * TAU;
        let rad: f32 = 2.05;
        let pos: Vec3 = Vec3::new(rad * ang.cos(), 2.25 + rad * ang.sin() * 0.65, -1.25);
        let mat_id: u32 = if idx % 3 == 0 {
            materials.get_qi_gold()
        } else {
            materials.get_ink_blade()
        };
        let (_, s_obj): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            &format!("MyriadSword_{idx:02}"),
            sword_mesh_id,
            Transform3D::from_trs(pos, Quat::from_euler_yxz(0.0, 0.0, ang), Vec3::splat(0.72)),
            mat_id,
            col_vfx,
            true,
        );
        scene_material_slots.push((s_obj, mat_id));
        myriad_sword_obj_indices.push(s_obj);
    }
    // Spawn colossal Crescent Sword-Qi Wave, Ink-Splash Shockwave Ring, and Cyan-Ink Sword Trail.
    let (_, crescent_qi_obj_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_CRESCENT_QI,
        crescent_mesh_id,
        Transform3D::new(Vec3::new(0.0, 2.2, 2.5), 0.0, Vec3::splat(0.001)),
        materials.get_qi_gold(),
        col_vfx,
        true,
    );
    scene_material_slots.push((crescent_qi_obj_idx, materials.get_qi_gold()));
    let (_, shockwave_ring_obj_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_SHOCKWAVE_RING,
        shockwave_mesh_id,
        Transform3D::new(Vec3::new(0.0, 0.12, 0.0), 0.0, Vec3::splat(0.001)),
        materials.get_qi_cyan(),
        col_vfx,
        true,
    );
    scene_material_slots.push((shockwave_ring_obj_idx, materials.get_qi_cyan()));
    let (_, sword_trail_obj_idx): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_SWORD_TRAIL,
        trail_mesh_id,
        Transform3D::new(Vec3::new(0.0, 1.32, 0.0), 0.0, Vec3::splat(0.001)),
        materials.get_qi_cyan(),
        col_vfx,
        true,
    );
    scene_material_slots.push((sword_trail_obj_idx, materials.get_qi_cyan()));
    // Spawn Carved Stone Bagua Terrace, Ancient Flying-Eave Pavilion, and 4 Glowing Lanterns.
    let (_, terrace_obj): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_TERRACE,
        terrace_mesh_id,
        Transform3D::default(),
        materials.get_ink_terrace(),
        col_cliff,
        false,
    );
    scene_material_slots.push((terrace_obj, materials.get_ink_terrace()));
    let pav_tr: Transform3D =
        Transform3D::new(Vec3::new(-4.35, 0.0, -4.95), 0.42, Vec3::splat(1.0));
    let (_, pav_roof_obj): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_PAVILION_ROOF,
        pav_roof_mesh_id,
        pav_tr,
        materials.get_pavilion_roof(),
        col_props,
        false,
    );
    scene_material_slots.push((pav_roof_obj, materials.get_pavilion_roof()));
    let (_, pav_roof_out): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_PAVILION_ROOF,
        pav_roof_outline_id,
        pav_tr,
        materials.get_freestyle_ink(),
        col_outlines,
        false,
    );
    freestyle_outline_obj_indices.push(pav_roof_out);
    let (_, pav_pil_obj): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_PAVILION_PILLARS,
        pav_pillars_mesh_id,
        pav_tr,
        materials.get_ink_cinnabar(),
        col_props,
        false,
    );
    scene_material_slots.push((pav_pil_obj, materials.get_ink_cinnabar()));
    let lantern_offsets: [Vec3; 4] = [
        Vec3::new(-2.15, 2.55, -3.55),
        Vec3::new(-6.45, 2.55, -3.75),
        Vec3::new(-2.45, 2.55, -6.75),
        Vec3::new(-6.15, 2.55, -6.65),
    ];
    for (idx, lpos) in lantern_offsets.iter().enumerate() {
        let (_, lobj): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            &format!("PalaceLantern_{idx}"),
            lantern_mesh_id,
            Transform3D::new(*lpos, 0.0, Vec3::splat(1.0)),
            materials.get_lantern_glow(),
            col_props,
            false,
        );
        scene_material_slots.push((lobj, materials.get_lantern_glow()));
        world.get_mut_point_lights().push(PointLight3D::from_linear(
            *lpos,
            Vec3::new(1.0, 0.58, 0.22),
            12.0,
            11.0,
        ));
    }
    // Spawn Eroded Cliff Terrain + 7 Distant Guilin Ink-Wash Karst Mountain Spires.
    let (_, cliff_obj): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_CLIFF_TERRAIN,
        cliff_mesh_id,
        Transform3D::default(),
        materials.get_ink_cliff(),
        col_cliff,
        false,
    );
    scene_material_slots.push((cliff_obj, materials.get_ink_cliff()));
    let spire_placements: [(Vec3, f32, Vec3, bool); 7] = [
        (
            Vec3::new(-14.5, -5.2, -16.5),
            0.3,
            Vec3::new(1.25, 1.35, 1.25),
            true,
        ),
        (
            Vec3::new(-4.8, -5.8, -21.0),
            1.2,
            Vec3::new(1.55, 1.65, 1.45),
            false,
        ),
        (
            Vec3::new(7.5, -5.4, -19.5),
            2.1,
            Vec3::new(1.35, 1.48, 1.35),
            true,
        ),
        (
            Vec3::new(16.2, -4.8, -11.5),
            0.8,
            Vec3::new(1.18, 1.25, 1.18),
            false,
        ),
        (
            Vec3::new(-18.0, -5.5, -4.2),
            2.6,
            Vec3::new(1.12, 1.18, 1.12),
            true,
        ),
        (
            Vec3::new(13.8, -5.8, 5.8),
            1.5,
            Vec3::new(1.05, 1.02, 1.05),
            false,
        ),
        (
            Vec3::new(-12.2, -5.6, 11.4),
            0.4,
            Vec3::new(0.95, 0.92, 0.95),
            true,
        ),
    ];
    for (idx, (pos, yaw, scale_v, use_a)) in spire_placements.iter().enumerate() {
        let mid: usize = if *use_a { spire_a_id } else { spire_b_id };
        let (_, sp_obj): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            &format!("KarstPeak_{idx:02}"),
            mid,
            Transform3D::new(*pos, *yaw, *scale_v),
            materials.get_ink_cliff(),
            col_cliff,
            false,
        );
        scene_material_slots.push((sp_obj, materials.get_ink_cliff()));
    }
    // Spawn Gnarled Cliffside Ink-Pine Tree.
    let pine_tr: Transform3D =
        Transform3D::new(Vec3::new(4.35, -0.10, -2.85), -0.35, Vec3::splat(1.08));
    let (_, pine_tr_obj): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_PINE_TRUNK,
        pine_trunk_id,
        pine_tr,
        materials.get_pine_bark(),
        col_props,
        false,
    );
    scene_material_slots.push((pine_tr_obj, materials.get_pine_bark()));
    let (_, pine_can_obj): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_PINE_CANOPY,
        pine_canopy_id,
        pine_tr,
        materials.get_pine_needles(),
        col_props,
        false,
    );
    scene_material_slots.push((pine_can_obj, materials.get_pine_needles()));
    // Spawn 6 Drifting Xuan-Paper Ink-Cloud Mist Ribbons.
    let mut cloud_ribbon_obj_indices: Vec<usize> = Vec::with_capacity(6);
    for idx in 0..6usize {
        let ang: f32 = ((idx as f32) / 6.0) * TAU;
        let rad: f32 = 8.2 + (idx as f32) * 1.45;
        let y_h: f32 = -1.6 + ((idx % 3) as f32) * 1.55;
        let (_, cl_obj): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            &format!("InkCloudRibbon_{idx}"),
            cloud_mesh_id,
            Transform3D::new(
                Vec3::new(rad * ang.cos(), y_h, rad * ang.sin()),
                ang + FRAC_PI_2,
                Vec3::new(1.25, 1.0, 1.25),
            ),
            materials.get_ink_cloud(),
            col_props,
            true,
        );
        scene_material_slots.push((cl_obj, materials.get_ink_cloud()));
        cloud_ribbon_obj_indices.push(cl_obj);
    }
    // Spawn 26 Octahedral Armature Bone Prisms (1 per parent->child bone segment).
    let mut bone_prism_obj_indices: Vec<usize> = Vec::with_capacity(JIANLAI_BONE_COUNT - 1);
    for bone_idx in 1..JIANLAI_BONE_COUNT {
        let (_, b_obj): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            &format!("BoneViz_{}", JIANLAI_BONE_NAMES[bone_idx]),
            bone_prism_mesh_id,
            Transform3D::new(rest_world[bone_idx], 0.0, Vec3::splat(0.15)),
            materials.get_bone_prism(),
            col_armature,
            true,
        );
        bone_prism_obj_indices.push(b_obj);
    }
    // Hide Armature Overlay collection by default (toggled live via Show Bones or Wire+Armature mode).
    let _: bool = world.set_collection_visible(JIANLAI_COLLECTION_ARMATURE, false);
    // Register 4 cinematic Blender cameras.
    world.get_mut_scene_cameras().push(make_jianlai_camera(
        CAM_NAME_HERO_THREE_QUARTER,
        Vec3::new(3.4, 2.35, 5.4),
        Vec3::new(-0.35, 1.25, -0.4),
        44.0,
    ));
    world.get_mut_scene_cameras().push(make_jianlai_camera(
        CAM_NAME_LOW_ULTIMATE,
        Vec3::new(2.8, 0.95, 4.4),
        Vec3::new(0.0, 2.05, -0.35),
        52.0,
    ));
    world.get_mut_scene_cameras().push(make_jianlai_camera(
        CAM_NAME_CLIFF_PANORAMA,
        Vec3::new(9.2, 4.4, 11.2),
        Vec3::new(-0.8, 1.8, -2.6),
        48.0,
    ));
    world.get_mut_scene_cameras().push(make_jianlai_camera(
        CAM_NAME_ARRAY_OVERHEAD,
        Vec3::new(0.4, 9.6, 4.8),
        Vec3::new(0.0, 0.8, -0.6),
        46.0,
    ));
    // Add Blender Studio AreaLight3D rim/key pair + Hero Sword-Qi PointLight3D.
    world.get_mut_area_lights().push(AreaLight3D::new_rect(
        Vec3::new(5.5, 6.2, 5.0),
        Vec3::new(-0.6, -0.55, -0.58),
        Vec3::new(1.0, 0.96, 0.88),
        18.0,
        (3.5, 2.5),
        28.0,
    ));
    world.get_mut_area_lights().push(AreaLight3D::new_disk(
        Vec3::new(-4.8, 4.8, 3.8),
        Vec3::new(0.65, -0.38, -0.65),
        Vec3::new(0.45, 0.86, 0.94),
        12.0,
        2.8,
        24.0,
    ));
    let handles: JianlaiSceneHandles = JianlaiSceneHandles {
        hero_node_id,
        hero_object_idx,
        hero_outline_obj_idx: Some(hero_out_idx),
        hero_skin_idx,
        bone_node_ids,
        bone_rest_translations,
        bone_rest_world_positions: rest_world,
        sword_obj_idx,
        sword_outline_obj_idx: Some(sword_out_idx),
        scabbard_obj_idx,
        myriad_sword_obj_indices,
        crescent_qi_obj_idx,
        shockwave_ring_obj_idx,
        sword_trail_obj_idx,
        cloud_ribbon_obj_indices,
        bone_prism_obj_indices,
        wireframe_cage_obj_indices,
        freestyle_outline_obj_indices,
        scene_material_slots,
        hero_vertices,
        hero_triangles,
        stage_triangles,
        total_triangles,
    };
    let mut controller: JianlaiSceneController = JianlaiSceneController::new(handles, materials);
    controller.apply_render_mode(&mut world, JianlaiRenderMode::InkWashDonghua);
    controller.step(&mut world, 1.0 / 60.0);
    world.bump_world_revision();
    (world, controller)
}

/// Builds Preset 2: Five sculpted Jianlai Spirit Swords resting on carved lotus stone pedestals showcasing Principled BSDF materials (zero cubes).
///
/// # Returns
///
/// - `World3D` - Populated spirit-sword PBR material gallery world.
#[must_use]
pub fn build_jianlai_sword_gallery_world() -> World3D {
    let mut world: World3D = World3D::default();
    world.set_use_agx_tonemap(true);
    let materials: JianlaiStyleMaterialIds = register_jianlai_materials(&mut world);
    let col_hero: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_HERO);
    let col_props: u64 = world
        .get_mut_scene_graph()
        .get_mut_collections()
        .register_collection(JIANLAI_COLLECTION_PROPS);
    let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(15.2);
    let _: &mut DirectionalLight3D = sun
        .set_direction(Vec3::new(0.52, 0.74, 0.42).normalize())
        .set_sky_zenith(Vec3::new(0.42, 0.56, 0.62))
        .set_sky_horizon(Vec3::new(0.86, 0.89, 0.86));
    let _: &mut World3D = world.set_sun(sun);
    let sword_mesh: Mesh3D = build_jianlai_spirit_sword_mesh();
    let pedestal_mesh: Mesh3D = build_jianlai_lotus_pedestal_mesh();
    let terrace_mesh: Mesh3D = build_jianlai_bagua_terrace_mesh();
    let sword_id: usize = world.register_mesh(build_qem_lod_chain(&sword_mesh, 3));
    let ped_id: usize = world.register_mesh(build_qem_lod_chain(&pedestal_mesh, 3));
    let terrace_id: usize = world.register_mesh(build_qem_lod_chain(&terrace_mesh, 3));
    let (_, _): (u32, usize) = spawn_jianlai_node_object(
        &mut world,
        MESH_NAME_TERRACE,
        terrace_id,
        Transform3D::default(),
        materials.get_ink_terrace(),
        col_props,
        false,
    );
    let gallery_names: [&str; 5] = [
        GALLERY_SWORD_LONGQUE,
        GALLERY_SWORD_QINGLIAN,
        GALLERY_SWORD_CHIXIAO,
        GALLERY_SWORD_XUANMING,
        GALLERY_SWORD_TIANMEN,
    ];
    let gallery_rgba: [[f32; 4]; 5] = [
        [0.84, 0.94, 0.98, 1.0],
        [0.34, 0.86, 0.72, 1.0],
        [0.84, 0.24, 0.18, 1.0],
        [0.12, 0.16, 0.22, 1.0],
        [0.98, 0.82, 0.34, 1.0],
    ];
    let gallery_mr: [(f32, f32); 5] = [
        (0.94, 0.14),
        (0.22, 0.16),
        (0.68, 0.24),
        (0.96, 0.10),
        (0.88, 0.16),
    ];
    let gallery_em: [[f32; 3]; 5] = [
        [0.24, 0.82, 0.95],
        [0.14, 0.65, 0.52],
        [0.95, 0.28, 0.12],
        [0.18, 0.34, 0.68],
        [1.0, 0.76, 0.22],
    ];
    for (idx, label) in gallery_names.iter().enumerate() {
        let rgba: [f32; 4] = gallery_rgba[idx];
        let (metal, rough): (f32, f32) = gallery_mr[idx];
        let em: [f32; 3] = gallery_em[idx];
        let x: f32 = ((idx as f32) - 2.0) * 1.72;
        let z: f32 = ((idx as f32) - 2.0).abs() * 0.38;
        let mut pmat: PrincipledMaterial3D = PrincipledMaterial3D::default();
        let _: &mut PrincipledMaterial3D = pmat
            .set_name((*label).to_string())
            .set_base_color_factor(rgba)
            .set_metallic_factor(metal)
            .set_roughness_factor(rough)
            .set_clearcoat_factor(0.75)
            .set_emissive_factor(em)
            .set_emissive_strength(1.15);
        let mat_id: u32 = world.get_principled_materials().len() as u32;
        world.get_mut_principled_materials().push(pmat);
        let (_, _): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            &format!("LotusPedestal_{idx}"),
            ped_id,
            Transform3D::new(Vec3::new(x, 0.0, z), (idx as f32) * 0.4, Vec3::splat(1.0)),
            materials.get_ink_terrace(),
            col_props,
            false,
        );
        let (_, _): (u32, usize) = spawn_jianlai_node_object(
            &mut world,
            label,
            sword_id,
            Transform3D::from_trs(
                Vec3::new(x, 1.28, z),
                Quat::from_euler_yxz((idx as f32) * 0.35, 0.06, 0.04),
                Vec3::splat(1.18),
            ),
            mat_id,
            col_hero,
            true,
        );
    }
    world.get_mut_scene_cameras().push(make_jianlai_camera(
        CAM_NAME_HERO_THREE_QUARTER,
        Vec3::new(0.0, 2.4, 6.2),
        Vec3::new(0.0, 1.4, 0.2),
        46.0,
    ));
    world.get_mut_scene_cameras().push(make_jianlai_camera(
        CAM_NAME_CLIFF_PANORAMA,
        Vec3::new(5.6, 3.2, 5.8),
        Vec3::new(0.0, 1.3, 0.2),
        48.0,
    ));
    let _: usize = world.get_mut_scene_graph().propagate_world_matrices();
    world.bump_world_revision();
    world
}

/// Builds Tab 2 Massive-Asset Stress Lab world: 256 instanced sculpted floating spirit swords, jade talismans, and sword-tomb monolith spires arranged in a sweeping celestial sword-vortex (ZERO cubes!).
///
/// # Returns
///
/// - `World3D` - Populated 256-entity sculpted celestial sword-vortex stress world with 4-level QEM LOD chains.
#[must_use]
pub fn build_jianlai_stress_vortex_world() -> World3D {
    let mut world: World3D = World3D::default();
    world.set_use_agx_tonemap(true);
    let materials: JianlaiStyleMaterialIds = register_jianlai_materials(&mut world);
    let mut sun: DirectionalLight3D = DirectionalLight3D::from_time_of_day(16.2);
    let _: &mut DirectionalLight3D = sun
        .set_direction(Vec3::new(0.42, 0.72, 0.55).normalize())
        .set_sky_zenith(Vec3::new(0.28, 0.44, 0.52))
        .set_sky_horizon(Vec3::new(0.84, 0.88, 0.86));
    let _: &mut World3D = world.set_sun(sun);
    let sword_mesh: Mesh3D = build_jianlai_spirit_sword_mesh();
    let talisman_mesh: Mesh3D = build_jianlai_jade_talisman_mesh();
    let monolith_mesh: Mesh3D = build_jianlai_monolith_spire_mesh();
    let sword_id: usize = world.register_mesh(build_qem_lod_chain(&sword_mesh, 4));
    let talisman_id: usize = world.register_mesh(build_qem_lod_chain(&talisman_mesh, 4));
    let monolith_id: usize = world.register_mesh(build_qem_lod_chain(&monolith_mesh, 4));
    let mat_palette: [u32; 4] = [
        materials.get_ink_blade(),
        materials.get_ink_jade(),
        materials.get_qi_gold(),
        materials.get_ink_cliff(),
    ];
    for idx in 0..JIANLAI_STRESS_VORTEX_COUNT {
        let t: f32 = (idx as f32) / (JIANLAI_STRESS_VORTEX_COUNT as f32);
        let spiral_turns: f32 = 5.5;
        let angle: f32 = t * TAU * spiral_turns + ((idx % 3) as f32) * (TAU / 3.0);
        let radius: f32 = 2.6 + t * 15.8;
        let px: f32 = radius * angle.cos();
        let pz: f32 = radius * angle.sin();
        let (mesh_id, py, rot, scale_v, mat_id): (usize, f32, Quat, Vec3, u32) = match idx % 4 {
            0 | 1 => {
                let lift: f32 = 1.4 + (t * PI * 4.0).sin().abs() * 5.2 + (idx % 5) as f32 * 0.45;
                let pitch: f32 = 0.25 + (t * 6.0).cos() * 0.18;
                (
                    sword_id,
                    lift,
                    Quat::from_euler_yxz(-angle + FRAC_PI_2, pitch, 0.12),
                    Vec3::splat(1.15 + ((idx % 3) as f32) * 0.22),
                    mat_palette[idx % 3],
                )
            }
            2 => {
                let lift: f32 = 2.0 + ((idx % 7) as f32) * 0.85;
                (
                    talisman_id,
                    lift,
                    Quat::from_euler_yxz(-angle, 0.15, (idx as f32) * 0.18),
                    Vec3::splat(0.95 + ((idx % 3) as f32) * 0.16),
                    materials.get_ink_jade(),
                )
            }
            _ => {
                let h_scale: f32 = 0.85 + ((idx % 5) as f32) * 0.34;
                (
                    monolith_id,
                    -0.25,
                    Quat::from_euler_yxz(angle * 0.5, 0.0, 0.0),
                    Vec3::new(1.0, h_scale, 1.0),
                    materials.get_ink_cliff(),
                )
            }
        };
        let legacy: PbrMaterial = world
            .get_principled_materials()
            .get(mat_id as usize)
            .map_or_else(PbrMaterial::default, PrincipledMaterial3D::to_legacy_pbr);
        let desc: SpawnObjectDesc = SpawnObjectDesc::new(&format!("SwordVortex_{idx:03}"), mesh_id)
            .with_transform(Transform3D::from_trs(Vec3::new(px, py, pz), rot, scale_v))
            .with_material(legacy);
        let obj_idx: usize = world.spawn_with(&desc);
        if let Some(obj_mut) = world.get_mut_objects().get_mut(obj_idx) {
            let _: &mut SceneObject3D = obj_mut.set_principled_material_id(Some(mat_id));
        }
    }
    world.bump_world_revision();
    world
}