alice-physics 1.2.0

Deterministic 128-bit Fixed-Point Physics Engine
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
# ALICE-Physics

**Deterministic 128-bit Fixed-Point Physics Engine** - **v1.0.0 stable**

English | [日本語](README_JP.md)

[![crates.io](https://img.shields.io/crates/v/alice-physics.svg)](https://crates.io/crates/alice-physics)
[![docs.rs](https://img.shields.io/docsrs/alice-physics)](https://docs.rs/alice-physics)
[![License: AGPL-3.0-or-later](https://img.shields.io/crates/l/alice-physics.svg)](#license)
[![CI](https://github.com/ext-sakamoro/ALICE-Physics/actions/workflows/ci.yml/badge.svg)](https://github.com/ext-sakamoro/ALICE-Physics/actions/workflows/ci.yml)

> Part of **[ALICE-Eco-System](https://github.com/ext-sakamoro/ALICE-Eco-System)** — 260+ crate Edge-to-Cloud data pipeline (SDF / Physics / LLM / Motion / Font / TTS)

A high-precision physics engine designed for deterministic simulation across different platforms and hardware. The rigid-body core uses 128-bit fixed-point arithmetic (`Fix128`); the surrounding engineering / field modules use IEEE `f32` / `f64` with every transcendental routed through the crate's own `det_math`. Either way the result is bit-exact regardless of CPU, compiler, or operating system — see [Determinism scope](#determinism-scope).
<!-- claim-test: determinism_freefall -->

**Published on crates.io** (1.0.0 semver-locked stable released 2026-09-14; 1.1.0 makes every module cross-platform bit-exact via `det_math`; 1.2.0 fixes the default-config physics found by the 2026-09-15 external review and adds analytic-solution oracles — see `CHANGELOG.md`).
<!-- claim-test: golden_sim_field --> Install with `cargo add alice-physics`. All 9 v1.0 roadmap items complete — see [`CHANGELOG.md`](CHANGELOG.md) for the full release scope, [`docs/MIGRATION_0.x_TO_1.0.md`](docs/MIGRATION_0.x_TO_1.0.md) for 0.x → 1.0 migration, and [`docs/ECOSYSTEM_CONTRACTS.md`](docs/ECOSYSTEM_CONTRACTS.md) for frozen partner API contracts.

### Determinism scope

Every module in the crate is **bit-exact across platforms**, for two different reasons:
<!-- claim-test: golden_rolling_contact -->

| Tier | Modules | Why the bits agree everywhere |
|------|---------|-------------------------------|
| **Fix128 core** | rigid-body solver, joints, distance / contact constraints, BVH broad-phase, GJK / EPA, CCD, sleeping, scene I/O, netcode snapshot / rollback, neural controller, and every module whose public API is expressed in `Fix128` / `Vec3Fix` / `QuatFix` | Pure `i64` / `u64` integer arithmetic. Pinned by `tests/determinism_golden.rs` |
| **`f32` / `f64` field modules** (27: `acoustic_wave`, `aeroelasticity`, `anomaly`, `convex_decompose`, `erosion`, `fracture`, `gpu_sdf`, `phase_change`, `piezoelectric`, `pressure`, `privacy`, `rolling_contact`, `sdf_adaptive`, `sdf_ccd`, `sdf_character`, `sdf_collider`, `sdf_destruction`, `sdf_fem_mesh`, `sdf_manifold`, `sdf_sph`, `sdf_wind_field`, `sim_field`, `sim_modifier`, `sketch`, `thermal`, `thin_wall`, `transient_thermal`; list generated by `scripts/f32_modules.py --check`, which CI-gates this row — 8 more modules carry floats only across an I/O boundary: `ffi`, `pipeline`, `analytics_bridge`, `db_bridge`, `replay`, `fluid_netcode`, `character_state`, `solver_tgs`) | IEEE 754 `+ - * / sqrt` and fused multiply-add are specified to the bit on every target Rust supports (SSE2+, aarch64, wasm32). Every transcendental (`sin`, `exp`, `ln`, `powf`, `cbrt`, `hypot`, …) goes through [`det_math`](src/det_math.rs) — integer range reduction + fixed-order polynomials — never the platform `libm`. `clippy.toml` `disallowed-methods` makes a stray `libm` call a CI error. Pinned by `tests/determinism_golden_f32.rs` (13 scenarios, 29 modules) |

Both golden suites run on macOS ARM / x86, Linux ARM / x86, Windows and `wasm32-wasip1` in CI.

**Boundary — code you pass in.** `ClosureSdf` takes a user closure `Fn(f32, f32, f32) -> f32`. The solver stays deterministic, but the closure is your code: call `alice_physics::det_math::{sin, exp, …}` instead of `f32::sin` etc. inside it, or hand in an SDF whose evaluator has the same discipline. (ALICE-SDF's CPU evaluator is being aligned with `det_math`; until then treat it as same-binary deterministic.)

**Out of scope.** Targets that do not honour IEEE 754 for the basic operations: 32-bit x86 built for x87 (`i586`, no SSE2) and any build with fast-math style flags.

### Correctness scope — what "deterministic" does and does not tell you

Bit-exactness says every peer computes the same numbers; it says nothing
about whether those numbers are right. The 2026-09-15 external review found
four physics bugs in the default configuration with 1456 tests and 44 golden
hashes green (see `CHANGELOG.md` 1.2.0), so the crate now separates the two
properties explicitly. **Validation** below means "compared against a
closed-form solution or an independent reference in `tests/`"; the golden
hashes only detect *change*.

| Layer | Modules | Validation |
|-------|---------|------------|
| **Core** — what the determinism guarantee is for | `math` (`Fix128`, `Vec3Fix`, `QuatFix`, CORDIC), `solver` (XPBD rigid bodies, distance / contact constraints, sleeping), `joint`, `bvh`, `collider` (GJK / EPA), `ccd`, `contact_cache`, `sdf_collider`, `netcode` / snapshot | `tests/analytic_physics.rs` — free fall, projectile, terminal velocity, `mg/k` extension, spring and pendulum periods, collision momentum + energy bound, kinematic targets, torque-free rotation, resting contact; `sqrt` / transcendental oracles in `math::tests`; `det_math` sweeps vs correctly-rounded references |
| **Engineering / field modules** — textbook formulas made deterministic | `transient_thermal`, `fatigue` | `tests/engineering_oracles.rs` — cosine eigenmode decay (Carslaw & Jaeger) for explicit and Crank–Nicolson steps, Basquin / Miner closed forms |
| | *solid / structural*: `beam_stress`, `buckling`, `thin_wall`, `fillet_stress`, `modal`, `vibration_wall`, `damping_rayleigh`, `hyperelastic`, `plastic`, `creep_longterm`, `structural_solver`, `laminate`, `laminate_failure` (Tsai-Wu / Hashin / Puck), `anisotropic`, `bimaterial`, `prestressed`, `bridging`, `thermal_stress`, `mass_properties`, `print_orientation`, `filament_db` | `tests/engineering_oracles_solid.rs` (34) — Roark beam deflection / stress and section properties, Euler–Johnson buckling (Shigley), Rayleigh damping (Chopra), CLT laminate ABD and ply transformation (Jones), Tsai-Wu / Hashin envelopes at the uniaxial strengths, Shigley bolt joint and Irvine cable, Kirsch / Inglis exact concentration and Peterson fit invariants, Norton creep, Findley / WLF, hyperelastic uniaxial stress as derivative of the strain energy, first modes (Blevins beam, Leissa plate, Rao SDOF), closed-form inertia tensors and Steiner parallel axis, rule of mixtures / thermal mismatch, thermal-stress magnitude and sign |
| | *fluid / thermal / field*: `cfd_solver`, `eulerian_grid`, `sdf_sph`, `multiphase`, `interface_capture`, `surface_tension_csf`, `compressible`, `non_newtonian`, `turbulence`, `buoyancy_zone`, `wind_zone`, `sdf_wind_field`, `cloth_fluid`, `fsi_advanced`, `smoke_fire`, `wave_ship`, `aeroelasticity` (Facchinetti 2004), `acoustic_wave`, `electromagnetic`, `piezoelectric`, `thermal`, `phase_change`, `pressure`, `erosion` | `tests/engineering_oracles_fluid.rs` (39) — viscous shear-mode decay, pressure projection removes divergence and is identity on solenoidal fields, SPH kernel normalisation and lattice rest density, Young–Laplace through the CSF band, ISA density / speed of sound, normal-shock and isentropic tables (Anderson), Bingham / Herschel–Bulkley / power-law / Carreau flow curves (integer and fractional index), Smagorinsky simple shear, Archimedes, quadratic drag, d'Alembert at Courant 1, Coulomb / Lorentz / dipole, d33 piezo relations, Arrhenius / Boussinesq, deep-water dispersion / Froude–Krylov / JONSWAP, van der Pol amplitude and Strouhal frequency, Newton cooling and conduction eigenmode, enthalpy-method plateau and conservation, level-set curvature and fast-sweeping distance, erosion rate-law invariants |
| | `cloth`, `rope`, `deformable`, `fluid` (PBF), `character`, `vehicle` (`WheelConfig` / `EngineConfig`), `sleeping`, `netcode`, `audio_physics`, `support` (print supports), `neural` | `tests/default_configs.rs` — every `Config::default()` on its most ordinary scenario: hanging curtain / rope geometry, free-fall closed form for a deformable cube and a fluid block's centre of mass, wheel compression `mg/k`, engine first-frame `Δv = T·gear/(r·m)·dt`, sleep at exactly `frames_to_sleep`, lockstep checksums + rollback bit-exact, support volumes to 1e-6 |
| | *mechanisms / fields / netcode*: `rolling_contact`, `fracture`, `kinematic_loop`, `sdf_force`, `anisotropic_friction`, `physics2d`, `sdf_destruction`, `soft_body_cut`, `layer_adhesion`, `fluid_netcode` | `tests/engineering_oracles_misc.rs` (27) — Hertz sphere contact and Basquin life (Johnson §4.2), crack growth `L = min(vt, L_max)` and Quilez capsule subtraction, PBD loop closure (mass-weighted projection, geometric residual contraction, four-bar link lengths), `F = −kφ∇φ` and the contain / repel / vortex closed forms, orthotropic friction ellipse (Zmitrowicz) with the Coulomb isotropic limit, 2-D free fall / `θ = ωt` / momentum / Newton restitution `v_sep = e·v_app` / Coulomb sliding `μ g` / inertia tensors (Meriam & Kraige), hemisphere crater and capped-cylinder bore volumes, plane-cut partition invariants, bit-exact snapshot round trip and lossless `τ = 0` delta |
| | `warp_risk` (empirical fit: two ALICE-Bamboo data points), `sim_field`, `layer_adhesion` (empirical FDM factors, invariants only) and the remaining utility / bridge modules | **none yet** — the formulas are implemented as published and the code is bit-exact, but no test compares them with a reference solver, a textbook worked example or experimental data. Treat their numbers as *implementations of the cited equation*, not as validated predictions, until the module gains an oracle (the 1.2.0 batches above show the pattern: closed form at `Config::default()`, precision parameter varied) |

**Where the crate fits.** The core is built for use cases where bit-exact
replay is the requirement, not a nicety: rollback netcode (fighting / RTS /
`.io` games, tens to hundreds of bodies), server-side replay verification and
anti-cheat, and reproducible research or audit batches. Measured on the
1000-overlapping-sphere scene (`cargo bench --bench physics_bench`,
`thousand_overlapping_spheres_1_step`) it runs at a few ms per frame with the
default configuration. It is **not** a drop-in replacement for a float engine
in a general game: destruction, crowds of thousands, VFX-grade contact counts
at 60 fps are outside its design point, and a float engine pays none of the
fixed-point cost for a determinism it does not need.
**v0.10-0.14 highlights** — a five-wave completeness push adds
**54 modules + 3 integrated solver loops + a Session 4 19-module tier-classified push**
covering the full spectrum from 3D-printing safety (warp / thin-wall /
stress / bridging) through composite / plastic / fatigue mechanics, up
to turbulence, VOF / level-set multi-phase flow, a runnable CFD
time-step loop, humanoid ragdoll, SDF-boundary SPH, transient thermal,
composite failure, VIV / piezoelectric / acoustic / electromagnetic,
IK / anisotropic friction / netcode prediction / character FSM /
kinematic loop / buoyancy zone / wind zone / SDF FEM / SDF wind.
All bit-exact across platforms — Fix128 modules by integer arithmetic, `f32` modules via `det_math` ([Determinism scope](#determinism-scope)); see
[Session 1-3 Additions](#session-1-3-additions-v010-012) and
[v0.13.0 Session 4 Additions](#v0130-session-4-additions-19-modules-across-3-tiers).

**v1.0.0 release highlights** (2026-09-14)

- **API surface freeze** — 32 module × 512 pub items audit (Iterations 1-6 + Final), 133+ items `pub → pub(crate)` downgraded, snapshot 20,201 → 19,406 (−795 items). `solver_tgs*` extension mechanism moved to `pub(crate)` (Option C). 7 prelude-exported structs marked `#[non_exhaustive]` for forward-compat.
- **6-platform bit-exact determinism** — golden hash (9 tests) + semantic invariant (22 tests) suite verified on macOS ARM/x86 + Linux ARM/x86 + Windows + WASM (`wasm32-wasip1` via `wasmtime`).
- **Hard-gated semver enforcement** — `cargo semver-checks` blocks breaking-API PRs.
- **Ecosystem contracts frozen** — [`docs/ECOSYSTEM_CONTRACTS.md`] catalogues API for ALICE-TRT (`GpuSolverBridge`), ALICE-SDF (`SdfField`), ALICE-Bamboo, ALICE-Anima, ALICE-Kinematics.
- **8/8 fuzz targets** — `fuzz_step` / `fuzz_collision` / `fuzz_deterministic_roundtrip` / `fuzz_joint` / `fuzz_cfd` / `fuzz_ccd` / `fuzz_trimesh` / `fuzz_structural`.
- **1695 lib tests + 44 determinism tests** — all passing on all 6 platforms.

**v0.12.0 addition** — `GpuSolverBridge` gains a joint-solve pipeline
(`send_joints` / `send_body_rotations` / `dispatch_joint_solve_iteration`)
and `PhysicsWorld` auto-routes both contact AND joint solve through the
installed bridge, coordinated with ALICE-TRT v3.1.0's
`FIX128_BALL_SOCKET_JOINT_SOLVE_WGSL` kernel (byte-exact vs CPU
`solve_ball_joint`). See [CHANGELOG.md](CHANGELOG.md).

## v0.13.0 Session 4 Additions (19 modules across 3 tiers)

Extends the v0.10-0.12 engineering-solver foundation with a
19-module push covering game-physics polish (ragdoll / character
state / netcode prediction / IK), soft-body simulation (SDF SPH /
SDF character / SDF FEM / SDF wind), engineering research
(composite failure / transient thermal / rolling contact fatigue /
VIV / piezoelectric / acoustic / electromagnetic), and
multi-material coupling (buoyancy zone / anisotropic friction /
kinematic loop). All bit-exact across platforms
([Determinism scope](#determinism-scope)); formula
sources cited in module docs.

### Tier ★★★ — 5 modules (real-world critical, downstream-load-bearing)

| Module | Purpose |
|--------|---------|
| `ragdoll` | Humanoid ragdoll builder with pose targets, joint limits, breakable constraints (G1) |
| `buoyancy_zone` | Bounded 3-D fluid volume with buoyancy + drag, fluid-surface CSF coupling (G2) |
| `laminate_failure` | Tsai-Wu / Tsai-Hill / Hashin / Puck composite failure indices (R1) |
| `transient_thermal` | Temperature-dependent material properties + 1-D unsteady heat solver + phase-boundary tracking (R2) |
| ALICE-SDF `morphology` | Signed offset + tolerance fit check for print clearance (S1, ships in ALICE-SDF v1.7.7) |

### Tier ★★ — 7 modules (broad utility, cross-domain glue)

| Module | Purpose |
|--------|---------|
| `wind_zone` | Bounded 3-D wind volume with drag + lift on rigid / soft bodies (G3) |
| `sdf_character` | SDF-terrain-aware character controller with slope / step / air-time state (S4) |
| `rolling_contact` | Rolling contact fatigue (Hertz + subsurface shear + Basquin S-N cycle counting) (R3) |
| `netcode_prediction` | Client-side prediction + reconciliation + input replay (G5) |
| `character_state` | Character FSM (idle / walk / run / jump / fall / crouch) with transition validation (G6) |
| `sdf_sph` | SDF-boundary SPH fluid with density / viscosity / surface tension (S3) |
| `kinematic_loop` | Kinematic body loop constraint solver for closed-chain mechanisms (R4) |

### Tier ★ — 8 modules (specialized engineering / research)

| Module | Purpose |
|--------|---------|
| `ik_physics_bridge` | Physics-aware IK solver with joint-limit respecting FABRIK / CCD backend (G4) |
| `anisotropic_friction` | Direction-dependent friction coefficient (rolling vs sliding, wood grain, fabric) (G7) |
| `aeroelasticity` | Vortex-induced vibration (VIV) + flutter + galloping for slender structures (R5) |
| `piezoelectric` | Piezoelectric coupling for sensors / actuators (voltage ↔ strain) (R6) |
| `acoustic_wave` | 1-D / 2-D / 3-D acoustic wave propagation with material impedance boundary (R7) |
| `electromagnetic` | Electromagnetic force field (Lorentz / induction / eddy current) for conductor bodies (R8) |
| `sdf_fem_mesh` | SDF-to-tetrahedral FEM mesh generator for large-deformation simulation (S2) |
| `sdf_wind_field` | SDF-boundary-aware wind field with turbulence intensity + gust modeling (S5) |

## Features

| Feature | Description |
|---------|-------------|
| **128-bit Fixed-Point** | I64F64 format (64-bit integer + 64-bit fraction) for extreme precision |
| **CORDIC Trigonometry** | Deterministic sin/cos/atan without FPU instructions |
| **XPBD Solver** | Extended Position Based Dynamics for stable constraint solving |
| **GJK/EPA Collision** | Robust collision detection for convex shapes |
| **Stackless BVH** | Morton code-based spatial acceleration with escape pointers |
| **Constraint Batching** | Graph-colored parallel constraint solving |
| **Rollback Support** | Complete state serialization for netcode |
| **Neural Controller** | Deterministic AI via ALICE-ML ternary weights + Fix128 inference |
| **12 Joint Types** | Ball, Hinge, Fixed, Slider, Spring, D6, Cone-Twist, Pulley, Gear, Weld (breakable), Rack-and-Pinion, Mouse |
| **Raycasting** | Ray and shape casting against spheres, AABBs, capsules, planes |
| **Shape Cast / Overlap** | Sphere cast, capsule cast, overlap sphere, overlap AABB queries |
| **CCD** | Continuous collision detection (TOI, conservative advancement) |
| **Sleep/Islands** | Automatic sleep with Union-Find island management |
| **Triangle Mesh** | BVH-accelerated triangle mesh collision (Moller-Trumbore) |
| **Height Field** | Grid terrain with bilinear interpolation |
| **Articulated Bodies** | Multi-joint chains, ragdolls, robotic arms with FK propagation |
| **Force Fields** | Wind, gravity wells, drag, buoyancy, vortex, explosion, magnetic dipole |
| **PD Controllers** | 1D/3D proportional-derivative joint motors |
| **Collision Filtering** | Layer/mask bitmask system with collision groups |
| **Trigger/Sensor** | Sensor bodies that detect overlap without physics response |
| **Character Controller** | Kinematic capsule-based move-and-slide with stair stepping and SDF terrain |
| **Rope** | XPBD distance chain rope and cable simulation |
| **Cloth** | XPBD triangle mesh cloth with self-collision (spatial hash grid) |
| **Fluid** | Position-Based Fluids (PBF) with spatial hash grid |
| **Deformable** | FEM-XPBD deformable body (tetrahedral mesh) |
| **Vehicle** | Wheel, suspension, engine, steering, gear shifting |
| **Animation Blend** | Ragdoll-to-animation blending with SLERP |
| **Audio Physics** | Physics-based audio parameter generation (impact, friction, rolling) |
| **SDF Manifold** | Multi-point contact manifold from SDF surfaces |
| **SDF CCD** | Sphere tracing continuous collision detection for SDF |
| **SDF Force Fields** | SDF-driven force fields (attract, repel, contain, flow) |
| **SDF Destruction** | Real-time CSG boolean destruction |
| **SDF Adaptive** | Adaptive SDF evaluation with distance-based LOD |
| **Convex Decompose** | Convex decomposition from SDF voxel grid |
| **GPU SDF** | GPU compute shader interface for batch SDF evaluation |
| **Fluid Netcode** | Deterministic fluid netcode with delta compression |
| **Simulation Fields** | 3D scalar/vector fields with trilinear interpolation and diffusion |
| **Thermal** | Heat diffusion, melt, thermal expansion, freeze |
| **Pressure** | Contact force accumulation, crush, bulge, dent deformation |
| **Erosion** | Wind, water, chemical corrosion, ablation |
| **Fracture** | Stress-driven crack propagation with CSG subtraction |
| **Phase Change** | Solid/liquid/gas transitions driven by temperature |
| **Deterministic RNG** | PCG-XSH-RR pseudo-random number generator |
| **Contact Events** | Begin/Persist/End contact and trigger event tracking |
| **Box/OBB Collider** | Oriented Bounding Box with GJK support and fast AABB |
| **Compound Shape** | Multi-shape compound collider with local transforms |
| **Contact Cache** | Persistent manifold cache with HashMap O(1) lookup and warm starting |
| **Dynamic AABB Tree** | Incremental BVH with O(log n) insert/remove/update, AVL balancing |
| **D6 Joint** | 6-DOF configurable joint with per-axis lock/free/limit |
| **Cone-Twist Joint** | Ball joint with cone swing limit and twist limit |
| **Material Table** | Per-pair friction/restitution with combine rules (Avg, Min, Max, Mul) |
| **Scaled Shape** | Uniform scale wrapper for any Support-implementing shape |
| **Speculative CCD** | Speculative contacts for fast-moving bodies without time rewinding |
| **Featherstone** | O(n) forward dynamics for articulated bodies |
| **Debug Render** | Wireframe visualization API (bodies, contacts, joints, BVH, forces) |
| **Profiling** | Per-stage timer and per-frame statistics API |
| **Substep Interpolation** | WorldSnapshot with NLERP quaternion blending for smooth rendering |
| **Probabilistic Sketches** | HyperLogLog, DDSketch, Count-Min Sketch, Heavy Hitters |
| **Streaming Anomaly Detection** | MAD, EWMA, Z-score composite detector |
| **Local Differential Privacy** | Laplace noise, RAPPOR, randomized response |
| **Metric Pipeline** | Lock-free ring buffer metric aggregation with registry |
| **Cone Collider** | Cone shape with GJK support (apex +Y, base -Y) |
| **Ellipsoid Collider** | Three independent semi-axes with anisotropic support |
| **Torus Collider** | Major/minor radii with Minkowski sum decomposition |
| **Plane Collider** | Infinite plane (Hessian normal form) with sphere/AABB intersection |
| **Wedge Collider** | Triangular prism with 6-vertex GJK support |
| **Convex Hull Builder** | Incremental convex hull from arbitrary point sets |
| **2D Physics** | Complete 2D subsystem: SAT collision, XPBD solver, Circle/Polygon/Capsule/Edge shapes |
| **Mass Properties** | Inertia tensor computation for sphere, box, cylinder, capsule, convex hull |
| **Collision Mesh Gen** | Marching cubes SDF-to-mesh with edge-collapse simplification |
| **Scene I/O** | Binary (.aphys) and JSON scene serialization with bit-exact Fix128 roundtrip |
| **Cloth-Fluid Coupling** | Bidirectional cloth-fluid interaction (drag, buoyancy, boundary repulsion) |
| **Rope Attachment** | Rigid body rope attachment with compliance and break force |
| **Soft Body Cutting** | Plane-based cutting of deformable bodies and cloth |
| **Stress Heatmap** | Stress/temperature/pressure 2D slice visualization with viridis colormap |
| **Flow Visualization** | Fluid velocity field arrows and streamline generation |
| **Contact Visualization** | Contact force arrows and friction cone rendering |
| **Multi-World** | Multiple independent physics worlds with body transfer |
| **Particle System** | General-purpose emitters, lifetime, force field integration |
| **no_std Compatible** | Works on embedded systems and WebAssembly |

## Session 1-3 Additions (v0.10-0.12)

Three completeness sessions added **35 modules + 3 integrated solver
loops + 3 runnable examples** to close the gap between "physics primitives"
and "usable engineering solvers." Every addition is bit-exact across
platforms (see [Determinism scope](#determinism-scope))
and cites the source formula (Roark / Timoshenko / Simo &
Hughes / Jones / Tsai-Wu / Hill / Norton / Findley / WLF / Brackbill /
Smagorinsky / Launder-Spalding / Wilcox / Hasselmann / Turns / Anderson /
etc.).

### Session 1 — 3D Print Safety + Structural Tier 1 (v0.10)

| Module | Purpose | Formula source |
|--------|---------|----------------|
| `filament_db` | 10-material property DB (Young's / yield / tensile / density / Tg / anisotropy) | MatWeb / ASM Metals Handbook |
| `thin_wall` | SDF sphere-marching wall thickness detection | Bambu/Prusa min-wall guidance |
| `beam_stress` | Cross-section + load case + Euler buckling + FoS | Roark's Formulas for Stress and Strain |
| `support_volume` | Overhang → filament mm³ + print time estimate | Bambu Studio support manual |
| `anisotropic` | 9-constant orthotropic + Hill + Tsai-Wu failure | Jones, *Mechanics of Composite Materials* |
| `plastic` | von Mises + isotropic/kinematic/combined hardening + Norton creep | Simo & Hughes; Norton (1929) |
| `buckling` | Johnson / Euler / plate / snap-through | Timoshenko & Gere; Bažant & Cedolin |
| `hyperelastic` | Neo-Hookean / Mooney-Rivlin / Yeoh | Ogden (1984); Yeoh (1990) |
| `bimaterial` | Timoshenko bimetal residual + Voigt/Reuss bounds | Timoshenko (1925) |
| `layer_adhesion` | XY vs Z 6-component effective strength envelope | Empirical FDM data |
| `print_orientation` | Load-direction optimization + Euler grid search | Anisotropy transformation |
| `bridging` | Material-specific max bridge distance check | Bambu/Prusa knowledge base |
| `warp_risk` | Cooling shrinkage × footprint → Low/Medium/High/Critical | ALICE-Bamboo docs incident-tuned |

### Session 2 — Structural Tier 2 + Fluid Tier 1-2 (v0.11-0.12)

| Module | Purpose | Formula source |
|--------|---------|----------------|
| `fatigue` | Basquin S-N + Miner cumulative damage | Basquin (1910); Miner (1945) |
| `modal` | 1-DOF / beam / Warburton plate / torsional natural frequency | Blevins; Warburton (1954) |
| `damping_rayleigh` | C = αM + βK + fit_two_modes | Clough & Penzien |
| `laminate` | Classical Laminate Theory ABD matrix | Jones eq. 2.84 |
| `prestressed` | Motosh bolt preload + parabolic cable pretension | Shigley; VDI 2230 |
| `fillet_stress` | Kirsch / Inglis / Peterson K_t | Peterson; Pilkey; Norton |
| `vibration_wall` | Thin-wall resonance vs 6 printer excitation presets | Blevins; Bambu X1C spec |
| `thermal_stress` | Constrained σ = c·E·α·ΔT + Tg proximity warning | Timoshenko & Goodier |
| `creep_longterm` | Findley 3-parameter + WLF time-temperature superposition | Findley (1989); Williams et al. (1955) |
| `non_newtonian` | Power-law / Carreau / Bingham / Herschel-Bulkley | Bird, Stewart, Lightfoot |
| `multiphase` | VOF advection + level set reinit + curvature | Hirt & Nichols (1981); Osher & Sethian (1988) |
| `compressible` | Ideal gas + Rankine-Hugoniot shock + Riemann invariants | Anderson, *Modern Compressible Flow* |
| `eulerian_grid` | Staggered MAC + Jacobi/red-black GS pressure projection | Harlow & Welch (1965) |
| `turbulence` | Smagorinsky LES + k-ε + k-ω + wall function | Pope; Wilcox; Launder & Spalding |
| `surface_tension_csf` | Continuum Surface Force | Brackbill, Kothe & Zemach (1992) |
| `fsi_advanced` | Solid ↔ fluid drag / buoyancy / reaction | Peskin immersed boundary |
| `smoke_fire` | Arrhenius reaction + soot + Boussinesq buoyancy | Turns; Kuo |
| `wave_ship` | JONSWAP spectrum + Froude-Krylov + 2-DOF | Hasselmann (1973); Faltinsen |
| `interface_capture` | Fast Sweeping FSM + PLIC (Rider-Kothe analytical) | Zhao (2005); Youngs (1982) |

### Session 3 — Solver Loops + 12 Improvements + 3 Demos (v0.12)

**Integrated solver loops** — single `step(dt)` entry points that compose
the Session 1-2 modules into a driven simulation:

| Solver | Composes |
|--------|----------|
| `cfd_solver::CfdSolver` | MAC + turbulence + non-Newtonian + level_set + CSF + Boussinesq + gravity |
| `structural_solver::StructuralSolver` | beam + plastic + creep + fatigue + buckling with history tracking |
| `print_pipeline_solver` | 10 print-safety checks (warp + layer + orientation + thermal + beam + bridging + support + fillet + bimaterial) in one shot |

**12 improvements** — accuracy / performance / robustness:

- I1 `math_util` shared `exp_fix` / `cbrt_fix` / `pow_int` / `clamp_fix`
- I2 `eulerian_grid` trilinear P2G / G2P (was nearest-cell)
- I3 `multiphase` semi-Lagrangian advection (was first-order upwind)
- I4 PLIC Rider-Kothe analytical + cbrt (bisection collapse)
- I5 FSM Godunov 3-neighbour quadratic Eikonal (was min + dx)
- I6 `safety::sdf_aabb` NaN/degenerate/min-dim guards
- I7 `safety_validate` integrates `thin_wall` + `layer_adhesion` + `thermal_stress`
- I8 turbulence log-law wall function + `ln_fix`
- I9 pressure projection red-black Gauss-Seidel (~2× convergence)
- I10 dynamic Smagorinsky Germano estimator
- I11 `laminate::compute_abd` rayon parallel (feature-gated)
- I12 `fatigue::stress_at_cycles` Newton early exit

**3 runnable examples** demonstrating the solvers end-to-end:

```bash
cargo run --example cfd_smoke_plume --release          # gravity settling in a 12³ MAC grid
cargo run --example structural_pla_shelf_creep --release  # 20 h PLA shelf under 20 N centre load
cargo run --example print_full_safety --release        # SKADIS-style plate full safety report
```

`cfd_smoke_plume` demonstrates bit-exact `v_y = -g·t` recovery, with the
pressure projection maintaining zero divergence at the grid centre throughout
the run. `print_full_safety` exercises all 10 safety checks and returns a
realistic UNSAFE verdict for a 300 × 300 × 5 mm PLA plate (Warp Critical /
Beam FoS 1.16 / Fillet K_t 3.30) — exactly matching the failure mode
documented in the ALICE-Bamboo warp incident.

### Mutation score (cargo-mutants, `quality-deep.yml`)

"Tests pass" says nothing about whether they check values. The core modules
are measured with [cargo-mutants](https://mutants.rs) (`-- --lib`, test
helpers excluded via `.cargo/mutants.toml`); a mutant is *caught* when some
test fails after the mutation. Score = caught / (caught + missed), unviable
mutants excluded. The campaign started at **32.0 %** (2026-09-15, 16-shard
weekly run) and found six real defects on the way (`remove_body` constraint
remap, `Fix128::atan` CORDIC shift, cloth bending sign, `LinearBvh::find_pairs`
n², joint angular split / unsigned twist, EPA normal sign).

| module | score | measured |
|---|---|---|
| `ccd` | **95.4 %** (208 / 218) | local run after batch 8 |
| `collider` | **93.5 %** (145 / 155) | local run after batch 8 |
| `math` | 92.2 % (295 / 320) | weekly run at `b187144`, partial shards; scoped run pending |
| `contact_cache` | 88.0 % (66 / 75) | scoped run at `3c12ee6`, before batch 7 tests |
| `solver_tgs` | 81.7 % (89 / 109) | weekly run at `b187144`, before batch 7 tests |
| `bvh` | 79.9 % (135 / 169) | weekly run at `b187144`, before batch 8 (9 tests added) |
| `solver` | 76.2 % compiled code (433 / 568) | weekly run at `b187144`, before batch 8 (24 tests added); 163 further mutants sit in `cfg(feature = "parallel" / "gpu-solver-bridge")` code and are measured on that feature axis |
| `joint` | 72.0 % (206 / 286) | weekly run at `b187144`, before batch 8 (15 tests + 8 re-derived after the angular-split fix) |

Rows marked "before batch N" are the last *measured* figure; the tests written
since target the listed misses (equivalent mutants documented in each test
module) and are re-measured by the scoped `quality-deep` dispatch. The next
measured numbers replace this table; estimates are not written here.

### Test count

Session 1 baseline (v0.9): 719 → Session 1 end (v0.10): 904 → Session 2 end
(v0.11): 1170 → **Session 3 end (v0.12): 1175 alice-physics tests + 53
alice-bamboo integration tests, all passing.**

### Sub-stepping TGS Solver — v1.0 status: `pub(crate)` internal

The trait-abstracted temporal Gauss-Seidel solver primitives (`TgsHooks`, `ImpulseCache`, `build_islands`, 6-DOF hooks, per-island scoped solve, rayon parallelisation, quaternion orientation integration) exist in-crate as `solver_tgs*` modules but are **`pub(crate)` since 1.0.0** — the extension mechanism had zero downstream adoption during the v1.0 API audit (Option C, see [`docs/PUB_AUDIT_FINAL.md`](docs/PUB_AUDIT_FINAL.md)). The primary `PhysicsWorld::step` API uses its own internal TGS solver in `crate::solver` and remains fully public. If your project needs a generic hooks-based TGS integrator, open an issue — re-exposing `pub(crate)` items via a semver-minor bump is non-breaking.

### Advanced solver primitives (Turn D / Phase E / Phase F)

Additional building blocks stacked on top of the sub-stepping TGS core:

- **Adaptive sub-stepping** — `AdaptiveSubStepConfig` + `HasVelocity` + `adaptive_substeps_for` compute a deterministic sub-step count from the fastest body's L∞ velocity (Fix128 pure, closed-form, division-free — safe under lockstep and rollback)
- **CCD-optimised adaptive sub-stepping** — `adaptive_substeps_for_ccd` tightens the per-step translation cap to `smallest_collider_radius × safety_factor`, guaranteeing fast bodies never tunnel through thin walls
- **Adaptive sub-TOI** — `adaptive_toi_substeps` bridges Adaptive sub-stepping with the existing `speculative_contact` TOI so a pair on a collision course over `dt` immediately requests `max_substeps` (Phase F 11.1, body complete)
- **`ImpulseCache` observability** — `hits/misses/stats/hit_rate/reset_stats` expose warm-starting effectiveness so callers can gauge whether contact IDs stay stable across frames (high hit rate) or the scene is churning (low hit rate)
- **Per-island scoped oriented solve** — `solver_tgs_hooks_6dof_oriented_scoped` extracts an isolated body / contact subset per island for the full 6-DOF oriented hook, prevents gravity double-counting, and preserves bit-perfect parallel-vs-serial equality
- **`LinearBvh::refit_leaves` (bottom-up)** — retains the flat tree structure while requantising leaf AABBs and propagating unions to internal nodes in the i32 domain (no CORDIC / rounding dependency), enabling `O(N)` refit as an alternative to full rebuild
- **`BroadphaseHybrid`** — layers a `SpatialGrid` hash grid over a static `LinearBvh` (Turn D 5' plan), reducing per-frame broad-phase work from `O(N_total log N_total)` to `O(N_dynamic + log N_static)`. Recommended per-frame flow: `clear_dynamic` → `insert_dynamic` × N → `build_dynamic` → `query_pairs`
- **`FeatherstoneSolver::solve_with_mass_splitting`** — extends the O(n) forward-dynamics solver with a mass-ratio split threshold (heavy / light > threshold → `dt / 2` × 2 recursion), relieving stiffness-induced ill-conditioning for extreme mass-ratio stacks. Determinism preserved via lookup-free multiplicative comparison and `Fix128::half` (Phase F 11.2, body + 3 tests complete)
- **FFI byte-for-byte determinism** — `AliceVec3Fix128Raw` + `alice_physics_body_get_position_fix128_raw` expose Fix128 hi/lo pairs across the C ABI. `ffi_contract_gravity_fall_deterministic` asserts a bracket bound plus a full second-world replay that must produce the exact same hi/lo pair, so Unity / UE5 hosts can assert bit-pattern equality (Phase F 11.3, runtime determinism gate complete)

- **`GpuSolverBridge` trait** (`--features gpu-solver-bridge`) — opt-in extension surface for external GPU offload backends (e.g. ALICE-TRT `TrtSolverAdapter`). Ships with `DiffFixture` / `GpuDivergence` types so implementations must certify byte-for-byte equivalence with the CPU-side solver before the runtime accepts them. Default builds keep the CPU-native TGS pipeline as the only code path

#### Companion crate — ALICE-TRT (GPU solver offload)

Pair with [ALICE-TRT v1.0.0+](https://github.com/ext-sakamoro/ALICE-TRT) `--features physics-solver` for the reference `GpuSolverBridge` implementation (`TrtSolverAdapter`). Enabling `physics-solver` on ALICE-TRT automatically activates `gpu-solver-bridge` on this crate, so a single feature line covers both sides. **ALICE-TRT v1.x is semver-stable** — public adapter surface (`send_island` / `dispatch_iterations` / `set_gravity` / `set_floor` / `push_distance_constraint` / `recv_island` / `assert_bit_exact_vs_cpu`) is byte-stable across the v1.x line.

```toml
[dependencies]
alice-physics = { version = "1", features = ["gpu-solver-bridge"] }
alice-trt     = { version = "3.1", features = ["physics-solver"] }
```

```rust
use alice_physics::gpu_bridge::{DiffFixture, GpuSolverBridge};
use alice_physics::math::Fix128;
use alice_trt::{GpuDevice, TrtSolverAdapter};

// Live PGS dispatch (integrate + gravity + floor + multi-distance constraints)
let device = GpuDevice::new()?;
let mut adapter = TrtSolverAdapter::new(&device);

adapter.send_island(&positions, &velocities);
adapter.set_gravity(Some([Fix128::ZERO, Fix128::from_ratio(-98, 10), Fix128::ZERO]));
adapter.set_floor(Some(Fix128::ZERO));
adapter.push_distance_constraint(0, 1, Fix128::from_int(2));   // Gauss-Seidel ordered
adapter.push_distance_constraint(1, 2, Fix128::from_int(2));

adapter.dispatch_iterations(10, Fix128::from_ratio(1, 60));    // real GPU dispatch, not a stub
adapter.recv_island(&mut positions, &mut velocities);

// Production gate: certify byte-for-byte equivalence with the CPU solver.
adapter.assert_bit_exact_vs_cpu(&DiffFixture {
    description: "3body_triangle_10iter",
    tolerance: Fix128::ZERO,
})?;
```

Companion releases: [ALICE-TRT v3.1.0](https://github.com/ext-sakamoro/ALICE-TRT/releases/tag/v3.1.0) (coordinated with alice-physics v0.12.0 for joint-solve GPU offload). Every ALICE-TRT release is validated on macOS (Metal) / Ubuntu (Vulkan lavapipe) / Windows (DX12 WARP) with 37 Fix128 unit tests + 170 physics-solver tests, all byte-exact against the CPU golden.

Determinism guardrails for every primitive above are documented in the [`deterministic-physics-lockstep-discipline`](https://github.com/ext-sakamoro/claude-config/blob/main/claude-skills/deterministic-physics-lockstep-discipline/SKILL.md) skill (private reference).

## Optimizations ("黒焦げ" Edition) — 100/100

ALICE-Physics achieves a **perfect 100/100 optimization score** across 6 layers:

### Optimization Scorecard

| Layer | Score | Key Techniques |
|-------|-------|----------------|
| **L1: Memory Layout** | 15/15 | `#[repr(C, align(64))]` on RigidBody/Cloth/Fluid, hot/cold field reorder |
| **L2: Execution** | 20/20 | `#[inline(always)]` on GJK/BVH/constraints, branchless select, precomputed grid_half |
| **L3: Compute** | 20/20 | Warm-start `cached_lambda`, reciprocal precomputation (`inv_rest_length`, `inv_rest_density`) |
| **L4: GPU & Throughput** | 15/15 | `SIMD_WIDTH` const + `simd_width()`, `GpuSdfInstancedBatch`/`GpuSdfMultiDispatch`, `batch_size()` |
| **L5: Build Profile** | 10/10 | `opt-level=3`, `lto="fat"`, `codegen-units=1`, `panic="abort"`, `strip=true` |
| **L6: Code Quality** | 20/20 | 1695 lib tests + 13 analytic-solution oracles + 105 engineering oracles (5 thermal/fatigue + 34 solid + 39 fluid + 27 misc) + 13 default-config oracles + 53 alice-bamboo integration tests + 8 fuzz targets + 44 determinism tests (6-platform bit-exact, Fix128 + f32 golden), clippy `-D warnings` (default + full native feature set, all targets), MSRV 1.85 CI job (default / no_std / native), `#![deny(missing_docs)]`, cargo-semver-checks hard-gated |
| **Total** | **100/100** | |

### L1: Memory Layout (15/15)

All hot data structures use 64-byte cache-line alignment with hot/cold field separation:

```rust
#[repr(C, align(64))]
pub struct RigidBody {
    // HOT fields (accessed every substep) — first cache line
    pub position: Vec3Fix,
    pub velocity: Vec3Fix,
    pub inv_mass: Fix128,
    pub inv_inertia: Vec3Fix,
    pub prev_position: Vec3Fix,
    // COLD fields (accessed occasionally)
    pub rotation: QuatFix,
    pub angular_velocity: Vec3Fix,
    pub restitution: Fix128,
    pub friction: Fix128,
    // ...
}
```

- **RigidBody** (`solver.rs`): `#[repr(C, align(64))]` + hot/cold field reorder
- **Cloth** (`cloth.rs`): `#[repr(C, align(64))]` + precomputed `inv_rest_length` per edge constraint
- **Fluid** (`fluid.rs`): `#[repr(C, align(64))]` + precomputed `inv_rest_density` and `grid_half`

### L2: Execution Model (20/20)

Aggressive inlining and branchless execution across all hot paths:

- **GJK/BVH**: All support functions and traversal marked `#[inline(always)]` (35 annotations total)
- **Constraint solving**: `#[inline(always)]` on distance/contact constraint kernels
- **Fluid spatial grid**: `grid_half` precomputed at construction, eliminates repeated division in `hash()` hot path
- **Branchless primitives** (`math.rs`): `select_fix128()`, `select_vec3()` — CMOV-equivalent using bitwise masks, zero pipeline flushes

### L3: Compute Strategy (20/20)

Division elimination and warm-starting for faster convergence:

- **Distance constraint warm-start**: `cached_lambda` field stores the Lagrange multiplier from the previous substep, biasing the initial guess for dramatically faster convergence
- **Cloth reciprocal precomputation**: `inv_rest_length` computed once at construction, constraint solving uses multiplication instead of division
- **Fluid reciprocal precomputation**: `inv_rest_density` eliminates 2+ divisions per particle per iteration in incompressibility constraint
- **Contact manifold warm-start**: Per-contact `lambda_n`, `lambda_t1`, `lambda_t2` accumulated across frames via `apply_warm_start()`
- **Contact modifier parallel pre-pass**: `pre_process_contacts()` runs sequentially before Rayon parallel dispatch, applying pre-solve hooks and contact modifiers safely without data races

### L4: GPU & Throughput (15/15)

SIMD-width-aware batching for optimal GPU and CPU utilization:

```rust
// Compile-time CPU feature detection
pub const SIMD_WIDTH: usize = simd_width();
// AVX2=8, SSE=4, NEON=4, scalar=1

#[inline(always)]
pub fn batch_size() -> usize { crate::math::SIMD_WIDTH }
```

- **`SIMD_WIDTH` constant** (`math.rs`): Compile-time CPU feature detection (AVX2=8, SSE=4, NEON=4, scalar=1)
- **`GpuSdfInstancedBatch`** (`gpu_sdf.rs`): Groups SDF queries by ID to minimize GPU kernel launches
- **`GpuSdfMultiDispatch`** (`gpu_sdf.rs`): Manages multiple GPU batches with `total_queries()` and `total_dispatches()` statistics
- **`batch_size()`** (`gpu_sdf.rs`): Returns `SIMD_WIDTH` for register-width-aligned data streams

### L5: Build Profile (10/10)

```toml
[profile.release]
opt-level = 3          # Maximum optimization
lto = "fat"            # Link-time optimization (all crates unified)
codegen-units = 1      # Single code generation unit (maximum optimization)
panic = "abort"        # No unwinding tables
strip = true           # Strip symbols
```

### L6: Code Quality (20/20)

- **1695 lib tests + 44 determinism tests** across the alice-physics crate (Iter 2-6 audit + v1.0 stable release additions + v1.0.1 coloring / island / Fix128 tests + 1.2.0 mutation-score batches 1-8 and analytic oracles)
- **53 alice-bamboo integration tests** (end-to-end 3D-print safety scenarios)
- **9 fuzz targets** (`fuzz_step`, `fuzz_collision`, `fuzz_deterministic_roundtrip`, `fuzz_joint`, `fuzz_cfd`, `fuzz_ccd`, `fuzz_trimesh`, `fuzz_structural`, `fuzz_step_parity`)
- **Total: 2001 passing tests** in `cargo test` (default features: 1695 lib + 44 determinism (9 Fix128 golden + 13 f32 golden + 22 semantic) + 220 integration / oracle (72 + 13 analytic + 105 engineering + 13 default-config + 3 parallel + 14 other) + 21 doctests + 3 ignored; 1728 lib tests with the full native feature set), clippy: 0 warnings under `-D warnings` (default + `std,simd,parallel,ffi,gpu-solver-bridge,neural,replay,analytics`, `--all-targets`), `#![deny(missing_docs)]` (0 warnings)

---

### Additional Optimizations

#### Stackless BVH Traversal

Traditional BVH traversal uses a stack to track nodes to visit. Our implementation uses **escape pointers** embedded in each node:

```
┌──────────────────────────────────────────────────────┐
│  BvhNode Layout (32 bytes, cache-aligned)            │
├──────────────────────────────────────────────────────┤
│  aabb_min[3]        (12 bytes)  - Bounding box min   │
│  first_child/prim   (4 bytes)   - Child or prim idx  │
│  aabb_max[3]        (12 bytes)  - Bounding box max   │
│  prim_count_escape  (4 bytes)   - [count:8|escape:24]│
└──────────────────────────────────────────────────────┘

Traversal: single index variable, no stack allocation
  if (hit)  → descend to first_child
  if (miss) → jump to escape_idx (skip entire subtree)
```

**Benefits:**
- Zero heap allocation during queries
- Single register for traversal state
- Better branch prediction
- i32 AABB comparison (no Fix128 reconstruction)

#### SIMD Acceleration (optional)

Enable with `--features simd`:

```rust
// x86_64 with SSE2
impl Fix128 {
    pub unsafe fn add_simd(self, rhs: Self) -> Self;
    pub unsafe fn sub_simd(self, rhs: Self) -> Self;
}

impl Vec3Fix {
    pub fn dot_simd(self, rhs: Self) -> Fix128;
    pub fn cross_simd(self, rhs: Self) -> Self;
    pub fn dot_batch_4(a: [Self; 4], b: [Self; 4]) -> [Fix128; 4];
}
```

#### Constraint Batching (optional)

Enable with `--features parallel`:

Constraints are grouped by **graph coloring** - constraints with no shared bodies are placed in the same "color" and can be solved independently:

```rust
// Rebuild constraint batches (greedy graph coloring)
world.rebuild_batches();

// Step with batched constraint solving
world.step_parallel(dt);

// Check number of color batches
println!("Batches: {}", world.num_batches());
```

**Benefits:**
- Zero heap allocation in constraint loop (index-based iteration)
- Rayon-ready parallel solving
- Reduced lock contention
- Better cache utilization

#### HashMap Contact Cache

Contact manifold lookup via `BodyPairKey → usize` HashMap for O(1) access:

```rust
// O(1) manifold lookup (was O(n) linear scan)
pub fn find(&self, a: usize, b: usize) -> Option<&ContactManifold> {
    let key = BodyPairKey::new(a, b);
    self.pair_index.get(&key).map(|&i| &self.manifolds[i])
}
```

Falls back to linear scan for `no_std` environments.

#### Rayon Parallel Integration

Enable with `--features parallel`:

Position integration and velocity updates run in parallel via `par_iter_mut()`:

```rust
// Parallel position integration (gravity + damping + Euler)
bodies.par_iter_mut().for_each(|body| {
    body.velocity = body.velocity + gravity * dt;
    body.velocity = body.velocity * damping;
    body.position = body.position + body.velocity * dt;
});
```

#### Python Batch APIs

Zero-copy NumPy batch operations with GIL release:

```python
# Batch body creation from (N,4) array [x, y, z, mass]
world.add_bodies_batch(np.array([[0,10,0,1.0], [5,10,0,2.0]]))

# Batch velocity update with GIL release
world.set_velocities_batch(velocities_array)  # (N,3)

# Combined state output as (N,10) array [px,py,pz,vx,vy,vz,qx,qy,qz,qw]
states = world.states()
```

## Why Deterministic Physics?

Traditional physics engines using IEEE 754 floating-point can produce different results across:
- Different CPU architectures (x86 vs ARM)
- Different compilers (GCC vs Clang vs MSVC)
- Different optimization levels (-O0 vs -O3)
- Different instruction sets (SSE vs AVX)

ALICE-Physics guarantees **bit-exact results** across platforms for every module (see [Determinism scope](#determinism-scope)), enabling:

- **Lockstep Multiplayer**: All clients compute identical simulation
- **Rollback Netcode**: Replay inputs deterministically
- **Replay Systems**: Perfect reproduction of game sessions
- **Distributed Simulation**: Parallel computation with consistent results

## Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                          ALICE-Physics v1.0.0 stable                         │
│    1695 lib tests + 44 determinism tests (9 golden + 22 semantic), 6 CI     │
├─────────────────────────────────────────────────────────────────────────────┤
│  Core Layer                                                                  │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │  math    │ │ collider │ │  solver  │ │   bvh    │ │sdf_colldr│          │
│  │ Fix128   │ │ AABB     │ │ RigidBody│ │ Morton   │ │ SdfField │          │
│  │ Vec3Fix  │ │ Sphere   │ │ XPBD     │ │ Stackless│ │ Gradient │          │
│  │ QuatFix  │ │ Capsule  │ │ Sensor   │ │ Zero-    │ │ Early-out│          │
│  │ CORDIC   │ │ GJK/EPA  │ │ Rollback │ │  alloc   │ │          │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│                                                                              │
│  AAA Engine Layer                                                            │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │box_colldr│ │ compound │ │cont_cache│ │dynamic_bv│ │ material │          │
│  │ OBB      │ │ Multi-   │ │ HashMap  │ │ Incr BVH │ │ Pair Tbl │          │
│  │ GJK Supp │ │ Shape    │ │ O(1) Get │ │ AVL Bal  │ │ Combine  │          │
│  │ Inertia  │ │ Local Tx │ │ Warm Str │ │ O(log n) │ │ Friction │          │
│  │ Corners  │ │ AABB Mrg │ │ 4-point  │ │ Fat AABB │ │ Restit   │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐                                    │
│  │dbg_rendr │ │profiling │ │ interp   │                                    │
│  │ Wireframe│ │ Timers   │ │ Snapshot │                                    │
│  │ Contacts │ │ Per-Stage│ │ NLERP    │                                    │
│  │ Joints   │ │ Stats    │ │ Blend    │                                    │
│  │ BVH/AABB │ │ History  │ │ Alpha    │                                    │
│  └──────────┘ └──────────┘ └──────────┘                                    │
│                                                                              │
│  Collision Shapes (v0.5.0)                                                  │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │  cone    │ │ellipsoid │ │  torus   │ │plane_col │ │  wedge   │          │
│  │ Apex/Base│ │ 3-Axis   │ │ Maj/Min  │ │ Hessian  │ │ TriPrism │          │
│  │ GJK Supp│ │ Aniso    │ │ Minkowsk │ │ Sph/AABB │ │ 6-Vertex │          │
│  │ Inertia  │ │ Support  │ │ Support  │ │ Intersct │ │ GJK Supp│          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐                                                               │
│  │cvx_mesh  │                                                               │
│  │ Incr Hull│                                                               │
│  │ Tetra    │                                                               │
│  │ Horizon  │                                                               │
│  └──────────┘                                                               │
│                                                                              │
│  Constraint & Dynamics Layer                                                 │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │  joint   │ │joint_extr│ │  motor   │ │articulatn│ │  force   │          │
│  │ Ball     │ │ Pulley   │ │ PD 1D/3D │ │ Ragdoll  │ │ Wind     │          │
│  │ Hinge    │ │ Gear     │ │ Position │ │ FK Chain │ │ Gravity  │          │
│  │ Fixed    │ │ Weld     │ │ Velocity │ │ Robotic  │ │ Buoyancy │          │
│  │ Slider   │ │ Rack&Pin │ │ Max Torq │ │ Feather- │ │ Drag     │          │
│  │ Spring   │ │ Mouse    │ │          │ │  stone   │ │ Vortex   │          │
│  │ D6       │ │ Breakabl │ │          │ │ 12-body  │ │ Explosion│          │
│  │ ConeTwst │ │          │ │          │ │          │ │ Magnetic │          │
│  │ Breakable│ │          │ │          │ │          │ │          │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐                                                               │
│  │ sleeping │                                                               │
│  │ Islands  │                                                               │
│  │ Union-   │                                                               │
│  │  Find    │                                                               │
│  └──────────┘                                                               │
│                                                                              │
│  Query & Collision Layer                                                     │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │ raycast  │ │   ccd    │ │ trimesh  │ │heightfld │ │  filter  │          │
│  │ Sphere   │ │ TOI      │ │ Triangle │ │ Bilinear │ │ Layer    │          │
│  │ AABB     │ │ Conserv. │ │ BVH-accel│ │ Normal   │ │ Mask     │          │
│  │ Capsule  │ │ Advance  │ │ Moller-  │ │ Sphere   │ │ Group    │          │
│  │ Plane    │ │ Swept    │ │ Trumbore │ │ Collide  │ │ Bidirect │          │
│  │ Sweep    │ │ Specultv │ │ Closest  │ │ Signed   │ │          │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐ ┌──────────┐                                                  │
│  │  query   │ │character │                                                  │
│  │ SphCast  │ │ Move&Sld │                                                  │
│  │ CapCast  │ │ Stair    │                                                  │
│  │ Overlap  │ │ Ground   │                                                  │
│  │ AABB Ovr │ │ SDF Terr │                                                  │
│  └──────────┘ └──────────┘                                                  │
│                                                                              │
│  Soft Body & Simulation Layer                                                │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │  rope    │ │  cloth   │ │  fluid   │ │deformable│ │ vehicle  │          │
│  │ XPBD     │ │ XPBD     │ │ PBF      │ │ FEM-XPBD │ │ Wheel    │          │
│  │ Distance │ │ Triangle │ │ SPH Hash │ │ Tetrahedr│ │ Suspensn │          │
│  │ Chain    │ │ Self-Col │ │ Density  │ │ Volume   │ │ Engine   │          │
│  │ Cable    │ │ SpatHash │ │ Viscosty │ │ Neo-Hook │ │ Steering │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐                       │
│  │clth_flud │ │rope_atth │ │soft_cut  │ │ particle │                       │
│  │ Drag     │ │ RigidBdy │ │ Plane    │ │ Emitters │                       │
│  │ Buoyancy │ │ Complnce │ │ Deform   │ │ Lifetime │                       │
│  │ Boundary │ │ Break    │ │ Cloth    │ │ ForceInt │                       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘                       │
│                                                                              │
│  SDF Advanced Layer                                                          │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │sdf_mnfld │ │ sdf_ccd  │ │sdf_force │ │sdf_destr │ │sdf_adapt │          │
│  │ Manifold │ │ SphTrace │ │ Attract  │ │ CSG Bool │ │ LOD      │          │
│  │ N-point  │ │ March    │ │ Repel    │ │ Subtract │ │ Distance │          │
│  │ Contact  │ │ TOI      │ │ Contain  │ │ Real-time│ │ Adaptive │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐ ┌──────────┐                                                  │
│  │cvx_decomp│ │ gpu_sdf  │                                                  │
│  │ Voxel    │ │ Compute  │                                                  │
│  │ Flood    │ │ Batch    │                                                  │
│  │ Convex   │ │ Shader   │                                                  │
│  └──────────┘ └──────────┘                                                  │
│                                                                              │
│  SDF Simulation Modifiers Layer                                              │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐          │
│  │sim_field │ │sim_modif │ │ thermal  │ │ pressure │ │ erosion  │          │
│  │ Scalar3D │ │ Modifier │ │ Heat Eq  │ │ Crush    │ │ Wind     │          │
│  │ Vector3D │ │ Chain    │ │ Melt     │ │ Bulge    │ │ Water    │          │
│  │ Trilin   │ │ Modified │ │ Freeze   │ │ Dent     │ │ Chemical │          │
│  │ Diffuse  │ │ SDF      │ │ Expand   │ │ Yield    │ │ Ablation │          │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘          │
│  ┌──────────┐ ┌──────────┐                                                  │
│  │ fracture │ │phase_chg │                                                  │
│  │ Stress   │ │ Solid    │                                                  │
│  │ Crack    │ │ Liquid   │                                                  │
│  │ CSG Sub  │ │ Gas      │                                                  │
│  │ Voronoi  │ │ Latent H │                                                  │
│  └──────────┘ └──────────┘                                                  │
│                                                                              │
│  2D Physics Subsystem (v0.5.0)                                              │
│  ┌─────────────────────────────────────────────────────────────────────┐    │
│  │ physics2d                                                           │    │
│  │ Vec2Fix, Shape2D (Circle/Polygon/Capsule/Edge), RigidBody2D         │    │
│  │ SAT + Voronoi collision, XPBD 2D solver, Joint2D (Rev/Dist/Weld/M) │    │
│  └─────────────────────────────────────────────────────────────────────┘    │
│                                                                              │
│  Mesh & I/O Utilities (v0.5.0)                                              │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐                       │
│  │mass_prop │ │col_mesh  │ │ scene_io │ │multi_wrld│                       │
│  │ Sphere   │ │ Marching │ │ Binary   │ │ N worlds │                       │
│  │ Box      │ │ Cubes    │ │ APHYS    │ │ Transfer │                       │
│  │ Cylinder │ │ EdgeClps │ │ JSON     │ │ Isolate  │                       │
│  │ PAxis    │ │ Simplify │ │ Fix128   │ │ Step All │                       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘                       │
│                                                                              │
│  Visualization (v0.5.0)                                                     │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐                                    │
│  │ heatmap  │ │ flow_viz │ │contct_viz│                                    │
│  │ Stress   │ │ Arrows   │ │ Force    │                                    │
│  │ Temp     │ │ Streamln │ │ Friction │                                    │
│  │ Viridis  │ │ Velocity │ │ Cone     │                                    │
│  └──────────┘ └──────────┘ └──────────┘                                    │
│                                                                              │
│  Game Systems Layer                                                          │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐                                    │
│  │anim_blnd │ │audio_phys│ │ netcode  │                                    │
│  │ SLERP    │ │ Impact   │ │ FrameInp │                                    │
│  │ Ragdoll  │ │ Friction │ │ Checksum │                                    │
│  │ Blend    │ │ Rolling  │ │ Snapshot │                                    │
│  │ IK Mix   │ │ Material │ │ Rollback │                                    │
│  └──────────┘ └──────────┘ └──────────┘                                    │
│                                                                              │
│  Analytics & Privacy Layer                                                   │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐                       │
│  │  sketch  │ │ anomaly  │ │ privacy  │ │ pipeline │                       │
│  │ HyperLog │ │ MAD      │ │ Laplace  │ │ MetricPi │                       │
│  │ DDSketch │ │ EWMA     │ │ RAPPOR   │ │ RingBuf  │                       │
│  │ CountMin │ │ Z-score  │ │ RandResp │ │ Registry │                       │
│  │ HeavyHit │ │ Composit │ │ XorShift │ │ Snapshot │                       │
│  └──────────┘ └──────────┘ └──────────┘ └──────────┘                       │
│                                                                              │
│  Utility Layer                                                               │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌─────────────────────────────────┐│
│  │   rng    │ │  event   │ │fluid_net │ │      neural (ALICE-ML × Phys)   ││
│  │ PCG-XSH  │ │ Begin    │ │ Delta    │ │ Ternary {-1,0,+1} → Fix128     ││
│  │ Fix128   │ │ Persist  │ │ Compress │ │ Deterministic AI                ││
│  │ Direction│ │ End      │ │ Snapshot │ │ Ragdoll Controller              ││
│  └──────────┘ └──────────┘ └──────────┘ └─────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────────────────┘
```

## Usage

### Choose Your Path

Pick the entry point that matches your role. All paths share the same deterministic `PhysicsWorld`, so you can start simple and layer in advanced features (rollback / GPU offload / joints) later without rewriting.

| You are… | Path | Best for | Section |
|----------|------|----------|---------|
| **First time here** | [Hello, first physics](#hello-first-physics-30-seconds) ↓ | Sanity-check the install with a falling sphere | ↓ |
| **Simulation dev, want the basics** | [Basic Simulation](#basic-simulation) | Rigid bodies, gravity, ground, per-frame stepping | ↓ |
| **Netcode / lockstep game dev** | [Rollback Netcode](#rollback-netcode) | Snapshot save/load, deterministic replay, Fix128 bit-exact | ↓ |
| **Rope / cloth / constraint dev** | [Distance Constraint](#distance-constraint-ropechain) + `joint` module | Chains, ropes, ragdolls, breakable constraints | ↓ |
| **Perf-sensitive (many bodies)** | [BVH Broad-Phase](#bvh-broad-phase-collision) | Spatial acceleration, zero-alloc queries, Morton codes | ↓ |
| **GPU offload (advanced)** | [GPU Solver Bridge](#companion-crate--alice-trt-gpu-solver-offload) | PGS iteration on GPU via ALICE-TRT, byte-exact vs CPU | ↑ |
| **Unity / UE5 / Godot integrator** | C-ABI FFI | Fix128 hi/lo pairs across the C ABI, bit-pattern equality | see `alice_physics_ffi::*` |
| **CCD / raycast / trimesh user** | Module-specific | `ccd` / `raycast` / `trimesh` modules with dedicated APIs | see [Modules](#modules) |

### Hello, First Physics (30 seconds)

The smallest working sample — one falling sphere onto static ground, step it, print the y-coord:

```rust
use alice_physics::prelude::*;

let mut world = PhysicsWorld::new(PhysicsConfig::default());

let sphere = RigidBody::new_dynamic(Vec3Fix::from_int(0, 10, 0), Fix128::ONE);
let _sphere_id = world.add_body(sphere);
world.add_body(RigidBody::new_static(Vec3Fix::ZERO));   // ground plane at y=0

let dt = Fix128::from_ratio(1, 60);
for frame in 0..60 {
    world.step(dt);
    println!("frame {frame}: y = {}", world.bodies[0].position.y.hi);
}
```

Once this runs, jump to the path that matches your role.

### Basic Simulation

```rust
use alice_physics::prelude::*;

fn main() {
    // Create physics world with default config
    let config = PhysicsConfig::default();
    let mut world = PhysicsWorld::new(config);

    // Add a dynamic body (falling sphere)
    let sphere = RigidBody::new_dynamic(
        Vec3Fix::from_int(0, 100, 0),  // position: (0, 100, 0)
        Fix128::ONE,                    // mass: 1.0
    );
    let sphere_id = world.add_body(sphere);

    // Add static ground
    let ground = RigidBody::new_static(Vec3Fix::ZERO);
    world.add_body(ground);

    // Simulate at 60 FPS
    let dt = Fix128::from_ratio(1, 60);  // 1/60 second

    for frame in 0..300 {  // 5 seconds
        world.step(dt);

        let pos = world.bodies[sphere_id].position;
        println!("Frame {}: y = {}", frame, pos.y.hi);
    }
}
```

### Distance Constraint (Rope/Chain)

```rust
use alice_physics::prelude::*;

fn create_rope(world: &mut PhysicsWorld, segments: usize) {
    let mut prev_id = None;

    for i in 0..segments {
        let body = RigidBody::new_dynamic(
            Vec3Fix::from_int(i as i64 * 2, 50, 0),
            Fix128::ONE,
        );
        let id = world.add_body(body);

        if let Some(prev) = prev_id {
            let constraint = DistanceConstraint {
                body_a: prev,
                body_b: id,
                local_anchor_a: Vec3Fix::ZERO,
                local_anchor_b: Vec3Fix::ZERO,
                target_distance: Fix128::from_int(2),
                compliance: Fix128::from_ratio(1, 1000),  // Soft constraint
            };
            world.add_distance_constraint(constraint);
        }

        prev_id = Some(id);
    }

    // Fix first segment in place
    world.bodies[0].inv_mass = Fix128::ZERO;
}
```

### Rollback Netcode

```rust
use alice_physics::prelude::*;

struct GameState {
    physics: PhysicsWorld,
    frame: u64,
    input_buffer: Vec<PlayerInput>,
}

impl GameState {
    fn save_snapshot(&self) -> Vec<u8> {
        self.physics.serialize_state()
    }

    fn load_snapshot(&mut self, data: &[u8]) {
        self.physics.deserialize_state(data);
    }

    fn rollback_and_resimulate(&mut self, to_frame: u64, new_input: PlayerInput) {
        // Load snapshot from frame
        let snapshot = self.get_snapshot(to_frame);
        self.load_snapshot(&snapshot);

        // Replay with corrected input
        self.input_buffer[to_frame as usize] = new_input;

        for frame in to_frame..self.frame {
            let input = &self.input_buffer[frame as usize];
            self.apply_input(input);
            self.physics.step(Fix128::from_ratio(1, 60));
        }
    }
}
```

### BVH Broad-Phase Collision

```rust
use alice_physics::bvh::{LinearBvh, BvhPrimitive};

// Build BVH from primitives
let primitives: Vec<BvhPrimitive> = bodies.iter().enumerate()
    .map(|(i, body)| BvhPrimitive {
        aabb: body.compute_aabb(),
        index: i as u32,
        morton: 0,  // Computed during build
    })
    .collect();

let bvh = LinearBvh::build(primitives);

// Query with zero heap allocation (callback version)
bvh.query_callback(&query_aabb, |prim_idx| {
    // Handle potential collision with primitive
});

// Or collect results
let hits = bvh.query(&query_aabb);

// Get BVH statistics
let stats = bvh.stats();
println!("Nodes: {}, Leaves: {}", stats.node_count, stats.leaf_count);
```

### Common Recipes

Additional patterns that come up frequently — copy-paste starting points.

**1. Raycast against the world**

```rust
use alice_physics::prelude::*;

let ray = Ray {
    origin:    Vec3Fix::from_int(0, 5, 0),
    direction: Vec3Fix::from_int(0, -1, 0),   // straight down
    max_distance: Fix128::from_int(100),
};
if let Some(hit) = world.raycast(&ray) {
    println!("hit body {} at distance {}", hit.body_id, hit.distance.hi);
}
```

**2. Put idle bodies to sleep (perf win)**

```rust
// PhysicsConfig has sleeping enabled by default; tune the thresholds when needed.
let mut config = PhysicsConfig::default();
config.sleeping.linear_threshold  = Fix128::from_ratio(1, 100);   // 0.01 m/s
config.sleeping.angular_threshold = Fix128::from_ratio(1, 100);
config.sleeping.time_to_sleep     = Fix128::from_ratio(1, 2);     // 0.5 s
let mut world = PhysicsWorld::new(config);
```

**3. Breakable constraint (rope snap under load)**

```rust
let constraint = DistanceConstraint {
    body_a: a,
    body_b: b,
    local_anchor_a: Vec3Fix::ZERO,
    local_anchor_b: Vec3Fix::ZERO,
    target_distance: Fix128::from_int(2),
    compliance:      Fix128::from_ratio(1, 1000),
};
let id = world.add_distance_constraint(constraint);
world.set_constraint_break_force(id, Fix128::from_int(500));   // snaps > 500 N
```

**4. Static-ground quick setup**

```rust
let ground = RigidBody::new_static(Vec3Fix::ZERO);
let ground_id = world.add_body(ground);
world.set_collider(ground_id, Collider::plane(Vec3Fix::from_int(0, 1, 0), Fix128::ZERO));
```

**5. Save + reload a snapshot (rollback primitive)**

```rust
let snapshot: Vec<u8> = world.serialize_state();     // byte-exact across arch
// ... later, or on another machine:
world.deserialize_state(&snapshot);                  // resumes at frame boundary
```

**6. Continuous collision (fast-moving projectile)**

```rust
use alice_physics::ccd;

let bullet = RigidBody::new_dynamic(Vec3Fix::from_int(0, 0, 0), Fix128::ONE);
let bullet_id = world.add_body(bullet);
world.enable_ccd(bullet_id);   // subswept collision, avoids tunneling
```

### Session 3 Solver Loops (v0.12)

**CFD gravity settling** — solve incompressible Navier-Stokes for one time
step with pressure projection:

```rust
use alice_physics::cfd_solver::CfdSolver;
use alice_physics::math::Fix128;

let mut solver = CfdSolver::new(12, 12, 12, Fix128::from_ratio(1, 10));
solver.jacobi_iterations = 100;

// Water in gravity, closed box → settles, divergence ≈ 0
for _ in 0..30 {
    solver.step(Fix128::from_ratio(1, 1000));  // 0.001 s per step
}
// solver.grid.v[…] centre column will read −0.294 m/s at t = 0.03 s
// matching −g·t exactly (bit-exact recovery of the free-fall analytical solution)
```

**Structural creep + fatigue history** — advance a PLA shelf through
20 h of sustained load at 55 °C and print the diagnostic table:

```rust
use alice_physics::beam_stress::{CrossSection, LoadCase};
use alice_physics::filament_db::MaterialProperties;
use alice_physics::math::Fix128;
use alice_physics::structural_solver::StructuralSolver;

let section = CrossSection::Rectangular {
    width_mm: Fix128::from_int(150),
    height_mm: Fix128::from_int(10),
};
let load = LoadCase::SimplySupportedCenter {
    load_n: Fix128::from_int(20),
    length_mm: Fix128::from_int(300),
};
let mut solver = StructuralSolver::new(section, load, MaterialProperties::pla());
solver.operating_temp_c = Fix128::from_int(55);
solver.dt_s = Fix128::from_int(3600);   // 1-hour steps

let history = solver.run(20);
println!(
    "creep {:.5}, fatigue D = {:.4}, failure step = {:?}",
    history.plastic_state.creep_strain.to_f32(),
    history.fatigue_damage.to_f32(),
    history.failure_step,
);
```

**Print pipeline safety** — run 10 print-safety checks in one call:

```rust
use alice_physics::beam_stress::{CrossSection, LoadCase};
use alice_physics::math::Fix128;
use alice_physics::print_orientation::LoadDirection;
use alice_physics::print_pipeline_solver::{analyze_print_pipeline, PrintPipelineInputs};
use alice_physics::support_volume::OverhangRegion;
use alice_physics::warp_risk::Footprint;

let footprint = Footprint {
    area_mm2: Fix128::from_int(300 * 300),
    max_dimension_mm: Fix128::from_int(300),
};
let inputs = PrintPipelineInputs {
    beam_load: Some((
        CrossSection::Rectangular {
            width_mm: Fix128::from_int(50),
            height_mm: Fix128::from_int(5),
        },
        LoadCase::CantileverEndPoint {
            load_n: Fix128::from_int(30),
            length_mm: Fix128::from_int(300),
        },
    )),
    load_direction: Some(LoadDirection::axis_z()),
    overhangs: vec![OverhangRegion {
        projected_area_mm2: Fix128::from_int(50 * 50),
        support_height_mm: Fix128::from_int(15),
    }],
    fillet: Some((Fix128::from_ratio(3, 10), Fix128::from_int(20), Fix128::from_int(40))),
    ..Default::default()
};

let report = analyze_print_pipeline(footprint, "PLA", &inputs);
report.print();
// Prints warp / strength envelope / thermal / beam FoS / bridging /
// support volume / K_t / bimaterial and an overall SAFE / UNSAFE verdict.
```

### Where to go next

| I want to… | See |
|------------|-----|
| Understand the full type surface | [Modules](#modules) section below |
| Deep dive into determinism guarantees | [Why Deterministic Physics?](#why-deterministic-physics) |
| Offload PGS iterations to the GPU | [Companion crate — ALICE-TRT](#companion-crate--alice-trt-gpu-solver-offload) |
| Wire into Unity / UE5 native plugin | `alice_physics_ffi::*` (module in this crate) |
| See the joint catalog (12 base + 5 advanced) | [`joint`](#joint---12-joint-types--breakable-constraints) / [`joint_extra`](#joint_extra---5-advanced-joints-v050) sections |
| Prove byte-exact CI on 3 platforms | See ALICE-TRT's Fix128 + physics-solver test matrix (companion release) |
| Compare to Rapier / PhysX / Box2D | [Why Deterministic Physics?](#why-deterministic-physics) benchmark table |

Companion crates that plug directly into `PhysicsWorld`:

- **[ALICE-TRT](https://github.com/ext-sakamoro/ALICE-TRT)** (`gpu-solver-bridge` feature) — GPU PGS solver offload with byte-exact CPU parity
- **[ALICE-Cloth](https://github.com/ext-sakamoro/ALICE-Cloth)** — XPBD cloth on top of the same Fix128 primitives
- **[ALICE-Vehicle](https://github.com/ext-sakamoro/ALICE-Vehicle)** — Deterministic vehicle rig
- **[ALICE-Netcode](https://github.com/ext-sakamoro/ALICE-Netcode)** — Rollback netcode plumbing built for `serialize_state` / `deserialize_state`

## Modules

### `math` - Fixed-Point Primitives

| Type | Description |
|------|-------------|
| `Fix128` | 128-bit fixed-point number (I64F64) |
| `Vec3Fix` | 3D vector with Fix128 components |
| `QuatFix` | Quaternion for rotations |
| `Mat3Fix` | 3x3 matrix for inertia tensors |

**Constants:**
- `Fix128::ZERO`, `Fix128::ONE`, `Fix128::NEG_ONE`
- `Fix128::PI`, `Fix128::HALF_PI`, `Fix128::TWO_PI`

**CORDIC functions (deterministic, no FPU):**
- `Fix128::sin()`, `Fix128::cos()`, `Fix128::sin_cos()`
- `Fix128::atan()`, `Fix128::atan2()`
- `Fix128::sqrt()` (Newton-Raphson, 64 iterations)

**Utility:**
- `Fix128::from_ratio(num, denom)` - Create from fraction
- `Fix128::half()`, `Fix128::double()` - Exact bit shifts
- `Fix128::abs()`, `Fix128::floor()`, `Fix128::ceil()`

### `collider` - Collision Detection

| Shape | Description |
|-------|-------------|
| `AABB` | Axis-Aligned Bounding Box |
| `Sphere` | Sphere collider |
| `Capsule` | Capsule (cylinder + hemispheres) |
| `ConvexHull` | Arbitrary convex polyhedron |
| `CollisionResult` | Contact information |

**Algorithms:**
- **GJK**: Gilbert-Johnson-Keerthi for intersection test (64 iterations max)
- **EPA**: Expanding Polytope Algorithm for penetration depth (64 iterations max)

### `solver` - XPBD Physics

**RigidBody fields:**
| Field | Type | Description |
|-------|------|-------------|
| `position` | `Vec3Fix` | Center of mass position |
| `rotation` | `QuatFix` | Orientation quaternion |
| `velocity` | `Vec3Fix` | Linear velocity |
| `angular_velocity` | `Vec3Fix` | Angular velocity |
| `inv_mass` | `Fix128` | Inverse mass (0 = static) |
| `inv_inertia` | `Vec3Fix` | Inverse inertia tensor (diagonal) |
| `restitution` | `Fix128` | Bounciness (0-1) |
| `friction` | `Fix128` | Friction coefficient |
| `is_sensor` | `bool` | Sensor mode: detects overlap but no physics response |

**Constraints:**
- `DistanceConstraint`: Fixed distance between anchor points
- `ContactConstraint`: Collision response with friction/restitution

**Methods:**
- `RigidBody::new(position, mass)` - Create dynamic body
- `RigidBody::new_dynamic(position, mass)` - Alias for new
- `RigidBody::new_static(position)` - Create immovable body
- `RigidBody::new_sensor(position)` - Create sensor/trigger body (no physics response)

### `bvh` - Spatial Acceleration

| Type | Description |
|------|-------------|
| `LinearBvh` | Flat array BVH with stackless traversal |
| `BvhNode` | 32-byte cache-aligned node with escape pointer |
| `BvhPrimitive` | Primitive entry for construction |
| `BvhStats` | Tree statistics |

**Features:**
- **Morton Codes**: Z-order curve for spatial locality
- **Escape Pointers**: Stackless traversal (zero allocation)
- **i32 AABB**: Fast integer comparison without Fix128 reconstruction

### `joint` - 12 Joint Types + Breakable Constraints

| Type | Description |
|------|-------------|
| `BallJoint` | Spherical joint (3 rotational DOF) |
| `HingeJoint` | Revolute joint (1 rotational DOF) with angle limits |
| `FixedJoint` | Weld joint (0 DOF) |
| `SliderJoint` | Prismatic joint (1 translational DOF) with limits |
| `SpringJoint` | Damped spring constraint |
| `D6Joint` | 6-DOF configurable joint with per-axis lock/free/limit |
| `ConeTwistJoint` | Ball joint with cone swing limit and twist limit |

### `joint_extra` - 5 Advanced Joints (v0.5.0)

| Type | Description |
|------|-------------|
| `PulleyJoint` | Pulley with 2 anchors and rope ratio (total distance constraint) |
| `GearJoint` | Gear coupling (angular velocity ratio between two bodies) |
| `WeldJoint` | Rigid weld with `break_force` / `break_torque` threshold |
| `RackAndPinionJoint` | Rotation-to-translation conversion with pitch radius |
| `MouseJoint` | Target-following joint for mouse/touch drag interaction |

All joint types support **breakable constraints** via `with_break_force(max_force)`. When the constraint force exceeds the threshold, the joint breaks and is removed from simulation.

```rust
use alice_physics::joint::*;
// Hinge with angle limits
let hinge = HingeJoint::new(body_a, body_b, anchor_a, anchor_b, axis_a, axis_b)
    .with_limits(-Fix128::HALF_PI, Fix128::HALF_PI);

// D6 joint (lock X translation, free Y rotation, limit Z rotation)
let d6 = D6Joint::new(body_a, body_b, anchor_a, anchor_b)
    .with_axis(Axis::LinearX, D6Mode::Locked)
    .with_axis(Axis::AngularY, D6Mode::Free)
    .with_axis(Axis::AngularZ, D6Mode::Limited(-Fix128::HALF_PI, Fix128::HALF_PI));

// Cone-twist joint (shoulder-like with cone + twist limits)
let cone = ConeTwistJoint::new(body_a, body_b, anchor_a, anchor_b, twist_axis)
    .with_cone_limit(Fix128::from_ratio(45, 1))  // 45° cone
    .with_twist_limit(Fix128::from_ratio(30, 1)); // 30° twist

// Breakable ball joint (breaks at force > 100)
let ball = BallJoint::new(body_a, body_b, anchor_a, anchor_b)
    .with_break_force(Fix128::from_int(100));

// Solve with breakable support — returns indices of broken joints
let broken = solve_joints_breakable(&joints, &mut bodies, dt);
```

### `raycast` - Ray & Shape Casting

| Function | Description |
|----------|-------------|
| `ray_sphere` | Ray vs sphere intersection |
| `ray_aabb` | Ray vs AABB (slab method) |
| `ray_capsule` | Ray vs capsule |
| `ray_plane` | Ray vs infinite plane |
| `sweep_sphere` | Moving sphere vs sphere (Minkowski expansion) |

### `ccd` - Continuous Collision Detection

| Function | Description |
|----------|-------------|
| `sphere_sphere_toi` | Sphere-sphere TOI via quadratic |
| `sphere_plane_toi` | Sphere-plane TOI |
| `conservative_advancement` | TOI via iterative safe stepping |
| `swept_aabb` | Swept AABB bounding volume |
| `speculative_contact` | Speculative contact for CCD integration with solver |
| `needs_ccd` | Velocity threshold check for CCD activation |

### `sleeping` - Sleep & Island System

| Type | Description |
|------|-------------|
| `IslandManager` | Union-Find island management |
| `SleepData` | Per-body sleep tracking |
| `SleepConfig` | Velocity thresholds, idle frame count |

### `trimesh` - Triangle Mesh Collision

| Type | Description |
|------|-------------|
| `Triangle` | Single triangle with Moller-Trumbore intersection |
| `TriMesh` | BVH-accelerated triangle mesh |

**Features:**
- Ray-triangle intersection (Moller-Trumbore)
- Closest point on triangle
- Sphere-mesh collision detection

### `heightfield` - Height Field Terrain

| Type | Description |
|------|-------------|
| `HeightField` | Grid-based terrain with bilinear interpolation |

**Features:**
- `sample_height(world_x, world_z)` with bilinear interpolation
- `sample_normal(world_x, world_z)` from central differences
- `collide_sphere()` for sphere-terrain collision
- `signed_distance(point)` for point-terrain distance

### `filter` - Collision Filtering

| Type | Description |
|------|-------------|
| `CollisionFilter` | Layer/mask bitmask with collision groups |
| `layers` module | Predefined layers (DEFAULT, STATIC, PLAYER, ENEMY, etc.) |

### `force` - 7 Force Fields

| Variant | Description |
|---------|-------------|
| `Directional` | Uniform wind/gravity (direction + strength) |
| `Point` | Radial gravity well with inverse-square falloff |
| `Drag` | Velocity-proportional drag |
| `Buoyancy` | Plane-based buoyancy with density |
| `Vortex` | Spinning vortex field (center + axis + strength) |
| `Explosion` | Radial impulse with configurable `falloff_power` attenuation |
| `Magnetic` | Simplified dipole model with 1/r^3 inverse cube law |

### `motor` - PD Controllers

| Type | Description |
|------|-------------|
| `PdController` | 1D proportional-derivative controller |
| `PdController3D` | 3D PD controller |
| `JointMotor` | Joint motor with position/velocity/torque modes |

### `articulation` - Articulated Bodies

| Type | Description |
|------|-------------|
| `ArticulatedBody` | Multi-joint chain with FK propagation |
| `Link` | Joint + body pair in a chain |

**Presets:**
- `build_ragdoll()` — 12-body humanoid (head, torso, arms, legs)

### `rng` - Deterministic Random

| Type | Description |
|------|-------------|
| `DeterministicRng` | PCG-XSH-RR 32-bit generator |

**Methods:**
- `next_fix128()` — Random Fix128 in [0, 1)
- `range_fix128(min, max)` — Random in [min, max)
- `next_direction()` — Random unit Vec3Fix

### `event` - Contact Events

| Type | Description |
|------|-------------|
| `EventCollector` | Tracks contact begin/persist/end per pair |
| `ContactEvent` | Body pair + event type + contact point |
| `ContactEventType` | Begin, Persist, End |

### `query` - Shape Cast & Overlap Queries

| Function | Description |
|----------|-------------|
| `sphere_cast` | Sweep a sphere along a direction (Minkowski sum approach) |
| `capsule_cast` | Sweep a capsule along a direction (3-point sphere cast) |
| `overlap_sphere` | Find all bodies overlapping a sphere |
| `overlap_aabb` | Find all bodies within an AABB (point test) |
| `overlap_aabb_expanded` | Find all bodies within an AABB expanded by body radius |

### `character` - Character Controller

| Type | Description |
|------|-------------|
| `CharacterController` | Kinematic capsule-based character with move-and-slide |
| `CharacterConfig` | Radius, height, max slope, step height, skin width |
| `MoveResult` | Movement result with ground state |

**Features:**
- Collide-and-slide algorithm with configurable max slides
- Ground detection via downward raycast + SDF
- Stair stepping (automatic step-up for small obstacles)
- SDF terrain integration (push out of SDF surfaces)

### `rope` - XPBD Rope & Cable

| Type | Description |
|------|-------------|
| `Rope` | XPBD distance-chain rope simulation |
| `RopeConfig` | Segment count, length, stiffness, damping |

### `cloth` - XPBD Cloth Simulation

| Type | Description |
|------|-------------|
| `Cloth` | XPBD triangle mesh cloth with stretch/shear/bend constraints |
| `ClothConfig` | Stiffness, damping, self-collision, gravity |

**Features:**
- Distance constraints (stretch resistance)
- Bending constraints
- Self-collision via spatial hash grid

### `fluid` - Position-Based Fluids

| Type | Description |
|------|-------------|
| `Fluid` | Position-Based Fluids (PBF) simulation |
| `FluidConfig` | Particle count, rest density, viscosity, kernel radius |

**Features:**
- SPH density estimation with spatial hash grid
- Incompressibility constraint solving
- Viscosity (XSPH)
- Surface tension

### `deformable` - FEM-XPBD Deformable Bodies

| Type | Description |
|------|-------------|
| `DeformableBody` | FEM tetrahedral mesh deformable body |
| `DeformableConfig` | Young's modulus, Poisson's ratio, damping |

### `vehicle` - Vehicle Physics

| Type | Description |
|------|-------------|
| `Vehicle` | Complete vehicle simulation |
| `VehicleConfig` | Wheel count, suspension, engine, steering parameters |

**Features:**
- Wheel contact with ground/terrain
- Spring-damper suspension
- Engine torque with gear shifting
- Ackermann steering geometry

### `cone` - Cone Collider (v0.5.0)

| Type | Description |
|------|-------------|
| `Cone` | Cone collider with apex at +Y and base at -Y |

**Features:**
- GJK `Support` trait implementation (apex/base center switching)
- AABB computation, volume, surface area, inertia diagonal
- Configurable radius and half-height with rotation

### `ellipsoid` - Ellipsoid Collider (v0.5.0)

| Type | Description |
|------|-------------|
| `Ellipsoid` | Ellipsoid with three independent semi-axes (rx, ry, rz) |

**Features:**
- Anisotropic GJK support (scale direction by radii, normalize, scale back)
- Volume, AABB, and inertia diagonal computation

### `torus` - Torus Collider (v0.5.0)

| Type | Description |
|------|-------------|
| `Torus` | Torus with major radius (ring) and minor radius (tube) |

**Features:**
- GJK support via Minkowski sum decomposition
- Volume and AABB computation

### `plane_collider` - Infinite Plane Collider (v0.5.0)

| Type | Description |
|------|-------------|
| `PlaneCollider` | Infinite plane in Hessian normal form (normal + offset) |

**Features:**
- `intersect_sphere()` — sphere-plane intersection with contact point
- `intersect_aabb()` — AABB-plane overlap test
- `signed_distance()` — point-plane signed distance

### `wedge` - Wedge Collider (v0.5.0)

| Type | Description |
|------|-------------|
| `Wedge` | Triangular prism (wedge) with 6 vertices |

**Features:**
- GJK support (iterates 6 vertices for max dot product)
- Volume, AABB, and centroid computation

### `convex_mesh_builder` - Convex Hull Builder (v0.5.0)

| Function | Description |
|----------|-------------|
| `build_convex_hull(points)` | Build convex hull from arbitrary point set |
| `compute_centroid(faces, vertices)` | Compute centroid of convex hull |

**Algorithm:** Incremental convex hull — find initial tetrahedron, incrementally insert points, remove visible faces, patch with horizon edges.

### `physics2d` - 2D Physics Engine (v0.5.0)

| Type | Description |
|------|-------------|
| `Vec2Fix` | 2D vector with Fix128 components |
| `Shape2D` | Circle, Polygon (max 16 vertices), Capsule, Edge |
| `RigidBody2D` | 2D rigid body with position, angle, velocity, angular velocity |
| `PhysicsWorld2D` | Complete 2D physics world with XPBD solver |
| `PhysicsConfig2D` | Gravity, substeps, iterations, sleep threshold |
| `Contact2D` | Contact point with normal, depth, body indices |
| `Joint2D` | Revolute, Distance, Weld, Mouse joint variants |
| `BodyType2D` | Dynamic, Static, Kinematic |

**Algorithms:**
- **SAT** (Separating Axis Theorem) with Voronoi region classification
- **XPBD** position-based solver with configurable substeps
- Broad-phase AABB overlap, narrow-phase polygon projection

### `mass_properties` - Mass & Inertia (v0.5.0)

| Function | Description |
|----------|-------------|
| `sphere_mass_properties(radius, density)` | Sphere mass + inertia tensor |
| `box_mass_properties(half_extents, density)` | Box mass + inertia tensor |
| `cylinder_mass_properties(radius, half_h, density)` | Cylinder mass + inertia |
| `capsule_mass_properties(radius, half_h, density)` | Capsule mass + inertia |
| `convex_hull_mass_properties(vertices, faces, density)` | Convex hull mass + inertia |
| `translate_inertia(inertia, mass, offset)` | Parallel axis theorem |

### `collision_mesh_gen` - SDF to Mesh (v0.5.0)

| Type / Function | Description |
|-----------------|-------------|
| `CollisionMeshConfig` | Grid resolution, bounding box, simplification target |
| `CollisionMesh` | Vertices + triangle indices output |
| `generate_collision_mesh(sdf, config)` | Marching cubes mesh generation |
| `simplify_mesh(mesh, target)` | Edge-collapse mesh simplification |

### `scene_io` - Scene Serialization (v0.5.0, std)

| Function | Description |
|----------|-------------|
| `save_binary(path, scene)` | Save to `.aphys` binary format (bit-exact Fix128) |
| `load_binary(path)` | Load from `.aphys` binary format |
| `save_json(path, scene)` | Save to `.aphys.json` human-readable format |
| `load_json(path)` | Load from `.aphys.json` format |

**Binary format:** Magic `APHYS\0`, little-endian, raw Fix128 `{hi: i64, lo: u64}` for bit-exact deterministic roundtrip.

### `cloth_fluid` - Cloth-Fluid Coupling (v0.5.0)

| Type | Description |
|------|-------------|
| `ClothFluidCoupling` | Bidirectional cloth-fluid interaction |

**Effects:** Fluid drag force on cloth vertices, buoyancy based on submersion, boundary repulsion to prevent penetration.

### `rope_attach` - Rope Attachment (v0.5.0)

| Type | Description |
|------|-------------|
| `RopeAttachment` | Attach rope endpoints to rigid bodies |

**Features:** Configurable compliance, break force threshold, automatic detachment.

### `soft_body_cut` - Soft Body Cutting (v0.5.0)

| Function | Description |
|----------|-------------|
| `cut_deformable(body, plane)` | Cut deformable body along a plane |
| `cut_cloth(cloth, plane)` | Cut cloth mesh along a plane |

**Algorithm:** Plane-based topology splitting — classifies vertices, creates new vertices at intersection points, rebuilds connectivity.

### `heatmap` - Stress/Temperature Heatmap (v0.5.0)

| Type | Description |
|------|-------------|
| `Heatmap` | 2D scalar field visualization with colormap |
| `HeatmapConfig` | Resolution, value range, colormap selection |

**Features:** Viridis colormap, RGBA pixel output, configurable min/max range.

### `flow_viz` - Flow Visualization (v0.5.0)

| Type | Description |
|------|-------------|
| `FlowArrow` | Velocity arrow with position, direction, magnitude |
| `Streamline` | Ordered list of points tracing a flow path |

**Functions:** `generate_flow_arrows()`, `generate_streamlines()` from velocity fields.

### `contact_viz` - Contact Visualization (v0.5.0)

| Type | Description |
|------|-------------|
| `ContactArrow` | Force arrow at contact point |
| `FrictionCone` | Cone geometry representing friction limit |

**Functions:** `visualize_contacts()`, `visualize_friction_cones()` from contact manifolds.

### `multi_world` - Multiple Physics Worlds (v0.5.0)

| Type | Description |
|------|-------------|
| `MultiWorld` | Container for N independent physics worlds |

**Features:**
- `add_world()` / `remove_world()` — manage independent worlds
- `step_all(dt)` — advance all worlds simultaneously
- `transfer_body(from, to, body_id)` — move body between worlds

### `particle` - Particle System (v0.5.0)

| Type | Description |
|------|-------------|
| `ParticleSystem` | General-purpose particle simulation |
| `ParticleEmitter` | Directional emitter with cone spread |
| `Particle` | Position, velocity, age, lifetime, mass |

**Features:**
- Configurable emission rate, spread angle, speed range
- Lifetime management with automatic recycling
- Full `ForceField` integration (including Explosion and Magnetic)
- Deterministic via `DeterministicRng`

### `animation_blend` - Animation Blending

| Type | Description |
|------|-------------|
| `AnimationBlender` | Ragdoll-to-animation pose blending |
| `BlendMode` | Lerp, Slerp, Additive |
| `SkeletonPose` | Joint transforms for a skeleton |
| `AnimationClip` | Keyframed animation data |

### `audio_physics` - Physics-Based Audio

| Type | Description |
|------|-------------|
| `AudioGenerator` | Generates audio parameters from physics contacts |
| `AudioConfig` | Material properties for audio synthesis |
| `AudioEvent` | Impact, friction, rolling audio events |
| `AudioMaterial` | Surface material with audio properties |

### `sdf_manifold` - SDF Contact Manifold

Multi-point contact generation from SDF surfaces for more stable collision response.

### `sdf_ccd` - SDF Continuous Collision Detection

Sphere tracing-based CCD for bodies moving against SDF surfaces.

### `sdf_force` - SDF Force Fields

| Variant | Description |
|---------|-------------|
| `Attract` | Pull bodies toward SDF surface |
| `Repel` | Push bodies away from SDF surface |
| `Contain` | Keep bodies inside SDF boundary |
| `Flow` | Flow field following SDF gradient |

### `sdf_destruction` - SDF Boolean Destruction

Real-time CSG boolean operations for destructible environments.

| Type | Description |
|------|-------------|
| `DestructibleSdf` | SDF that accumulates destruction shapes |
| `DestructionShape` | Sphere, box, or custom SDF subtraction |

### `sdf_adaptive` - Adaptive SDF Evaluation

Distance-based LOD for SDF evaluation — faraway queries use coarser sampling.

### `convex_decompose` - Convex Decomposition

Generate convex hull decomposition from an SDF voxel grid for use with GJK/EPA.

### `gpu_sdf` - GPU Compute Shader

Batch SDF evaluation on GPU via compute shaders. Requires `--features std`.

### `fluid_netcode` - Fluid Netcode

Deterministic fluid simulation with delta-compressed snapshots for network sync. Requires `--features std`.

### `sim_field` - 3D Simulation Fields

| Type | Description |
|------|-------------|
| `ScalarField3D` | Uniform grid scalar field with trilinear interpolation |
| `VectorField3D` | Uniform grid vector field with trilinear interpolation |

**Features:**
- Trilinear interpolation for smooth sampling
- Diffusion (heat equation solver)
- Decay over time
- Point splatting for localized effects

### `sim_modifier` - SDF Simulation Modifiers

| Type | Description |
|------|-------------|
| `PhysicsModifier` | Trait for physics-driven SDF modification |
| `ModifiedSdf` | Chain of modifiers that alter SDF distance |
| `SingleModifiedSdf` | Single-modifier convenience wrapper |

### `thermal` - Thermal Simulation

| Type | Description |
|------|-------------|
| `ThermalModifier` | Heat diffusion SDF modifier |
| `ThermalConfig` | Conductivity, melt/freeze thresholds |
| `HeatSource` | Point/area heat source |

**Effects:** Melt (surface recedes), thermal expansion, freeze (crystalline growth)

### `pressure` - Pressure Simulation

| Type | Description |
|------|-------------|
| `PressureModifier` | Contact-force-driven deformation |
| `PressureConfig` | Yield threshold, elastic spring-back |

**Effects:** Crush (high pressure), bulge (internal pressure), permanent dents

### `erosion` - Erosion Simulation

| Type | Description |
|------|-------------|
| `ErosionModifier` | Surface material removal from forces |
| `ErosionConfig` | Hardness, erosion rate |
| `ErosionType` | Wind, Water, Chemical, Ablation |

### `fracture` - Fracture Simulation

| Type | Description |
|------|-------------|
| `FractureModifier` | Stress-driven crack propagation |
| `FractureConfig` | Fracture toughness, crack speed |
| `Crack` | Individual crack with position and direction |

**Effects:** Stress accumulation, crack seeds, Voronoi-like fragmentation via CSG subtraction

### `phase_change` - Phase Change Simulation

| Type | Description |
|------|-------------|
| `PhaseChangeModifier` | Temperature-driven state transitions |
| `PhaseChangeConfig` | Melt/boil temperatures, latent heat |
| `Phase` | Solid, Liquid, Gas |

**Effects:** Melting (solid→liquid, flows downward), vaporization (liquid→gas, expands), solidification, condensation

### `box_collider` - Oriented Bounding Box

| Type | Description |
|------|-------------|
| `OrientedBox` | OBB with center, half-extents, and rotation quaternion |

**Features:**
- GJK `Support` trait implementation for collision detection
- Fast world-space AABB computation from OBB
- Corner vertices, volume, surface area, inertia tensor

### `compound` - Compound Shape

| Type | Description |
|------|-------------|
| `CompoundShape` | Multi-shape collider with local transforms |
| `ChildShape` | Individual shape + local offset/rotation |

**Features:**
- Merges child AABBs for broadphase
- Per-child GJK support (transforms direction to child local space)
- Mass properties from children

### `contact_cache` - Persistent Contact Cache

| Type | Description |
|------|-------------|
| `ContactCache` | Frame-persistent contact manifold storage |
| `ContactManifold` | Up to 4 contact points with warm-started lambdas |

**Features:**
- HashMap O(1) manifold lookup by body pair
- Warm starting (carry lambda across frames for stable stacking)
- Automatic manifold pruning at end of frame

### `dynamic_bvh` - Dynamic AABB Tree

| Type | Description |
|------|-------------|
| `DynamicBvh` | Incremental BVH with insert/remove/update |

**Features:**
- O(log n) insert, remove, and update operations
- AVL-style tree balancing (rotation on height imbalance)
- Fat AABBs with margin to reduce update frequency
- AABB query and ray query

### `material` - Material Pair Table

| Type | Description |
|------|-------------|
| `MaterialTable` | Per-pair friction/restitution override table |
| `MaterialProperties` | Friction, restitution, combine rule |
| `CombineRule` | Average, Min, Max, Multiply |

### `debug_render` - Debug Visualization

| Type | Description |
|------|-------------|
| `DebugRenderer` | Wireframe rendering of physics state |
| `DebugLine` | Line segment with color |
| `DebugDrawFlags` | Bitmask for bodies, contacts, joints, BVH, forces |

### `profiling` - Performance Profiling

| Type | Description |
|------|-------------|
| `PhysicsProfiler` | Per-stage timing and statistics |
| `StageTimer` | Individual stage measurement |
| `FrameStats` | Broadphase/narrowphase/solver/total times |

### `interpolation` - Substep Interpolation

| Type | Description |
|------|-------------|
| `WorldSnapshot` | Captured physics state for interpolation |
| `interpolate_snapshots` | NLERP blending between two snapshots |

**Features:**
- Capture position + rotation snapshots
- NLERP quaternion interpolation (faster than SLERP, visually smooth)
- Alpha-based blending for fixed-timestep rendering

### `pipeline` - Metric Aggregation Pipeline

| Type | Description |
|------|-------------|
| `MetricPipeline` | Lock-free ring buffer metric aggregation engine |
| `MetricRegistry` | Named metric registration and lookup |
| `MetricSnapshot` | Point-in-time metric state capture |
| `MetricEvent` | Timestamped metric event with type and value |
| `MetricType` | Counter, Gauge, Histogram metric kinds |
| `RingBuffer` | Fixed-capacity circular buffer for time-series data |

**Features:**
- Lock-free ring buffer for high-throughput metric collection
- Named metric registry with typed metric support
- Snapshot capture for periodic reporting
- Integrates with `sketch` module for probabilistic aggregation

### `sketch` - Probabilistic Sketches

| Type | Description |
|------|-------------|
| `HyperLogLog` | Cardinality estimation with configurable precision |
| `DDSketch` | Distribution-aware quantile sketch (P50/P99/P99.9) |
| `CountMinSketch` | Frequency estimation with configurable width/depth |
| `HeavyHitters` | Top-k frequent item tracking via Count-Min Sketch |
| `FnvHasher` | FNV-1a hash for deterministic, allocation-free hashing |
| `Mergeable` | Trait for sketch merging across distributed workers |

**Size variants:**
- `HyperLogLog10` (1 KB), `HyperLogLog12` (4 KB), `HyperLogLog14` (16 KB), `HyperLogLog16` (64 KB)
- `DDSketch128`, `DDSketch256`, `DDSketch512`
- `CountMinSketch256x4`, `CountMinSketch512x4`, `CountMinSketch1024x8`

### `anomaly` - Streaming Anomaly Detection

| Type | Description |
|------|-------------|
| `MadDetector` | Median Absolute Deviation detector |
| `EwmaDetector` | Exponentially Weighted Moving Average detector |
| `ZScoreDetector` | Standard Z-score detector with running statistics |
| `CompositeDetector` | Combines multiple detectors with voting |
| `StreamingMedian` | O(log n) streaming median via sorted-insert buffer |
| `AnomalyEvent` | Timestamped anomaly report with severity |
| `AnomalyCallback` | Callback trait for anomaly notifications |

**Features:**
- Streaming operation with constant memory per detector
- Composite detector with configurable voting threshold
- Callback-driven anomaly notification

### `privacy` - Local Differential Privacy

| Type | Description |
|------|-------------|
| `LaplaceNoise` | Calibrated Laplace mechanism for numeric queries |
| `Rappor` | RAPPOR protocol for categorical data collection |
| `RandomizedResponse` | Binary randomized response with tunable epsilon |
| `PrivacyBudget` | Epsilon budget tracker with composition accounting |
| `PrivateAggregator` | Privacy-preserving aggregation over multiple queries |
| `XorShift64` | Deterministic PRNG for reproducible noise generation |

**Features:**
- Laplace noise calibrated to sensitivity/epsilon
- RAPPOR with Bloom filter encoding for categorical data
- Composable privacy budget tracking

## SDF Collider (ALICE-SDF Integration)

ALICE-Physics can use [ALICE-SDF](../ALICE-SDF) distance fields as collision shapes. Instead of approximating complex shapes with convex hulls (GJK/EPA), the solver samples the SDF directly — giving mathematically exact surfaces at O(1) cost per query.

### How It Works

```
Body (sphere)                    SdfCollider
  ┌───┐                         ┌──────────────────────┐
  │ ● │──world_to_local(pos)──▶│ SdfField::distance() │─── >0 → no hit (early-out)
  └───┘                         │ SdfField::normal()   │─── ≤0 → contact + resolve
                                │ cached inv_rotation   │
                                │ cached scale_f32      │
                                └──────────────────────┘
```

### Key Optimizations

| Optimization | Description | Benefit |
|-------------|-------------|---------|
| **Early-out** | Call `distance()` (1 eval) first, only compute `normal()` (4 evals) on collision | 80% fewer evals for non-colliding bodies |
| **Cached invariants** | Pre-computed `inv_rotation`, `scale_f32`, `inv_scale_f32` | No per-query recomputation |
| **Rayon parallel** | `par_iter_mut` over bodies with `--features parallel` | Linear speedup with cores |
| **4-eval combined** | Tetrahedral gradient gives distance + normal from 4 evals | 1 eval saved vs naive 1+4 |

### Usage

```rust
use alice_physics::prelude::*;
use alice_physics::sdf_collider::SdfCollider;
use alice_sdf::physics_bridge::CompiledSdfField;
use alice_sdf::prelude::*;

// 1. Create SDF shape in ALICE-SDF
let terrain = SdfNode::plane(0.0, 1.0, 0.0, 0.0)  // ground plane
    .union(SdfNode::sphere(2.0).translate(0.0, -1.5, 0.0));  // hill

let field = CompiledSdfField::new(terrain);

// 2. Create physics world
let mut world = PhysicsWorld::new(PhysicsConfig::default());

// 3. Register SDF as static collider
let collider = SdfCollider::new_static(
    Box::new(field),
    Vec3Fix::ZERO,                    // position
    QuatFix::IDENTITY,                // rotation
);
world.add_sdf_collider(collider);

// 4. Add dynamic bodies — they will collide with the SDF surface
let ball = RigidBody::new_dynamic(
    Vec3Fix::from_int(0, 10, 0),     // start above terrain
    Fix128::ONE,                      // mass
);
world.add_body(ball);

// 5. Simulate — SDF collisions resolved automatically in step()
let dt = Fix128::from_ratio(1, 60);
for _ in 0..300 {
    world.step(dt);
}
```

### SdfCollider API

| Method | Description |
|--------|-------------|
| `SdfCollider::new_static(field, position, rotation)` | Static SDF collider |
| `SdfCollider::new_dynamic(field, position, rotation, body_index)` | Attached to a body |
| `.with_scale(scale)` | Set uniform scale (updates cached invariants) |
| `.update_cache()` | Recompute cached `inv_rotation`, `scale_f32` after manual changes |
| `collide_point_sdf(point, sdf)` | Point vs SDF contact test |
| `collide_sphere_sdf(center, radius, sdf)` | Sphere vs SDF contact test |

### Requirements

Enable the `physics` feature in ALICE-SDF:

```toml
[dependencies]
alice-sdf = { path = "../ALICE-SDF", features = ["physics"] }
```

See the [ALICE-SDF README](../ALICE-SDF/README.md#physics-bridge-alice-physics-integration) for `CompiledSdfField` details.

## Rendering Pipeline Integration (ALICE-SDF v1.4.0+)

ALICE-Physics provides physics state data that drives ALICE-SDF's rendering pipeline destruction uniforms. The physics engine simulates thermal, fracture, erosion, and pressure fields — the application layer samples these fields and uploads them as shader uniforms for real-time visual feedback.

### Architecture

```
ALICE-Physics (CPU)                    ALICE-SDF Shader (GPU)
┌─────────────────────┐                ┌──────────────────────┐
│ ThermalModifier      │──→ sample ──→│ uniform float uShatter│
│ FractureModifier     │──→ sample ──→│ uniform float uEntropy│
│ PressureModifier     │──→ sample ──→│ uniform float uImpact │
│ ErosionModifier      │──→ sample ──→│ uniform vec2 uShake   │
│ ForceField::Explosion│──→ sample ──→│ uniform float uMeteorY│
└─────────────────────┘                └──────────────────────┘
         ↓ Application layer bridges the gap (each frame)
```

### Uniform Mapping

| Physics Source | Field / Method | Rendering Uniform | Description |
|---------------|---------------|-------------------|-------------|
| `ThermalModifier` | `temperature.sample(pos)` | `uShatter` | Temperature above melt threshold → destruction intensity |
| `ThermalModifier` | `melt_accumulator.sample(pos)` | `uEntropy` | Cumulative material loss (0-1) |
| `FractureModifier` | `stress_field.sample(pos)` | `uShatter` | Stress-driven crack propagation |
| `PressureModifier` | `pressure_field.sample(pos)` | `uImpact` | Contact force deformation depth |
| `ForceField::Explosion` | `center`, `radius` | `uMeteorImpact`, `uImpactRing` | Explosion center and blast radius |
| Impact event | collision velocity | `uShake` | Camera shake from impact force |
| Projectile body | `body.position.y` | `uMeteorY` | Falling object altitude |

### Example: Physics-Driven Destruction

```rust
use alice_physics::{PhysicsWorld, ThermalModifier, ThermalConfig, HeatSource};
use alice_sdf::compiled::glsl::RenderConfig;

// Physics side: thermal simulation
let mut thermal = ThermalModifier::new(ThermalConfig {
    melt_temperature: 800.0,
    melt_rate: 0.01,
    droop_strength: 0.5,
    ..Default::default()
});
thermal.add_heat_source(HeatSource::point(impact_pos, 2000.0));

// Each frame:
thermal.step(&mut world, dt);

// Application bridge: sample physics → upload to shader
let shatter = thermal.melt_accumulator.sample(surface_pos).min(1.0);
let entropy = thermal.temperature.sample(surface_pos) / 1000.0;
gl.uniform1f(u_shatter_loc, shatter);
gl.uniform1f(u_entropy_loc, entropy.min(1.0));
```

### Relevant Modules

| Module | Description | Drives Uniform |
|--------|-------------|----------------|
| `thermal.rs` | Heat diffusion, melt, thermal expansion, freeze | `uShatter`, `uEntropy` |
| `fracture.rs` | Stress-driven crack propagation (CSG subtraction) | `uShatter` |
| `pressure.rs` | Contact force → crush/bulge/dent deformation | `uImpact` |
| `erosion.rs` | Wind, water, chemical, ablation erosion | `uEntropy` |
| `sdf_destruction.rs` | Real-time CSG boolean destruction | `uImpactRing` |
| `force.rs` | Explosion force field (center, radius, falloff) | `uMeteorImpact`, `uImpactRing` |
| `sim_field.rs` | 3D scalar/vector field with trilinear interpolation | All (infrastructure) |

### RenderConfig Compatibility

Enable `destruction: true` in ALICE-SDF's `RenderConfig` to activate the shader-side destruction features:

```rust
let config = RenderConfig {
    destruction: true,       // Voronoi cracking, debris, shockwave visuals
    spectral_rendering: true, // Blackbody radiation for heated surfaces
    vfx_effects: true,       // Domain warp for melting surfaces
    ..Default::default()
};
```

## Deterministic Neural Controller (ALICE-ML Integration)

ALICE-Physics integrates with [ALICE-ML](../ALICE-ML) to provide **bit-exact deterministic AI** for game characters. By combining 1.58-bit ternary weights {-1, 0, +1} with 128-bit fixed-point arithmetic, neural inference reduces to pure addition/subtraction — the inference path is integer-only (`Fix128` mat-vec, no IEEE 754 rounding, no platform-dependent behavior).
<!-- claim-test: test_fix128_ternary_matvec_manual -->

This is the "holy grail" for networked fighting games and action games: all clients compute identical AI behavior without synchronization.

### How It Works

```
Ternary Weight {-1, 0, +1}:
  +1 → Fix128 addition
  -1 → Fix128 subtraction
   0 → skip (free sparsity)

Result: Zero floating-point multiplication in the entire inference pipeline.
```

### Ragdoll Controller Example

```rust
use alice_physics::prelude::*;
use alice_ml::{TernaryWeight, quantize_to_ternary};

// 1. Quantize pre-trained weights to ternary
let (w1, _) = quantize_to_ternary(&trained_weights_l1, hidden_size, input_size);
let (w2, _) = quantize_to_ternary(&trained_weights_l2, output_size, hidden_size);

// 2. Convert to fixed-point (one-time)
let ftw1 = FixedTernaryWeight::from_ternary_weight(w1);
let ftw2 = FixedTernaryWeight::from_ternary_weight(w2);

// 3. Build deterministic network
let network = DeterministicNetwork::new(
    vec![ftw1, ftw2],
    vec![Activation::ReLU, Activation::HardTanh],
);

// 4. Create ragdoll controller
let config = ControllerConfig {
    max_torque: Fix128::from_int(100),
    num_joints: 8,    // 8 joints × 3 axes = 24 outputs
    num_bodies: 9,    // 9 body parts × 13 features = 117 inputs
    features_per_body: 13,  // pos(3) + vel(3) + rot(4) + angvel(3)
};
let mut controller = RagdollController::new(network, config);

// 5. In physics loop — deterministic across ALL clients
for frame in 0..3600 {
    let output = controller.compute(&world.bodies);
    for (joint_idx, torque) in output.torques.iter().enumerate() {
        world.bodies[joint_idx].apply_impulse(*torque);
    }
    world.step(dt);
}
```

### Neural Controller API

| Type | Description |
|------|-------------|
| `FixedTernaryWeight` | TernaryWeight wrapper with Fix128 scale |
| `DeterministicNetwork` | Multi-layer network (zero-allocation forward pass) |
| `RagdollController` | Body states → joint torques |
| `ControllerConfig` | max_torque, num_joints, num_bodies |
| `ControllerOutput` | Vec3Fix torque per joint |
| `Activation` | ReLU, HardTanh, TanhApprox, None |

| Function | Description |
|----------|-------------|
| `fix128_ternary_matvec()` | Core kernel — pure add/sub, zero multiplication |
| `fix128_relu()` | max(0, x) via sign-bit comparison |
| `fix128_hard_tanh()` | clamp(x, -1, 1) for bounded output |
| `fix128_tanh_approx()` | Padé rational x(27+x²)/(27+9x²) |
| `fix128_leaky_relu()` | Leaky ReLU with Fix128 alpha |

### Requirements

```toml
[dependencies]
alice-physics = { path = "../ALICE-Physics", features = ["neural"] }
```

## Configuration

```rust
// SolverConfig / PhysicsConfig
let config = PhysicsConfig {
    substeps: 8,       // XPBD substeps per frame (more = stable but slower)
    iterations: 1,     // Solver passes per substep (default 1: Small Steps — raise substeps, not iterations)
    gravity: Vec3Fix::new(
        Fix128::ZERO,
        Fix128::from_int(-10),  // -10 m/s²
        Fix128::ZERO,
    ),
    damping: Fix128::from_ratio(99, 100),  // 0.99 velocity retention
};

// Or use defaults
let config = PhysicsConfig::default();
```

## Performance Characteristics

Measured, not estimated: `cargo bench --bench physics_bench` (criterion, release
profile) on Apple M-series, 2026-09-15, alice-physics 1.2.0. Absolute numbers are
machine-dependent; the algorithmic column is what the implementation actually does.
<!-- perf-measured: 2026-09-15 benches/physics_bench.rs -->

| Operation | Algorithm | Measured |
|-----------|-----------|----------|
| Fix128 add/sub | 128-bit add with carry | < 1 ns |
| Fix128 mul | 3 × 64×64→128 partial products | 1.1 ns |
| Fix128 div | u128 integer quotient + 64-step long division for the fraction | 141 ns |
| Fix128 sqrt | 96-step restoring digit recurrence (exact floor) | 193–354 ns across runs (1.1.0: 9,676 ns, Newton × 64 divisions) |
| Vec3Fix normalize | length via sqrt + 3 div | 618 ns (1.1.0: 10,390 ns) |
| CORDIC sin/cos / atan | 48 fixed iterations | ~1 µs |
| GJK intersection | max 64 iterations | — |
| EPA penetration | max 64 iterations | — |
| BVH build | Morton code sort, O(n log n) | — |
| BVH query / find_pairs | stackless traversal per leaf AABB, O(n log n) expected | 1.1.0 queried the root AABB → O(n²) |
| World step, 10 bodies × 60 steps (default config) | | 398 µs (1.1.0: 5.11 ms) |
| World step, 1000 overlapping spheres (10³ grid, default config: detection in each of 8 substeps) | `thousand_overlapping_spheres_1_step` | first frame 65 ms (2 700 contacts, 57 k broad-phase candidates × 8); frames 2–10 as the bodies separate: 7.7 ms/frame |

External review of 1.1.0 (Linux x86_64) measured 1000 overlapping bodies at
432 ms/frame with frame-level detection; 1.2.0 detects in every substep (a
correctness requirement, see CHANGELOG), so the dense first frame costs more and
the steady state less. Re-run the bench on your target before quoting numbers.

## MSRV Policy

**Minimum Supported Rust Version: 1.85**

ALICE-Physics follows a Serde-style MSRV policy:

- MSRV bumps within the 0.x line are treated as **minor version bumps** (`0.13.x → 0.14.0`), never patch bumps
- MSRV bumps within a stable 1.x line will also be treated as **minor version bumps** (`1.x → 1.(x+1)`), never patch
- The MSRV commitment covers the **latest 3 stable Rust channels** (N-2 policy) — at the time of a release, we support the current stable + previous 2
- `alice-physics` does not require a nightly toolchain
- CI enforces the declared MSRV via a dedicated `msrv` job: `cargo +1.85 check` on the default feature set, the `no_std` build (rlib) and the core native feature set, resolved by `resolver = "3"` (MSRV-aware). 1.0.x–1.1.0 declared 1.70.0; that toolchain could not even parse the lockfile and the `no_std` build needed `core::f32::abs` (1.85), so the claim was corrected in 1.2.0 (minor bump per the policy above)

**Scope of the MSRV guarantee** — the *library* with the default feature set, `no_std` (`--no-default-features`, as rlib) and the core native features (`std`, `simd`, `parallel`, `ffi`, `gpu-solver-bridge`) builds on 1.85. Outside that scope:

| Component | Effective MSRV | Why |
|-----------|----------------|-----|
| `neural` / `replay` / `analytics` bridge features | follows the sibling crate (`alice-ml` / `alice-db` / `alice-analytics`); 1.87 as of `alice-db 0.2.0-beta.2` → `alice-zip 0.3.0` | sibling crates set their own MSRV |
| Tests / benches (dev-dependencies) | 1.85+ | `criterion`, `serde_derive` |
| `wasm` feature | stable channel recommended | `wasm-bindgen` moves fast |

Downstream crates can rely on `alice-physics` not raising its MSRV within a patch release, preserving their own MSRV window.

## Building

**Note on `--all-features`**: `alice-physics` uses `wasm` and `ffi` as mutually exclusive features (they link `wasm-bindgen` and C ABI FFI respectively, which cannot coexist in a single binary). `cargo build --all-features` will fail with a `compile_error!` by design. Build with one or the other.

**Recommended feature combinations:**

| Target | Command |
|--------|---------|
| Native app / game engine host (Unity, UE5, Godot) | `cargo build --features "std,simd,parallel,ffi,gpu-solver-bridge"` |
| Browser (WebGL / WebGPU via wasm-bindgen) | `cargo build --features "std,simd,parallel,wasm,gpu-solver-bridge"` |
| Embedded / no_std | as a dependency: `default-features = false`; standalone: `cargo rustc --lib --no-default-features --crate-type rlib` (the package also declares `cdylib`/`staticlib` for the C ABI, which need `std`) |
| Python bindings | `cargo build --features "std,simd,parallel,python"` |

docs.rs builds with the native feature set (see `[package.metadata.docs.rs]` in `Cargo.toml`).

```bash
# Standard build
cargo build --release

# no_std library build (for embedded/WASM); downstream crates just set default-features = false
cargo rustc --release --lib --no-default-features --crate-type rlib

# C ABI artifacts for Unity / UE5 (target/release/libalice_physics.{so,dylib,a}, alice_physics.dll)
cargo build --release --features ffi

# Run tests
cargo test

# Run all feature combinations
cargo test --features simd
cargo test --features parallel
cargo test --features neural
cargo test --features "simd,parallel"

# Run benchmarks (requires nightly or criterion)
cargo bench
```

## Cargo Features

| Feature | Default | Description |
|---------|---------|-------------|
| `std` | Yes | Standard library support |
| `simd` | No | `*_simd` / `dot_batch_4` API surface + `SIMD_WIDTH`. **Scalar-equivalent as of 1.2.0**: SSE2/AVX2 have no 128-bit multiply and cannot carry lo→hi, so no intrinsic path is faster than the scalar ADC chain; kept for a future AVX-512 / NEON batch path |
| `parallel` | No | Constraint batching with Rayon (graph-colored parallel solving) |
| `neural` | No | Deterministic neural controller via ALICE-ML ternary inference |
| `python` | No | Python bindings (PyO3 + NumPy zero-copy) |
| `replay` | No | Replay recording/playback via ALICE-DB |
| `ffi` | No | C FFI for Unity, Unreal Engine, and other game engines |
| `wasm` | No | WebAssembly bindings via wasm-bindgen |
| `analytics` | No | Simulation profiling via ALICE-Analytics |

> **Note:** `wasm` and `ffi` are mutually exclusive — enabling both causes a compile error.

```bash
# Enable SIMD optimizations
cargo build --release --features simd

# Enable parallel constraint solving
cargo build --release --features parallel

# Enable both
cargo build --release --features "simd,parallel"

# Enable neural controller (requires ALICE-ML)
cargo build --release --features neural

# Build C shared library for game engines
cargo build --release --features ffi
```

## Tested Feature Combinations

All feature combinations are tested in CI across macOS, Ubuntu, and Windows:

| Combination | Status | Tests |
|-------------|--------|-------|
| `--no-default-features` (no_std) | ✅ | 9 |
| `--features std` (default) | ✅ | 1695 unit + 72 integration + 13 analytic + 105 engineering + 13 default-config oracles + 44 determinism + 21 doc |
| `--features simd` | ✅ | 20 |
| `--features parallel` | ✅ | 20 |
| `--features "simd,parallel"` | ✅ | 20 |
| `--features ffi` | ✅ | build + cdylib/staticlib artifact check |
| `--features python` | ✅ | 1 |
| `--features replay` | ✅ | build only |
| `--features analytics` | ✅ | build only |
| `--features neural` | ✅ | build only |
| `--features wasm` | ✅ | build only |

Feature compatibility matrix:

| | std | simd | parallel | neural | python | ffi | wasm | replay | analytics |
|---|---|---|---|---|---|---|---|---|---|
| **std** | - | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| **simd** | ✅ | - | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| **parallel** | ✅ | ✅ | - | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ |
| **wasm** | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | - | ❌ | ❌ |

## Game Engine Integration (C FFI / Unity / UE5)

ALICE-Physics provides a C FFI layer for integration with Unity, Unreal Engine, and any language that can call C functions.

### Building the Shared Library

```bash
# macOS (.dylib)
cargo build --release --features ffi

# Linux (.so)
cargo build --release --features ffi

# Windows (.dll)
cargo build --release --features ffi
```

The output library is in `target/release/` (`libalice_physics.dylib`, `libalice_physics.so`, or `alice_physics.dll`).

### C API

The C header is at `include/alice_physics.h`. All types use `f64` at the FFI boundary and convert to `Fix128` internally.

```c
#include "alice_physics.h"

// Create world
AlicePhysicsWorld* world = alice_physics_world_create();

// Add bodies
AliceVec3 pos = {0.0, 10.0, 0.0};
uint32_t body = alice_physics_body_add_dynamic(world, pos, 1.0);

// Step simulation
alice_physics_world_step(world, 1.0 / 60.0);

// Read back position
AliceVec3 out_pos;
alice_physics_body_get_position(world, body, &out_pos);

// State serialization (rollback netcode)
uint32_t len;
uint8_t* state = alice_physics_state_serialize(world, &len);
alice_physics_state_deserialize(world, state, len);
alice_physics_state_free(state, len);

// Cleanup
alice_physics_world_destroy(world);
```

### Unity C# Bindings

Copy `bindings/AlicePhysics.cs` and the native library to your Unity project:

```
Assets/
  Plugins/
    macOS/    libalice_physics.dylib
    Win64/    alice_physics.dll
    Linux/    libalice_physics.so
  Scripts/
    AlicePhysics.cs
```

```csharp
using AlicePhysics;

var world = new AlicePhysicsWorld();
uint body = world.AddDynamicBody(new Vector3(0, 10, 0), 1.0);
world.Step(1.0 / 60.0);
Vector3 pos = world.GetBodyPosition(body);

// Rollback netcode
byte[] state = world.SerializeState();
world.DeserializeState(state);

world.Dispose();
```

### Unreal Engine 5 Plugin

Copy the `unreal-plugin/` contents to `Plugins/AlicePhysics/` in your UE5 project and place the native library in `ThirdParty/AlicePhysics/lib/<Platform>/`.

The plugin provides `UAlicePhysicsWorldComponent` with full Blueprint support:

- `AddDynamicBody`, `AddStaticBody` — body creation
- `GetBodyPosition`, `GetBodyRotation`, `GetBodyVelocity` — state queries
- `ApplyImpulse`, `ApplyImpulseAt` — force application
- `SerializeState`, `DeserializeState` — rollback netcode
- Automatic coordinate system conversion (UE5 Z-up cm → ALICE Y-up m)

### Release Workflow

Tag a version to trigger automatic cross-platform builds:

```bash
git tag v0.5.0
git push origin v0.5.0
```

GitHub Actions builds for macOS (ARM + Intel), Windows, and Linux, then packages:
- **UE5 Plugin ZIP** — includes native library + plugin source + header
- **Unity Package ZIP** — includes native library + C# bindings + header

## Comparison with Floating-Point Engines

| Aspect | ALICE-Physics | Float Engines |
|--------|---------------|---------------|
| Determinism | Guaranteed | Platform-dependent |
| Precision | 64-bit fraction | 23-bit (f32) / 52-bit (f64) |
| Speed | Slower (2-5x) | Faster |
| Rollback | Trivial | Requires care |
| Embedded | no_std | Requires FPU |
| Range | ±9.2×10^18 | ±3.4×10^38 (f32) |

## Deterministic Netcode

ALICE-Physics includes a frame-based deterministic netcode foundation. Because the engine guarantees bit-exact results, **only player inputs need to be synchronized** — state sync is unnecessary.

### Bandwidth Savings

| Approach | Per-Frame (10 bodies, 2 players) |
|----------|-------------------------------|
| State sync (traditional) | ~1,600 bytes |
| **Input sync (ALICE)** | **~40 bytes** |
| Savings | **97.5%** |

### Core Types

| Type | Description |
|------|-------------|
| `FrameInput` | 20-byte serializable player input (movement, actions, aim) |
| `SimulationChecksum` | XOR rolling hash of physics state (WyHash-style avalanche) |
| `SimulationSnapshot` | Full state capture for rollback |
| `DeterministicSimulation` | PhysicsWorld wrapper with frame counter, checksum history, snapshot ring buffer |
| `InputApplicator` | Trait for game-specific input → physics force mapping |

### Usage

```rust
use alice_physics::prelude::*;

// Both clients create identical simulation
let mut sim = DeterministicSimulation::new(NetcodeConfig::default());

// Add bodies and assign to players
let body0 = sim.add_body(RigidBody::new_dynamic(
    Vec3Fix::from_int(0, 10, 0), Fix128::ONE,
));
sim.assign_player_body(0, body0);

// Each frame: collect inputs, advance, compare checksums
let inputs = vec![
    FrameInput::new(0).with_movement(Vec3Fix::from_int(1, 0, 0)),
    FrameInput::new(1).with_movement(Vec3Fix::from_int(0, 0, -1)),
];
let checksum = sim.advance_frame(&inputs);

// Save snapshot for rollback
sim.save_snapshot();

// Verify remote client's checksum
assert_eq!(sim.verify_checksum(1, checksum), Some(true));
```

## ALICE-Sync Integration (Game Engine Pipeline)

ALICE-Physics integrates with [ALICE-Sync](../ALICE-Sync) for complete multiplayer game networking. Enable `physics` feature in ALICE-Sync:

```toml
[dependencies]
alice-sync = { path = "../ALICE-Sync", features = ["physics"] }
```

### How It Works

```
Player Input ──► InputFrame (i16, 24B) ──► FrameInput (Fix128) ──► PhysicsWorld
                     ALICE-Sync                 bridge                 step()
                                                  │
PhysicsWorld ──► SimulationChecksum ──► WorldHash ──► Desync Verify
                   from_world()           bridge        ALICE-Sync
```

ALICE-Sync's `PhysicsRollbackSession` wraps both `RollbackSession` (input sync) and `DeterministicSimulation` (physics) into a single game loop driver:

1. Submit local input → predict remote inputs
2. Convert InputFrame (i16) → FrameInput (Fix128)
3. Save snapshot → step physics → record checksum
4. On mismatch: auto rollback + re-simulate

### Bandwidth

| Approach | Per-Frame (4 players, 60fps) |
|----------|----------------------------|
| State sync | ~960 KB/s |
| **Input sync (ALICE)** | **5.6 KB/s** |
| Savings | **99.4%** |

See [ALICE-Sync README](../ALICE-Sync/README.md#game-engine-pipeline-alice-physics-bridge) for full API.

## Python Bindings (PyO3 + NumPy Zero-Copy)

Install with:

```bash
pip install maturin
maturin develop --release --features python
```

### Optimization Layers

| Layer | Technique | Effect |
|-------|-----------|--------|
| L1 | GIL Release (`py.allow_threads`) | Parallel physics stepping |
| L2 | Zero-Copy NumPy (`into_pyarray_bound`) | No memcpy for bulk positions/velocities |
| L3 | Batch API (`step_n`, `positions`, `states`) | FFI amortization |
| L4 | Batch Mutation (`add_bodies_batch`, `set_velocities_batch`, `apply_impulses_batch`) | Bulk operations with GIL release |
| L5 | Rust backend (Fix128, XPBD, BVH) | Hardware-speed simulation |

### Python API

```python
import alice_physics

# Basic physics world
world = alice_physics.PhysicsWorld()
body0 = world.add_dynamic_body(0.0, 10.0, 0.0, mass=1.0)
ground = world.add_static_body(0.0, 0.0, 0.0)

# Step with GIL release (other Python threads can run)
world.step(1.0 / 60.0)

# Batch step for training loops
world.step_n(1.0 / 60.0, steps=300)

# Get all positions as NumPy (N, 3) float64 array (zero-copy)
positions = world.positions()  # shape: (N, 3)
velocities = world.velocities()  # shape: (N, 3)

# Deterministic netcode simulation
sim = alice_physics.DeterministicSimulation(player_count=2, fps=60)
body = sim.add_body(0.0, 10.0, 0.0, mass=1.0)
sim.assign_player(0, body)

# Advance with player inputs: (player_id, move_x, move_y, move_z, actions)
checksum = sim.advance_frame([(0, 1.0, 0.0, 0.0, 0), (1, 0.0, 0.0, -1.0, 0)])

# Snapshot for rollback
frame = sim.save_snapshot()
sim.load_snapshot(frame)

# Serialization
state = world.serialize_state()  # NumPy uint8 array
world.deserialize_state(state.tolist())

# Frame input encoding (20 bytes, network-ready)
data = alice_physics.encode_frame_input(player_id=0, move_x=1.0, actions=0x3)
player_id, mx, my, mz, actions, ax, ay, az = alice_physics.decode_frame_input(data)

# === Batch APIs (v0.4.0) ===

import numpy as np

# Batch body creation from (N,4) array [x, y, z, mass]
ids = world.add_bodies_batch(np.array([
    [0.0, 10.0, 0.0, 1.0],
    [5.0, 10.0, 0.0, 2.0],
    [10.0, 10.0, 0.0, 0.5],
]))

# Batch velocity update (N,3) with GIL release
world.set_velocities_batch(np.array([
    [1.0, 0.0, 0.0],
    [0.0, 0.0, -1.0],
    [0.0, 5.0, 0.0],
]))

# Batch impulse (M,4) [body_id, ix, iy, iz] with GIL release
world.apply_impulses_batch(np.array([
    [0.0, 100.0, 0.0, 0.0],
    [2.0, 0.0, 50.0, 0.0],
]))

# Combined state output (N,10) [px,py,pz, vx,vy,vz, qx,qy,qz,qw]
states = world.states()  # shape: (N, 10), zero-copy NumPy
```

## Replay Recording (ALICE-DB Integration)

ALICE-Physics can record and replay simulation trajectories via [ALICE-DB](../ALICE-DB). Enable with `--features replay`.

```toml
[dependencies]
alice-physics = { path = "../ALICE-Physics", features = ["replay"] }
```

### Recording

```rust
use alice_physics::replay::ReplayRecorder;

// Create recorder (path, body_count)
let mut recorder = ReplayRecorder::new("./replay_data", 3)?;

// In game loop: record every frame
for _ in 0..300 {
    world.step(dt);
    recorder.record_frame(&world)?;
}

recorder.flush()?;
recorder.close()?;
```

### Playback

```rust
use alice_physics::replay::ReplayPlayer;

let player = ReplayPlayer::open("./replay_data", 3)?;

// Random access: get position at any frame
let pos = player.get_position(frame, body_id)?;
// Returns Option<(f32, f32, f32)>

// Range query: scan positions over frame range
let trajectory = player.scan_positions(0, 299, body_id)?;
// Returns Vec<(u64, f32, f32, f32)>

player.close()?;
```

### Storage Format

Each body stores 6 channels (pos_x/y/z, vel_x/y/z) in ALICE-DB. ALICE-DB's model-based compression automatically fits trajectories:
- Constant velocity → linear model (2 coefficients)
- Projectile motion → quadratic model (3 coefficients)
- Complex motion → Fourier model

## Test Results

```
v0.4.0 Test Summary:
  - 358 unit tests across 63 modules
  - 62 integration tests (end-to-end physics scenarios)
  - 12 doc tests (runnable examples)
  - Total: 432 passing tests (435 with --features parallel)
  - Clippy: 0 warnings
  - CI: Format + Clippy + Test (macOS/Ubuntu/Windows)
  - All feature combinations pass (default, parallel, simd, no_std)
```

## Cross-Crate Bridges

ALICE-Physics connects to other ALICE ecosystem crates via feature-gated bridge modules:

| Bridge | Feature | Target Crate | Description |
|--------|---------|--------------|-------------|
| Physics Visualization | `view` | [ALICE-View](../ALICE-View) | Real-time physics debug overlay rendering |
| GPU Physics Controller | `trt` | [ALICE-TRT](../ALICE-TRT) | GPU ternary inference for physics control policies |
| Physics State Streaming | `asp` | [ALICE-Streaming-Protocol](../ALICE-Streaming-Protocol) | Physics body state delta encoding as ASP D-packets |
| `db_bridge` | `replay` | [ALICE-DB](../ALICE-DB) | Physics state snapshot persistence (energy, bodies, contacts) |
| `analytics_bridge` | `analytics` | [ALICE-Analytics](../ALICE-Analytics) | Simulation profiling (step time, collision pairs, energy drift) |

### Recent Performance Improvements

| Module | Change | Impact |
|--------|--------|--------|
| `fluid.rs` | Buffer reuse in neighbor queries | ~99% allocation reduction in SPH simulation |
| `animation_blend.rs` | `clone_from()` replaces `clone()` | Eliminates 60 allocs/sec during blend |

### Cargo Profile

Standardized `[profile.bench]` added for consistent benchmarking across ALICE crates.

## Complete API Reference

### Core Types

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `math` | `Fix128` | 128-bit fixed-point number (I64F64) |
| `math` | `Vec3Fix` | 3D vector with Fix128 components |
| `math` | `QuatFix` | Quaternion for rotations |
| `math` | `Mat3Fix` | 3x3 matrix for inertia tensors |
| `math` | `SIMD_WIDTH` | Compile-time SIMD lane count (AVX2=8, NEON=4, scalar=1) |
| `math` | `simd_width()` | Returns SIMD width at compile time |
| `math` | `select_fix128()` | Branchless conditional select |
| `math` | `select_vec3()` | Branchless Vec3 conditional select |

### Collision Detection

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `collider` | `AABB` | Axis-Aligned Bounding Box |
| `collider` | `Sphere` | Sphere collider |
| `collider` | `Capsule` | Capsule (cylinder + hemispheres) |
| `collider` | `ConvexHull` | Arbitrary convex polyhedron |
| `collider` | `ScaledShape` | Uniform scale wrapper for any Support shape |
| `collider` | `CollisionResult` | Contact point, normal, depth |
| `collider` | `Support` trait | GJK support function interface |
| `box_collider` | `OrientedBox` | OBB with center, half-extents, rotation |
| `compound` | `CompoundShape` | Multi-shape compound collider |
| `compound` | `ShapeRef` | Shape reference within compound |
| `cylinder` | `Cylinder` | Cylinder collider with GJK support |
| `filter` | `CollisionFilter` | Layer/mask bitmask collision groups |

### Solver & Dynamics

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `solver` | `PhysicsWorld` | Main simulation world |
| `solver` | `PhysicsConfig` | Substeps, iterations, gravity, damping |
| `solver` | `RigidBody` | Dynamic/static/sensor rigid body |
| `solver` | `BodyType` | Dynamic, Static, Kinematic |
| `solver` | `DistanceConstraint` | Fixed distance between anchor points |
| `solver` | `ContactConstraint` | Collision response with friction/restitution |
| `solver` | `ContactModifier` | Trait for custom contact modification (std) |
| `joint` | `BallJoint` | Spherical joint (3 rotational DOF) |
| `joint` | `HingeJoint` | Revolute joint with angle limits |
| `joint` | `FixedJoint` | Weld joint (0 DOF) |
| `joint` | `SliderJoint` | Prismatic joint with limits |
| `joint` | `SpringJoint` | Damped spring constraint |
| `joint` | `D6Joint` | 6-DOF configurable joint |
| `joint` | `ConeTwistJoint` | Cone swing + twist limit joint |
| `joint` | `solve_joints_breakable()` | Solve with break-force support |
| `motor` | `PdController` | 1D proportional-derivative controller |
| `motor` | `JointMotor` | Joint motor (position/velocity/torque modes) |
| `force` | `ForceField` | Wind, gravity well, drag, buoyancy, vortex |
| `force` | `ForceFieldInstance` | Active force field in simulation |
| `material` | `MaterialTable` | Per-pair friction/restitution override |
| `material` | `PhysicsMaterial` | Material properties |
| `material` | `CombineRule` | Average, Min, Max, Multiply |

### Spatial Acceleration

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `bvh` | `LinearBvh` | Flat array BVH with stackless traversal |
| `bvh` | `BvhNode` | 32-byte cache-aligned node |
| `bvh` | `BvhPrimitive` | Primitive entry for BVH construction |
| `dynamic_bvh` | `DynamicAabbTree` | Incremental BVH with O(log n) insert/remove |
| `spatial` | `SpatialGrid` | Hash grid for neighbor queries |

### Queries

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `raycast` | `Ray` | Ray origin + direction |
| `raycast` | `RayHit` | Hit result (t, normal, index) |
| `raycast` | `ray_sphere()`, `ray_aabb()`, `ray_capsule()`, `ray_plane()` | Shape-specific ray tests |
| `raycast` | `raycast_all_spheres()`, `raycast_all_aabbs()` | Batch raycasts |
| `query` | `sphere_cast()` | Sweep sphere along direction |
| `query` | `capsule_cast()` | Sweep capsule along direction |
| `query` | `overlap_sphere()` | Find bodies in sphere |
| `query` | `overlap_aabb()` | Find bodies in AABB |
| `query` | `batch_raycast()`, `batch_sphere_cast()` | Batch queries |
| `ccd` | `sphere_sphere_toi()` | Time of impact (sphere-sphere) |
| `ccd` | `conservative_advancement()` | Iterative safe stepping TOI |
| `ccd` | `speculative_contact()` | Speculative CCD contacts |

### Soft Body & Simulation

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `rope` | `Rope` | XPBD distance-chain rope |
| `rope` | `RopeConfig` | Segment count, stiffness, damping |
| `cloth` | `Cloth` | XPBD triangle mesh cloth |
| `cloth` | `ClothConfig` | Stiffness, self-collision, gravity |
| `fluid` | `Fluid` | Position-Based Fluids (PBF) |
| `fluid` | `FluidConfig` | Rest density, viscosity, kernel radius |
| `deformable` | `DeformableBody` | FEM tetrahedral mesh |
| `deformable` | `DeformableConfig` | Young's modulus, Poisson's ratio |
| `vehicle` | `Vehicle` | Vehicle simulation |
| `vehicle` | `VehicleConfig` | Wheels, suspension, engine, steering |
| `character` | `CharacterController` | Kinematic capsule move-and-slide |
| `character` | `CharacterConfig` | Radius, height, max slope, step height |

### SDF Integration

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `sdf_collider` | `SdfCollider` | SDF as collision shape |
| `sdf_collider` | `SdfField` trait | Distance + normal evaluation interface |
| `sdf_collider` | `ClosureSdf` | Closure-based SDF implementation |
| `sdf_manifold` | `SdfManifold` | Multi-point contact from SDF surface |
| `sdf_manifold` | `ManifoldConfig` | Contact point count, spread |
| `sdf_ccd` | `SdfCcdConfig` | Sphere tracing CCD for SDF |
| `sdf_force` | `SdfForceField` | SDF-driven force field |
| `sdf_force` | `SdfForceType` | Attract, Repel, Contain, Flow |
| `sdf_destruction` | `DestructibleSdf` | CSG boolean destruction (std) |
| `sdf_destruction` | `DestructionShape` | Sphere/box subtraction shape |
| `sdf_adaptive` | `AdaptiveSdfEvaluator` | Distance-based LOD evaluation (std) |
| `convex_decompose` | `DecomposeConfig` | Voxel grid decomposition settings (std) |
| `gpu_sdf` | `GpuSdfBatch` | GPU compute SDF batch (std) |
| `gpu_sdf` | `GpuSdfInstancedBatch` | Instanced GPU SDF batch |
| `gpu_sdf` | `GpuSdfMultiDispatch` | Multi-batch GPU dispatch |

### SDF Simulation Modifiers

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `sim_field` | `ScalarField3D` | 3D scalar field with trilinear interpolation (std) |
| `sim_field` | `VectorField3D` | 3D vector field with trilinear interpolation (std) |
| `sim_modifier` | `PhysicsModifier` trait | SDF modifier interface (std) |
| `sim_modifier` | `ModifiedSdf` | Modifier chain (std) |
| `thermal` | `ThermalModifier` | Heat diffusion, melt, freeze (std) |
| `thermal` | `ThermalConfig` | Conductivity, melt/freeze thresholds |
| `pressure` | `PressureModifier` | Contact-force deformation (std) |
| `pressure` | `PressureConfig` | Yield threshold, spring-back |
| `erosion` | `ErosionModifier` | Wind/water/chemical erosion (std) |
| `erosion` | `ErosionType` | Wind, Water, Chemical, Ablation |
| `fracture` | `FractureModifier` | Stress-driven crack propagation (std) |
| `fracture` | `FractureConfig` | Toughness, crack speed |
| `phase_change` | `PhaseChangeModifier` | Solid/liquid/gas transitions (std) |
| `phase_change` | `Phase` | Solid, Liquid, Gas |

### Game Systems

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `animation_blend` | `AnimationBlender` | Ragdoll-to-animation blending |
| `animation_blend` | `BlendMode` | Lerp, Slerp, Additive |
| `animation_blend` | `SkeletonPose` | Joint transforms for skeleton |
| `audio_physics` | `AudioGenerator` | Physics-based audio parameters |
| `audio_physics` | `AudioEvent` | Impact, friction, rolling events |
| `audio_physics` | `AudioMaterial` | Surface material with audio properties |
| `netcode` | `DeterministicSimulation` | PhysicsWorld + frame counter + checksum |
| `netcode` | `FrameInput` | 20-byte serializable player input |
| `netcode` | `SimulationChecksum` | XOR rolling hash of physics state |
| `netcode` | `SimulationSnapshot` | Full state capture for rollback |
| `netcode` | `InputApplicator` trait | Game-specific input → force mapping |
| `fluid_netcode` | `FluidSnapshot` | Deterministic fluid state (std) |
| `fluid_netcode` | `FluidDelta` | Delta-compressed fluid update (std) |

### Analytics & Privacy

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `sketch` | `HyperLogLog` | Cardinality estimation (std) |
| `sketch` | `DDSketch` | Quantile sketch (P50/P99/P99.9) (std) |
| `sketch` | `CountMinSketch` | Frequency estimation (std) |
| `sketch` | `HeavyHitters` | Top-k frequent items (std) |
| `sketch` | `FnvHasher` | FNV-1a deterministic hasher (std) |
| `sketch` | `Mergeable` trait | Distributed sketch merging (std) |
| `anomaly` | `MadDetector` | Median Absolute Deviation (std) |
| `anomaly` | `EwmaDetector` | Exponentially Weighted Moving Average (std) |
| `anomaly` | `ZScoreDetector` | Standard Z-score detector (std) |
| `anomaly` | `CompositeDetector` | Multi-detector voting (std) |
| `anomaly` | `StreamingMedian` | O(log n) streaming median (std) |
| `privacy` | `LaplaceNoise` | Calibrated Laplace mechanism (std) |
| `privacy` | `Rappor` | RAPPOR protocol for categorical data (std) |
| `privacy` | `RandomizedResponse` | Binary randomized response (std) |
| `privacy` | `PrivacyBudget` | Epsilon budget tracker (std) |
| `privacy` | `PrivateAggregator` | Privacy-preserving aggregation (std) |
| `privacy` | `XorShift64` | Deterministic PRNG (std) |
| `pipeline` | `MetricPipeline` | Lock-free ring buffer aggregation (std) |
| `pipeline` | `MetricRegistry` | Named metric registration (std) |
| `pipeline` | `MetricEvent` | Timestamped metric event (std) |
| `pipeline` | `MetricType` | Counter, Gauge, Histogram (std) |
| `pipeline` | `RingBuffer` | Fixed-capacity circular buffer (std) |

### Utility

| Module | Type / Function | Description |
|--------|----------------|-------------|
| `rng` | `DeterministicRng` | PCG-XSH-RR 32-bit generator |
| `event` | `EventCollector` | Contact begin/persist/end tracking |
| `event` | `ContactEvent` | Body pair + event type + contact point |
| `sleeping` | `IslandManager` | Union-Find island management |
| `sleeping` | `SleepConfig` | Velocity thresholds, idle frame count |
| `trimesh` | `TriMesh` | BVH-accelerated triangle mesh |
| `trimesh` | `Triangle` | Single triangle (Moller-Trumbore) |
| `heightfield` | `HeightField` | Grid terrain with bilinear interpolation |
| `articulation` | `ArticulatedBody` | Multi-joint chain with FK propagation |
| `articulation` | `FeatherstoneSolver` | O(n) forward dynamics |
| `contact_cache` | `ContactCache` | HashMap O(1) manifold lookup |
| `contact_cache` | `ContactManifold` | Up to 4 contact points |
| `interpolation` | `WorldSnapshot` | Physics state for interpolation |
| `debug_render` | `DebugDrawData` | Wireframe visualization |
| `debug_render` | `DebugDrawFlags` | Bitmask for what to draw |
| `profiling` | `PhysicsProfiler` | Per-stage timing |
| `profiling` | `StepStats` | Broadphase/narrowphase/solver times |
| `error` | `PhysicsError` | Typed physics error enum |

### Feature-Gated Modules

| Module | Feature | Description |
|--------|---------|-------------|
| `neural` | `neural` | Deterministic ternary neural controller (ALICE-ML) |
| `python` | `python` | PyO3 + NumPy zero-copy Python bindings |
| `ffi` | `ffi` | C FFI for Unity/UE5 game engines |
| `wasm` | `wasm` | WebAssembly bindings (wasm-bindgen) |
| `replay` | `replay` | Replay recording/playback via ALICE-DB |
| `db_bridge` | `replay` | Physics state persistence bridge |
| `analytics_bridge` | `analytics` | Simulation profiling bridge (ALICE-Analytics) |

### Python API (PyO3)

| Class / Function | Description |
|-----------------|-------------|
| `PhysicsWorld` | Python wrapper for physics simulation |
| `PhysicsWorld.add_dynamic_body(x, y, z, mass)` | Add dynamic body |
| `PhysicsWorld.add_static_body(x, y, z)` | Add static body |
| `PhysicsWorld.step(dt)` | Step with GIL release |
| `PhysicsWorld.step_n(dt, steps)` | Batch step for training |
| `PhysicsWorld.positions()` | NumPy (N,3) zero-copy |
| `PhysicsWorld.velocities()` | NumPy (N,3) zero-copy |
| `PhysicsWorld.states()` | NumPy (N,10) combined state |
| `PhysicsWorld.add_bodies_batch(array)` | Batch body creation from (N,4) |
| `PhysicsWorld.set_velocities_batch(array)` | Batch velocity update (N,3) |
| `PhysicsWorld.apply_impulses_batch(array)` | Batch impulse (M,4) |
| `PhysicsWorld.serialize_state()` | State to NumPy uint8 |
| `PhysicsWorld.deserialize_state(data)` | Restore from bytes |
| `DeterministicSimulation` | Netcode simulation wrapper |
| `DeterministicSimulation.advance_frame(inputs)` | Advance with player inputs |
| `DeterministicSimulation.save_snapshot()` | Save for rollback |
| `DeterministicSimulation.load_snapshot(frame)` | Restore snapshot |
| `encode_frame_input(...)` | Encode 20-byte input |
| `decode_frame_input(data)` | Decode 20-byte input |

### C FFI API

| Function | Description |
|----------|-------------|
| `alice_physics_world_create()` | Create physics world |
| `alice_physics_world_destroy(world)` | Destroy physics world |
| `alice_physics_world_step(world, dt)` | Step simulation |
| `alice_physics_body_add_dynamic(world, pos, mass)` | Add dynamic body |
| `alice_physics_body_add_static(world, pos)` | Add static body |
| `alice_physics_body_get_position(world, id, out)` | Get body position |
| `alice_physics_body_apply_impulse(world, id, impulse)` | Apply impulse |
| `alice_physics_state_serialize(world, len)` | Serialize state |
| `alice_physics_state_deserialize(world, data, len)` | Deserialize state |
| `alice_physics_state_free(data, len)` | Free serialized buffer |

## License

AGPL-3.0-or-later - See [LICENSE](LICENSE) for details.

AGPL is a strong copyleft: a game or application that links `alice-physics`
(including through the Unity / UE5 bindings) and is distributed or served to
users must be released under the AGPL as well. That is intentional for the open
ecosystem. For commercial use without the AGPL obligations, contact
<sakamoro@alicelaw.net> for a separate license.

Copyright (C) 2024-2026 Moroya Sakamoto

## Acknowledgments

- XPBD: Müller et al., "XPBD: Position-Based Simulation of Compliant Constrained Dynamics"
- GJK/EPA: Ericson, "Real-Time Collision Detection"
- Morton Codes: Morton, "A Computer Oriented Geodetic Data Base"
- CORDIC: Volder, "The CORDIC Trigonometric Computing Technique"