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
//! Scene-graph root, nodes, transforms, ID newtypes, and coordinate
//! metadata.
//!
//! The container is [`Scene3D`]. Every collection it owns
//! ([`Node`], [`Mesh`](crate::Mesh), [`Material`](crate::Material),
//! ...) is addressed by an `IdT(u32)` newtype that indexes into the
//! corresponding `Vec`. This keeps the model arena-friendly — clones
//! are cheap, identity is comparable, and serde round-tripping works
//! without back-references — while still letting decoders bulk-load
//! every mesh first and then point nodes at them.
//!
//! Coordinate convention defaults to **glTF 2.0**: right-handed,
//! Y-up, -Z forward, metres. Format crates that consume Z-up content
//! (STL, OBJ Wavefront) set [`Scene3D::up_axis`] to [`Axis::PosZ`]
//! and leave geometry untouched — the orientation metadata is
//! authoritative, no implicit rotation is applied.
use std::collections::{HashMap, HashSet};
use crate::{
animation::Animation,
audio::{AudioEmitter, AudioEmitterId, AudioSource, AudioSourceId},
camera::Camera,
light::Light,
material::Material,
mesh::Mesh,
skin::Skeleton,
skin::Skin,
texture::Texture,
};
macro_rules! id_newtype {
($(#[$meta:meta])* $name:ident) => {
$(#[$meta])*
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct $name(pub u32);
};
}
id_newtype!(
/// Index into [`Scene3D::nodes`].
NodeId
);
id_newtype!(
/// Index into [`Scene3D::meshes`].
MeshId
);
id_newtype!(
/// Index into [`Scene3D::materials`].
MaterialId
);
id_newtype!(
/// Index into [`Scene3D::textures`].
TextureId
);
id_newtype!(
/// Index into [`Scene3D::material_variants`].
MaterialVariantId
);
id_newtype!(
/// Index into [`Scene3D::skeletons`].
SkeletonId
);
id_newtype!(
/// Index into [`Scene3D::skins`].
SkinId
);
id_newtype!(
/// Index into [`Scene3D::cameras`].
CameraId
);
id_newtype!(
/// Index into [`Scene3D::lights`].
LightId
);
/// Axis-aligned bounding box over a set of 3D points.
///
/// `min` is the componentwise minimum corner, `max` the componentwise
/// maximum corner. Both are inclusive; for an empty point set this
/// type returns [`None`] from its constructors rather than carrying a
/// degenerate `[inf; 3]` / `[-inf; 3]` sentinel.
///
/// Use [`BoundingBox::from_points`] to build one from an iterator of
/// `[f32; 3]`, [`BoundingBox::union`] to merge two boxes, and
/// [`BoundingBox::transform`] to rotate / translate / scale the box
/// by a 4x4 row-major-column-vector matrix (the eight corners are
/// transformed and a new AABB is fitted around them — the rotated
/// box's tight bound).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct BoundingBox {
pub min: [f32; 3],
pub max: [f32; 3],
}
impl BoundingBox {
/// Bounding box of exactly one point. Both corners coincide.
pub fn from_point(p: [f32; 3]) -> Self {
Self { min: p, max: p }
}
/// Bounding box over a stream of points. Returns `None` if the
/// iterator yields zero finite points (NaN coordinates are
/// skipped on a per-component basis).
pub fn from_points<I: IntoIterator<Item = [f32; 3]>>(points: I) -> Option<Self> {
let mut acc: Option<Self> = None;
for p in points {
if p[0].is_nan() || p[1].is_nan() || p[2].is_nan() {
continue;
}
acc = Some(match acc {
None => Self::from_point(p),
Some(b) => b.expand(p),
});
}
acc
}
/// Grow the box to include `p`. Returns a new box; the input is
/// left unchanged. NaN components are kept as-is on the
/// existing box (they are not propagated by [`from_points`] either).
pub fn expand(self, p: [f32; 3]) -> Self {
Self {
min: [
self.min[0].min(p[0]),
self.min[1].min(p[1]),
self.min[2].min(p[2]),
],
max: [
self.max[0].max(p[0]),
self.max[1].max(p[1]),
self.max[2].max(p[2]),
],
}
}
/// Componentwise union of two boxes — the smallest AABB
/// containing both.
pub fn union(self, other: Self) -> Self {
Self {
min: [
self.min[0].min(other.min[0]),
self.min[1].min(other.min[1]),
self.min[2].min(other.min[2]),
],
max: [
self.max[0].max(other.max[0]),
self.max[1].max(other.max[1]),
self.max[2].max(other.max[2]),
],
}
}
/// Centre of the box (average of `min` and `max`).
pub fn center(self) -> [f32; 3] {
[
0.5 * (self.min[0] + self.max[0]),
0.5 * (self.min[1] + self.max[1]),
0.5 * (self.min[2] + self.max[2]),
]
}
/// Componentwise size of the box (`max - min`).
pub fn size(self) -> [f32; 3] {
[
self.max[0] - self.min[0],
self.max[1] - self.min[1],
self.max[2] - self.min[2],
]
}
/// `true` if every component of `min` is less than or equal to the
/// corresponding component of `max` (i.e. the box is non-empty
/// and well-formed).
pub fn is_valid(self) -> bool {
self.min[0] <= self.max[0] && self.min[1] <= self.max[1] && self.min[2] <= self.max[2]
}
/// Tight AABB around the box transformed by a row-major
/// column-vector 4x4 matrix (`out = M * v`, same convention as
/// [`Transform::Matrix`]).
///
/// Returns the AABB of the eight transformed corners. For
/// non-affine matrices (perspective `w != 1`) the result may not
/// be physically meaningful — this method is intended for the
/// scene-graph TRS / matrix chain composing every ancestor node's
/// local transform.
pub fn transform(self, m: [[f32; 4]; 4]) -> Self {
let corners = [
[self.min[0], self.min[1], self.min[2]],
[self.max[0], self.min[1], self.min[2]],
[self.min[0], self.max[1], self.min[2]],
[self.max[0], self.max[1], self.min[2]],
[self.min[0], self.min[1], self.max[2]],
[self.max[0], self.min[1], self.max[2]],
[self.min[0], self.max[1], self.max[2]],
[self.max[0], self.max[1], self.max[2]],
];
let xf = corners.map(|c| {
[
m[0][0] * c[0] + m[0][1] * c[1] + m[0][2] * c[2] + m[0][3],
m[1][0] * c[0] + m[1][1] * c[1] + m[1][2] * c[2] + m[1][3],
m[2][0] * c[0] + m[2][1] * c[1] + m[2][2] * c[2] + m[2][3],
]
});
Self::from_points(xf).expect("eight corners always yield a finite AABB")
}
/// Slab-method ray-AABB intersection — returns the entry / exit
/// parametric distances along the ray clamped to `[0, t_max]`, or
/// `None` if the ray misses.
///
/// `t_enter == 0.0` indicates the ray's origin lies inside the
/// box; `t_exit` is the parameter at which the ray leaves through
/// the far face. Both values are along the (not-necessarily-unit)
/// `ray.direction`, so the actual world-space point at the
/// intersection is `ray.point_at(t)`.
///
/// Delegates to [`crate::ray::intersect_aabb`]; see its docs for
/// the axis-parallel-ray + NaN / Inf handling.
pub fn intersect_ray(self, ray: crate::ray::Ray, t_max: f32) -> Option<(f32, f32)> {
crate::ray::intersect_aabb(ray, self.min, self.max, t_max)
}
}
/// Coordinate-system principal axis. Stored on [`Scene3D`] so a
/// renderer can apply (or skip) a global rotation when the file
/// convention disagrees with its own.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Axis {
PosX,
NegX,
PosY,
NegY,
PosZ,
NegZ,
}
/// Linear unit a single coordinate-space-1.0 represents in the file.
/// glTF defaults to metres; CAD/STL files often ship in millimetres
/// or inches. Renderers that mix scenes from different unit systems
/// scale by the ratio of [`Unit::to_metres`] values.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unit {
Metres,
Centimetres,
Millimetres,
Inches,
Feet,
Yards,
}
impl Unit {
/// Multiplier from this unit to metres, e.g. `Inches.to_metres() == 0.0254`.
pub fn to_metres(self) -> f32 {
match self {
Self::Metres => 1.0,
Self::Centimetres => 0.01,
Self::Millimetres => 0.001,
Self::Inches => 0.0254,
Self::Feet => 0.3048,
Self::Yards => 0.9144,
}
}
}
/// Per-node local-to-parent transform. Decoders can store the raw
/// matrix as-is or decompose into translation/rotation/scale; the
/// [`Transform::to_matrix`] / [`Transform::from_matrix`] helpers
/// convert in either direction within float tolerance.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Transform {
/// Row-major column-vector 4x4 transform — pre-multiplied
/// (`out = M * v`). Layout matches glTF's `node.matrix` field.
Matrix([[f32; 4]; 4]),
/// Decomposed translation + rotation (xyzw quaternion) + scale.
/// glTF's TRS form; preferred for animation since each channel is
/// independent.
Trs {
translation: [f32; 3],
rotation: [f32; 4],
scale: [f32; 3],
},
}
impl Transform {
/// Identity TRS — `(0,0,0)` translation, identity quaternion,
/// `(1,1,1)` scale.
pub fn identity() -> Self {
Self::Trs {
translation: [0.0; 3],
rotation: [0.0, 0.0, 0.0, 1.0],
scale: [1.0, 1.0, 1.0],
}
}
/// Compose this transform into a single 4x4 matrix.
///
/// For `Matrix(m)` this is the identity passthrough; for
/// `Trs { t, r, s }` the build order is `T * R * S`.
pub fn to_matrix(&self) -> [[f32; 4]; 4] {
match *self {
Self::Matrix(m) => m,
Self::Trs {
translation,
rotation,
scale,
} => trs_to_matrix(translation, rotation, scale),
}
}
/// Best-effort decomposition of a 4x4 affine transform into TRS.
///
/// Assumes the input is `T * R * S` with no shear and no negative
/// scale; under that assumption the recovery is exact within
/// float epsilon. For matrices with shear the output is the
/// closest pure TRS (scales are column lengths, rotation is the
/// orthonormalised basis).
pub fn from_matrix(m: [[f32; 4]; 4]) -> Self {
let translation = [m[0][3], m[1][3], m[2][3]];
let cx = [m[0][0], m[1][0], m[2][0]];
let cy = [m[0][1], m[1][1], m[2][1]];
let cz = [m[0][2], m[1][2], m[2][2]];
let sx = vec3_len(cx);
let sy = vec3_len(cy);
let sz = vec3_len(cz);
// Avoid div-by-zero if a column was zero — fall back to a sentinel
// axis; this lets the from_matrix(to_matrix(t)) round-trip remain
// total even for pathological inputs.
let inv_sx = if sx > f32::EPSILON { 1.0 / sx } else { 1.0 };
let inv_sy = if sy > f32::EPSILON { 1.0 / sy } else { 1.0 };
let inv_sz = if sz > f32::EPSILON { 1.0 / sz } else { 1.0 };
let r00 = cx[0] * inv_sx;
let r10 = cx[1] * inv_sx;
let r20 = cx[2] * inv_sx;
let r01 = cy[0] * inv_sy;
let r11 = cy[1] * inv_sy;
let r21 = cy[2] * inv_sy;
let r02 = cz[0] * inv_sz;
let r12 = cz[1] * inv_sz;
let r22 = cz[2] * inv_sz;
let rotation = rot_matrix_to_quat([[r00, r01, r02], [r10, r11, r12], [r20, r21, r22]]);
Self::Trs {
translation,
rotation,
scale: [sx, sy, sz],
}
}
}
fn vec3_len(v: [f32; 3]) -> f32 {
(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt()
}
/// Row-major column-vector 4x4 matrix multiply `a * b`.
pub(crate) fn mat4_mul(a: [[f32; 4]; 4], b: [[f32; 4]; 4]) -> [[f32; 4]; 4] {
let mut out = [[0.0f32; 4]; 4];
for (i, row) in out.iter_mut().enumerate() {
for (j, slot) in row.iter_mut().enumerate() {
*slot = a[i][0] * b[0][j] + a[i][1] * b[1][j] + a[i][2] * b[2][j] + a[i][3] * b[3][j];
}
}
out
}
/// Signed determinant of the upper-left 3x3 of a row-major
/// column-vector 4x4 matrix, returned as `f64` for accumulator-safe
/// volume scaling. The translation column does not enter the result.
fn mat3_det_of_world(m: [[f32; 4]; 4]) -> f64 {
let a = m[0][0] as f64;
let b = m[0][1] as f64;
let c = m[0][2] as f64;
let d = m[1][0] as f64;
let e = m[1][1] as f64;
let f = m[1][2] as f64;
let g = m[2][0] as f64;
let h = m[2][1] as f64;
let i = m[2][2] as f64;
a * (e * i - f * h) - b * (d * i - f * g) + c * (d * h - e * g)
}
/// Inverse of an affine row-major column-vector 4x4 whose bottom row
/// is `[0, 0, 0, 1]`. Returns `None` when the upper-left 3x3 is
/// singular (zero or non-finite determinant), when any input entry
/// is non-finite, or when the bottom row deviates from
/// `[0, 0, 0, 1]` (the matrix is non-affine and not handled here —
/// `world_node_transforms` only produces affines from TRS, so a
/// non-affine input is a malformed user transform).
///
/// The inverse uses the classical adjugate / determinant of the
/// 3x3 linear part, then applies the inverse linear to the negated
/// translation column. Computed in `f64` so very-different-scale
/// matrices (e.g. `1e-3` cm-scale child of a `1e3` km-scale parent)
/// round-trip without precision collapse, then cast back to `f32`.
pub(crate) fn mat4_affine_inverse(m: [[f32; 4]; 4]) -> Option<[[f32; 4]; 4]> {
for row in &m {
for v in row {
if !v.is_finite() {
return None;
}
}
}
// Affinity guard: bottom row must be [0, 0, 0, 1] within a tight
// tolerance (TRS-derived matrices satisfy this exactly).
let bot_eps = 1e-6_f32;
if m[3][0].abs() > bot_eps
|| m[3][1].abs() > bot_eps
|| m[3][2].abs() > bot_eps
|| (m[3][3] - 1.0).abs() > bot_eps
{
return None;
}
let a = m[0][0] as f64;
let b = m[0][1] as f64;
let c = m[0][2] as f64;
let d = m[1][0] as f64;
let e = m[1][1] as f64;
let f = m[1][2] as f64;
let g = m[2][0] as f64;
let h = m[2][1] as f64;
let i = m[2][2] as f64;
// Cofactors of the 3x3 linear part.
let c00 = e * i - f * h;
let c01 = -(d * i - f * g);
let c02 = d * h - e * g;
let c10 = -(b * i - c * h);
let c11 = a * i - c * g;
let c12 = -(a * h - b * g);
let c20 = b * f - c * e;
let c21 = -(a * f - c * d);
let c22 = a * e - b * d;
let det = a * c00 + b * c01 + c * c02;
if !det.is_finite() || det == 0.0 {
return None;
}
let inv = 1.0 / det;
// Adjugate-transpose: inv_linear[row][col] = cofactor[col][row] / det.
let l00 = c00 * inv;
let l01 = c10 * inv;
let l02 = c20 * inv;
let l10 = c01 * inv;
let l11 = c11 * inv;
let l12 = c21 * inv;
let l20 = c02 * inv;
let l21 = c12 * inv;
let l22 = c22 * inv;
// Translation: t_inv = -L^-1 * t.
let tx = m[0][3] as f64;
let ty = m[1][3] as f64;
let tz = m[2][3] as f64;
let ix = -(l00 * tx + l01 * ty + l02 * tz);
let iy = -(l10 * tx + l11 * ty + l12 * tz);
let iz = -(l20 * tx + l21 * ty + l22 * tz);
// Finite-check on the assembled inverse — a near-singular det can
// produce inf / NaN entries; reject so callers fall through to the
// "skip this instance" branch.
let out = [
[l00 as f32, l01 as f32, l02 as f32, ix as f32],
[l10 as f32, l11 as f32, l12 as f32, iy as f32],
[l20 as f32, l21 as f32, l22 as f32, iz as f32],
[0.0, 0.0, 0.0, 1.0],
];
for row in &out {
for v in row {
if !v.is_finite() {
return None;
}
}
}
Some(out)
}
/// Transform an [`crate::ray::Ray`] into mesh-local space by an affine
/// 4x4 inverse. The translation column moves the origin; the 3x3
/// linear part rotates / scales the direction (but is not normalised —
/// the same ray parameter `t` resolves to the same world-space point
/// before and after the change of frame).
pub(crate) fn ray_into_local(world_inv: [[f32; 4]; 4], ray: crate::ray::Ray) -> crate::ray::Ray {
let o = ray.origin;
let d = ray.direction;
let lo = [
world_inv[0][0] * o[0] + world_inv[0][1] * o[1] + world_inv[0][2] * o[2] + world_inv[0][3],
world_inv[1][0] * o[0] + world_inv[1][1] * o[1] + world_inv[1][2] * o[2] + world_inv[1][3],
world_inv[2][0] * o[0] + world_inv[2][1] * o[1] + world_inv[2][2] * o[2] + world_inv[2][3],
];
let ld = [
world_inv[0][0] * d[0] + world_inv[0][1] * d[1] + world_inv[0][2] * d[2],
world_inv[1][0] * d[0] + world_inv[1][1] * d[1] + world_inv[1][2] * d[2],
world_inv[2][0] * d[0] + world_inv[2][1] * d[1] + world_inv[2][2] * d[2],
];
crate::ray::Ray::new(lo, ld)
}
fn trs_to_matrix(t: [f32; 3], r: [f32; 4], s: [f32; 3]) -> [[f32; 4]; 4] {
// Quaternion (x, y, z, w) → 3x3 rotation matrix (Shoemake).
let (x, y, z, w) = (r[0], r[1], r[2], r[3]);
let xx = x * x;
let yy = y * y;
let zz = z * z;
let xy = x * y;
let xz = x * z;
let yz = y * z;
let wx = w * x;
let wy = w * y;
let wz = w * z;
let r00 = 1.0 - 2.0 * (yy + zz);
let r01 = 2.0 * (xy - wz);
let r02 = 2.0 * (xz + wy);
let r10 = 2.0 * (xy + wz);
let r11 = 1.0 - 2.0 * (xx + zz);
let r12 = 2.0 * (yz - wx);
let r20 = 2.0 * (xz - wy);
let r21 = 2.0 * (yz + wx);
let r22 = 1.0 - 2.0 * (xx + yy);
[
[r00 * s[0], r01 * s[1], r02 * s[2], t[0]],
[r10 * s[0], r11 * s[1], r12 * s[2], t[1]],
[r20 * s[0], r21 * s[1], r22 * s[2], t[2]],
[0.0, 0.0, 0.0, 1.0],
]
}
fn rot_matrix_to_quat(m: [[f32; 3]; 3]) -> [f32; 4] {
// Shepperd's branchless variant — picks the column with the
// largest diagonal to avoid catastrophic cancellation near
// 180-degree rotations. Returns (x, y, z, w).
let trace = m[0][0] + m[1][1] + m[2][2];
if trace > 0.0 {
let s = (trace + 1.0).sqrt() * 2.0;
let w = 0.25 * s;
let x = (m[2][1] - m[1][2]) / s;
let y = (m[0][2] - m[2][0]) / s;
let z = (m[1][0] - m[0][1]) / s;
[x, y, z, w]
} else if m[0][0] > m[1][1] && m[0][0] > m[2][2] {
let s = (1.0 + m[0][0] - m[1][1] - m[2][2]).sqrt() * 2.0;
let w = (m[2][1] - m[1][2]) / s;
let x = 0.25 * s;
let y = (m[0][1] + m[1][0]) / s;
let z = (m[0][2] + m[2][0]) / s;
[x, y, z, w]
} else if m[1][1] > m[2][2] {
let s = (1.0 + m[1][1] - m[0][0] - m[2][2]).sqrt() * 2.0;
let w = (m[0][2] - m[2][0]) / s;
let x = (m[0][1] + m[1][0]) / s;
let y = 0.25 * s;
let z = (m[1][2] + m[2][1]) / s;
[x, y, z, w]
} else {
let s = (1.0 + m[2][2] - m[0][0] - m[1][1]).sqrt() * 2.0;
let w = (m[1][0] - m[0][1]) / s;
let x = (m[0][2] + m[2][0]) / s;
let y = (m[1][2] + m[2][1]) / s;
let z = 0.25 * s;
[x, y, z, w]
}
}
/// A single scene-graph node.
///
/// Nodes form a forest rooted at [`Scene3D::roots`]. Each node has at
/// most one parent (enforced by walking children top-down only — the
/// `parent` back-pointer isn't stored; decoders that need it should
/// build a side-table).
#[derive(Clone, Debug)]
pub struct Node {
pub name: Option<String>,
pub transform: Transform,
pub children: Vec<NodeId>,
pub mesh: Option<MeshId>,
pub camera: Option<CameraId>,
pub light: Option<LightId>,
pub skin: Option<SkinId>,
/// Node-level morph-weight override (glTF 2.0 `node.weights`).
///
/// When non-empty, this vector replaces the instantiated mesh's
/// default [`Mesh::weights`](crate::Mesh::weights) for **this
/// instance** — two nodes sharing one mesh can hold different
/// static blend states. Empty means "no override": the mesh's own
/// defaults apply. An animated
/// [`MorphWeights`](crate::AnimationProperty::MorphWeights)
/// channel targeting the node beats both — the §3.7.4 weight
/// precedence chain is *animation > node > mesh*.
/// [`Scene3D::effective_morph_weights`] resolves the static
/// (node > mesh) half of that chain;
/// [`Scene3D::world_mesh`](crate::Scene3D::world_mesh) and its
/// animated variants honour the whole chain.
///
/// When non-empty, the node must carry a mesh and the length must
/// match the morph-target count of every primitive of that mesh
/// ([`Scene3D::validate`] reports both).
pub weights: Vec<f32>,
/// Optional audio emitter attached to this node. The emitter's
/// position + orientation come from this node's world transform
/// when [`AudioEmitter::spatial`](crate::AudioEmitter::spatial)
/// is `Some`; non-spatial emitters ignore the transform and play
/// globally.
pub audio_emitter: Option<AudioEmitterId>,
pub extras: HashMap<String, serde_json::Value>,
}
impl Node {
/// Construct an empty node with identity transform.
pub fn new() -> Self {
Self {
name: None,
transform: Transform::identity(),
children: Vec::new(),
mesh: None,
camera: None,
light: None,
skin: None,
weights: Vec::new(),
audio_emitter: None,
extras: HashMap::new(),
}
}
/// Builder-style name setter.
pub fn with_name(mut self, name: impl Into<String>) -> Self {
self.name = Some(name.into());
self
}
/// Builder-style transform setter.
pub fn with_transform(mut self, transform: Transform) -> Self {
self.transform = transform;
self
}
/// Builder-style mesh attachment.
pub fn with_mesh(mut self, mesh: MeshId) -> Self {
self.mesh = Some(mesh);
self
}
/// Builder-style node-level morph-weight override (glTF 2.0
/// `node.weights` — see [`Node::weights`]). The vector length
/// should match the morph-target count of every primitive of the
/// mesh this node instantiates.
pub fn with_weights(mut self, weights: impl Into<Vec<f32>>) -> Self {
self.weights = weights.into();
self
}
/// Builder-style audio-emitter attachment.
pub fn with_audio_emitter(mut self, emitter: AudioEmitterId) -> Self {
self.audio_emitter = Some(emitter);
self
}
}
impl Default for Node {
fn default() -> Self {
Self::new()
}
}
/// Closest-hit record produced by [`Scene3D::intersect_ray`].
///
/// Pairs a world-space ray query with the scene-graph location of
/// the hit:
///
/// * `node` — the [`NodeId`] of the reachable node whose attached
/// mesh produced the hit. Look up `nodes[node]` for the node's
/// transform / parenting; pass the same index into
/// [`Scene3D::world_node_transforms`]`[node.0 as usize]` for the
/// world matrix that maps mesh-local coordinates back to world
/// space.
/// * `primitive_index` — the index into `nodes[node].mesh`'s
/// `Mesh::primitives` array identifying which primitive within the
/// mesh was struck. The inner `hit.triangle_index` then names the
/// triangle inside *that* primitive's
/// [`crate::Primitive::triangle_indices`] enumeration.
/// * `hit` — the underlying [`crate::ray::RayHit`] in mesh-local
/// coordinates (barycentric, triangle index, front-face flag) but
/// with `t` already in world-space units: affine change-of-frame
/// leaves the ray-parameter scalar invariant, so the same `t`
/// reconstructs the world hit point via
/// `world_ray.point_at(scene_hit.hit.t)`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SceneRayHit {
pub node: NodeId,
pub primitive_index: usize,
pub hit: crate::ray::RayHit,
}
/// Top-level container for a 3D scene.
///
/// Owns every resource referenced by the scene graph. Add resources
/// with the `add_*` helpers — they push into the corresponding `Vec`
/// and return the freshly-issued ID. Roots are explicit: a node added
/// with [`Scene3D::add_node`] is not automatically a root, so that
/// child nodes added later can be re-parented without re-shuffling.
#[derive(Clone, Debug)]
pub struct Scene3D {
pub nodes: Vec<Node>,
pub roots: Vec<NodeId>,
pub meshes: Vec<Mesh>,
pub materials: Vec<Material>,
/// `KHR_materials_variants` variant names, addressed by
/// [`MaterialVariantId`]. The asset-level roster of switchable
/// material configurations (e.g. product colourways); primitives
/// opt in via
/// [`Primitive::variant_mappings`](crate::Primitive::variant_mappings).
/// Empty means the scene has no material variants.
pub material_variants: Vec<String>,
pub textures: Vec<Texture>,
pub skeletons: Vec<Skeleton>,
pub skins: Vec<Skin>,
pub animations: Vec<Animation>,
pub cameras: Vec<Camera>,
pub lights: Vec<Light>,
/// Audio assets owned by the scene; addressed by [`AudioSourceId`].
pub audio_sources: Vec<AudioSource>,
/// In-scene audio-emitter instances; addressed by [`AudioEmitterId`].
pub audio_emitters: Vec<AudioEmitter>,
pub up_axis: Axis,
pub front_axis: Axis,
pub unit: Unit,
pub extras: HashMap<String, serde_json::Value>,
}
impl Scene3D {
/// Empty scene with glTF-default orientation (Y-up, -Z forward,
/// metres) and no resources.
pub fn new() -> Self {
Self {
nodes: Vec::new(),
roots: Vec::new(),
meshes: Vec::new(),
materials: Vec::new(),
material_variants: Vec::new(),
textures: Vec::new(),
skeletons: Vec::new(),
skins: Vec::new(),
animations: Vec::new(),
cameras: Vec::new(),
lights: Vec::new(),
audio_sources: Vec::new(),
audio_emitters: Vec::new(),
up_axis: Axis::PosY,
front_axis: Axis::NegZ,
unit: Unit::Metres,
extras: HashMap::new(),
}
}
/// Push a node and return its id.
pub fn add_node(&mut self, node: Node) -> NodeId {
let id = NodeId(self.nodes.len() as u32);
self.nodes.push(node);
id
}
/// Push a mesh and return its id.
pub fn add_mesh(&mut self, mesh: Mesh) -> MeshId {
let id = MeshId(self.meshes.len() as u32);
self.meshes.push(mesh);
id
}
/// Push a material and return its id.
pub fn add_material(&mut self, material: Material) -> MaterialId {
let id = MaterialId(self.materials.len() as u32);
self.materials.push(material);
id
}
/// Push a `KHR_materials_variants` variant name and return its id.
/// No name dedup is performed — use
/// [`find_or_add_material_variant`](Self::find_or_add_material_variant)
/// when merging rosters.
pub fn add_material_variant(&mut self, name: impl Into<String>) -> MaterialVariantId {
let id = MaterialVariantId(self.material_variants.len() as u32);
self.material_variants.push(name.into());
id
}
/// Id of the variant named `name`, adding it to the roster if
/// absent. This is the name-unification primitive used by
/// [`append`](Self::append) so two scenes sharing variant names
/// (e.g. "Red" in both) end up with one merged roster entry.
pub fn find_or_add_material_variant(&mut self, name: &str) -> MaterialVariantId {
match self.material_variants.iter().position(|v| v == name) {
Some(i) => MaterialVariantId(i as u32),
None => self.add_material_variant(name),
}
}
/// Push a texture and return its id.
pub fn add_texture(&mut self, texture: Texture) -> TextureId {
let id = TextureId(self.textures.len() as u32);
self.textures.push(texture);
id
}
/// Push a skeleton and return its id.
pub fn add_skeleton(&mut self, skeleton: Skeleton) -> SkeletonId {
let id = SkeletonId(self.skeletons.len() as u32);
self.skeletons.push(skeleton);
id
}
/// Push a skin and return its id.
pub fn add_skin(&mut self, skin: Skin) -> SkinId {
let id = SkinId(self.skins.len() as u32);
self.skins.push(skin);
id
}
/// Push an animation and return its id (animations are
/// list-ordered, no separate id type — reference by index).
pub fn add_animation(&mut self, animation: Animation) -> usize {
let idx = self.animations.len();
self.animations.push(animation);
idx
}
/// Push a camera and return its id.
pub fn add_camera(&mut self, camera: Camera) -> CameraId {
let id = CameraId(self.cameras.len() as u32);
self.cameras.push(camera);
id
}
/// Push a light and return its id.
pub fn add_light(&mut self, light: Light) -> LightId {
let id = LightId(self.lights.len() as u32);
self.lights.push(light);
id
}
/// Push an [`AudioSource`] and return its id.
pub fn add_audio_source(&mut self, source: AudioSource) -> AudioSourceId {
let id = AudioSourceId(self.audio_sources.len() as u32);
self.audio_sources.push(source);
id
}
/// Push an [`AudioEmitter`] and return its id.
pub fn add_audio_emitter(&mut self, emitter: AudioEmitter) -> AudioEmitterId {
let id = AudioEmitterId(self.audio_emitters.len() as u32);
self.audio_emitters.push(emitter);
id
}
/// Borrow an audio source by id, if it exists.
pub fn audio_source(&self, id: AudioSourceId) -> Option<&AudioSource> {
self.audio_sources.get(id.0 as usize)
}
/// Borrow an audio emitter by id, if it exists.
pub fn audio_emitter(&self, id: AudioEmitterId) -> Option<&AudioEmitter> {
self.audio_emitters.get(id.0 as usize)
}
/// Promote a node to a root of the scene-graph forest.
pub fn add_root(&mut self, node: NodeId) {
self.roots.push(node);
}
/// Borrow a node by id, if it exists.
pub fn node(&self, id: NodeId) -> Option<&Node> {
self.nodes.get(id.0 as usize)
}
/// Mutably borrow a node by id, if it exists.
pub fn node_mut(&mut self, id: NodeId) -> Option<&mut Node> {
self.nodes.get_mut(id.0 as usize)
}
/// Borrow a mesh by id, if it exists.
pub fn mesh(&self, id: MeshId) -> Option<&Mesh> {
self.meshes.get(id.0 as usize)
}
/// World-space 4x4 transform per scene node, indexed by `NodeId.0`.
///
/// Walks every root in [`Scene3D::roots`] in order, composing each
/// node's local [`Transform`] (via [`Transform::to_matrix`]) onto
/// its parent's already-composed world transform. The returned
/// vector has length `nodes.len()`; each slot holds:
///
/// * `Some([[f32; 4]; 4])` — the row-major column-vector world
/// transform of that node, i.e. the matrix that takes a position
/// in the node's local frame to world space (`p_world = M *
/// p_local`, treating `p_local` as `[x, y, z, 1]ᵀ`).
/// * `None` — the node is not reachable from any root in
/// [`Scene3D::roots`] (detached). Detached nodes are common
/// during incremental scene construction; the caller can detect
/// them without a separate reachability pass.
///
/// The walk is depth-first iterative on an explicit stack, matching
/// [`Scene3D::bounding_box`]'s traversal. Re-entry through a cycle
/// (a node listed as its own descendant) is guarded against — each
/// node receives **exactly one** world transform, the first one
/// encountered on the depth-first walk. Out-of-range `NodeId`
/// entries in `roots` / `children` are silently skipped.
///
/// A node referenced by two parents (shared-instance pattern) is
/// visited only once, so `world_node_transforms()[id.0 as usize]`
/// resolves to a single matrix — the one obtained via the first
/// parent on the DFS path. Decoders that need per-instance world
/// transforms (mesh-instancing) should keep an explicit
/// instance-list side-channel rather than relying on this helper.
///
/// **What this does NOT include:**
///
/// * Skin pose deformation — the static scene-graph transform is
/// reported, not the skinned-pose transform at any particular
/// animation time. Apply animation channels separately to obtain
/// pose-time transforms.
/// * Camera / projection transforms.
/// * Up-axis or unit conversion. [`Scene3D::up_axis`] and
/// [`Scene3D::unit`] are metadata; the returned matrices live in
/// whatever coordinate system the scene stored.
///
/// ## Use cases
///
/// * Transform-aware aggregate metrics (multiply each primitive's
/// `surface_area` by `|det(scale_part)|` or its `signed_volume`
/// by `sign(det) * |det|` to obtain a transform-folded total —
/// the per-component scales fall out of the upper-left 3x3 of
/// the world matrix).
/// * Renderer-side world-matrix prep (one DFS pass at scene load,
/// then constant-time lookup per node when issuing draw calls).
/// * Authoring-tool node inspection ("show me the world position
/// of `nodes[7]`" without re-walking the ancestor chain).
///
/// Cost: `O(nodes.len() + total_children)`; allocates one
/// `Vec<Option<...>>` of length `nodes.len()` plus the DFS stack.
pub fn world_node_transforms(&self) -> Vec<Option<[[f32; 4]; 4]>> {
let n_nodes = self.nodes.len();
let mut out: Vec<Option<[[f32; 4]; 4]>> = vec![None; n_nodes];
if n_nodes == 0 {
return out;
}
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
// Iterative depth-first walk; stack carries (node_id, ancestor_matrix).
// Roots are pushed in order so that, after the LIFO pop order,
// the leftmost root is visited first — matching `bounding_box`'s
// determinism contract.
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || out[idx].is_some() {
continue;
}
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
out[idx] = Some(world);
// Walk children in reverse so leftmost child is popped first
// (deterministic ordering for snapshot consumers).
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
out
}
/// World-space axis-aligned bounding box per scene node, indexed by
/// `NodeId.0`.
///
/// Walks the [`Scene3D::roots`] forest with the same depth-first
/// shape as [`Scene3D::world_node_transforms`] / [`Scene3D::bounding_box`].
/// For every reachable node that carries a mesh (`Node::mesh ==
/// Some(id)`), the contained mesh's local AABB
/// ([`crate::Mesh::bounding_box`]) is transformed through the
/// node's full ancestor-chain world matrix via
/// [`BoundingBox::transform`] (eight-corner refit). The returned
/// vector has length `nodes.len()`; each slot holds:
///
/// * `Some(BoundingBox)` — the world-space tight AABB of the
/// node's attached mesh, transformed by the node's world matrix.
/// * `None` — the node is not reachable from any root, the node
/// carries no mesh, the referenced mesh is empty, or the mesh
/// reference is out of range. The four `None` reasons are not
/// distinguished; callers needing the distinction can pair this
/// with [`Scene3D::world_node_transforms`] (whose `None` slots
/// are reachability-only).
///
/// The output is the per-instance complement to
/// [`Scene3D::bounding_box`], which collapses every reachable
/// instance into a single scene-wide union. Each slot here is the
/// tight bound of one instance, fit around the eight transformed
/// corners of its mesh's local AABB — orientation-aware (an
/// arbitrary rotation widens the AABB to wrap the rotated content)
/// the same way [`BoundingBox::transform`] documents.
///
/// ## Use cases
///
/// * **Per-instance frustum / view-volume culling.** A renderer
/// tests each slot's AABB against the view frustum before
/// issuing the instance's draw call.
/// * **Scene-level ray AABB pre-pass.** A ray query walks the
/// slots once and only descends into
/// [`crate::Mesh::intersect_ray`] for instances whose AABB the
/// ray actually pierces (via [`BoundingBox::intersect_ray`]).
/// For triangle-budget-dominated scenes this reduces the ray
/// walk from `Σ triangle_count` to `Σ triangle_count over hit instances` —
/// the same kind of pruning [`crate::Bvh::intersect_ray`] applies
/// at the leaf level, lifted to the per-instance level.
/// * **BVH-of-instances seed.** A future scene-level BVH builder
/// feeds each slot's AABB + the slot index (a `NodeId`) into
/// the same median-split AABB-tree construction
/// [`crate::Bvh::build`] already runs per primitive — see
/// the round-210 docs gesture toward this layered acceleration.
///
/// ## What this does NOT include
///
/// * Skin pose deformation — the rest-pose vertices are used
/// verbatim. A rigged mesh reports the rest-pose extent, not
/// the skinned-pose extent at any particular animation time.
/// * Morph targets — only base
/// [`crate::Primitive::positions`] are folded into each mesh's
/// local AABB.
/// * Animation channels — the static scene-graph transform is
/// reported, not the post-animation transform.
/// * Up-axis or unit conversion. [`Scene3D::up_axis`] and
/// [`Scene3D::unit`] are metadata; the returned boxes live in
/// whatever coordinate system the scene stored.
///
/// ## Determinism + cycle contract
///
/// The walk is depth-first iterative on an explicit stack, with
/// roots visited in `roots`-order and children in source order —
/// identical to [`Scene3D::world_node_transforms`]. A node listed
/// as its own descendant (cycle) is visited once via the
/// first-arrival DFS path; out-of-range `NodeId` entries in
/// `roots` / `children` are silently skipped. A node referenced
/// by two parents (shared-instance) resolves to the first
/// parent's chain — per-instance world AABBs for the
/// shared-instance pattern need an explicit instance-list
/// side-channel.
///
/// Cost: `O(nodes.len() + total_children + Σ mesh_vertex_count_for_reachable_nodes)`,
/// where the per-mesh cost is the one
/// [`crate::Mesh::bounding_box`] iteration. Allocates one
/// `Vec<Option<BoundingBox>>` of length `nodes.len()` plus the
/// DFS stack.
pub fn world_node_bounds(&self) -> Vec<Option<BoundingBox>> {
let n_nodes = self.nodes.len();
let mut out: Vec<Option<BoundingBox>> = vec![None; n_nodes];
if n_nodes == 0 {
return out;
}
let n_meshes = self.meshes.len();
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
// `visited` is keyed on reachability so a node-with-no-mesh
// (returning `None` in `out`) is still detected as visited and
// not re-walked through a cycle.
let mut visited = vec![false; n_nodes];
// Iterative depth-first walk; stack carries (node_id, ancestor_matrix).
// Roots pushed in reverse so the LIFO pop visits the leftmost
// root first — matching `world_node_transforms`'s ordering.
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if n_meshes > 0 {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
if let Some(local) = mesh.bounding_box() {
out[idx] = Some(local.transform(world));
}
}
}
}
// Walk children in reverse so leftmost child is popped first
// (deterministic ordering for snapshot consumers).
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
out
}
/// Convenience wrapper around [`crate::InstanceBvh::build`].
///
/// Builds a scene-level bounding-volume hierarchy over every
/// reachable node-mesh instance — the next acceleration layer
/// above [`crate::Bvh::intersect_ray`] / per-instance
/// [`Mesh::intersect_ray`]. The same per-instance walk
/// [`Scene3D::intersect_ray`] performs becomes a
/// `O(log reachable_instance_count)` median-split traversal once
/// the tree is built. Cache the build alongside the scene; rebuild
/// when any node transform or mesh AABB changes.
pub fn build_instance_bvh(&self) -> Option<crate::InstanceBvh> {
crate::InstanceBvh::build(self)
}
/// Axis-aligned bounding box over every mesh referenced by a node
/// reachable from [`Scene3D::roots`], with each mesh's vertices
/// projected through its node's full ancestor transform chain.
///
/// Returns `None` when no reachable node carries a mesh, or every
/// reachable mesh is empty.
///
/// **What this does NOT include:**
///
/// * Skin pose deformation — the rest-pose vertices are used
/// verbatim. A bound mesh whose vertices are rigged to a
/// skeleton will report the *rest-pose* extent, not the
/// skinned-pose extent at any particular animation time.
/// * Morph targets — only base [`Primitive::positions`](crate::Primitive::positions)
/// are folded in.
/// * Meshes referenced by `nodes` not reachable from any root —
/// detached resources are ignored. Use [`Scene3D::meshes`] +
/// [`Mesh::bounding_box`](crate::Mesh::bounding_box) directly if
/// you need every resource regardless of scene-graph reachability.
///
/// Re-entry through a cycle (a node listed as its own descendant)
/// is guarded against — each node is visited at most once.
pub fn bounding_box(&self) -> Option<BoundingBox> {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return None;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut acc: Option<BoundingBox> = None;
// Iterative depth-first walk; stack carries (node_id, ancestor_matrix).
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
if let Some(b) = mesh.bounding_box() {
let xf = b.transform(world);
acc = Some(match acc {
None => xf,
Some(a) => a.union(xf),
});
}
}
}
// Walk children in reverse so leftmost child is popped first
// (deterministic for the deterministic-debug-output use case).
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
acc
}
/// Sum of triangles across every mesh primitive.
///
/// Lists / strips / fans contribute as if tessellated:
/// - `Triangles` → `vertex_count / 3` (or `index_count / 3`)
/// - `TriangleStrip` / `TriangleFan` → `max(0, n - 2)` triangles
/// - non-triangle topologies contribute 0.
pub fn triangle_count(&self) -> usize {
self.meshes
.iter()
.flat_map(|m| m.primitives.iter())
.map(|p| p.triangle_count())
.sum()
}
/// Sum of `positions.len()` across every mesh primitive.
pub fn vertex_count(&self) -> usize {
self.meshes
.iter()
.flat_map(|m| m.primitives.iter())
.map(|p| p.positions.len())
.sum()
}
/// Sum of every mesh primitive's [`Primitive::surface_area`] in the
/// scene's local unit-squared (matching [`Scene3D::unit`]). This
/// does *not* apply node transforms — primitives instanced by
/// multiple nodes contribute their unscaled area once per mesh,
/// not once per node. For a transform-aware total, walk
/// [`Scene3D::world_node_transforms`] and apply the per-node
/// scale's determinant per primitive instance.
pub fn surface_area(&self) -> f64 {
self.meshes.iter().map(|m| m.surface_area()).sum()
}
/// Area-weighted surface centroid across every mesh in the scene
/// — the area-weighted combination of every mesh's own
/// [`crate::Mesh::surface_centroid`]. This walks meshes once, not
/// node instances: a mesh instanced by multiple reachable nodes
/// contributes its centroid (with its area as the weight) once,
/// not once per node. For a transform-aware, per-instance
/// centroid total, walk [`Scene3D::world_node_transforms`]
/// alongside [`crate::Primitive::surface_centroid`] and combine
/// the per-instance centroids with their post-transform areas
/// (`|(M_3·E1) × (M_3·E2)|/2`) as weights — the local centroid
/// transforms by `world * [c, 1]` so each per-instance numerator
/// is `(world * centroid) * post_transform_area`.
///
/// Returns `None` when every contained mesh returns `None` (or
/// the scene holds zero meshes). Coordinates are in the scene's
/// local frame ([`Scene3D::unit`]); contract matches
/// [`crate::Primitive::surface_centroid`] for finiteness,
/// degenerate-skipping, and out-of-range / NaN handling.
pub fn surface_centroid(&self) -> Option<[f64; 3]> {
let mut sum_x = 0.0_f64;
let mut sum_y = 0.0_f64;
let mut sum_z = 0.0_f64;
let mut sum_area = 0.0_f64;
for m in &self.meshes {
let area = m.surface_area();
if area == 0.0 || !area.is_finite() {
continue;
}
if let Some(c) = m.surface_centroid() {
sum_x += c[0] * area;
sum_y += c[1] * area;
sum_z += c[2] * area;
sum_area += area;
}
}
if sum_area == 0.0 || !sum_area.is_finite() {
return None;
}
let inv = 1.0 / sum_area;
Some([sum_x * inv, sum_y * inv, sum_z * inv])
}
/// Sum of every mesh primitive's
/// [`crate::Primitive::signed_volume`] in the scene's local
/// unit-cubed (matching [`Scene3D::unit`]). This does *not* apply
/// node transforms — primitives instanced by multiple nodes
/// contribute their unscaled volume once per mesh, not once per
/// node. For a transform-aware total, walk
/// [`Scene3D::world_node_transforms`] and apply the per-node
/// scale's signed determinant per primitive instance (a negative
/// scale flips winding and so flips the sign of the enclosed
/// volume).
///
/// **Only physically meaningful when each contained mesh is a
/// closed two-manifold surface.** See
/// [`crate::Primitive::is_closed_manifold`] /
/// [`crate::Primitive::edge_manifold_report`].
pub fn signed_volume(&self) -> f64 {
self.meshes.iter().map(|m| m.signed_volume()).sum()
}
/// Unsigned `|signed_volume()|` across the scene. Same
/// shell-cancellation caveat as [`crate::Mesh::volume`]: this is
/// `|Σ signed|`, not `Σ |signed|`. For a multi-shell scene where
/// individual shells may differ in sign, prefer summing each mesh's
/// [`crate::Mesh::volume`] separately.
pub fn volume(&self) -> f64 {
self.signed_volume().abs()
}
/// Volume-weighted centroid (centre of mass) across every mesh in
/// the scene — the signed-volume-weighted combination of every
/// mesh's own [`crate::Mesh::volume_centroid`]. This walks meshes
/// once, not node instances: a mesh instanced by multiple reachable
/// nodes contributes its centroid (with its signed volume as the
/// weight) once, not once per node. For a transform-aware
/// per-instance centroid total, walk
/// [`Scene3D::world_node_transforms`] alongside
/// [`crate::Primitive::volume_centroid`] and combine the
/// per-instance centroids with their post-transform signed volumes
/// (`det(M_3x3) · V_local` for each closed-mesh instance) as
/// weights.
///
/// **Only physically meaningful when each contained mesh is a
/// closed two-manifold surface.** See
/// [`crate::Primitive::is_closed_manifold`] /
/// [`crate::Primitive::edge_manifold_report`]. An open patch (a
/// hemisphere, a plane) gives an answer that depends on where the
/// origin sits because the surface-cancellation argument no longer
/// applies; for those callers should use
/// [`Scene3D::surface_centroid`].
///
/// Returns `None` when every contained mesh returns `None` (or the
/// scene holds zero meshes), or when the accumulated signed volume
/// is `0.0` / non-finite (a flat sheet, or perfectly cancelling
/// inside-out shells). Coordinates are in the scene's local frame
/// ([`Scene3D::unit`]); contract matches
/// [`crate::Primitive::volume_centroid`] for finiteness,
/// degenerate-skipping, and out-of-range / NaN handling.
pub fn volume_centroid(&self) -> Option<[f64; 3]> {
let mut sum_x = 0.0_f64;
let mut sum_y = 0.0_f64;
let mut sum_z = 0.0_f64;
let mut sum_v = 0.0_f64;
for m in &self.meshes {
let v = m.signed_volume();
if v == 0.0 || !v.is_finite() {
continue;
}
if let Some(c) = m.volume_centroid() {
sum_x += c[0] * v;
sum_y += c[1] * v;
sum_z += c[2] * v;
sum_v += v;
}
}
if sum_v == 0.0 || !sum_v.is_finite() {
return None;
}
let inv = 1.0 / sum_v;
Some([sum_x * inv, sum_y * inv, sum_z * inv])
}
/// Unit-density inertia tensor across every mesh in the scene —
/// the element-wise sum of every contained mesh's
/// [`crate::Mesh::inertia_tensor`].
///
/// This walks meshes once, **not node instances**: a mesh
/// instantiated by multiple reachable nodes contributes its
/// inertia tensor once, not once per node. The result is in the
/// scene's local frame (no node transforms applied); to fold in
/// per-instance transforms, walk [`Scene3D::world_node_transforms`]
/// alongside [`crate::Primitive::inertia_tensor`] and apply the
/// rigid-body transform rule (`I_world = M_3 · I_local · M_3ᵀ +
/// parallel-axis correction`).
///
/// **Only physically meaningful when each contained mesh is a
/// closed two-manifold surface.** See
/// [`crate::Primitive::is_closed_manifold`] /
/// [`crate::Primitive::edge_manifold_report`]. An open patch yields
/// a tensor that depends on where the origin sits in the mesh's
/// frame because the closed-mesh boundary-term cancellation no
/// longer applies.
///
/// Returns `None` when every contained mesh returns `None` (or the
/// scene holds zero meshes). Coordinates are in the scene's local
/// frame ([`Scene3D::unit`]); contract matches
/// [`crate::Primitive::inertia_tensor`] for finiteness,
/// degenerate-skipping, and out-of-range / NaN handling.
pub fn inertia_tensor(&self) -> Option<[[f64; 3]; 3]> {
let mut total = [[0.0_f64; 3]; 3];
let mut any = false;
for m in &self.meshes {
if let Some(t) = m.inertia_tensor() {
for r in 0..3 {
for c in 0..3 {
total[r][c] += t[r][c];
}
}
any = true;
}
}
if !any {
None
} else {
Some(total)
}
}
/// Transform-aware total surface area across every node-instantiated
/// mesh in the scene, in world units squared (matching
/// [`Scene3D::unit`]² when the scene's root has identity transform).
///
/// Whereas [`Scene3D::surface_area`] sums each *mesh resource* once
/// regardless of how many nodes carry it (the geometric-content
/// total), `world_surface_area` walks the [`Scene3D::roots`] forest
/// the same way [`Scene3D::bounding_box`] does, applies each
/// reachable node's full ancestor-chain world matrix to its
/// primitive's triangle vertices, and sums the post-transform
/// triangle areas. A mesh instanced under two nodes therefore
/// contributes twice (once per instance), and each instance's
/// contribution reflects the world-space scale (and any
/// non-uniform skew) on the path to that node.
///
/// # Derivation
///
/// For a triangle `(P_a, P_b, P_c)` mapped through the affine world
/// matrix `M`, the post-transform edge vectors are
/// `M_3·(P_b - P_a)` and `M_3·(P_c - P_a)` (the translation row
/// cancels in the difference; `M_3` is the upper-left 3x3). The
/// transformed triangle's area is
///
/// ```text
/// A_world = |(M_3·E1) × (M_3·E2)| / 2.
/// ```
///
/// Under a uniform scale `s` the factor collapses to `s²`. Under a
/// non-uniform diagonal scale `(sx, sy, sz)` the factor depends on
/// the triangle's facing axis, so per-triangle evaluation — rather
/// than a single det-based scale — is required for correctness.
/// The translation column of `M` does not enter the area
/// computation, so the result is translation-invariant per
/// triangle (as expected for an intrinsic area metric).
///
/// # Contract
///
/// * Topology handling, degenerate-triangle skipping, NaN-guarding,
/// and out-of-range-index skipping all mirror
/// [`crate::Primitive::surface_area`]. Non-triangle topologies
/// contribute 0.0. Result is finite and non-negative for any
/// finite input.
/// * Mesh resources not reachable from any [`Scene3D::roots`] node
/// contribute 0.0 — the count is per-instance over the
/// scene-graph, not per-resource. For a resource-level total see
/// [`Scene3D::surface_area`].
/// * Cycles in the scene-graph are guarded the same way as
/// [`Scene3D::bounding_box`] / [`Scene3D::world_node_transforms`]:
/// each node is visited at most once. A node instanced under two
/// parents resolves to one world matrix (the first parent on the
/// DFS path); use an explicit instance side-table if your decoder
/// needs both.
/// * Skin pose deformation, morph targets, and unit-axis conversion
/// are *not* applied — the static scene-graph transform is the
/// only thing folded in. For a pose-time area, apply the
/// animation pose before calling.
/// * Cost `O(reachable_nodes + Σ triangle_count_per_reachable_mesh)`.
/// Allocates the DFS stack only; the per-triangle math is in
/// `f64` to avoid `f32` drift on dense meshes.
pub fn world_surface_area(&self) -> f64 {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return 0.0;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut total = 0.0_f64;
// Push roots in reverse so the LIFO pop visits the leftmost
// root first — matching `world_node_transforms`'s documented
// single-resolution policy (a shared instance reachable from
// two parents resolves via the first parent on the DFS path).
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
for prim in &mesh.primitives {
total += prim.world_surface_area(world);
}
}
}
// Walk children in reverse so leftmost child is popped first.
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
total
}
/// Transform-aware total signed volume across every
/// node-instantiated mesh, in world units cubed.
///
/// Whereas [`Scene3D::signed_volume`] sums each *mesh resource* once
/// in its local frame, `world_signed_volume` walks the
/// [`Scene3D::roots`] forest, applies each reachable node's
/// world-space transform to the underlying primitives, and
/// accumulates the per-instance signed enclosed volume.
///
/// # Derivation
///
/// For a primitive with local signed volume
/// `V_local = (1/6) Σ P_a · (P_b × P_c)` and an affine world
/// transform `M` whose upper-left 3x3 is `M_3` with translation
/// column `t`, every transformed corner is `M_3·P + t`. Expanding
/// the per-triangle scalar triple product:
///
/// ```text
/// (M_3·P_a + t) · ((M_3·P_b + t) × (M_3·P_c + t))
/// = det(M_3) · (P_a · (P_b × P_c)) + boundary_terms(t).
/// ```
///
/// The `boundary_terms(t)` involve only the open-mesh boundary and
/// vanish for a closed two-manifold (the same origin-cancellation
/// that makes the local signed volume translation-invariant). For
/// such a mesh the world signed volume reduces to
///
/// ```text
/// V_world = det(M_3) · V_local.
/// ```
///
/// `det(M_3)` is the *signed* 3x3 determinant: a uniform scale of
/// `s` gives `s³`; a single-axis mirror (`-1` on one axis) gives
/// `-1`, correctly flipping the enclosed-volume sign because the
/// triangle winding flips with the mirror. For an open mesh, the
/// translation-dependent boundary term means this scaling identity
/// is only an approximation; the helper still returns the
/// closed-form `det(M_3) · V_local` because that is the
/// physically-meaningful summand whenever the per-instance mesh is
/// itself a closed surface (the usual case for which the
/// volume reduction is defined).
///
/// # Contract
///
/// * Reachability, cycle-guarding, and per-instance accumulation
/// match [`Scene3D::world_surface_area`].
/// * Each node's world matrix is reduced to its upper-left 3x3
/// determinant; non-finite determinants (matrix corruption,
/// inf/NaN entries) skip the contribution.
/// * Each mesh resource contributes once per reachable node that
/// references it. A two-node instance with mirrored scale
/// `[-1, 1, 1]` and an unmirrored sibling cancel each other in
/// the signed sum — that is the geometric truth.
/// * Skin pose, morph targets, and unit-axis conversion are not
/// applied.
/// * Returns `0.0` for an empty scene or one with no
/// reachable meshes.
/// * Result is finite for any finite input; the accumulator is
/// `f64`.
/// * Cost `O(reachable_nodes + Σ triangle_count_per_reachable_mesh)`.
pub fn world_signed_volume(&self) -> f64 {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return 0.0;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut total = 0.0_f64;
// Push roots in reverse so the LIFO pop visits the leftmost
// root first — matching `world_node_transforms`'s
// single-resolution policy.
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
let det = mat3_det_of_world(world);
if det.is_finite() {
let local = mesh.signed_volume();
let scaled = det * local;
if scaled.is_finite() {
total += scaled;
}
}
}
}
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
total
}
/// Unsigned `|world_signed_volume()|` across the scene.
///
/// Same shell-cancellation caveat as
/// [`Scene3D::volume`] / [`crate::Mesh::volume`]: this is
/// `|Σ signed_world|`, not `Σ |signed_world|`. For a scene where
/// instances may carry mirrored scales (producing per-instance
/// negative signed volumes), prefer summing each instance's
/// `|det(M_3) · signed_volume|` separately.
pub fn world_volume(&self) -> f64 {
self.world_signed_volume().abs()
}
/// Transform-aware area-weighted surface centroid across every
/// node-instantiated mesh in the scene, in world units.
///
/// Whereas [`Scene3D::surface_centroid`] recombines each *mesh
/// resource* once regardless of how many nodes carry it,
/// `world_surface_centroid` walks the [`Scene3D::roots`] forest
/// the same way [`Scene3D::world_surface_area`] does, applies each
/// reachable node's full ancestor-chain world matrix to its
/// primitive's triangle vertices, and recombines the post-
/// transform per-instance centroids weighted by the per-instance
/// post-transform surface area. A mesh instanced under two nodes
/// therefore contributes twice (once per instance), and each
/// instance's contribution reflects the world-space scale and skew
/// on the path to that node.
///
/// # Derivation
///
/// Picking up where [`Scene3D::world_surface_area`] leaves off:
/// for a triangle `(P_a, P_b, P_c)` mapped through the affine
/// world matrix `M`, the post-transform centroid is `(M·P_a +
/// M·P_b + M·P_c) / 3` and the post-transform area is
/// `|(M_3·E1) × (M_3·E2)| / 2`. Substituting into the continuous
/// identity `C = (Σ area_i · centroid_i) / Σ area_i` and
/// accumulating across every reachable node's every primitive
/// gives the world-frame centroid. The recombination across
/// primitives (and across instances) is additivity of the surface
/// integral over a union of patches — the same reasoning that
/// makes [`Mesh::surface_centroid`] / [`Scene3D::surface_centroid`]
/// well-defined.
///
/// # Contract
///
/// * Topology handling, degenerate-triangle skipping, NaN guards,
/// and out-of-range-index skipping all mirror
/// [`crate::Primitive::world_surface_centroid`].
/// * Mesh resources not reachable from any [`Scene3D::roots`] node
/// contribute nothing — the count is per-instance over the
/// scene-graph, not per-resource. For a resource-level total see
/// [`Scene3D::surface_centroid`].
/// * Cycles in the scene-graph are guarded the same way as
/// [`Scene3D::bounding_box`] / [`Scene3D::world_node_transforms`]
/// / [`Scene3D::world_surface_area`]: each node is visited at
/// most once. A node instanced under two parents resolves to one
/// world matrix (the first parent on the DFS path).
/// * Returns `None` when no reachable triangle survives — empty
/// scene, no reachable mesh, every reachable mesh degenerate, or
/// every world transform collapsing the surface to zero area
/// under the transform.
/// * Skin pose deformation, morph targets, and unit-axis conversion
/// are *not* applied — the static scene-graph transform is the
/// only thing folded in. For a pose-time centroid, apply the
/// animation pose before calling.
/// * Cost `O(reachable_nodes + Σ triangle_count_per_reachable_mesh)`.
/// Allocates the DFS stack only; per-triangle math is in `f64` to
/// avoid `f32` drift on dense meshes.
pub fn world_surface_centroid(&self) -> Option<[f64; 3]> {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return None;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut sum_x = 0.0_f64;
let mut sum_y = 0.0_f64;
let mut sum_z = 0.0_f64;
let mut sum_area = 0.0_f64;
// Push roots in reverse so the LIFO pop visits the leftmost
// root first — matching `world_node_transforms`'s documented
// single-resolution policy (a shared instance reachable from
// two parents resolves via the first parent on the DFS path).
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
for prim in &mesh.primitives {
let area = prim.world_surface_area(world);
if area == 0.0 || !area.is_finite() {
continue;
}
if let Some(c) = prim.world_surface_centroid(world) {
sum_x += c[0] * area;
sum_y += c[1] * area;
sum_z += c[2] * area;
sum_area += area;
}
}
}
}
// Walk children in reverse so leftmost child is popped first.
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
if sum_area == 0.0 || !sum_area.is_finite() {
return None;
}
let inv = 1.0 / sum_area;
Some([sum_x * inv, sum_y * inv, sum_z * inv])
}
/// Transform-aware volume-weighted centroid (centre of mass) across
/// every node-instantiated mesh in the scene, in world units.
///
/// Whereas [`Scene3D::volume_centroid`] recombines each *mesh
/// resource* once regardless of how many nodes carry it,
/// `world_volume_centroid` walks the [`Scene3D::roots`] forest the
/// same way [`Scene3D::world_signed_volume`] /
/// [`Scene3D::world_surface_centroid`] do, applies each reachable
/// node's full ancestor-chain world matrix to its primitive's
/// triangle vertices, and recombines the post-transform per-instance
/// centroids weighted by the per-instance post-transform signed
/// volume. A mesh instanced under two nodes therefore contributes
/// twice (once per instance), and each instance's contribution
/// reflects the world-space scale, skew, *and* translation on the
/// path to that node — unlike the surface variants, the per-
/// instance volume integral picks up the translation column too
/// (the origin-anchored tet sum is not translation-invariant).
///
/// # Derivation
///
/// Picking up where [`Scene3D::world_volume`] leaves off: for a
/// closed mesh under affine `M = [M_3 | t]`, the per-instance
/// signed volume is `det(M_3) · V_local` and the per-instance
/// centroid is `M · C_local = M_3 · C_local + t`. The
/// signed-volume-weighted recombination across instances is then
/// additivity of the volume integral over a union of solid bodies
/// — the same reasoning that fixes [`Mesh::volume_centroid`] /
/// [`Scene3D::volume_centroid`] in the local frame. For an open
/// patch the recombination still goes through, but the per-
/// instance signed volume is no longer `det(M_3) · V_local` — the
/// origin-anchored tet sum picks up a translation-dependent
/// boundary term — so the helper computes both the per-primitive
/// centroid and signed volume in the transformed frame
/// independently and feeds them through the
/// `Σ V_i · C_i / Σ V_i` recombination directly.
///
/// # Contract
///
/// * Topology handling, degenerate / NaN guards, and out-of-range-
/// index skipping all mirror
/// [`crate::Primitive::world_volume_centroid`].
/// * Mesh resources not reachable from any [`Scene3D::roots`] node
/// contribute nothing — the count is per-instance over the
/// scene-graph, not per-resource. For a resource-level total see
/// [`Scene3D::volume_centroid`].
/// * Cycles in the scene-graph are guarded the same way as
/// [`Scene3D::bounding_box`] / [`Scene3D::world_node_transforms`]
/// / [`Scene3D::world_surface_centroid`]: each node is visited at
/// most once. A node instanced under two parents resolves to one
/// world matrix (the first parent on the DFS path).
/// * Returns `None` when no reachable instance contributes —
/// empty scene, no reachable mesh, every reachable mesh
/// non-triangle / degenerate, or every world transform
/// collapsing every tet to zero signed volume.
/// * Skin pose deformation, morph targets, and unit-axis conversion
/// are *not* applied — the static scene-graph transform is the
/// only thing folded in. For a pose-time centroid, apply the
/// animation pose before calling.
/// * Only physically meaningful when each reachable mesh is a
/// closed two-manifold surface (see
/// [`crate::Primitive::edge_manifold_report`]). For an open patch
/// the result depends on where the origin sits in the
/// transformed frame — same caveat as
/// [`crate::Primitive::world_volume_centroid`].
/// * Cost `O(reachable_nodes + Σ triangle_count_per_reachable_mesh)`.
/// Allocates the DFS stack only; per-triangle math is in `f64`.
pub fn world_volume_centroid(&self) -> Option<[f64; 3]> {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return None;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut sum_x = 0.0_f64;
let mut sum_y = 0.0_f64;
let mut sum_z = 0.0_f64;
let mut sum_v = 0.0_f64;
// Push roots in reverse so the LIFO pop visits the leftmost
// root first — matching `world_node_transforms`'s documented
// single-resolution policy (a shared instance reachable from
// two parents resolves via the first parent on the DFS path).
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
for prim in &mesh.primitives {
let v = prim.world_signed_volume(world);
if v == 0.0 || !v.is_finite() {
continue;
}
if let Some(c) = prim.world_volume_centroid(world) {
sum_x += c[0] * v;
sum_y += c[1] * v;
sum_z += c[2] * v;
sum_v += v;
}
}
}
}
// Walk children in reverse so leftmost child is popped first.
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
if sum_v == 0.0 || !sum_v.is_finite() {
return None;
}
let inv = 1.0 / sum_v;
Some([sum_x * inv, sum_y * inv, sum_z * inv])
}
/// Transform-aware unit-density inertia tensor across every
/// node-instantiated mesh in the scene, about the **world origin**,
/// returned as a row-major symmetric `[[f64; 3]; 3]`.
///
/// Closes the per-instance world-frame gap that
/// [`Scene3D::inertia_tensor`]'s prose (round 259) flagged as the
/// next-round candidate. Whereas [`Scene3D::inertia_tensor`] sums
/// each *mesh resource* once in the scene's local frame regardless of
/// how many nodes carry it, `world_inertia_tensor` walks the
/// [`Scene3D::roots`] forest the same way
/// [`Scene3D::world_volume_centroid`] /
/// [`Scene3D::world_surface_centroid`] /
/// [`Scene3D::world_node_transforms`] do, applies each reachable
/// node's full ancestor-chain world matrix to its primitive's
/// triangle vertices, and sums the per-instance world-frame tensors
/// element-wise. A mesh instanced under two nodes therefore
/// contributes **twice** (once per instance), and each instance
/// carries the world-space rotation, scale, skew, *and* translation
/// on the path to that node.
///
/// # Derivation
///
/// Each reachable node-mesh instance contributes
/// [`crate::Mesh::world_inertia_tensor`] of its mesh under the
/// composed world matrix `M` — the same per-corner mapping
/// [`crate::Primitive::world_inertia_tensor`] performs, so rotation,
/// non-uniform scale, skew, and the translation column of `M` are all
/// folded in. Element-wise summation across instances is additivity
/// of the second-moment integral over a union of disjoint solids
/// (the same argument [`Scene3D::world_signed_volume`] /
/// [`Scene3D::world_volume_centroid`] rest on). A mirrored instance
/// (`det(M_3) < 0`) contributes a negated tensor, matching the
/// sign-flip [`crate::Primitive::world_signed_volume`] carries.
///
/// # Contract
///
/// * Topology / degenerate / NaN / out-of-range skipping all mirror
/// [`crate::Primitive::inertia_tensor`].
/// * Mesh resources not reachable from any [`Scene3D::roots`] node
/// contribute nothing — the count is per-instance over the
/// scene-graph. For a resource-level local-frame total see
/// [`Scene3D::inertia_tensor`].
/// * Cycles are guarded the same way as
/// [`Scene3D::world_node_transforms`] / [`Scene3D::bounding_box`]:
/// each node is visited at most once; a node instanced under two
/// parents resolves to one world matrix (the first parent on the
/// DFS path).
/// * Returns `None` when no reachable mesh contributes a finite
/// tensor — empty scene, no reachable mesh node, or every reachable
/// primitive degenerate / non-triangle under its world transform.
/// * Skin pose deformation, morph targets, and unit-axis conversion
/// are *not* applied — the static scene-graph transform is the only
/// thing folded in.
/// * The result is the inertia tensor **about the world origin**; for
/// the tensor about the scene's centre of mass apply the parallel-
/// axis theorem with [`Scene3D::world_volume_centroid`] as the
/// reference point (`I_about_C = I_about_O - M_total · D`,
/// `D_αβ = c_α·c_β - δ_αβ·|c|²`).
/// * Pure; cost
/// `O(reachable_nodes + Σ triangle_count_per_reachable_mesh)`.
/// Allocates the DFS stack only; per-triangle math is in `f64`.
pub fn world_inertia_tensor(&self) -> Option<[[f64; 3]; 3]> {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return None;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut total = [[0.0_f64; 3]; 3];
let mut any = false;
// Push roots in reverse so the LIFO pop visits the leftmost
// root first — matching `world_node_transforms`'s documented
// single-resolution policy (a shared instance reachable from
// two parents resolves via the first parent on the DFS path).
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
if let Some(t) = mesh.world_inertia_tensor(world) {
for r in 0..3 {
for c in 0..3 {
total[r][c] += t[r][c];
}
}
any = true;
}
}
}
// Walk children in reverse so leftmost child is popped first.
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
if any {
Some(total)
} else {
None
}
}
/// Closest-hit ray query across every reachable node-mesh
/// instance in world space.
///
/// Walks the [`Scene3D::roots`] forest with the same DFS shape as
/// [`Scene3D::world_node_transforms`] / [`Scene3D::world_surface_area`].
/// At each reachable node carrying a mesh, the world ray is
/// transformed into the mesh's local frame via the inverse of the
/// node's world matrix, [`crate::Mesh::intersect_ray`] runs in that
/// frame, and the returned ray-parameter `t` is reported back
/// verbatim — affine change-of-frame leaves the `t` value
/// invariant (`P_world = M · P_local = M · (O_local + t · D_local) =
/// O_world + t · D_world`).
///
/// Each hit shrinks the search bound (`t_max`) before the next
/// node is tested, so a scene with many instances pays the
/// per-instance test only until the closest hit is fixed; later
/// instances behind that hit do triangle-level work only if their
/// transformed bound still satisfies the surviving `t_max`. That
/// pruning matches the per-primitive shrinking inside
/// [`crate::Mesh::intersect_ray`] and the
/// per-leaf shrinking inside [`crate::Bvh::intersect_ray`].
///
/// Returns `None` when the scene has no reachable mesh node, or
/// when no triangle on any reachable mesh is struck within
/// `t_max`.
///
/// # Returned hit
///
/// The [`SceneRayHit`] carries the `NodeId` that produced the hit,
/// the primitive index within that node's mesh, and the
/// mesh-local [`crate::ray::RayHit`] (barycentric, triangle index,
/// front-face flag, and the world-space `t`). The triangle index
/// indexes [`crate::Primitive::triangle_indices`] of the named
/// primitive — callers needing world-space corner positions
/// look up the local positions, then push them through
/// [`Scene3D::world_node_transforms`]`[node]`.
///
/// # Cycle / reachability contract
///
/// Each reachable node is visited at most once; a node listed as
/// its own descendant resolves only via the first DFS arrival
/// (same convention as [`Scene3D::world_node_transforms`]).
/// Detached mesh resources (not referenced from any root-reachable
/// node) are not queried; the caller drives those directly through
/// [`crate::Mesh::intersect_ray`] if needed.
///
/// # Singular instance transforms
///
/// If a node's world matrix is non-affine, contains non-finite
/// entries, or has a singular linear part (zero determinant —
/// e.g. a degenerate scale collapsing one axis to zero), that
/// instance is silently skipped. The surrounding scene still
/// produces hits where it can. The skip is the geometrically
/// honest answer — a degenerate transform projects the mesh onto
/// a sub-plane / sub-line whose ray intersection is undefined
/// without a regularised limit.
///
/// # Cost
///
/// `O(reachable_nodes + Σ instance_triangle_tests)`. For ray
/// budgets dominated by triangle-level work, pair this with a
/// per-primitive [`crate::Bvh`] cached on each instance for the
/// `O(log triangle_count)` per ray narrowing — see the
/// `Bvh::build` builder. Scene-level BVH-of-instances is a
/// candidate for a later round; the current walk is the
/// reference brute-force baseline.
///
/// # Degenerate ray
///
/// A zero-direction or non-finite ray reaches
/// [`crate::ray::intersect_triangle`] / [`crate::ray::intersect_aabb`]
/// unchanged after the local-frame transform; both helpers reject
/// such inputs with `None` (the slab test's `1/0` produces `Inf`,
/// the cross-product `det` collapses to zero or `NaN`, and the
/// existing finite-check guards short-circuit the test).
pub fn intersect_ray(&self, ray: crate::ray::Ray, t_max: f32) -> Option<SceneRayHit> {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return None;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut best: Option<SceneRayHit> = None;
let mut best_t = t_max;
// Push roots in reverse so the LIFO pop visits the leftmost
// root first — matching world_node_transforms's deterministic
// ordering. The deterministic walk order matters when two
// instances tie on `t` exactly (e.g. two coincident mirrored
// copies); the leftmost-first convention picks the same
// winner across runs.
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
if let Some(world_inv) = mat4_affine_inverse(world) {
let local_ray = ray_into_local(world_inv, ray);
if let Some((prim_idx, hit)) = mesh.intersect_ray(local_ray, best_t) {
// hit.t is in the local-frame ray
// parameter, which equals the world-frame
// ray parameter (affine change of frame is
// parameter-preserving). Shrink best_t.
// A later instance whose hit ties exactly
// (`hit.t == best_t`) is not allowed to
// override the existing winner — the
// earlier-visited (leftmost-first DFS)
// instance is the deterministic winner.
if best.is_none() || hit.t < best_t {
best_t = hit.t;
best = Some(SceneRayHit {
node: nid,
primitive_index: prim_idx,
hit,
});
}
}
}
}
}
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
best
}
/// Any-hit (shadow-ray) world-space query over the same reachable
/// node-mesh instances as [`Scene3D::intersect_ray`].
///
/// Returns `true` as soon as **any** reachable node-mesh instance
/// reports a hit within `t_max` for the ray, transformed into
/// each instance's local frame the same way
/// [`Scene3D::intersect_ray`] does. Returns `false` only after
/// exhausting every reachable instance without a hit.
///
/// Used for shadow rays / occlusion queries: the caller needs to
/// know whether *something* blocks the segment from the surface
/// hit point to the light, not which thing or where. The
/// short-circuit lets the walk skip the rest of the scene as soon
/// as the answer is decided.
///
/// Reachability, cycle-guarding, singular-transform skipping, and
/// degenerate-ray handling match [`Scene3D::intersect_ray`].
///
/// # Determinism
///
/// The walk visits instances in the same DFS order as
/// [`Scene3D::intersect_ray`], but the answer (`true` / `false`)
/// does not depend on visit order — the existence of a blocker
/// is order-invariant. Visit order only changes which instance
/// is the *first* blocker discovered, never the return value.
pub fn any_ray_intersection(&self, ray: crate::ray::Ray, t_max: f32) -> bool {
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
if n_nodes == 0 || n_meshes == 0 {
return false;
}
let mut visited = vec![false; n_nodes];
let identity: [[f32; 4]; 4] = [
[1.0, 0.0, 0.0, 0.0],
[0.0, 1.0, 0.0, 0.0],
[0.0, 0.0, 1.0, 0.0],
[0.0, 0.0, 0.0, 1.0],
];
let mut stack: Vec<(NodeId, [[f32; 4]; 4])> =
self.roots.iter().rev().map(|r| (*r, identity)).collect();
while let Some((nid, parent)) = stack.pop() {
let idx = nid.0 as usize;
if idx >= n_nodes || visited[idx] {
continue;
}
visited[idx] = true;
let node = &self.nodes[idx];
let world = mat4_mul(parent, node.transform.to_matrix());
if let Some(m) = node.mesh {
if let Some(mesh) = self.meshes.get(m.0 as usize) {
if let Some(world_inv) = mat4_affine_inverse(world) {
let local_ray = ray_into_local(world_inv, ray);
// We reuse the closest-hit primitive walk —
// it has the same finite-time termination
// contract and short-circuits at the first
// primitive hit within `t_max`. A dedicated
// any-hit `Mesh::any_ray_intersection`
// wouldn't change the answer; the closest-hit
// walk still examines every primitive in
// `mesh` because each primitive's hit might
// be closer than the last, but it returns
// `Some(_)` whenever any does.
if mesh.intersect_ray(local_ray, t_max).is_some() {
return true;
}
}
}
}
for child in node.children.iter().rev() {
stack.push((*child, world));
}
}
false
}
/// Walk every cross-collection reference and report dangling
/// indices + inconsistent buffer lengths. Returns `Ok(())` when
/// the scene is internally consistent, or `Err` carrying every
/// problem found (the walk does not short-circuit, so callers see
/// the full set in one pass).
///
/// Currently checks:
///
/// * `roots` reference live `nodes`.
/// * Every `Node::children`, `Node::mesh`, `Node::camera`,
/// `Node::light`, `Node::skin`, `Node::audio_emitter` references
/// a live entry in the corresponding arena.
/// * Every primitive's optional attribute buffer (`normals`,
/// `tangents`, `uvs[i]`, `colors[i]`, `joints`, `weights`)
/// matches `positions.len()`.
/// * `Primitive::indices` values stay within `positions.len()`.
/// * `Primitive::material` indices are live.
/// * Each `MorphTarget` slot length matches the corresponding
/// base attribute on the parent `Primitive`.
/// * `Mesh::weights.len()` matches the morph-target count of
/// every contained primitive (or every primitive has zero
/// targets and `weights` is empty).
/// * `Mesh::target_names.len()`, when non-empty, matches the
/// morph-target count of every contained primitive (glTF 2.0
/// §3.7.2.2 implementation note — the `targetNames` array and
/// all primitive `targets` arrays must have the same length).
/// * Every [`Inbetween`](crate::Inbetween) declares a legal,
/// unique weight station (finite, not `0`/`1`, no duplicates
/// within one target) and its delta arrays match the base
/// `positions` length.
/// * A non-empty `Node::weights` override sits on a node that
/// instantiates a mesh, and its length matches the morph-target
/// count of every primitive of that mesh (glTF 2.0 `node.weights`
/// count/`mesh`-presence requirements).
/// * Every `Skeleton::inverse_bind_matrices` entry has its fourth
/// row set to `[0, 0, 0, 1]` (glTF 2.0 §5.28.1 affine-IBM
/// constraint), and at least as many entries as joints exist
/// when the list is non-empty (§3.7.3.1 count >= joints; extra
/// trailing entries are conforming).
/// * Per-vertex joint weights are finite and non-negative
/// (§3.7.3.3), and — for every node binding a mesh to a skin —
/// every joint index stays within the bound skeleton's joint
/// count.
/// * `MorphWeights` animation samplers carry exactly one weight
/// per morph target of the mesh their target node instantiates
/// (§3.6), when that node → mesh chain resolves.
///
/// This is a defensive check for fuzzers and codec authors —
/// production decoders are expected to produce valid scenes
/// already; the runtime cost is `O(N)` over every typed buffer.
pub fn validate(&self) -> std::result::Result<(), Vec<ValidationError>> {
let mut errors = Vec::new();
let n_nodes = self.nodes.len();
let n_meshes = self.meshes.len();
let n_materials = self.materials.len();
let n_textures = self.textures.len();
let n_cameras = self.cameras.len();
let n_lights = self.lights.len();
let n_skeletons = self.skeletons.len();
let n_skins = self.skins.len();
let n_emitters = self.audio_emitters.len();
let n_audio_sources = self.audio_sources.len();
for (i, root) in self.roots.iter().enumerate() {
if (root.0 as usize) >= n_nodes {
errors.push(ValidationError::DanglingId {
location: format!("roots[{i}]"),
id: root.0,
arena: "nodes",
});
}
}
for (i, node) in self.nodes.iter().enumerate() {
for (j, child) in node.children.iter().enumerate() {
if (child.0 as usize) >= n_nodes {
errors.push(ValidationError::DanglingId {
location: format!("nodes[{i}].children[{j}]"),
id: child.0,
arena: "nodes",
});
}
}
if let Some(m) = node.mesh {
if (m.0 as usize) >= n_meshes {
errors.push(ValidationError::DanglingId {
location: format!("nodes[{i}].mesh"),
id: m.0,
arena: "meshes",
});
}
}
if let Some(c) = node.camera {
if (c.0 as usize) >= n_cameras {
errors.push(ValidationError::DanglingId {
location: format!("nodes[{i}].camera"),
id: c.0,
arena: "cameras",
});
}
}
if let Some(l) = node.light {
if (l.0 as usize) >= n_lights {
errors.push(ValidationError::DanglingId {
location: format!("nodes[{i}].light"),
id: l.0,
arena: "lights",
});
}
}
if let Some(s) = node.skin {
if (s.0 as usize) >= n_skins {
errors.push(ValidationError::DanglingId {
location: format!("nodes[{i}].skin"),
id: s.0,
arena: "skins",
});
}
}
if let Some(e) = node.audio_emitter {
if (e.0 as usize) >= n_emitters {
errors.push(ValidationError::DanglingId {
location: format!("nodes[{i}].audio_emitter"),
id: e.0,
arena: "audio_emitters",
});
}
}
// Node-level morph-weight overrides (glTF 2.0
// `node.weights`): only meaningful on a node that
// instantiates a mesh, and the vector must carry one
// weight per morph target of every contained primitive —
// the per-instance mirror of the `Mesh::weights` parity
// check below.
if !node.weights.is_empty() {
match node.mesh {
None => errors.push(ValidationError::NodeMorphWeightsWithoutMesh {
location: format!("nodes[{i}].weights"),
}),
Some(m) => {
// A dangling mesh id is already reported above;
// the count check only applies when it resolves.
if let Some(mesh) = self.meshes.get(m.0 as usize) {
for (pi, prim) in mesh.primitives.iter().enumerate() {
if prim.targets.len() != node.weights.len() {
errors.push(ValidationError::NodeMorphWeightCountMismatch {
location: format!(
"nodes[{i}].weights -> meshes[{mi}].primitives[{pi}]",
mi = m.0
),
node_weights: node.weights.len(),
primitive_targets: prim.targets.len(),
});
}
}
}
}
}
}
}
for (mi, mesh) in self.meshes.iter().enumerate() {
let mesh_weights = mesh.weights.len();
for (pi, prim) in mesh.primitives.iter().enumerate() {
let n_pos = prim.positions.len();
let here = |field: &str| format!("meshes[{mi}].primitives[{pi}].{field}");
if let Some(v) = &prim.normals {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: here("normals"),
expected: n_pos,
actual: v.len(),
});
}
}
if let Some(v) = &prim.tangents {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: here("tangents"),
expected: n_pos,
actual: v.len(),
});
}
}
for (k, set) in prim.uvs.iter().enumerate() {
if set.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: here(&format!("uvs[{k}]")),
expected: n_pos,
actual: set.len(),
});
}
}
for (k, set) in prim.colors.iter().enumerate() {
if set.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: here(&format!("colors[{k}]")),
expected: n_pos,
actual: set.len(),
});
}
}
if let Some(v) = &prim.joints {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: here("joints"),
expected: n_pos,
actual: v.len(),
});
}
}
if let Some(v) = &prim.weights {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: here("weights"),
expected: n_pos,
actual: v.len(),
});
}
// glTF 2.0 §3.7.3.3: joint weights MUST NOT be
// negative (and NaN/Inf would poison the blend).
// Report the first offending component only — one
// corrupt buffer would otherwise flood the report.
'weights: for (vi, row) in v.iter().enumerate() {
for (ci, w) in row.iter().enumerate() {
if !w.is_finite() || *w < 0.0 {
errors.push(ValidationError::JointWeightInvalid {
location: here(&format!("weights[{vi}][{ci}]")),
value: *w,
});
break 'weights;
}
}
}
}
if let Some(idx) = &prim.indices {
let max_ok = n_pos as u32;
let bad = match idx {
crate::mesh::Indices::U16(v) => v.iter().any(|i| (*i as u32) >= max_ok),
crate::mesh::Indices::U32(v) => v.iter().any(|i| *i >= max_ok),
};
if bad {
errors.push(ValidationError::IndexOutOfRange {
location: here("indices"),
vertex_count: n_pos,
});
}
}
if let Some(m) = prim.material {
if (m.0 as usize) >= n_materials {
errors.push(ValidationError::DanglingId {
location: here("material"),
id: m.0,
arena: "materials",
});
}
}
// KHR_materials_variants mappings: material + variant
// ids must be live, and across the whole mappings list
// each variant may be claimed by at most one mapping.
let n_variants = self.material_variants.len();
let mut seen_variants: HashSet<u32> = HashSet::new();
for (ki, mapping) in prim.variant_mappings.iter().enumerate() {
if (mapping.material.0 as usize) >= n_materials {
errors.push(ValidationError::DanglingId {
location: here(&format!("variant_mappings[{ki}].material")),
id: mapping.material.0,
arena: "materials",
});
}
for (vi, v) in mapping.variants.iter().enumerate() {
if (v.0 as usize) >= n_variants {
errors.push(ValidationError::DanglingId {
location: here(&format!("variant_mappings[{ki}].variants[{vi}]")),
id: v.0,
arena: "material_variants",
});
}
if !seen_variants.insert(v.0) {
errors.push(ValidationError::DuplicateVariantMapping {
location: here(&format!("variant_mappings[{ki}].variants[{vi}]")),
variant: v.0,
});
}
}
}
// Texture-coordinate coverage: every texture slot of
// every material this primitive can draw with (the
// base material plus each variant-mapping override)
// must sample a UV channel the primitive actually
// carries — glTF 2.0 requires the corresponding
// TEXCOORD attribute for the material to be
// applicable. The checked set is the *effective* one:
// a `KHR_texture_transform` `texCoord` override wins
// over the reference's own `uv_set`.
{
let mut checked: HashSet<u32> = HashSet::new();
let base = prim.material.iter().map(|m| (*m, None));
let mapped = prim
.variant_mappings
.iter()
.enumerate()
.map(|(ki, mapping)| (mapping.material, Some(ki)));
for (mid, mapping_idx) in base.chain(mapped) {
if !checked.insert(mid.0) {
continue; // shared material: report once
}
let Some(mat) = self.materials.get(mid.0 as usize) else {
continue; // dangling id already reported
};
for (field, r) in mat.texture_refs() {
let uv_set = r.effective_uv_set();
if (uv_set as usize) >= prim.uvs.len() {
let via = match mapping_idx {
None => String::new(),
Some(ki) => format!(".variant_mappings[{ki}]"),
};
errors.push(ValidationError::UvSetOutOfRange {
location: format!(
"meshes[{mi}].primitives[{pi}]{via} -> materials[{id}].{field}",
id = mid.0
),
uv_set,
available: prim.uvs.len(),
});
}
}
}
}
for (ti, tgt) in prim.targets.iter().enumerate() {
let tgt_loc = |field: &str| here(&format!("targets[{ti}].{field}"));
if let Some(v) = &tgt.position {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: tgt_loc("position"),
expected: n_pos,
actual: v.len(),
});
}
}
if let Some(v) = &tgt.normal {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: tgt_loc("normal"),
expected: n_pos,
actual: v.len(),
});
}
}
if let Some(v) = &tgt.tangent {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: tgt_loc("tangent"),
expected: n_pos,
actual: v.len(),
});
}
}
// In-between shapes (USD blend-shape §1.4.1
// authoring rules): the endpoint weights 0 and 1
// are implicitly defined and must not be
// authored, weights must be finite, and no two
// in-betweens of one target may share a weight.
// Delta arrays are per-vertex parallel like the
// primary slots.
for (ii, ib) in tgt.inbetweens.iter().enumerate() {
let ib_loc =
|field: &str| here(&format!("targets[{ti}].inbetweens[{ii}]{field}"));
if !ib.is_valid_weight() {
errors.push(ValidationError::InbetweenWeightInvalid {
location: ib_loc(""),
weight: ib.weight,
});
} else if tgt.inbetweens[..ii].iter().any(|o| o.weight == ib.weight) {
errors.push(ValidationError::InbetweenDuplicateWeight {
location: ib_loc(""),
weight: ib.weight,
});
}
if let Some(v) = &ib.position {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: ib_loc(".position"),
expected: n_pos,
actual: v.len(),
});
}
}
if let Some(v) = &ib.normal {
if v.len() != n_pos {
errors.push(ValidationError::AttributeLengthMismatch {
location: ib_loc(".normal"),
expected: n_pos,
actual: v.len(),
});
}
}
}
}
if mesh_weights != 0 && prim.targets.len() != mesh_weights {
errors.push(ValidationError::MorphWeightCountMismatch {
location: format!("meshes[{mi}].primitives[{pi}].targets"),
mesh_weights,
primitive_targets: prim.targets.len(),
});
}
// Morph-target names: glTF 2.0 §3.7.2.2 implementation
// note — the `targetNames` array and all primitive
// `targets` arrays must have the same length. Empty
// means unnamed and is always fine.
if !mesh.target_names.is_empty() && prim.targets.len() != mesh.target_names.len() {
errors.push(ValidationError::MorphTargetNameCountMismatch {
location: format!("meshes[{mi}].primitives[{pi}].targets"),
target_names: mesh.target_names.len(),
primitive_targets: prim.targets.len(),
});
}
}
}
// Materials → textures. `Material::texture_refs` enumerates
// every slot — the five core maps plus every extension map on
// `MaterialExt` — so a newly added slot is validated the day
// it exists rather than needing a matching edit here.
for (mi, mat) in self.materials.iter().enumerate() {
for (field, r) in mat.texture_refs() {
if (r.texture.0 as usize) >= n_textures {
errors.push(ValidationError::DanglingId {
location: format!("materials[{mi}].{field}"),
id: r.texture.0,
arena: "textures",
});
}
// A `KHR_texture_transform` with a non-finite affine
// component would poison every coordinate it maps.
if let Some(t) = r.transform {
if !t.is_finite() {
errors.push(ValidationError::TextureTransformNotFinite {
location: format!("materials[{mi}].{field}.transform"),
});
}
}
}
}
// Skeletons → nodes + inverse-bind-matrix parity.
for (si, skel) in self.skeletons.iter().enumerate() {
for (ji, joint) in skel.joints.iter().enumerate() {
if (joint.0 as usize) >= n_nodes {
errors.push(ValidationError::DanglingId {
location: format!("skeletons[{si}].joints[{ji}]"),
id: joint.0,
arena: "nodes",
});
}
}
// glTF 2.0 §3.7.3.1: the inverse-bind element count MUST
// be greater than *or equal to* the joint count — extra
// trailing matrices are conforming (the skinning math
// ignores them); only a shortfall is an error. Empty stays
// the "identity for every joint" escape hatch (§5.28's
// documented default when the accessor is omitted).
if !skel.inverse_bind_matrices.is_empty()
&& skel.inverse_bind_matrices.len() < skel.joints.len()
{
errors.push(ValidationError::SkeletonBindMatrixCountMismatch {
location: format!("skeletons[{si}]"),
joints: skel.joints.len(),
inverse_bind_matrices: skel.inverse_bind_matrices.len(),
});
}
// glTF 2.0 §5.28.1: an accessor referenced by
// `inverseBindMatrices` MUST have its fourth row set to
// `[0.0, 0.0, 0.0, 1.0]` (the matrix is affine — a pure
// composition of rotations/translations/scales/shears,
// never projective). Our matrix is row-major
// column-vector, so the "fourth row" of the math matrix
// is the row at index 3.
for (ji, ibm) in skel.inverse_bind_matrices.iter().enumerate() {
let last = ibm[3];
if last[0] != 0.0 || last[1] != 0.0 || last[2] != 0.0 || last[3] != 1.0 {
errors.push(ValidationError::SkeletonBindMatrixNotAffine {
location: format!("skeletons[{si}].inverse_bind_matrices[{ji}]"),
last_row: last,
});
}
}
}
// Skins → skeletons + optional root node.
for (si, skin) in self.skins.iter().enumerate() {
if (skin.skeleton.0 as usize) >= n_skeletons {
errors.push(ValidationError::DanglingId {
location: format!("skins[{si}].skeleton"),
id: skin.skeleton.0,
arena: "skeletons",
});
}
if let Some(r) = skin.root_node {
if (r.0 as usize) >= n_nodes {
errors.push(ValidationError::DanglingId {
location: format!("skins[{si}].root_node"),
id: r.0,
arena: "nodes",
});
}
}
}
// Skinned nodes: every joint index used by the mesh's
// primitives must stay within the bound skeleton's joint list
// (glTF 2.0 §3.7.3.3: "All joint values MUST be within the
// range of joints in the skin"). This is the only check that
// needs the node → skin → skeleton binding, since the same
// mesh could be bound to differently-sized skeletons by
// different nodes.
for (ni, node) in self.nodes.iter().enumerate() {
let (Some(mesh_id), Some(skin_id)) = (node.mesh, node.skin) else {
continue;
};
let Some(mesh) = self.meshes.get(mesh_id.0 as usize) else {
continue; // dangling mesh already reported above
};
let Some(skin) = self.skins.get(skin_id.0 as usize) else {
continue; // dangling skin already reported above
};
let Some(skel) = self.skeletons.get(skin.skeleton.0 as usize) else {
continue; // dangling skeleton already reported above
};
let joint_count = skel.joints.len();
for (pi, prim) in mesh.primitives.iter().enumerate() {
let Some(joints) = &prim.joints else {
continue;
};
// First offender per primitive, same anti-flood shape
// as the weight scan.
'joints: for (vi, row) in joints.iter().enumerate() {
for (ci, j) in row.iter().enumerate() {
if (*j as usize) >= joint_count {
errors.push(ValidationError::JointIndexOutOfRange {
location: format!(
"nodes[{ni}] -> meshes[{mi}].primitives[{pi}].joints[{vi}][{ci}]",
mi = mesh_id.0
),
joint: *j,
joint_count,
});
break 'joints;
}
}
}
}
}
// Audio emitters → audio sources.
for (ei, em) in self.audio_emitters.iter().enumerate() {
if (em.source.0 as usize) >= n_audio_sources {
errors.push(ValidationError::DanglingId {
location: format!("audio_emitters[{ei}].source"),
id: em.source.0,
arena: "audio_sources",
});
}
}
// Animations: channel target nodes + sampler parity.
for (ai, anim) in self.animations.iter().enumerate() {
for (ci, ch) in anim.channels.iter().enumerate() {
let loc = |suffix: &str| format!("animations[{ai}].channels[{ci}]{suffix}");
if (ch.target.node.0 as usize) >= n_nodes {
errors.push(ValidationError::DanglingId {
location: loc(".target.node"),
id: ch.target.node.0,
arena: "nodes",
});
}
let k = ch.sampler.keyframes.len();
if k == 0 {
errors.push(ValidationError::AnimationSamplerEmpty {
location: loc(".sampler"),
});
} else {
let mut prev = f32::NEG_INFINITY;
for (ki, t) in ch.sampler.keyframes.iter().enumerate() {
if t.partial_cmp(&prev) != Some(std::cmp::Ordering::Greater) {
errors.push(ValidationError::AnimationKeyframesNotStrictlyIncreasing {
location: loc(&format!(".sampler.keyframes[{ki}]")),
at: *t,
previous: prev,
});
break;
}
prev = *t;
}
}
use crate::animation::{AnimationProperty as P, AnimationValues as V};
let variant_ok = matches!(
(ch.target.property, &ch.sampler.values),
(P::Translation | P::Scale, V::Vec3(_))
| (P::Rotation, V::Quat(_))
| (P::MorphWeights, V::Scalar(_))
);
if !variant_ok {
let expected: &'static str = match ch.target.property {
P::Translation | P::Scale => "Vec3",
P::Rotation => "Quat",
P::MorphWeights => "Scalar",
};
let actual: &'static str = match ch.sampler.values {
V::Vec3(_) => "Vec3",
V::Quat(_) => "Quat",
V::Scalar(_) => "Scalar",
};
errors.push(ValidationError::AnimationValueVariantMismatch {
location: loc(""),
property: match ch.target.property {
P::Translation => "Translation",
P::Rotation => "Rotation",
P::Scale => "Scale",
P::MorphWeights => "MorphWeights",
},
expected_variant: expected,
actual_variant: actual,
});
}
if k != 0 {
let v = ch.sampler.values.len();
let expected_factor = match ch.sampler.interpolation {
crate::animation::Interpolation::CubicSpline => 3,
_ => 1,
};
let ok = match (ch.target.property, &ch.sampler.values) {
(P::MorphWeights, V::Scalar(_)) => {
let denom = k * expected_factor;
denom != 0 && v % denom == 0 && v >= denom
}
_ => v == k * expected_factor,
};
if !ok {
errors.push(ValidationError::AnimationSamplerLengthMismatch {
location: loc(".sampler"),
keyframes: k,
values: v,
interpolation: match ch.sampler.interpolation {
crate::animation::Interpolation::Step => "Step",
crate::animation::Interpolation::Linear => "Linear",
crate::animation::Interpolation::CubicSpline => "CubicSpline",
},
});
} else if ch.target.property == P::MorphWeights
&& matches!(ch.sampler.values, V::Scalar(_))
{
// The per-frame weight-vector stride must equal
// the morph-target count of the mesh the target
// node instantiates (glTF 2.0 §3.6: a weights
// sampler carries count(targets) floats per
// keyframe). Only checkable when the node →
// mesh chain resolves; dangling links are
// already reported above.
let stride = v / (k * expected_factor);
let targets = self
.nodes
.get(ch.target.node.0 as usize)
.and_then(|n| n.mesh)
.and_then(|m| self.meshes.get(m.0 as usize))
.and_then(|mesh| mesh.primitives.first())
.map(|prim| prim.targets.len());
if let Some(targets) = targets {
if stride != targets {
errors.push(ValidationError::AnimationMorphStrideMismatch {
location: loc(".sampler"),
stride,
targets,
});
}
}
}
}
}
}
if errors.is_empty() {
Ok(())
} else {
Err(errors)
}
}
}
/// One issue surfaced by [`Scene3D::validate`]. The variants intentionally
/// carry breadcrumb strings (`"meshes[3].primitives[0].normals"`) so a
/// caller can render a usable diagnostic without re-walking the scene.
///
/// `Eq` is not implemented because
/// [`AnimationKeyframesNotStrictlyIncreasing`](Self::AnimationKeyframesNotStrictlyIncreasing)
/// carries `f32` keyframe values; use `PartialEq` or pattern-match on
/// the variant fields when asserting in tests.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum ValidationError {
/// A typed `IdT(u32)` field points outside its arena.
DanglingId {
location: String,
id: u32,
arena: &'static str,
},
/// An optional attribute buffer is present but its length disagrees
/// with the parent primitive's `positions.len()`.
AttributeLengthMismatch {
location: String,
expected: usize,
actual: usize,
},
/// A primitive's index buffer references a vertex past
/// `positions.len()`.
IndexOutOfRange {
location: String,
vertex_count: usize,
},
/// `Mesh::weights` is non-empty and disagrees with one of the
/// child primitives' morph-target count.
MorphWeightCountMismatch {
location: String,
mesh_weights: usize,
primitive_targets: usize,
},
/// [`Mesh::target_names`](crate::Mesh::target_names) is non-empty
/// and its length disagrees with one of the child primitives'
/// morph-target count (glTF 2.0 §3.7.2.2 implementation note:
/// the `targetNames` array and all primitive `targets` arrays
/// must have the same length).
MorphTargetNameCountMismatch {
location: String,
target_names: usize,
primitive_targets: usize,
},
/// An [`Inbetween`](crate::Inbetween) declares an illegal weight
/// station: non-finite, or exactly `0.0` / `1.0` (the USD
/// blend-shape schema defines those endpoints implicitly — the
/// null shape and the primary deltas — and forbids authoring
/// them). [`MorphTarget::at_weight`](crate::MorphTarget::at_weight)
/// ignores the shape.
InbetweenWeightInvalid { location: String, weight: f32 },
/// Two in-betweens of one [`MorphTarget`](crate::MorphTarget)
/// share a weight station (forbidden — averaging colliding shapes
/// would leave the result unnamed and non-round-trippable).
/// Reported on the second and later claimants;
/// [`MorphTarget::at_weight`](crate::MorphTarget::at_weight)
/// ignores every shape at the duplicated weight.
InbetweenDuplicateWeight { location: String, weight: f32 },
/// A [`Node::weights`](crate::Node::weights) override is non-empty
/// and its length disagrees with the morph-target count of one of
/// the instantiated mesh's primitives (glTF 2.0 `node.weights`:
/// the element count MUST match the referenced mesh's morph-target
/// count).
NodeMorphWeightCountMismatch {
location: String,
node_weights: usize,
primitive_targets: usize,
},
/// A [`Node::weights`](crate::Node::weights) override is non-empty
/// on a node that carries no mesh (glTF 2.0 `node.weights`: when
/// defined, `mesh` MUST also be defined) — there is nothing to
/// blend.
NodeMorphWeightsWithoutMesh { location: String },
/// [`Skeleton::inverse_bind_matrices`](crate::Skeleton::inverse_bind_matrices)
/// is non-empty and its length disagrees with
/// [`Skeleton::joints`](crate::Skeleton::joints).
SkeletonBindMatrixCountMismatch {
location: String,
joints: usize,
inverse_bind_matrices: usize,
},
/// One of [`Skeleton::inverse_bind_matrices`](crate::Skeleton::inverse_bind_matrices)
/// has a non-affine fourth row. The glTF 2.0 spec §5.28.1
/// requires every IBM's last row to be `[0.0, 0.0, 0.0, 1.0]`;
/// any other value implies a projective component that the
/// skinning math `(weight_i * joint_world_i * IBM_i * pos)` would
/// silently corrupt.
SkeletonBindMatrixNotAffine {
location: String,
last_row: [f32; 4],
},
/// An animation channel's sampler has zero keyframes; no
/// keyframe-time table to interpolate against.
AnimationSamplerEmpty { location: String },
/// An animation sampler's keyframe times are not strictly
/// increasing — the renderer would search ambiguously.
AnimationKeyframesNotStrictlyIncreasing {
location: String,
at: f32,
previous: f32,
},
/// An animation sampler's value variant disagrees with the
/// channel target's property kind (e.g. `Rotation` channel
/// fed `Vec3` values).
AnimationValueVariantMismatch {
location: String,
property: &'static str,
expected_variant: &'static str,
actual_variant: &'static str,
},
/// An animation sampler's value count doesn't match the expected
/// `keyframes.len() * factor` (`factor = 1` for Step/Linear,
/// `factor = 3` for CubicSpline; MorphWeights additionally
/// multiplies by per-mesh morph-target count, so we only check
/// divisibility there).
AnimationSamplerLengthMismatch {
location: String,
keyframes: usize,
values: usize,
interpolation: &'static str,
},
/// A `MorphWeights` sampler's per-keyframe weight-vector stride
/// disagrees with the morph-target count of the mesh instantiated
/// by the channel's target node (glTF 2.0 §3.6: one weight per
/// morph target per keyframe).
AnimationMorphStrideMismatch {
location: String,
stride: usize,
targets: usize,
},
/// A primitive bound to a skin (via a node carrying both `mesh`
/// and `skin`) references a joint index at or beyond the bound
/// skeleton's joint count (glTF 2.0 §3.7.3.3: all joint values
/// MUST be within the range of joints in the skin). Only the
/// first offending component per primitive is reported.
JointIndexOutOfRange {
location: String,
joint: u16,
joint_count: usize,
},
/// A vertex joint weight is negative or non-finite (glTF 2.0
/// §3.7.3.3: weights MUST NOT be negative; NaN/Inf would poison
/// the linear blend). Only the first offending component per
/// primitive is reported.
JointWeightInvalid { location: String, value: f32 },
/// A `KHR_materials_variants` variant index appears in more than
/// one mapping of the same primitive's
/// [`variant_mappings`](crate::Primitive::variant_mappings) list.
/// The extension requires each variant index to be used at most
/// once across the whole list, so the active-variant lookup is
/// unambiguous.
DuplicateVariantMapping { location: String, variant: u32 },
/// A material applied by a primitive (directly or through a
/// `KHR_materials_variants` mapping) references a texture through
/// a UV set the primitive does not carry. glTF 2.0 requires the
/// corresponding `TEXCOORD_<set>` attribute to be present for the
/// material to be applicable; the checked value is
/// [`TextureRef::effective_uv_set`](crate::TextureRef::effective_uv_set),
/// so a `KHR_texture_transform` `texCoord` override is honoured.
UvSetOutOfRange {
location: String,
uv_set: u32,
available: usize,
},
/// A [`TextureTransform`](crate::TextureTransform) on one of a
/// material's texture references carries a non-finite offset,
/// rotation, or scale component — every UV coordinate mapped
/// through it would be poisoned.
TextureTransformNotFinite { location: String },
}
impl std::fmt::Display for ValidationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::DanglingId {
location,
id,
arena,
} => write!(f, "{location}: id {id} is out of bounds for {arena}"),
Self::AttributeLengthMismatch {
location,
expected,
actual,
} => write!(
f,
"{location}: length {actual} disagrees with positions length {expected}"
),
Self::IndexOutOfRange {
location,
vertex_count,
} => write!(
f,
"{location}: index buffer references vertex >= {vertex_count}"
),
Self::MorphWeightCountMismatch {
location,
mesh_weights,
primitive_targets,
} => write!(
f,
"{location}: mesh has {mesh_weights} weights but primitive carries {primitive_targets} morph targets"
),
Self::MorphTargetNameCountMismatch {
location,
target_names,
primitive_targets,
} => write!(
f,
"{location}: mesh names {target_names} morph targets but primitive carries {primitive_targets}"
),
Self::InbetweenWeightInvalid { location, weight } => write!(
f,
"{location}: in-between weight {weight} is not a legal station (finite, not 0 or 1)"
),
Self::InbetweenDuplicateWeight { location, weight } => write!(
f,
"{location}: duplicate in-between weight station {weight}"
),
Self::NodeMorphWeightCountMismatch {
location,
node_weights,
primitive_targets,
} => write!(
f,
"{location}: node overrides {node_weights} weights but primitive carries {primitive_targets} morph targets"
),
Self::NodeMorphWeightsWithoutMesh { location } => write!(
f,
"{location}: node carries morph-weight overrides but no mesh"
),
Self::SkeletonBindMatrixCountMismatch {
location,
joints,
inverse_bind_matrices,
} => write!(
f,
"{location}: skeleton has {joints} joints but {inverse_bind_matrices} inverse-bind matrices"
),
Self::SkeletonBindMatrixNotAffine { location, last_row } => write!(
f,
"{location}: inverse-bind matrix last row {last_row:?} is not [0, 0, 0, 1]"
),
Self::AnimationSamplerEmpty { location } => {
write!(f, "{location}: sampler has no keyframes")
}
Self::AnimationKeyframesNotStrictlyIncreasing {
location,
at,
previous,
} => write!(
f,
"{location}: keyframe time {at} is not greater than previous {previous}"
),
Self::AnimationValueVariantMismatch {
location,
property,
expected_variant,
actual_variant,
} => write!(
f,
"{location}: property {property} expects {expected_variant} values but sampler carries {actual_variant}"
),
Self::AnimationSamplerLengthMismatch {
location,
keyframes,
values,
interpolation,
} => write!(
f,
"{location}: interpolation {interpolation} with {keyframes} keyframes expects matching values, got {values}"
),
Self::AnimationMorphStrideMismatch {
location,
stride,
targets,
} => write!(
f,
"{location}: sampler carries {stride} weights per keyframe but the target mesh has {targets} morph targets"
),
Self::JointIndexOutOfRange {
location,
joint,
joint_count,
} => write!(
f,
"{location}: joint index {joint} is out of range for a {joint_count}-joint skeleton"
),
Self::JointWeightInvalid { location, value } => {
write!(f, "{location}: joint weight {value} is negative or non-finite")
}
Self::DuplicateVariantMapping { location, variant } => {
write!(
f,
"{location}: material variant {variant} is claimed by more than one mapping"
)
}
Self::UvSetOutOfRange {
location,
uv_set,
available,
} => write!(
f,
"{location}: texture samples UV set {uv_set} but the primitive carries {available} UV channel(s)"
),
Self::TextureTransformNotFinite { location } => {
write!(f, "{location}: texture transform has non-finite components")
}
}
}
}
impl std::error::Error for ValidationError {}
impl Default for Scene3D {
fn default() -> Self {
Self::new()
}
}