crcbl-phys 0.12.1

Crucible physics: queries, forces, CCD
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
//! Physics world: collider storage, BVH management, and query dispatch.
//!
//! [`PhysicsWorld`] is the main entry point for physics queries during
//! simulation. It stores collider shapes indexed by a generic `ColliderId`,
//! maintains a lazily-rebuilt BVH over their AABBs, and dispatches rays and
//! sweeps to the shape-level intersection functions.

use glam::{DQuat, DVec3};

use crate::broadphase::{Bvh, BvhHit, Ray, Segment};
use crate::collider::{Aabb, BoxCollider, Capsule, LyingCapsule, Sphere};
use crate::components::Transform;
use crate::compound_shape::CompoundShape;
use crate::contact::manifold::gap;
use crate::contact::shape::ContactShape;
use crate::mesh::{MeshScratch, PlacedMesh, TriangleMesh};
use crate::query::{self, OverlapHit, Penetration, ShapeHit, TurnedCapsule};

mod arc_sweep;
mod candidate_sweeps;
mod capsule_sweep;
pub(crate) use capsule_sweep::CapsuleSweepShape;
mod entry;
mod placement;

use entry::{ColliderEntry, PlacedCompound, Primitive};

/// Opaque identifier for a registered collider.
///
/// Created by [`PhysicsWorld::add_sphere`], [`PhysicsWorld::add_box`],
/// [`PhysicsWorld::add_capsule`], [`PhysicsWorld::add_mesh`] or
/// [`PhysicsWorld::add_compound`]. Use it to remove or update the collider.
///
/// This is a *generational* id — a storage slot plus the generation that slot
/// was issued with — for the same reason [`crcbl_ecs::Entity`] is: removing a
/// collider recycles its slot, and a bare index kept across the removal would
/// silently start addressing whatever collider landed there next. A stale id
/// resolves to nothing instead.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ColliderId {
    index: u32,
    generation: u32,
}

impl ColliderId {
    /// The storage slot this id names.
    ///
    /// A small integer to subscript a caller's own per-collider array with,
    /// which is what a hot loop wants where a `HashMap<ColliderId, _>` would
    /// otherwise stand: turning a query result back into "which of my bodies
    /// is this" costs an array index rather than a hash.
    ///
    /// What the number does and does not promise:
    ///
    /// - **Bounded** by the number of slots the world has ever allocated. That
    ///   equals [`PhysicsWorld::len`] only while nothing has been removed —
    ///   afterwards the slot count stays where it was and `len` drops below it,
    ///   so an array sized from `len` is too short.
    /// - **Stable** for as long as the collider lives. Nothing compacts the
    ///   slot array, so a collider keeps its slot however many others are added
    ///   or removed around it.
    /// - **Not dense** once anything has been removed: the freed slot is a hole
    ///   until a later `add` recycles it.
    /// - **Not an identity.** A recycled slot names a different collider, and
    ///   only the generation the id also carries tells the two apart. Comparing
    ///   slots is not comparing colliders; compare the ids themselves.
    #[inline]
    #[must_use]
    pub const fn index(self) -> u32 {
        self.index
    }

    /// Build an id from its parts. Crate-internal: only [`PhysicsWorld`] knows
    /// which generation a slot is currently on.
    #[inline]
    const fn new(index: u32, generation: u32) -> Self {
        Self { index, generation }
    }
}

// ---------------------------------------------------------------------------
// Collider shape storage
// ---------------------------------------------------------------------------

/// `bvh_slot_to_elem` entry for a collider slot with no element in the tree.
const NO_ELEMENT: u32 = u32::MAX;

/// The layer bits a collider starts with: every one, so a query with any
/// non-zero mask sees it and a world that never touches layers behaves as if
/// they did not exist.
pub const ALL_LAYERS: u32 = u32::MAX;

/// Repartition a refit-aged tree once its normalized traversal cost grows this
/// far past the last build or structural-change baseline.
const BROADPHASE_REBUILD_COST_RATIO: f64 = 1.2;

/// Full-tree equivalents of refits between quality scans.
const BROADPHASE_QUALITY_CHECK_REFIT_PASSES: usize = 4;

/// A collider stored in the [`PhysicsWorld`], with an optional trigger flag.
#[derive(Debug, Clone)]
struct ColliderSlot {
    entry: ColliderEntry,
    /// When true, this collider is a trigger (generates overlap events rather
    /// than collision response).
    is_trigger: bool,
    /// The query layers this collider is on; see [`PhysicsWorld::set_layers`].
    layers: u32,
}

/// Which colliders a query may report: one collider left out, and a mask of
/// the layers it looks at.
///
/// A collider passes when it is not [`exclude`](Self::exclude) and its
/// [layers](PhysicsWorld::set_layers) match [`mask`](Self::mask) the way
/// [`layer_match`](Self::layer_match) says: by sharing at least one bit with
/// it (the default), or by lying wholly [`within`](Self::within) it. The solid
/// queries — rays, sweeps and capsule
/// penetrations — also skip triggers, exactly as their unfiltered forms do;
/// the overlap queries report triggers, as theirs do. A filter never makes a
/// query see something its unfiltered form would not.
///
/// The [`Default`] excludes nothing and looks at every layer, which is what
/// every unfiltered query passes: `cast_ray(ray)` is
/// `cast_ray_filtered(ray, QueryFilter::default())`.
///
/// ```
/// use crcbl_phys::{BoxCollider, PhysicsWorld, QueryFilter, Ray};
/// use glam::DVec3;
///
/// const ITEMS: u32 = 1 << 1;
///
/// let mut world = PhysicsWorld::new();
/// let item = world.add_box(BoxCollider::new(DVec3::new(2.0, 0.0, 0.0), DVec3::splat(0.5)));
/// world.set_layers(item, ITEMS);
/// let ray = Ray::new(DVec3::ZERO, DVec3::X);
///
/// // A movement query looks past items; an interaction ray looks only at them.
/// assert!(world.cast_ray_filtered(&ray, QueryFilter::masked(!ITEMS)).is_none());
/// assert_eq!(
///     world.cast_ray_filtered(&ray, QueryFilter::masked(ITEMS)).map(|(id, _)| id),
///     Some(item),
/// );
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryFilter {
    /// A collider to leave out of the answer, or `None`. A stale or invalid id
    /// excludes nothing, which is the same answer as `None`.
    pub exclude: Option<ColliderId>,
    /// The layers the query looks at. A collider on none of them is skipped,
    /// so a mask of `0` sees nothing.
    pub mask: u32,
    /// How a collider's layers must match [`mask`](Self::mask) to be looked
    /// at.
    pub layer_match: LayerMatch,
}

/// How a [`QueryFilter`] holds a collider's layers to its mask.
///
/// Every collider starts on [`ALL_LAYERS`], so under
/// [`Shares`](Self::Shares) a mask of one query-only layer still reports every
/// ordinary collider beside the ones put on it. [`Within`](Self::Within) is the
/// query for those alone — a walker barrier, a concealment volume — without a
/// second, inverted query to subtract.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LayerMatch {
    /// A collider sharing at least one layer with the mask: `layers & mask !=
    /// 0`.
    #[default]
    Shares,
    /// A collider on at least one layer, every one of them in the mask:
    /// `layers & mask != 0 && layers & !mask == 0`. A collider still on
    /// [`ALL_LAYERS`] is within no mask short of every layer.
    Within,
}

impl LayerMatch {
    /// Whether a collider on `layers` matches `mask` this way.
    const fn admits(self, layers: u32, mask: u32) -> bool {
        match self {
            Self::Shares => layers & mask != 0,
            Self::Within => layers & mask != 0 && layers & !mask == 0,
        }
    }
}

impl QueryFilter {
    /// Excludes nothing and looks at every layer: the [`Default`].
    pub const ALL: Self = Self {
        exclude: None,
        mask: ALL_LAYERS,
        layer_match: LayerMatch::Shares,
    };

    /// Every layer, with `exclude` left out — what the `_excluding` queries
    /// pass.
    #[must_use]
    pub const fn excluding(exclude: Option<ColliderId>) -> Self {
        Self {
            exclude,
            mask: ALL_LAYERS,
            layer_match: LayerMatch::Shares,
        }
    }

    /// Only the layers in `mask`, excluding nothing.
    #[must_use]
    pub const fn masked(mask: u32) -> Self {
        Self {
            exclude: None,
            mask,
            layer_match: LayerMatch::Shares,
        }
    }

    /// Only the colliders whose layers all lie in `mask`, excluding nothing:
    /// [`LayerMatch::Within`].
    #[must_use]
    pub const fn within(mask: u32) -> Self {
        Self {
            exclude: None,
            mask,
            layer_match: LayerMatch::Within,
        }
    }

    /// This filter with its mask replaced by `mask`.
    #[must_use]
    pub const fn with_mask(self, mask: u32) -> Self {
        Self { mask, ..self }
    }

    /// This filter with its exclusion replaced by `exclude`.
    #[must_use]
    pub const fn with_exclude(self, exclude: Option<ColliderId>) -> Self {
        Self { exclude, ..self }
    }

    /// This filter with its layer test replaced by `layer_match`.
    #[must_use]
    pub const fn with_layer_match(self, layer_match: LayerMatch) -> Self {
        Self {
            layer_match,
            ..self
        }
    }
}

impl Default for QueryFilter {
    fn default() -> Self {
        Self::ALL
    }
}

/// A [`QueryFilter`] resolved against one world for one query: the excluded
/// id turned into its storage slot, and whether triggers count.
///
/// Every candidate loop asks [`admits`](Self::admits) and nothing else, so
/// what a trigger, an excluded collider and a layer mask mean is one rule
/// shared by every query family, not a copy per loop.
#[derive(Debug, Clone, Copy)]
struct ResolvedFilter {
    /// The storage slot of the excluded collider, if it is live.
    skip: Option<usize>,
    mask: u32,
    layer_match: LayerMatch,
    /// Whether triggers are skipped — true for the solid queries.
    solid: bool,
}

impl ResolvedFilter {
    /// For a ray, sweep or penetration query: triggers are skipped.
    fn solid(colliders: &[Option<ColliderSlot>], generations: &[u32], filter: QueryFilter) -> Self {
        Self::resolve(colliders, generations, filter, true)
    }

    /// For an overlap query: triggers are reported.
    fn overlap(
        colliders: &[Option<ColliderSlot>],
        generations: &[u32],
        filter: QueryFilter,
    ) -> Self {
        Self::resolve(colliders, generations, filter, false)
    }

    fn resolve(
        colliders: &[Option<ColliderSlot>],
        generations: &[u32],
        filter: QueryFilter,
        solid: bool,
    ) -> Self {
        Self {
            skip: filter
                .exclude
                .and_then(|id| slot_of_in(colliders, generations, id)),
            mask: filter.mask,
            layer_match: filter.layer_match,
            solid,
        }
    }

    /// Whether the collider at storage slot `idx` may be reported.
    fn admits(&self, idx: usize, slot: &ColliderSlot) -> bool {
        Some(idx) != self.skip
            && self.layer_match.admits(slot.layers, self.mask)
            && !(self.solid && slot.is_trigger)
    }
}

// ---------------------------------------------------------------------------
// PhysicsWorld
// ---------------------------------------------------------------------------

/// A reading of the broadphase, from [`PhysicsWorld::broadphase_stats`].
///
/// Two kinds of number, read two different ways.
///
/// **The shape, as it is right now:** [`elements`](Self::elements),
/// [`nodes`](Self::nodes), [`depth`](Self::depth) and
/// [`surface_area_cost`](Self::surface_area_cost). These are what let a
/// structural policy (a teleport rule, a rebuild cadence) be argued from
/// measurement — depth is the query-cost bound, node count the footprint
/// including recycled slots, and surface-area cost exposes overlap inside a
/// tree whose depth stayed balanced.
///
/// **The totals, counting up from the moment the world was created and never
/// reset:** [`refits`](Self::refits),
/// [`updates_without_refit`](Self::updates_without_refit) and
/// [`rebuilds`](Self::rebuilds). There is no reset call, deliberately: take a
/// reading either side of a phase and subtract, and the phase's own numbers
/// come out exactly, with no second observer able to zero the counters halfway
/// through somebody else's measurement.
///
/// Taking the reading is itself an event the totals see.
/// [`PhysicsWorld::broadphase_stats`] forces the lazy rebuild, so a reading
/// taken while the tree is dirty reports a `rebuilds` that includes the one it
/// just caused — which is the honest number, since that rebuild happened.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BroadphaseStats {
    /// Live colliders (leaves) in the tree.
    pub elements: usize,
    /// Allocated node slots, including those a `remove` recycled.
    pub nodes: usize,
    /// Longest root-to-leaf path, counted in nodes ([`Bvh::depth`]'s units).
    pub depth: usize,
    /// Sum of every live internal node's half-surface area.
    ///
    /// [`Bvh::surface_area_cost`] is the definition and the reason this catches
    /// refit degradation that [`depth`](Self::depth) cannot. Compare readings
    /// over the same collider set and world scale; the absolute value carries
    /// units squared and is not a portable threshold by itself.
    pub surface_area_cost: f64,
    /// Collider updates ([`PhysicsWorld::set_sphere`] and its siblings) that a
    /// built tree absorbed in place, refitting one root-to-leaf path.
    ///
    /// How far the collider moved does not enter into it. [`Bvh::update_aabb`]
    /// never refuses a new box for being far from the old one — it grows the
    /// ancestors it walks back through — so a body that teleports across the
    /// world is counted here too, and pays for the trip in a looser tree rather
    /// than in a rebuild.
    pub refits: u64,
    /// Collider updates that did not refit, leaving the BVH absent so that the
    /// next query rebuilds it.
    ///
    /// An update refits whenever the id resolves *and* the tree both exists and
    /// still holds an element for that slot, so what lands here is an update
    /// made with no tree to refit: before the first query, or after something
    /// else already dropped the tree.
    ///
    /// Counted per update, not per rebuild — several of these before the next
    /// query cost one rebuild between them. With [`refits`](Self::refits) it
    /// accounts for every `set_*` call that resolved to a live collider; a call
    /// on a stale id is counted by neither.
    pub updates_without_refit: u64,
    /// Full [`Bvh::build`]s performed, whether asked for by
    /// [`PhysicsWorld::rebuild`] or forced by a query finding the tree absent.
    ///
    /// The number that says which of the two a phase's timing actually
    /// measured, and the reason the other two totals are here at all.
    pub rebuilds: u64,
}

/// The running totals [`BroadphaseStats`] hands out.
///
/// Separate from the stats struct because these are the world's own state,
/// while `BroadphaseStats` is a reading of it taken alongside the tree's shape.
#[derive(Debug, Clone, Copy, Default)]
struct BroadphaseCounters {
    refits: u64,
    updates_without_refit: u64,
    rebuilds: u64,
}

/// A spatial world that stores colliders and supports ray/sweep queries.
///
/// Colliders are added with `add_sphere`, `add_box`, `add_capsule` or
/// `add_mesh` and removed with `remove`. The internal BVH is rebuilt lazily — call
/// [`PhysicsWorld::rebuild`] after batch mutations, or it auto-rebuilds on
/// the next query.
///
/// # Queries only: the contact solver never reads this world
///
/// A collider added here directly answers rays, sweeps and overlaps and
/// nothing else. The contact solver in a
/// [`PhysicsSystem`](crate::PhysicsSystem) built
/// [`with_contacts`](crate::PhysicsSystem::with_contacts) pairs bodies through
/// its own broadphase, which holds only the colliders bodies own as a
/// [`ColliderComponent`](crate::ColliderComponent): a body falls straight
/// through a floor registered with `add_box` or `add_mesh` through
/// [`PhysicsSystem::world_mut`](crate::PhysicsSystem::world_mut). Ground that
/// bodies must stand on is a static body carrying the collider, such as a
/// [`ColliderComponent::Mesh`](crate::ColliderComponent::Mesh) for terrain.
pub struct PhysicsWorld {
    /// Dense storage of collider entries.
    colliders: Vec<Option<ColliderSlot>>,
    /// Generation counter per slot, parallel to `colliders`. Bumped when a
    /// slot is freed, so ids issued before the removal stop resolving.
    generations: Vec<u32>,
    /// Free slots for reuse (indices into `colliders`).
    free_slots: Vec<u32>,
    /// Live collider count, so `len` does not scan the slot array.
    live_count: usize,
    /// Lazily-rebuilt BVH. `None` when dirty.
    bvh: Option<Bvh>,
    /// Scale-independent surface-area cost at the last build or structural
    /// change. `None` asks the next query batch to establish a new baseline.
    bvh_quality_baseline: Option<f64>,
    /// Successful leaf refits since the last quality scan.
    refits_since_quality_check: usize,
    /// Refit and rebuild totals, handed out by
    /// [`PhysicsWorld::broadphase_stats`]. Never reset.
    counters: BroadphaseCounters,
    /// Maps collider slot index → BVH element position (`u32::MAX` for slots
    /// with no element). Populated during [`PhysicsWorld::rebuild`]. Used by
    /// update methods for O(log n) refit.
    bvh_slot_to_elem: Vec<u32>,
    /// The buffers an overlap query works in, kept between calls.
    ///
    /// None of them outlives the call, so allocating them per call is a cost a
    /// caller running one query per body per tick pays for nothing. They live
    /// here rather than being passed in because `&mut self` query methods
    /// already take the exclusive borrow that makes one shared set sound —
    /// [`OverlapQueries`] is the shape for callers who cannot, and it asks for
    /// a [`QueryScratch`] of their own instead.
    scratch: QueryScratch,
}

/// The buffers one overlap query works in, owned by whoever runs the query.
///
/// [`OverlapQueries::overlap_sphere_into`] takes `&self`, so it cannot reach
/// the world's own buffers — several threads running queries at once would be
/// writing the same ones. One of these per thread is what replaces them, and it
/// is reused across calls exactly as the world's are: the contents are cleared
/// on entry and mean nothing between calls, so a scratch buffer never changes
/// an answer, only what a query has to allocate to reach it.
#[derive(Debug, Default)]
pub struct QueryScratch {
    /// The BVH descent stack.
    stack: Vec<u32>,
    /// The elements the descent turned up, before the exact shape test.
    candidates: Vec<u32>,
    /// The leaves a ray descent turned up. Separate from `candidates` because
    /// a ray leaf carries the AABB entry distance alongside its element id.
    ray_hits: Vec<BvhHit>,
    /// The collider ids the exact test kept, for a caller mapping them onto
    /// something of its own — [`crate::system::EntityOverlapQueries`] maps them
    /// to entities, which is why this is reachable from that module and from
    /// nowhere outside the crate.
    pub(crate) ids: Vec<ColliderId>,
    /// The sphere overlaps' hits, kept for the same caller and the same
    /// reason as `ids`.
    pub(crate) hits: Vec<(ColliderId, OverlapHit)>,
    /// The buffers a mesh's own tree is descended in, while the world's
    /// candidates are still being walked.
    mesh: MeshScratch,
}

impl QueryScratch {
    /// Empty buffers, which the first query grows.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }
}

/// Read-only overlap queries against a world whose broadphase is already built.
///
/// **The type is the proof, not a comment.** A query needs the BVH to be
/// current, and building it needs `&mut PhysicsWorld` — so
/// [`PhysicsWorld::overlap_queries`] takes that exclusive borrow, builds the
/// tree, and hands back a shared borrow of the world in its place. A caller
/// cannot reach these queries without the tree being current and cannot mutate
/// the world while one is outstanding, which is what makes the query itself
/// `&self` and therefore `Sync`.
///
/// That is the whole point of it: a data-parallel pass over a crowd hands the
/// same view to every chunk and gives each chunk a [`QueryScratch`] of its own.
/// A caller that is not doing that wants
/// [`PhysicsWorld::overlap_sphere_into`], which keeps the scratch itself.
#[derive(Clone, Copy, Debug)]
pub struct OverlapQueries<'a> {
    colliders: &'a [Option<ColliderSlot>],
    generations: &'a [u32],
    bvh: &'a Bvh,
}

impl OverlapQueries<'_> {
    /// [`PhysicsWorld::overlap_sphere_into`] under a shared borrow, working in
    /// `scratch` instead of the world's own buffers.
    ///
    /// `out` is cleared and then filled. The results are identical to the
    /// `&mut self` form's — same tree, same traversal order, same exact tests —
    /// because the two are one implementation and not two that agree;
    /// `crcbl_phys::world::tests::the_shared_view_finds_exactly_what_a_scan_would`
    /// is what checks that implementation against a scan.
    pub fn overlap_sphere_into(
        &self,
        centre: DVec3,
        radius: f64,
        scratch: &mut QueryScratch,
        out: &mut Vec<(ColliderId, OverlapHit)>,
    ) {
        self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, scratch, out);
    }

    /// [`overlap_sphere_into`](Self::overlap_sphere_into) reporting only the
    /// colliders `filter` admits. Triggers are still reported.
    pub fn overlap_sphere_filtered_into(
        &self,
        centre: DVec3,
        radius: f64,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
        out: &mut Vec<(ColliderId, OverlapHit)>,
    ) {
        out.clear();
        overlap_sphere_core(
            self.bvh,
            self.colliders,
            self.generations,
            &Sphere::new(centre, radius),
            filter,
            scratch,
            |id, hit| out.push((id, hit)),
        );
    }

    /// [`overlap_sphere_into`](Self::overlap_sphere_into) naming the colliders
    /// and dropping their hits: the same colliders in the same order, because
    /// it is the same traversal and the same measurement, written into ids.
    ///
    /// **The fast path for a caller that never reads a hit**, and it exists
    /// because one measured it: on 2026-10-05 `crcbl bench --scenario phys`,
    /// which stands in for `apps/horde`'s steering pass, ran its query phase
    /// about a fifth slower answering hits at a crowd of twenty-eight
    /// neighbours a query, and this form gave back most of that — the record
    /// is in `docs/backlog.md`.
    /// The depth is still worked out, because a positive depth is what decides
    /// a hit; the normal, the point and the bigger buffer are what it saves.
    pub fn overlap_sphere_ids_into(
        &self,
        centre: DVec3,
        radius: f64,
        scratch: &mut QueryScratch,
        out: &mut Vec<ColliderId>,
    ) {
        out.clear();
        overlap_sphere_core(
            self.bvh,
            self.colliders,
            self.generations,
            &Sphere::new(centre, radius),
            QueryFilter::ALL,
            scratch,
            |id, _| out.push(id),
        );
    }

    /// [`PhysicsWorld::overlap_aabb`] under a shared borrow, working in
    /// `scratch` and writing into a buffer the caller owns.
    ///
    /// `out` is cleared and then filled, with the same ids in the same tree
    /// order the `&mut self` form produces, because the two are one
    /// implementation and not two that agree.
    pub fn overlap_aabb_into(
        &self,
        aabb: &Aabb,
        scratch: &mut QueryScratch,
        out: &mut Vec<ColliderId>,
    ) {
        self.overlap_aabb_filtered_into(aabb, QueryFilter::ALL, scratch, out);
    }

    /// [`overlap_aabb_into`](Self::overlap_aabb_into) reporting only the
    /// colliders `filter` admits. Triggers are still reported.
    pub fn overlap_aabb_filtered_into(
        &self,
        aabb: &Aabb,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
        out: &mut Vec<ColliderId>,
    ) {
        overlap_aabb_core(
            self.bvh,
            self.colliders,
            self.generations,
            aabb,
            filter,
            scratch,
            out,
        );
    }

    /// [`PhysicsWorld::cast_ray`] under a shared borrow, working in `scratch`
    /// instead of the world's own buffers.
    ///
    /// Triggers are skipped and the closest exact hit wins, exactly as in the
    /// `&mut self` form, because the two are one implementation.
    #[must_use]
    pub fn cast_ray(
        &self,
        ray: &Ray,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.cast_ray_excluding(ray, None, scratch)
    }

    /// [`PhysicsWorld::cast_ray_excluding`] under a shared borrow, working in
    /// `scratch` instead of the world's own buffers.
    ///
    /// This leaves one live collider out of the narrow phase while preserving
    /// the closest hit behind it. The shared and `&mut self` forms call the
    /// same implementation.
    #[must_use]
    pub fn cast_ray_excluding(
        &self,
        ray: &Ray,
        exclude: Option<ColliderId>,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.cast_ray_filtered(ray, QueryFilter::excluding(exclude), scratch)
    }

    /// [`PhysicsWorld::cast_ray_filtered`] under a shared borrow, working in
    /// `scratch` instead of the world's own buffers.
    #[must_use]
    pub fn cast_ray_filtered(
        &self,
        ray: &Ray,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        cast_ray_core(
            self.bvh,
            self.colliders,
            self.generations,
            ray,
            filter,
            scratch,
        )
    }

    /// [`PhysicsWorld::sweep_sphere`] under a shared borrow, working in
    /// `scratch` instead of the world's own buffers.
    #[must_use]
    pub fn sweep_sphere(
        &self,
        segment: &Segment,
        radius: f64,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_sphere_excluding(segment, radius, None, scratch)
    }

    /// [`PhysicsWorld::sweep_sphere_excluding`] under a shared borrow, working
    /// in `scratch` instead of the world's own buffers.
    ///
    /// This is the form a body sweeping its own path needs — see the `&mut
    /// self` method for why the exclusion happens in the narrow phase and not
    /// after the fact. The two forms are one implementation.
    #[must_use]
    pub fn sweep_sphere_excluding(
        &self,
        segment: &Segment,
        radius: f64,
        exclude: Option<ColliderId>,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_sphere_filtered(segment, radius, QueryFilter::excluding(exclude), scratch)
    }

    /// [`PhysicsWorld::sweep_sphere_filtered`] under a shared borrow, working
    /// in `scratch` instead of the world's own buffers.
    #[must_use]
    pub fn sweep_sphere_filtered(
        &self,
        segment: &Segment,
        radius: f64,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        let mut closest = None;
        sweep_sphere_hits(*self, segment, radius, filter, scratch, |id, hit| {
            keep_closest(&mut closest, id, hit);
        });
        closest
    }

    /// [`PhysicsWorld::sweep_capsule`] under a shared borrow, working in
    /// `scratch` instead of the world's own buffers.
    #[must_use]
    pub fn sweep_capsule(
        &self,
        segment: &Segment,
        radius: f64,
        half_height: f64,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_capsule_excluding(segment, radius, half_height, None, scratch)
    }

    /// [`PhysicsWorld::sweep_capsule_excluding`] under a shared borrow, working
    /// in `scratch` instead of the world's own buffers.
    ///
    /// This is the form a character controller needs, and it excludes in the
    /// narrow phase for the reason the sphere form gives. The two forms are one
    /// implementation.
    #[must_use]
    pub fn sweep_capsule_excluding(
        &self,
        segment: &Segment,
        radius: f64,
        half_height: f64,
        exclude: Option<ColliderId>,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_capsule_filtered(
            segment,
            radius,
            half_height,
            QueryFilter::excluding(exclude),
            scratch,
        )
    }

    /// [`PhysicsWorld::sweep_capsule_filtered`] under a shared borrow, working
    /// in `scratch` instead of the world's own buffers.
    #[must_use]
    pub fn sweep_capsule_filtered(
        &self,
        segment: &Segment,
        radius: f64,
        half_height: f64,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, ShapeHit)> {
        let capsule = Capsule::new(segment.start, radius, half_height);
        self.sweep_upright_where(&capsule, segment.end, filter, scratch, |_| true)
    }

    /// [`PhysicsWorld::capsule_penetrations_into`] under a shared borrow,
    /// working in `scratch` instead of the world's own buffers.
    pub fn capsule_penetrations_into(
        &self,
        capsule: &Capsule,
        exclude: Option<ColliderId>,
        scratch: &mut QueryScratch,
        out: &mut Vec<(ColliderId, Penetration)>,
    ) {
        self.capsule_penetrations_filtered_into(
            capsule,
            QueryFilter::excluding(exclude),
            scratch,
            out,
        );
    }

    /// [`PhysicsWorld::capsule_penetrations_filtered_into`] under a shared
    /// borrow, working in `scratch` instead of the world's own buffers.
    pub fn capsule_penetrations_filtered_into(
        &self,
        capsule: &Capsule,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
        out: &mut Vec<(ColliderId, Penetration)>,
    ) {
        capsule_penetrations_core(
            self.bvh,
            self.colliders,
            self.generations,
            capsule,
            filter,
            scratch,
            out,
        );
    }

    /// The push-out normal of every surface an upright `capsule` is inside,
    /// appended to `out`: one per sphere, box or capsule primitive, and one per
    /// **triangle** of a mesh, where
    /// [`capsule_penetrations_filtered_into`](Self::capsule_penetrations_filtered_into)
    /// keeps a collider's deepest. What a character wedged between two faces
    /// of one mesh stands on is both of them. Triggers and the filter's
    /// exclusions are skipped as there.
    pub(crate) fn capsule_contact_normals_into(
        &self,
        capsule: &Capsule,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
        out: &mut Vec<DVec3>,
    ) {
        let filter = ResolvedFilter::solid(self.colliders, self.generations, filter);
        self.bvh
            .traverse_aabb_into(&capsule.aabb(), &mut scratch.stack, &mut scratch.candidates);
        for &element in scratch.candidates.iter() {
            let idx = element as usize;
            let Some(Some(slot)) = self.colliders.get(idx) else {
                continue;
            };
            if !filter.admits(idx, slot) {
                continue;
            }
            for (_, shape) in slot.entry.primitives() {
                let penetration = match shape {
                    Primitive::Sphere(s) => query::capsule_penetration_vs_sphere(capsule, s),
                    Primitive::Box(b) => query::capsule_penetration_vs_box(capsule, b),
                    Primitive::Capsule(c) => {
                        query::capsule_penetration_vs_turned_capsule(capsule, c)
                    }
                    Primitive::Mesh(m) => {
                        m.capsule_contact_normals(capsule, &mut scratch.mesh, out);
                        None
                    }
                };
                out.extend(penetration.map(|penetration| penetration.normal));
            }
        }
    }

    /// [`PhysicsWorld::lying_capsule_blocker`] under a shared borrow, working
    /// in `scratch` instead of the world's own buffers.
    #[must_use]
    pub fn lying_capsule_blocker(
        &self,
        capsule: &LyingCapsule,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
    ) -> Option<ColliderId> {
        lying_capsule_blocker_core(
            self.bvh,
            self.colliders,
            self.generations,
            capsule,
            filter,
            scratch,
        )
    }

    /// What a [`LyingCapsule`] moved by `motion`, without turning, meets first
    /// among the solid colliders `filter` admits, and how far along the motion
    /// it gets: the sweep [`crate::CharacterController::move_lying`] slides
    /// with. Uses the shared oriented-capsule sweep.
    pub(crate) fn sweep_lying_capsule(
        &self,
        capsule: &LyingCapsule,
        motion: DVec3,
        filter: QueryFilter,
        scratch: &mut QueryScratch,
    ) -> Option<(ColliderId, SweptContact)> {
        self.sweep_capsule_shape(
            CapsuleSweepShape::Lying(*capsule),
            motion,
            filter,
            scratch,
            |_| true,
        )
        .map(|(id, hit)| (id, hit.contact))
    }
}

/// The one implementation of "which colliders overlap this sphere, and how".
///
/// Both the `&mut self` form and [`OverlapQueries`] come through here, so there
/// is no second copy of the traversal for the two to disagree in — which
/// matters more than usual, because a caller mixing the two in one pass is
/// exactly what a `par_for` adoption looks like mid-migration. Each hit is
/// handed to `keep`, in order, so the ids-only form
/// ([`OverlapQueries::overlap_sphere_ids_into`]) is this one too, keeping less.
///
/// # Shape-aware: `radius` is expanded by each collider's own shape
///
/// The query sphere is measured against every collider's *shape* (see
/// `query::sphere_overlap_vs_*`), not against its centre. A sphere collider of
/// radius `r_b` is therefore returned iff its centre is within
/// `radius + r_b` of `centre`, which is what makes `apps/horde`'s
/// `separation_query_radius` correct without adding the neighbour's radius to
/// the query. `tests::a_sphere_overlap_is_expanded_by_the_colliders_own_radius`
/// pins the boundary.
///
/// # One hit per collider, the deepest
///
/// A hit is a positive depth: a collider the sphere only touches is not
/// returned (see [`OverlapHit`]). A compound is one entry, its deepest part's
/// hit; of two parts equally deep, the lower — the rule
/// [`capsule_penetrations_core`] keeps. Triggers are reported, and the order
/// is the tree's traversal order, which is a pure function of the world.
///
/// The query is one [`Sphere`] argument rather than a centre and a radius, as
/// the capsule sweep's is one [`Capsule`].
fn overlap_sphere_core(
    bvh: &Bvh,
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    query_sphere: &Sphere,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
    mut keep: impl FnMut(ColliderId, OverlapHit),
) {
    let filter = ResolvedFilter::overlap(colliders, generations, filter);
    let query_aabb = Aabb::from_centre_half(query_sphere.centre, DVec3::splat(query_sphere.radius));

    bvh.traverse_aabb_into(&query_aabb, &mut scratch.stack, &mut scratch.candidates);

    for &element in scratch.candidates.iter() {
        let idx = element as usize;
        let Some(Some(slot)) = colliders.get(idx) else {
            continue;
        };
        if !filter.admits(idx, slot) {
            continue;
        }
        let mut deepest: Option<OverlapHit> = None;
        for (part, shape) in slot.entry.primitives() {
            let hit = match shape {
                Primitive::Sphere(s) => query::sphere_overlap_vs_sphere(query_sphere, s),
                Primitive::Box(b) => query::sphere_overlap_vs_box(query_sphere, b),
                Primitive::Capsule(c) => query::sphere_overlap_vs_turned_capsule(query_sphere, c),
                Primitive::Mesh(m) => m.sphere_overlap(query_sphere, &mut scratch.mesh),
            };
            if let Some(hit) = hit
                && deepest.is_none_or(|deepest| hit.depth > deepest.depth)
            {
                deepest = Some(OverlapHit { part, ..hit });
            }
        }
        if let Some(hit) = deepest {
            keep(id_for_slot_in(generations, element), hit);
        }
    }
}

/// The one implementation of "which colliders meet this AABB".
///
/// A box, turned or not, is refined against the box itself
/// ([`query::aabb_overlaps_box`]), and so is each part of a compound, whose
/// leaf is the bounds of all its parts. A mesh's leaf is the bounds of a
/// whole level, which would meet every query, so a mesh is refined against
/// its triangles, exactly. A sphere and a capsule are broadphase-only: their
/// leaves are their bounds, and a query meeting a corner of those bounds
/// reports them though it misses the round surface. Both
/// [`PhysicsWorld::overlap_aabb`] and [`OverlapQueries::overlap_aabb_into`]
/// come through here.
fn overlap_aabb_core(
    bvh: &Bvh,
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    aabb: &Aabb,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
    out: &mut Vec<ColliderId>,
) {
    let filter = ResolvedFilter::overlap(colliders, generations, filter);
    bvh.traverse_aabb_into(aabb, &mut scratch.stack, &mut scratch.candidates);
    out.clear();
    for &slot in &scratch.candidates {
        let admitted = colliders
            .get(slot as usize)
            .and_then(|s| s.as_ref())
            .filter(|data| filter.admits(slot as usize, data))
            .is_some_and(|data| {
                data.entry.primitives().any(|(_, shape)| match shape {
                    Primitive::Mesh(m) => m.overlaps_aabb(aabb, &mut scratch.mesh),
                    Primitive::Box(b) => query::aabb_overlaps_box(aabb, b),
                    Primitive::Sphere(_) | Primitive::Capsule(_) => true,
                })
            });
        if admitted {
            out.push(id_for_slot_in(generations, slot));
        }
    }
}

/// The one implementation of "what does this ray hit first".
///
/// Both [`PhysicsWorld::cast_ray_filtered`] and
/// [`OverlapQueries::cast_ray_filtered`] come through here — and so do the
/// `cast_ray` and `cast_ray_excluding` forms, which are this with a narrower
/// filter. Triggers are non-solid and are skipped by `closest_hit_core`.
fn cast_ray_core(
    bvh: &Bvh,
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    ray: &Ray,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
) -> Option<(ColliderId, ShapeHit)> {
    // Out of the scratch and back into it, because the descent borrows the
    // stack at the same time and the two are fields of one struct.
    let mut hits = core::mem::take(&mut scratch.ray_hits);
    bvh.traverse_ray_into(ray, &mut scratch.stack, &mut hits);
    let filter = ResolvedFilter::solid(colliders, generations, filter);
    let best = closest_hit_core(
        colliders,
        generations,
        ray,
        &hits,
        filter,
        &mut scratch.mesh,
    );
    scratch.ray_hits = hits;
    best
}

/// The one implementation of "what does this swept sphere hit": every
/// admitted collider it meets, handed to `visit` with its exact hit.
///
/// Both [`PhysicsWorld::sweep_sphere_filtered`] and
/// [`OverlapQueries::sweep_sphere_filtered`] come through here, keeping the
/// closest — and so do the `sweep_sphere` and `sweep_sphere_excluding` forms,
/// which are this with a narrower filter, and
/// [`PhysicsWorld::sweep_sphere_all`], which keeps them all.
///
/// The broadphase query is the swept *volume* and not the centre line; see
/// [`PhysicsWorld::sweep_sphere`] for what that costs and what it fixes.
fn sweep_sphere_hits(
    view: OverlapQueries<'_>,
    segment: &Segment,
    radius: f64,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
    visit: impl FnMut(ColliderId, ShapeHit),
) {
    let filter = ResolvedFilter::solid(view.colliders, view.generations, filter);
    let bounds = swept_bounds(segment, DVec3::splat(radius));
    view.bvh
        .traverse_aabb_into(&bounds, &mut scratch.stack, &mut scratch.candidates);
    swept_hits_core(
        view.colliders,
        view.generations,
        &scratch.candidates,
        filter,
        |_, _, shape| match shape {
            Primitive::Sphere(s) => query::swept_sphere_vs_sphere(segment, radius, s),
            Primitive::Box(b) => query::swept_sphere_vs_box(segment, radius, b),
            Primitive::Capsule(c) => query::swept_sphere_vs_turned_capsule(segment, radius, c),
            Primitive::Mesh(m) => m.sweep(segment, radius, DVec3::ZERO, &mut scratch.mesh),
        },
        visit,
    );
}

/// The one implementation of "what does this swept Y-aligned capsule hit":
/// `capsule` sits at the start of the sweep and its centre travels to `end`,
/// and every admitted collider it meets is handed to `visit` with its exact
/// hit.
///
/// Both [`PhysicsWorld::sweep_capsule_filtered`] and
/// [`OverlapQueries::sweep_capsule_filtered`] come through here, keeping the
/// closest — and so do the `sweep_capsule` and `sweep_capsule_excluding`
/// forms, which are this with a narrower filter, and
/// [`PhysicsWorld::sweep_capsule_all`], which keeps them all. They take a
/// [`Segment`] and a radius the way the sphere sweeps do; the shape is one
/// argument here so that the swept capsule's two dimensions travel together.
///
/// The broadphase query is the swept *volume*, for the reason
/// [`PhysicsWorld::sweep_sphere`] gives: the capsule is `radius` wide and
/// `half_height + radius` tall, so the candidates are everything within that of
/// the path its centre takes.
fn sweep_capsule_hits(
    view: OverlapQueries<'_>,
    capsule: &Capsule,
    end: DVec3,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
    accept: impl Fn(&ShapeHit) -> bool,
    visit: impl FnMut(ColliderId, ShapeHit),
) {
    let Capsule {
        radius,
        half_height,
        ..
    } = *capsule;
    let segment = &Segment::new(capsule.centre, end);
    let filter = ResolvedFilter::solid(view.colliders, view.generations, filter);
    let bounds = swept_bounds(segment, DVec3::new(radius, radius + half_height, radius));
    view.bvh
        .traverse_aabb_into(&bounds, &mut scratch.stack, &mut scratch.candidates);
    swept_hits_core(
        view.colliders,
        view.generations,
        &scratch.candidates,
        filter,
        |_, _, shape| {
            let hit = match shape {
                Primitive::Sphere(s) => {
                    query::swept_capsule_vs_sphere(segment, radius, half_height, s)
                }
                Primitive::Box(b) => query::swept_capsule_vs_box(segment, radius, half_height, b),
                Primitive::Capsule(c) => {
                    query::swept_capsule_vs_turned_capsule(segment, radius, half_height, c)
                }
                Primitive::Mesh(m) => m.sweep_where(
                    segment,
                    radius,
                    DVec3::Y * half_height,
                    &mut scratch.mesh,
                    &accept,
                ),
            }?;
            accept(&hit).then_some(hit)
        },
        visit,
    );
}

/// The one implementation of "what is this capsule inside, and how far out does
/// each one need it pushed".
///
/// Both [`PhysicsWorld::capsule_penetrations_filtered_into`] and
/// [`OverlapQueries::capsule_penetrations_filtered_into`] come through here,
/// and so do the two unfiltered forms.
///
/// Triggers are non-solid and are skipped, and so is the filter's exclusion —
/// a character whose own capsule is registered in the world is inside itself
/// by the whole of its own radius, which is the deepest contact it would ever
/// find. A compound is one entry, its deepest part's push-out; of two parts
/// equally deep, the lower.
fn capsule_penetrations_core(
    bvh: &Bvh,
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    capsule: &Capsule,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
    out: &mut Vec<(ColliderId, Penetration)>,
) {
    out.clear();
    let filter = ResolvedFilter::solid(colliders, generations, filter);
    bvh.traverse_aabb_into(&capsule.aabb(), &mut scratch.stack, &mut scratch.candidates);

    for &element in scratch.candidates.iter() {
        let idx = element as usize;
        let Some(Some(slot)) = colliders.get(idx) else {
            continue;
        };
        if !filter.admits(idx, slot) {
            continue;
        }
        let mut deepest: Option<Penetration> = None;
        for (_, shape) in slot.entry.primitives() {
            let penetration = match shape {
                Primitive::Sphere(s) => query::capsule_penetration_vs_sphere(capsule, s),
                Primitive::Box(b) => query::capsule_penetration_vs_box(capsule, b),
                Primitive::Capsule(c) => query::capsule_penetration_vs_turned_capsule(capsule, c),
                Primitive::Mesh(m) => m.capsule_penetration(capsule, &mut scratch.mesh),
            };
            if let Some(penetration) = penetration
                && deepest.is_none_or(|deepest| penetration.depth > deepest.depth)
            {
                deepest = Some(penetration);
            }
        }
        if let Some(penetration) = deepest {
            out.push((id_for_slot_in(generations, element), penetration));
        }
    }
}

/// The one implementation of "is this lying capsule inside anything solid".
///
/// Both [`PhysicsWorld::lying_capsule_blocker`] and
/// [`OverlapQueries::lying_capsule_blocker`] come through here.
///
/// The parametric shapes are measured by the contact pipeline's own [`gap`],
/// which already takes a capsule at any angle: the lying capsule is its core
/// segment from head to feet, and the query world's shapes are placed as that
/// pipeline places them — a box turned as its collider is, a capsule along
/// `+Y`. A mesh
/// is measured by its own capsule push-out, turned to lie along the core.
/// Either way it is a *penetration* that blocks, as in
/// [`capsule_penetrations_core`]: a shape the capsule only touches does not.
fn lying_capsule_blocker_core(
    bvh: &Bvh,
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    capsule: &LyingCapsule,
    filter: QueryFilter,
    scratch: &mut QueryScratch,
) -> Option<ColliderId> {
    let filter = ResolvedFilter::solid(colliders, generations, filter);
    bvh.traverse_aabb_into(&capsule.aabb(), &mut scratch.stack, &mut scratch.candidates);

    let (head, feet) = (capsule.head, capsule.feet());
    let lying = ContactShape::Capsule {
        a: head,
        b: feet,
        radius: capsule.radius,
    };
    let inside = |target: ContactShape| gap(&lying, &target).0 < 0.0;

    for &element in scratch.candidates.iter() {
        let idx = element as usize;
        let Some(Some(slot)) = colliders.get(idx) else {
            continue;
        };
        if !filter.admits(idx, slot) {
            continue;
        }
        let blocked = slot.entry.primitives().any(|(_, shape)| match shape {
            Primitive::Sphere(s) => inside(ContactShape::Sphere {
                centre: s.centre,
                radius: s.radius,
            }),
            Primitive::Box(b) => inside(query::contact_box(b)),
            Primitive::Capsule(c) => inside(c.contact_shape()),
            Primitive::Mesh(m) => m
                .turned_capsule_penetration(
                    (head + feet) * 0.5,
                    (head - feet) * 0.5,
                    capsule.radius,
                    &mut scratch.mesh,
                )
                .is_some(),
        });
        if blocked {
            return Some(id_for_slot_in(generations, element));
        }
    }
    None
}

/// Where a sweep that reports no contact point met a collider:
/// [`OverlapQueries::sweep_lying_capsule`]'s answer.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct SweptContact {
    /// The share of the motion covered before the contact, in `[0, 1]`.
    pub(crate) t: f64,
    /// Unit normal pointing away from the surface met, toward the swept shape.
    pub(crate) normal: DVec3,
    /// Whether the swept shape began already touching or inside the collider,
    /// as [`ShapeHit::started_inside`] means it; `t` is then zero.
    pub(crate) started_inside: bool,
    /// The part of the collider met, as [`ShapeHit::part`] means it.
    pub(crate) part: usize,
}

impl From<ShapeHit> for SweptContact {
    fn from(hit: ShapeHit) -> Self {
        Self {
            t: hit.t,
            normal: hit.normal,
            started_inside: hit.started_inside,
            part: hit.part,
        }
    }
}

/// The broadphase bounds of a sweep: the box the segment covers, grown by the
/// swept shape's half-extents so the traversal offers the narrow phase every
/// collider the *volume* touches and not only the ones its centre line runs
/// through.
fn swept_bounds(segment: &Segment, half_extents: DVec3) -> Aabb {
    Aabb::new(
        segment.start.min(segment.end) - half_extents,
        segment.start.max(segment.end) + half_extents,
    )
}

/// Given BVH hits (AABB-level), find the closest exact hit using shape-level
/// intersection, over the colliders `filter` admits — which skips triggers.
fn closest_hit_core(
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    ray: &Ray,
    bvh_hits: &[BvhHit],
    filter: ResolvedFilter,
    mesh: &mut MeshScratch,
) -> Option<(ColliderId, ShapeHit)> {
    let mut best: Option<(f64, ColliderId, ShapeHit)> = None;
    for bvh_hit in bvh_hits {
        let idx = bvh_hit.element_id as usize;
        let Some(Some(slot)) = colliders.get(idx) else {
            continue;
        };
        if !filter.admits(idx, slot) {
            continue;
        }
        for (part, shape) in slot.entry.primitives() {
            let hit = match shape {
                Primitive::Sphere(s) => query::ray_vs_sphere(ray, s),
                Primitive::Box(b) => query::ray_vs_box(ray, b),
                Primitive::Capsule(c) => query::ray_vs_turned_capsule(ray, c),
                Primitive::Mesh(m) => m.cast_ray(ray, mesh),
            };
            if let Some(hit) = hit
                && hit.t < best.as_ref().map_or(f64::INFINITY, |&(t, _, _)| t)
            {
                let id = id_for_slot_in(generations, bvh_hit.element_id);
                best = Some((hit.t, id, ShapeHit { part, ..hit }));
            }
        }
    }
    best.map(|(_, id, hit)| (id, hit))
}

/// Given broadphase candidates, hand `visit` every exact swept hit, with
/// `narrow` supplying the shape-level TOI for whichever shape is being swept,
/// over the colliders `filter` admits — which skips triggers.
///
/// The sphere, capsule and lying capsule sweeps share this rather than each
/// carrying a copy: what a trigger, a dead slot, an excluded collider and a
/// layer mask mean is one rule, and a second copy of it is where they would
/// drift. The closest sweeps keep one of the hits it hands over
/// ([`keep_closest`]) and the candidate sweeps keep them all, so the two
/// agree on which hits there are.
///
/// A hit whose `t` is not below infinity — a `NaN` from degenerate input —
/// ranks against nothing, and is no hit.
fn swept_hits_core<H: SweptHit>(
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    candidates: &[u32],
    filter: ResolvedFilter,
    mut narrow: impl FnMut(ColliderId, usize, Primitive<'_>) -> Option<H>,
    mut visit: impl FnMut(ColliderId, H),
) {
    for &element in candidates {
        let idx = element as usize;
        let Some(Some(slot)) = colliders.get(idx) else {
            continue;
        };
        if !filter.admits(idx, slot) {
            continue;
        }
        for (part, shape) in slot.entry.primitives() {
            if let Some(hit) = narrow(id_for_slot_in(generations, element), part, shape)
                && hit.t() < f64::INFINITY
            {
                visit(id_for_slot_in(generations, element), hit.with_part(part));
            }
        }
    }
}

/// [`swept_hits_core`] keeping only the hit that comes first by
/// [`sweep_order`]: the lying capsule sweep's closest hit.
fn closest_swept_core<H: SweptHit>(
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    candidates: &[u32],
    filter: ResolvedFilter,
    mut narrow: impl FnMut(Primitive<'_>) -> Option<H>,
) -> Option<(ColliderId, H)> {
    let mut closest = None;
    swept_hits_core(
        colliders,
        generations,
        candidates,
        filter,
        |_, _, shape| narrow(shape),
        |id, hit| {
            keep_closest(&mut closest, id, hit);
        },
    );
    closest
}

/// Replace `closest` with `(id, hit)` if that comes first by [`sweep_order`].
fn keep_closest<H: SweptHit>(closest: &mut Option<(ColliderId, H)>, id: ColliderId, hit: H) {
    if closest.as_ref().is_none_or(|&(best, best_hit)| {
        sweep_order(
            (id, hit.part_index(), hit.t()),
            (best, best_hit.part_index(), best_hit.t()),
        )
        .is_lt()
    }) {
        *closest = Some((id, hit));
    }
}

/// The order a sweep's hits come in: nearer `t` first, of two at the same
/// `t` the one in the lower storage slot, and of two parts of one compound
/// at the same `t` the lower part.
///
/// The tie needs a rule because the alternative is the order the broadphase
/// happened to offer the candidates in, which follows the tree's shape and so
/// the world's history of adds, refits and rebuilds. A slot index is stable
/// for the collider's whole life. The closest sweeps and the candidate sweeps
/// both rank by this, which is what makes the candidate list's first entry
/// the closest sweep's answer.
fn sweep_order(a: (ColliderId, usize, f64), b: (ColliderId, usize, f64)) -> std::cmp::Ordering {
    if a.2 < b.2 {
        std::cmp::Ordering::Less
    } else if b.2 < a.2 {
        std::cmp::Ordering::Greater
    } else {
        (a.0.index, a.1).cmp(&(b.0.index, b.1))
    }
}

/// What [`closest_swept_core`] ranks a sweep's hits by: how far along the
/// sweep each one is, and which part of its collider it met.
trait SweptHit: Copy {
    fn t(&self) -> f64;
    fn part_index(&self) -> usize;
    /// This hit, on part `part` of its collider.
    #[must_use]
    fn with_part(self, part: usize) -> Self;
}

impl SweptHit for ShapeHit {
    fn t(&self) -> f64 {
        self.t
    }

    fn part_index(&self) -> usize {
        self.part
    }

    fn with_part(self, part: usize) -> Self {
        Self { part, ..self }
    }
}

impl SweptHit for SweptContact {
    fn t(&self) -> f64 {
        self.t
    }

    fn part_index(&self) -> usize {
        self.part
    }

    fn with_part(self, part: usize) -> Self {
        Self { part, ..self }
    }
}

/// Resolve an id to a live storage slot, or `None` if the id is stale
/// (generation mismatch) or names an empty slot.
///
/// The free form of [`PhysicsWorld::slot_of`], which is what
/// `ResolvedFilter` needs: a shared view has the two arrays but not the world.
fn slot_of_in(
    colliders: &[Option<ColliderSlot>],
    generations: &[u32],
    id: ColliderId,
) -> Option<usize> {
    let slot = id.index as usize;
    if generations.get(slot).copied() != Some(id.generation) {
        return None;
    }
    colliders.get(slot).and_then(|s| s.as_ref()).map(|_| slot)
}

/// The id currently naming `slot`. Only call with a slot the BVH just
/// reported, i.e. one that is live.
fn id_for_slot_in(generations: &[u32], slot: u32) -> ColliderId {
    ColliderId::new(slot, generations[slot as usize])
}

impl PhysicsWorld {
    /// Create an empty physics world.
    #[must_use]
    pub fn new() -> Self {
        Self {
            colliders: Vec::new(),
            generations: Vec::new(),
            free_slots: Vec::new(),
            live_count: 0,
            bvh: None,
            bvh_quality_baseline: None,
            refits_since_quality_check: 0,
            counters: BroadphaseCounters::default(),
            bvh_slot_to_elem: Vec::new(),
            scratch: QueryScratch::new(),
        }
    }

    /// Register a sphere collider. Returns a [`ColliderId`] that can be used
    /// to remove or update the collider later.
    ///
    /// # Adding does not cost a rebuild
    ///
    /// Once the BVH exists, a new collider is *inserted* into it
    /// ([`Bvh::insert`]) rather than the tree being dropped and rebuilt on the
    /// next query. A game that spawns and kills colliders every tick — a
    /// bullet per shot, two rocks per split — would otherwise pay `O(n log n)`
    /// per frame for a tree it had already built, and pay it again for the
    /// removal.
    ///
    /// Before the first query there is no tree, and adds simply accumulate: a
    /// world populated in one batch still gets one bulk [`Bvh::build`], which
    /// produces a better tree than the same elements inserted one at a time.
    pub fn add_sphere(&mut self, sphere: Sphere) -> ColliderId {
        self.add(ColliderEntry::Sphere(sphere))
    }

    /// Register a box collider, turned or not: every query answers for the
    /// turned box itself ([`crate::query::ray_vs_box`] and its siblings), and
    /// the broadphase holds the world-axis box around it.
    pub fn add_box(&mut self, box_collider: BoxCollider) -> ColliderId {
        self.add(ColliderEntry::Box(box_collider))
    }

    /// Register a capsule collider, standing up the world's `Y`.
    pub fn add_capsule(&mut self, capsule: Capsule) -> ColliderId {
        self.add(ColliderEntry::Capsule(TurnedCapsule::upright(capsule)))
    }

    /// Register `capsule` turned by `rotation` about its centre, its core
    /// along `rotation * Y`, as the contact pipeline places a body's capsule.
    /// A turn that leaves the core along `Y` answers as
    /// [`add_capsule`](Self::add_capsule) does, to the bit.
    pub(crate) fn add_turned_capsule(&mut self, capsule: Capsule, rotation: DQuat) -> ColliderId {
        self.add(ColliderEntry::Capsule(TurnedCapsule::new(
            capsule, rotation,
        )))
    }

    /// Register a triangle mesh, its vertices in the frame of `transform`.
    ///
    /// It is one entry in this world's tree, and every query that reaches its
    /// bounds descends the mesh's own tree and tests the triangles exactly:
    /// see [`TriangleMesh`]'s module docs. To a query a triangle has two
    /// sides, and a hit's normal faces the side the query came from.
    ///
    /// Queries see the mesh and the contact solver does not, so bodies fall
    /// through it: a mesh they must collide with is a static body's
    /// [`ColliderComponent::Mesh`](crate::ColliderComponent::Mesh). See
    /// [queries only](Self#queries-only-the-contact-solver-never-reads-this-world).
    pub fn add_mesh(&mut self, mesh: TriangleMesh, transform: Transform) -> ColliderId {
        self.add(ColliderEntry::Mesh(PlacedMesh::new(mesh, transform)))
    }

    /// Register a [`CompoundShape`] `offset` from a body at `transform`: its
    /// parts placed as [`crate::ColliderComponent::Compound`] places them,
    /// turned with the body.
    ///
    /// It is one collider — one id, one trigger flag, one set of layers — and
    /// every query answers for its parts themselves, not for the world-axis
    /// box around them that the broadphase holds: a ray down the gap between
    /// two parts passes through. A hit names the part it met in
    /// [`ShapeHit::part`], an index into [`CompoundShape::parts`].
    pub fn add_compound(
        &mut self,
        shape: &CompoundShape,
        offset: DVec3,
        transform: &Transform,
    ) -> ColliderId {
        self.add(ColliderEntry::Compound(PlacedCompound::place(
            Vec::new(),
            shape,
            offset,
            transform,
        )))
    }

    /// Update an existing sphere collider. Returns `true` if the id was valid.
    ///
    /// If the BVH is built, this refits the tree in O(log n). Otherwise the
    /// BVH is simply marked dirty for the next query.
    pub fn set_sphere(&mut self, id: ColliderId, sphere: Sphere) -> bool {
        self.set(id, ColliderEntry::Sphere(sphere))
    }

    /// Update an existing box collider.
    pub fn set_box(&mut self, id: ColliderId, box_collider: BoxCollider) -> bool {
        self.set(id, ColliderEntry::Box(box_collider))
    }

    /// Update an existing capsule collider, standing up the world's `Y`.
    pub fn set_capsule(&mut self, id: ColliderId, capsule: Capsule) -> bool {
        self.set(id, ColliderEntry::Capsule(TurnedCapsule::upright(capsule)))
    }

    /// Update an existing collider to be `capsule` turned by `rotation`, as
    /// [`add_turned_capsule`](Self::add_turned_capsule) places it.
    pub(crate) fn set_turned_capsule(
        &mut self,
        id: ColliderId,
        capsule: Capsule,
        rotation: DQuat,
    ) -> bool {
        self.set(
            id,
            ColliderEntry::Capsule(TurnedCapsule::new(capsule, rotation)),
        )
    }

    /// Update an existing collider to be `mesh` at `transform`.
    pub fn set_mesh(&mut self, id: ColliderId, mesh: TriangleMesh, transform: Transform) -> bool {
        self.set(id, ColliderEntry::Mesh(PlacedMesh::new(mesh, transform)))
    }

    /// Update an existing collider to be `shape` `offset` from a body at
    /// `transform`, as [`add_compound`](Self::add_compound) places it.
    /// Returns `true` if the id was valid.
    ///
    /// A collider that was already a compound lends its parts' buffer to the
    /// new placement, so a moving compound placed every tick reuses one
    /// buffer rather than allocating a new one each time.
    pub fn set_compound(
        &mut self,
        id: ColliderId,
        shape: &CompoundShape,
        offset: DVec3,
        transform: &Transform,
    ) -> bool {
        let Some(slot) = self.slot_of(id) else {
            return false;
        };
        let buffer = match self.colliders[slot].as_mut().map(|s| &mut s.entry) {
            Some(ColliderEntry::Compound(placed)) => placed.take_parts(),
            _ => Vec::new(),
        };
        self.set(
            id,
            ColliderEntry::Compound(PlacedCompound::place(buffer, shape, offset, transform)),
        )
    }

    /// Mark a collider as a trigger.
    ///
    /// A trigger is *non-solid*: [`PhysicsWorld::cast_ray`],
    /// [`PhysicsWorld::sweep_sphere`] and [`PhysicsWorld::sweep_capsule`] pass
    /// straight through it, while
    /// [`PhysicsWorld::overlap_sphere`] and [`PhysicsWorld::overlap_aabb`]
    /// still report it — that is what makes it an overlap-only volume.
    ///
    /// Returns `false` if the id is invalid.
    pub fn set_trigger(&mut self, id: ColliderId, is_trigger: bool) -> bool {
        let Some(slot) = self.slot_of(id) else {
            return false;
        };
        if let Some(slot_data) = self.colliders[slot].as_mut() {
            slot_data.is_trigger = is_trigger;
        }
        true
    }

    /// Whether a collider is a trigger.
    pub fn is_trigger(&self, id: ColliderId) -> bool {
        self.slot_of(id)
            .is_some_and(|slot| self.colliders[slot].as_ref().is_some_and(|s| s.is_trigger))
    }

    /// Put a collider on the query layers in `bits`, replacing whatever it was
    /// on. Returns `false` if the id is invalid.
    ///
    /// A layer is a bit, and a [`QueryFilter`]'s mask is the set of layers a
    /// query looks at: a collider is reported only when `bits & mask != 0`,
    /// or under [`LayerMatch::Within`] only when every bit is in the mask too.
    /// Every collider starts on [`ALL_LAYERS`], so a world that never calls
    /// this answers every query exactly as before. Layers survive
    /// [`set_sphere`](Self::set_sphere) and its siblings, as the trigger flag
    /// does; removing the collider drops them, and a new collider landing in
    /// the recycled slot starts on [`ALL_LAYERS`] again.
    ///
    /// Layers filter **queries** only — the ones on this world and the
    /// character controller's. They do not touch the contact solver, which
    /// never reads this world.
    pub fn set_layers(&mut self, id: ColliderId, bits: u32) -> bool {
        let Some(slot) = self.slot_of(id) else {
            return false;
        };
        if let Some(slot_data) = self.colliders[slot].as_mut() {
            slot_data.layers = bits;
        }
        true
    }

    /// The query layers a collider is on, or `None` if the id is invalid.
    #[must_use]
    pub fn layers(&self, id: ColliderId) -> Option<u32> {
        let slot = self.slot_of(id)?;
        self.colliders[slot].as_ref().map(|s| s.layers)
    }

    /// Remove a collider by its id. Returns `true` if the id was valid.
    ///
    /// The slot is recycled, but its generation is bumped first, so `id` (and
    /// any copy of it) stops resolving even once a new collider lands there.
    ///
    /// If a BVH is built, the element is taken out of it incrementally rather
    /// than the tree being thrown away — see [`PhysicsWorld::add_sphere`] for
    /// why that matters.
    pub fn remove(&mut self, id: ColliderId) -> bool {
        let Some(slot) = self.slot_of(id) else {
            return false;
        };
        self.colliders[slot] = None;
        self.generations[slot] = self.generations[slot].wrapping_add(1);
        self.free_slots.push(slot as u32);
        self.live_count -= 1;

        if let Some(bvh) = self.bvh.as_mut() {
            match self.bvh_slot_to_elem.get(slot).copied() {
                Some(elem) if elem != NO_ELEMENT && bvh.remove(elem as usize) => {
                    self.bvh_slot_to_elem[slot] = NO_ELEMENT;
                    self.bvh_quality_baseline = None;
                    self.refits_since_quality_check = 0;
                }
                // A live collider with no element in a built tree should not
                // happen; if it ever does, the tree no longer describes the
                // collider set and querying it would report a ghost.
                _ => self.invalidate_bvh(),
            }
        }
        true
    }

    /// Rebuild the BVH from the current set of colliders.
    ///
    /// Called automatically on the first query after an invalidation and when
    /// refits make the existing partition sufficiently loose. Explicitly
    /// calling this is only needed when you want to control the timing.
    pub fn rebuild(&mut self) {
        let elements: Vec<_> = self
            .colliders
            .iter()
            .enumerate()
            .filter_map(|(idx, slot)| slot.as_ref().map(|s| (s.entry.aabb(), idx as u32)))
            .collect();
        // Build slot→elem reverse mapping.  `elem_idx` is the element's
        // position in the array handed to `Bvh::build` — its *build order* —
        // which is exactly what `Bvh::update_aabb` is indexed by.
        self.bvh_slot_to_elem = vec![NO_ELEMENT; self.colliders.len()];
        for (elem_idx, (_, slot)) in elements.iter().enumerate() {
            self.bvh_slot_to_elem[*slot as usize] = elem_idx as u32;
        }
        let bvh = Bvh::build(elements);
        self.bvh_quality_baseline = Some(bvh.normalized_surface_area_cost());
        self.refits_since_quality_check = 0;
        self.bvh = Some(bvh);
        self.counters.rebuilds += 1;
    }

    /// Number of colliders currently registered.
    #[must_use]
    pub fn len(&self) -> usize {
        self.live_count
    }

    /// Whether the world has no colliders.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.live_count == 0
    }

    // ── Queries ────────────────────────────────────────────────────────

    /// Every collider whose shape the query sphere is inside, each with how
    /// deep, which way out and where ([`OverlapHit`]).
    ///
    /// Uses the BVH for broadphase culling, then measures the exact overlap
    /// against each shape — sphere, box, capsule, mesh, and each part of a
    /// compound, whose deepest part answers for it. A collider the sphere only
    /// touches is not inside it and is not returned. Triggers are included —
    /// overlap is the query they exist for. A caller that wants only the ids
    /// maps the pairs.
    #[must_use]
    pub fn overlap_sphere(&mut self, centre: DVec3, radius: f64) -> Vec<(ColliderId, OverlapHit)> {
        let mut out = Vec::new();
        self.overlap_sphere_into(centre, radius, &mut out);
        out
    }

    /// [`overlap_sphere`](Self::overlap_sphere) writing into a buffer the
    /// caller owns.
    ///
    /// `out` is cleared and then filled. The intermediate buffers — the BVH
    /// descent stack and its candidate list — are the world's own and are
    /// reused between calls, so a caller that hoists one `out` out of its loop
    /// runs the whole pass without allocating.
    pub fn overlap_sphere_into(
        &mut self,
        centre: DVec3,
        radius: f64,
        out: &mut Vec<(ColliderId, OverlapHit)>,
    ) {
        self.overlap_sphere_filtered_into(centre, radius, QueryFilter::ALL, out);
    }

    /// [`overlap_sphere`](Self::overlap_sphere) reporting only the colliders
    /// `filter` admits. Triggers are still reported.
    #[must_use]
    pub fn overlap_sphere_filtered(
        &mut self,
        centre: DVec3,
        radius: f64,
        filter: QueryFilter,
    ) -> Vec<(ColliderId, OverlapHit)> {
        let mut out = Vec::new();
        self.overlap_sphere_filtered_into(centre, radius, filter, &mut out);
        out
    }

    /// [`overlap_sphere_into`](Self::overlap_sphere_into) reporting only the
    /// colliders `filter` admits. Triggers are still reported.
    pub fn overlap_sphere_filtered_into(
        &mut self,
        centre: DVec3,
        radius: f64,
        filter: QueryFilter,
        out: &mut Vec<(ColliderId, OverlapHit)>,
    ) {
        // Lent to the view and put straight back, which is what lets one
        // implementation serve both borrow shapes: the view cannot reach a
        // field of the world it is only sharing.
        let mut scratch = core::mem::take(&mut self.scratch);
        self.overlap_queries().overlap_sphere_filtered_into(
            centre,
            radius,
            filter,
            &mut scratch,
            out,
        );
        self.scratch = scratch;
    }

    /// Builds the broadphase and hands back a shared view that can query it.
    ///
    /// The exchange this makes is the point: it costs the caller's exclusive
    /// borrow *once*, and buys a [`Sync`] query it can run from several threads
    /// at a time — see [`OverlapQueries`] for why the type is what enforces
    /// that rather than a rule in a comment.
    pub fn overlap_queries(&mut self) -> OverlapQueries<'_> {
        self.overlap_queries_with_scratch().0
    }

    /// [`overlap_queries`](Self::overlap_queries) together with the world's
    /// own query buffers, for a caller in this crate that runs a whole
    /// sequence of queries against one view — a character move — under the
    /// exclusive borrow it already holds, and so needs no buffers of its own.
    pub(crate) fn overlap_queries_with_scratch(
        &mut self,
    ) -> (OverlapQueries<'_>, &mut QueryScratch) {
        self.ensure_bvh();
        let view = OverlapQueries {
            colliders: &self.colliders,
            generations: &self.generations,
            bvh: self.bvh.as_ref().expect("ensure_bvh built it"),
        };
        (view, &mut self.scratch)
    }

    /// Return all collider ids that meet the query AABB.
    ///
    /// A box, turned or not, is reported only where it meets the query itself
    /// ([`crate::aabb_overlaps_box`]), a compound only where one of its parts
    /// does, and a mesh only where one of its triangles does. A sphere or a
    /// capsule is reported wherever the world-axis box around it meets the
    /// query, round surface or not; use [`PhysicsWorld::overlap_sphere`] for an
    /// exact round query. Triggers are included.
    #[must_use]
    pub fn overlap_aabb(&mut self, aabb: &Aabb) -> Vec<ColliderId> {
        self.overlap_aabb_filtered(aabb, QueryFilter::ALL)
    }

    /// [`overlap_aabb`](Self::overlap_aabb) reporting only the colliders
    /// `filter` admits. Triggers are still reported.
    #[must_use]
    pub fn overlap_aabb_filtered(&mut self, aabb: &Aabb, filter: QueryFilter) -> Vec<ColliderId> {
        let mut scratch = core::mem::take(&mut self.scratch);
        let mut out = Vec::new();
        self.overlap_queries()
            .overlap_aabb_filtered_into(aabb, filter, &mut scratch, &mut out);
        self.scratch = scratch;
        out
    }

    /// Cast a ray against all colliders, returning the closest hit (if any).
    ///
    /// Results are tested against the exact shape geometry (not just the AABB).
    /// The returned `ColliderId` is the handle you got from `add_*`.
    ///
    /// Triggers are non-solid and are skipped — use
    /// [`PhysicsWorld::overlap_sphere`] to detect them.
    #[must_use]
    pub fn cast_ray(&mut self, ray: &Ray) -> Option<(ColliderId, ShapeHit)> {
        self.cast_ray_excluding(ray, None)
    }

    /// [`cast_ray`](Self::cast_ray) with one collider left out of the answer.
    ///
    /// A character whose collision capsule is registered in the world can
    /// cast from inside itself. Excluding that capsule in the narrow phase
    /// keeps the wall behind it, which discarding a self-hit afterwards loses.
    ///
    /// A stale or invalid `exclude` excludes nothing, which is the same answer
    /// as `None`. Triggers remain non-solid and are skipped.
    ///
    /// **It matches every layer**: the filter is only
    /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
    /// mask queries through [`cast_ray_filtered`](Self::cast_ray_filtered) with the same
    /// filter, or a query-only layer it ignores elsewhere blocks it here.
    #[must_use]
    pub fn cast_ray_excluding(
        &mut self,
        ray: &Ray,
        exclude: Option<ColliderId>,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.cast_ray_filtered(ray, QueryFilter::excluding(exclude))
    }

    /// [`cast_ray`](Self::cast_ray) over only the colliders `filter` admits:
    /// its exclusion is left out and so is every collider on none of its
    /// mask's layers, in the narrow phase, so the closest hit behind them
    /// survives. Triggers remain non-solid and are skipped.
    #[must_use]
    pub fn cast_ray_filtered(
        &mut self,
        ray: &Ray,
        filter: QueryFilter,
    ) -> Option<(ColliderId, ShapeHit)> {
        let mut scratch = core::mem::take(&mut self.scratch);
        let hit = self
            .overlap_queries()
            .cast_ray_filtered(ray, filter, &mut scratch);
        self.scratch = scratch;
        hit
    }

    /// Sweep a sphere along a segment, returning the closest hit (if any).
    ///
    /// Uses the shape-level swept-sphere TOI functions for exact results.
    /// Triggers are non-solid and are skipped. Of two colliders met at exactly
    /// the same `t`, the one with the lower [`ColliderId::index`] is the
    /// answer. [`sweep_sphere_all`](Self::sweep_sphere_all) reports every hit,
    /// in the same order.
    ///
    /// # The broadphase query is the swept *volume*, not the centre line
    ///
    /// A sphere is `radius` wide, so the colliders it can touch are the ones
    /// within `radius` of the path its centre takes. Traversing the BVH with the
    /// centre line as a ray — which this did — offers the narrow phase only the
    /// colliders that line runs through, and every shape the sphere merely
    /// grazes is dropped before the exact test that would have caught it. The
    /// visible form of that: a ball rolling along a wall never touches it, and a
    /// ball approaching one is reported as hitting only once its centre is level
    /// with the surface, half a diameter inside.
    ///
    /// Traversing the segment's bounds inflated by `radius` offers a superset
    /// instead. The extra candidates cost one exact test each and are rejected
    /// by the same narrow phase as before.
    #[must_use]
    pub fn sweep_sphere(
        &mut self,
        segment: &Segment,
        radius: f64,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_sphere_excluding(segment, radius, None)
    }

    /// [`sweep_sphere`](Self::sweep_sphere) with one collider left out of the
    /// answer.
    ///
    /// This is the query a *body* sweeping its own path needs: the segment ends
    /// where the body is, so the body's own shape is sitting on the far end of
    /// it and is reported as the closest hit at `t = 0`. Excluding it here — and
    /// not by discarding the result afterwards — is what keeps the *next*
    /// closest hit: the narrow phase picks a single winner, so a caller that
    /// throws away a self-hit throws away the wall behind it too.
    ///
    /// A stale or invalid `exclude` excludes nothing, which is the same answer
    /// as `None`.
    ///
    /// # One id, and a mask — not a callback
    ///
    /// The field's general form is a filter the query calls back into — PhysX's
    /// `PxQueryFilterData`/`PxQueryFilterCallback`, Jolt's `BodyFilter`,
    /// Bullet's `ClosestRayResultCallback` and its mask. Every one of them also
    /// ships the degenerate case as its own thing, because it is the case that
    /// actually comes up: Jolt has `IgnoreSingleBodyFilter`, and Bullet's
    /// character controller carries a `ClosestNotMeConvexResultCallback`. That
    /// degenerate case was the whole of what this crate's consumers asked for,
    /// so for a while it was the whole of what this took.
    ///
    /// Then a consumer needed the mask as well. EW keeps its level, its
    /// characters and its dropped items in one world, and an item must not
    /// block a player's or an AI's sweep while an interaction ray still hits
    /// it — "skip everything of this kind", which no single excluded id can
    /// say. So [`QueryFilter`] exists, and carries exactly the two things asked
    /// for: the excluded id, and a layer mask tested against each collider's
    /// [layers](Self::set_layers) — Bullet's group/mask and PhysX's
    /// `PxFilterData` words, cut down to one word. It is still plain data and
    /// not a callback: tested in the narrow phase with no indirection, `Copy`
    /// into a shared [`OverlapQueries`] view, and the same answer on every
    /// thread. This method is [`sweep_sphere_filtered`](Self::sweep_sphere_filtered)
    /// with [`QueryFilter::excluding`].
    ///
    /// **It matches every layer**: the filter is only
    /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
    /// mask queries through [`sweep_sphere_filtered`](Self::sweep_sphere_filtered) with the same
    /// filter, or a query-only layer it ignores elsewhere blocks it here.
    #[must_use]
    pub fn sweep_sphere_excluding(
        &mut self,
        segment: &Segment,
        radius: f64,
        exclude: Option<ColliderId>,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_sphere_filtered(segment, radius, QueryFilter::excluding(exclude))
    }

    /// [`sweep_sphere`](Self::sweep_sphere) over only the colliders `filter`
    /// admits, left out in the narrow phase so the closest hit behind them
    /// survives. Triggers remain non-solid and are skipped.
    #[must_use]
    pub fn sweep_sphere_filtered(
        &mut self,
        segment: &Segment,
        radius: f64,
        filter: QueryFilter,
    ) -> Option<(ColliderId, ShapeHit)> {
        let mut scratch = core::mem::take(&mut self.scratch);
        let hit =
            self.overlap_queries()
                .sweep_sphere_filtered(segment, radius, filter, &mut scratch);
        self.scratch = scratch;
        hit
    }

    /// Sweep a Y-aligned capsule along a segment, returning the closest hit (if
    /// any). `segment` is the path of the capsule's **centre**; `radius` and
    /// `half_height` describe the same capsule [`Capsule`] does.
    ///
    /// This is [`sweep_sphere`](Self::sweep_sphere)'s sibling and shares its
    /// semantics: exact shape-level TOI, triggers skipped, ties to the lower
    /// collider index, and a broadphase query over the swept volume rather
    /// than the centre line. [`sweep_capsule_all`](Self::sweep_capsule_all)
    /// reports every hit, in the same order.
    ///
    /// # Why a character wants this and not the sphere sweep
    ///
    /// A sphere is the wrong probe for anything that stands up. Given a
    /// character's width it is too short, so it rides over a step or a railing
    /// the character's chest should have struck; given the character's height it
    /// is too wide, so it collides with walls the character is clear of and
    /// cannot fit through its own doorway. Neither is tunable away — the two
    /// errors are the same sphere. The capsule is the shape every engine's
    /// character controller uses for exactly that reason.
    #[must_use]
    pub fn sweep_capsule(
        &mut self,
        segment: &Segment,
        radius: f64,
        half_height: f64,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_capsule_excluding(segment, radius, half_height, None)
    }

    /// [`sweep_capsule`](Self::sweep_capsule) with one collider left out of the
    /// answer.
    ///
    /// The same query, and the same reason, as
    /// [`sweep_sphere_excluding`](Self::sweep_sphere_excluding): a character
    /// whose own capsule is registered in the world is sitting on the start of
    /// every segment it sweeps, so it is reported as the closest hit at
    /// `t = 0`. Dropping it in the narrow phase is what keeps the *next*
    /// closest hit — the wall behind it — which a caller discarding a self-hit
    /// afterwards has already thrown away.
    ///
    /// A stale or invalid `exclude` excludes nothing, which is the same answer
    /// as `None`.
    ///
    /// **It matches every layer**: the filter is only
    /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
    /// mask queries through [`sweep_capsule_filtered`](Self::sweep_capsule_filtered) with the same
    /// filter, or a query-only layer it ignores elsewhere blocks it here.
    #[must_use]
    pub fn sweep_capsule_excluding(
        &mut self,
        segment: &Segment,
        radius: f64,
        half_height: f64,
        exclude: Option<ColliderId>,
    ) -> Option<(ColliderId, ShapeHit)> {
        self.sweep_capsule_filtered(
            segment,
            radius,
            half_height,
            QueryFilter::excluding(exclude),
        )
    }

    /// [`sweep_capsule`](Self::sweep_capsule) over only the colliders `filter`
    /// admits, left out in the narrow phase so the closest hit behind them
    /// survives. Triggers remain non-solid and are skipped. This is the sweep
    /// [`CharacterController`](crate::CharacterController) runs, with its
    /// self collider and its query mask.
    #[must_use]
    pub fn sweep_capsule_filtered(
        &mut self,
        segment: &Segment,
        radius: f64,
        half_height: f64,
        filter: QueryFilter,
    ) -> Option<(ColliderId, ShapeHit)> {
        let mut scratch = core::mem::take(&mut self.scratch);
        let hit = self.overlap_queries().sweep_capsule_filtered(
            segment,
            radius,
            half_height,
            filter,
            &mut scratch,
        );
        self.scratch = scratch;
        hit
    }

    /// Every solid collider a Y-aligned capsule is *inside*, with the push-out
    /// each one needs, written into `out` (which is cleared first).
    ///
    /// # A sweep cannot answer this, which is why it is its own query
    ///
    /// [`sweep_capsule`](Self::sweep_capsule) reports a capsule that starts
    /// overlapping as a contact at `t = 0` and stops there: there is no earlier
    /// time to report, and the *depth* is a measurement the time of impact does
    /// not contain. A character that spawned inside the level, or that a moving
    /// platform closed on, has to know how far out to go — see [`Penetration`].
    ///
    /// Triggers are non-solid and are skipped, and so is `exclude`. Nothing
    /// here allocates beyond growing `out`: the broadphase's descent stack and
    /// candidate list are the world's own, so a character resolving its
    /// overlaps every tick costs no allocation.
    ///
    /// **It matches every layer**: the filter is only
    /// [`QueryFilter::excluding`]. A caller whose body and rays use a layer
    /// mask queries through [`capsule_penetrations_filtered_into`](Self::capsule_penetrations_filtered_into) with the same
    /// filter, or a query-only layer it ignores elsewhere blocks it here.
    pub fn capsule_penetrations_into(
        &mut self,
        capsule: &Capsule,
        exclude: Option<ColliderId>,
        out: &mut Vec<(ColliderId, Penetration)>,
    ) {
        self.capsule_penetrations_filtered_into(capsule, QueryFilter::excluding(exclude), out);
    }

    /// [`capsule_penetrations_into`](Self::capsule_penetrations_into) over
    /// only the colliders `filter` admits. Triggers are still skipped.
    pub fn capsule_penetrations_filtered_into(
        &mut self,
        capsule: &Capsule,
        filter: QueryFilter,
        out: &mut Vec<(ColliderId, Penetration)>,
    ) {
        let mut scratch = core::mem::take(&mut self.scratch);
        self.overlap_queries().capsule_penetrations_filtered_into(
            capsule,
            filter,
            &mut scratch,
            out,
        );
        self.scratch = scratch;
    }

    /// A solid collider a [`LyingCapsule`] would be *inside*, or `None` if it
    /// is clear of every one `filter` admits: whether a prone body fits at
    /// that pose.
    ///
    /// Nothing moves — this is the question to ask before letting a body lie
    /// down, or before turning one that already is. A shape the capsule only
    /// touches does not block it, as it is no
    /// [penetration](Self::capsule_penetrations_into): a body lying with its
    /// underside a [`radius`](LyingCapsule::radius) above the floor fits.
    ///
    /// Triggers are non-solid and are skipped, as the penetration query skips
    /// them, and so is the filter's exclusion — which is where a character's
    /// own collider goes. When several colliders block the pose, which one is
    /// named is the first the broadphase offers: the same one for the same
    /// world, and no nearer or deeper than the others.
    #[must_use]
    pub fn lying_capsule_blocker(
        &mut self,
        capsule: &LyingCapsule,
        filter: QueryFilter,
    ) -> Option<ColliderId> {
        let mut scratch = core::mem::take(&mut self.scratch);
        let blocker = self
            .overlap_queries()
            .lying_capsule_blocker(capsule, filter, &mut scratch);
        self.scratch = scratch;
        blocker
    }

    /// [`OverlapQueries::sweep_lying_capsule`] in the world's own buffers.
    ///
    /// Only the world's tests ask it this way: the controller's slide runs
    /// against a view it holds for the whole move.
    #[cfg(test)]
    pub(crate) fn sweep_lying_capsule(
        &mut self,
        capsule: &LyingCapsule,
        motion: DVec3,
        filter: QueryFilter,
    ) -> Option<(ColliderId, SweptContact)> {
        let (view, scratch) = self.overlap_queries_with_scratch();
        view.sweep_lying_capsule(capsule, motion, filter, scratch)
    }

    /// Get the AABB of a collider by id.
    #[must_use]
    pub fn aabb_of(&self, id: ColliderId) -> Option<Aabb> {
        let slot = self.slot_of(id)?;
        self.colliders[slot].as_ref().map(|s| s.entry.aabb())
    }

    /// The broadphase's shape and its refit/rebuild totals, as a reading a
    /// game can measure a policy against.
    ///
    /// **For diagnostics, not for the frame path.** It forces the lazy rebuild
    /// if the tree is dirty, and the two shape diagnostics walk the whole tree
    /// — `O(n)` — so this is what a teleport rule's cost/benefit is argued
    /// from, the way `docs/backlog.md`'s "A consumer cannot see the cost it is
    /// being asked to avoid" asked for, and nothing a hot loop should call.
    ///
    /// The forced rebuild is counted: call this on a dirty tree and the
    /// [`rebuilds`](BroadphaseStats::rebuilds) it returns includes that one.
    /// A caller subtracting two readings to measure a phase therefore sees the
    /// phase it asked about *plus* whatever the first reading itself forced,
    /// which is why the first reading is best taken with the tree already
    /// built.
    #[must_use]
    pub fn broadphase_stats(&mut self) -> BroadphaseStats {
        self.ensure_bvh();
        let bvh = self.bvh.as_ref().expect("ensure_bvh built it");
        BroadphaseStats {
            elements: bvh.len(),
            nodes: bvh.node_count(),
            depth: bvh.depth(),
            surface_area_cost: bvh.surface_area_cost(),
            refits: self.counters.refits,
            updates_without_refit: self.counters.updates_without_refit,
            rebuilds: self.counters.rebuilds,
        }
    }

    // ── Internal helpers ───────────────────────────────────────────────

    /// Resolve an id to a live storage slot, or `None` if the id is stale
    /// (generation mismatch) or names an empty slot.
    fn slot_of(&self, id: ColliderId) -> Option<usize> {
        slot_of_in(&self.colliders, &self.generations, id)
    }

    /// The id currently naming `slot`. Only call with a slot the BVH just
    /// reported, i.e. one that is live.
    fn id_for_slot(&self, slot: u32) -> ColliderId {
        id_for_slot_in(&self.generations, slot)
    }

    fn add(&mut self, entry: ColliderEntry) -> ColliderId {
        let aabb = entry.aabb();
        let slot_data = ColliderSlot {
            entry,
            is_trigger: false,
            layers: ALL_LAYERS,
        };
        let index = if let Some(slot) = self.free_slots.pop() {
            self.colliders[slot as usize] = Some(slot_data);
            slot
        } else {
            let idx = self.colliders.len() as u32;
            self.colliders.push(Some(slot_data));
            self.generations.push(0);
            idx
        };
        self.live_count += 1;

        // A tree that exists absorbs the new collider; one that does not stays
        // absent, so a batch of adds before the first query still costs one
        // bulk build rather than n insertions.
        if let Some(bvh) = self.bvh.as_mut() {
            let elem = bvh.insert(aabb, index);
            if self.bvh_slot_to_elem.len() <= index as usize {
                self.bvh_slot_to_elem.resize(index as usize + 1, NO_ELEMENT);
            }
            self.bvh_slot_to_elem[index as usize] = elem as u32;
            self.bvh_quality_baseline = None;
            self.refits_since_quality_check = 0;
        }
        self.id_for_slot(index)
    }

    /// Drop the BVH so the next query rebuilds it from the collider set.
    fn invalidate_bvh(&mut self) {
        self.bvh = None;
        self.bvh_quality_baseline = None;
        self.refits_since_quality_check = 0;
        self.bvh_slot_to_elem.clear();
    }

    /// Update an existing collider entry, refitting the BVH if built.
    fn set(&mut self, id: ColliderId, entry: ColliderEntry) -> bool {
        let Some(slot) = self.slot_of(id) else {
            return false;
        };
        let new_aabb = entry.aabb();
        if let Some(slot_data) = self.colliders[slot].as_mut() {
            // Only the shape changes: the trigger flag and the layers stay.
            slot_data.entry = entry;
        }

        // Try incremental refit.  A refit that reports failure leaves the tree
        // holding the old bounds, so the BVH must be dropped rather than
        // queried against stale geometry.
        let refit = match self.bvh {
            Some(ref mut bvh) => match self.bvh_slot_to_elem.get(slot).copied() {
                Some(elem) if elem != NO_ELEMENT => bvh.update_aabb(elem as usize, new_aabb),
                _ => false,
            },
            None => false,
        };
        if refit {
            self.counters.refits += 1;
            self.refits_since_quality_check = self.refits_since_quality_check.saturating_add(1);
        } else {
            self.counters.updates_without_refit += 1;
            self.invalidate_bvh();
        }
        true
    }

    fn ensure_bvh(&mut self) {
        if self.bvh.is_none() {
            self.rebuild();
            return;
        }

        let bvh = self.bvh.as_ref().expect("the absent tree returned above");
        if self.bvh_quality_baseline.is_none() {
            self.bvh_quality_baseline = Some(bvh.normalized_surface_area_cost());
            self.refits_since_quality_check = 0;
            return;
        }
        let refits_per_check = self
            .live_count
            .saturating_mul(BROADPHASE_QUALITY_CHECK_REFIT_PASSES)
            .max(1);
        if self.refits_since_quality_check < refits_per_check {
            return;
        }

        let current_cost = bvh.normalized_surface_area_cost();
        self.refits_since_quality_check = 0;
        let baseline = self
            .bvh_quality_baseline
            .expect("the absent baseline returned above");
        if current_cost > baseline * BROADPHASE_REBUILD_COST_RATIO {
            self.rebuild();
        }
    }
}

impl Default for PhysicsWorld {
    fn default() -> Self {
        Self::new()
    }
}

impl std::fmt::Debug for PhysicsWorld {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("PhysicsWorld")
            .field("collider_count", &self.len())
            .field("bvh_cached", &self.bvh.is_some())
            .finish()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    /// The colliders an overlap answered, in its order, without their hits.
    pub(super) fn ids_of(hits: &[(ColliderId, OverlapHit)]) -> Vec<ColliderId> {
        hits.iter().map(|&(id, _)| id).collect()
    }

    #[test]
    fn empty_world_is_empty() {
        let world = PhysicsWorld::new();
        assert!(world.is_empty());
        assert_eq!(world.len(), 0);
    }

    /// **The stats a teleport rule would measure with.** `broadphase_stats`
    /// forces the lazy rebuild and reports the tree's shape: one entry per
    /// live collider, at least one node per leaf, and a depth that exists for
    /// a non-empty tree. The exact node count and depth are the AVL balance's
    /// business — what is pinned is that the observable exists and agrees with
    /// the world's own count.
    #[test]
    fn broadphase_stats_report_the_trees_shape() {
        let mut world = PhysicsWorld::new();
        assert_eq!(
            world.broadphase_stats(),
            BroadphaseStats {
                elements: 0,
                nodes: 0,
                depth: 0,
                surface_area_cost: 0.0,
                refits: 0,
                updates_without_refit: 0,
                rebuilds: 1,
            },
            "an empty world has an empty tree, built by the reading itself"
        );

        for x in 0..16 {
            world.add_sphere(Sphere::new(DVec3::new(f64::from(x), 0.0, 0.0), 0.4));
        }
        let stats = world.broadphase_stats();
        assert_eq!(stats.elements, 16, "every collider is a leaf");
        assert!(
            stats.nodes >= 16,
            "a binary tree holds at least one node per leaf; got {stats:?}"
        );
        assert!(
            stats.depth >= 1,
            "a non-empty tree has a depth; got {stats:?}"
        );
    }

    /// A line of spheres, and the ids naming them.
    ///
    /// One row rather than a lattice: the refit counters are about *when* the
    /// tree is refit rather than about what it answers, so the cheapest fixture
    /// that still gives a real tree with real ancestors to walk back through is
    /// the right one.
    fn line_of_spheres(n: u32) -> (PhysicsWorld, Vec<ColliderId>) {
        let mut world = PhysicsWorld::new();
        let ids = (0..n)
            .map(|x| world.add_sphere(Sphere::new(DVec3::new(f64::from(x), 0.0, 0.0), 0.4)))
            .collect();
        (world, ids)
    }

    /// **A small move is absorbed in place: one refit, nothing invalidated,
    /// nothing rebuilt.**
    ///
    /// The counters exist to answer "did that phase refit or did it rebuild",
    /// and this is the answer they have to give for the case a game actually
    /// runs — a body that walked a fraction of its own radius since last tick.
    #[test]
    fn a_small_update_is_counted_as_a_refit() {
        let (mut world, ids) = line_of_spheres(16);
        let before = world.broadphase_stats();
        assert_eq!(before.rebuilds, 1, "the reading itself built the tree");
        assert_eq!(before.refits, 0, "and nothing has been updated yet");

        assert!(world.set_sphere(ids[7], Sphere::new(DVec3::new(7.05, 0.0, 0.0), 0.4)));

        let after = world.broadphase_stats();
        assert_eq!(
            after.refits,
            before.refits + 1,
            "the update should have refit the tree in place; got {after:?}"
        );
        assert_eq!(
            after.updates_without_refit, before.updates_without_refit,
            "nothing should have been left for a rebuild; got {after:?}"
        );
        assert_eq!(
            after.rebuilds, before.rebuilds,
            "and no rebuild should have happened; got {after:?}"
        );
    }

    /// **A teleport refits too — a tree is never thrown away for a move being
    /// large.**
    ///
    /// [`Bvh::update_aabb`] fails only when the element index names nothing. It
    /// has no notion of the new box escaping the old one, and grows the
    /// ancestors it walks instead. Worth pinning rather than assuming, because
    /// the opposite is the intuitive guess and a `refits` read under it would be
    /// read as a rebuild that never happened. The move is checked to have
    /// *landed* as well, so a refit that counted itself without touching the
    /// tree fails here rather than passing quietly.
    #[test]
    fn a_teleport_refits_rather_than_rebuilding() {
        let (mut world, ids) = line_of_spheres(16);
        let before = world.broadphase_stats();

        assert!(world.set_sphere(ids[7], Sphere::new(DVec3::new(0.0, 900.0, 0.0), 0.4)));

        let after = world.broadphase_stats();
        assert_eq!(
            after.refits,
            before.refits + 1,
            "a teleport is still a refit; got {after:?}"
        );
        assert_eq!(
            after.rebuilds, before.rebuilds,
            "and costs no rebuild; got {after:?}"
        );
        assert_eq!(
            after.updates_without_refit, before.updates_without_refit,
            "and leaves nothing for one; got {after:?}"
        );

        assert_eq!(
            ids_of(&world.overlap_sphere(DVec3::new(0.0, 900.0, 0.0), 0.1)),
            vec![ids[7]],
            "the refit tree must answer at the new place"
        );
        assert!(
            world
                .overlap_sphere(DVec3::new(7.0, 0.0, 0.0), 0.1)
                .is_empty(),
            "and no longer at the old one"
        );
    }

    #[test]
    fn a_spatially_loose_tree_rebuilds_when_the_quality_check_is_due() {
        let (mut world, ids) = line_of_spheres(16);
        let before = world.broadphase_stats();

        for _ in 0..BROADPHASE_QUALITY_CHECK_REFIT_PASSES {
            for (x, &id) in (0_u32..).zip(&ids) {
                let side = if x % 2 == 0 { -1.0 } else { 1.0 };
                let centre = DVec3::new(side * (1_000.0 + f64::from(x)), 0.0, 0.0);
                assert!(world.set_sphere(id, Sphere::new(centre, 0.4)));
            }
            world.overlap_queries();
        }

        let after = world.broadphase_stats();
        assert_eq!(
            after.rebuilds,
            before.rebuilds + 1,
            "the interleaved distant leaves should be repartitioned: {after:?}"
        );
    }

    #[test]
    fn uniform_world_scaling_does_not_look_like_tree_degradation() {
        let mut world = PhysicsWorld::new();
        let ids: Vec<_> = (0..16)
            .map(|x| {
                world.add_box(BoxCollider::new(
                    DVec3::new(f64::from(x), 0.0, 0.0),
                    DVec3::splat(0.4),
                ))
            })
            .collect();
        let before = world.broadphase_stats();

        for _ in 0..BROADPHASE_QUALITY_CHECK_REFIT_PASSES {
            for (x, &id) in (0_u32..).zip(&ids) {
                let scaled =
                    BoxCollider::new(DVec3::new(f64::from(x) * 10.0, 0.0, 0.0), DVec3::splat(4.0));
                assert!(world.set_box(id, scaled));
            }
            world.overlap_queries();
        }

        let after = world.broadphase_stats();
        assert_eq!(
            after.rebuilds, before.rebuilds,
            "scaling preserved the partition and should not rebuild it: {after:?}"
        );
    }

    /// **An update the tree cannot absorb drops it, and the next query pays for
    /// the rebuild.**
    ///
    /// The state that produces it is unreachable through the public API — a
    /// live collider whose built tree holds no element for its slot — so the
    /// test reaches in and builds it. That state is the whole of what
    /// `updates_without_refit` counts while a tree exists, and leaving it
    /// unexercised would leave the invalidation branch guarded by nothing.
    #[test]
    fn an_update_with_no_element_to_refit_invalidates_and_the_next_query_rebuilds() {
        let (mut world, ids) = line_of_spheres(16);
        let before = world.broadphase_stats();
        assert!(world.bvh.is_some(), "the reading built the tree");

        world.bvh_slot_to_elem[ids[3].index() as usize] = NO_ELEMENT;
        assert!(world.set_sphere(ids[3], Sphere::new(DVec3::new(3.0, 40.0, 0.0), 0.4)));
        assert!(
            world.bvh.is_none(),
            "an update that could not refit must drop the tree rather than \
             leave it holding the old bounds"
        );

        let after = world.broadphase_stats();
        assert_eq!(
            after.updates_without_refit,
            before.updates_without_refit + 1,
            "the update should be counted as one that did not refit; got {after:?}"
        );
        assert_eq!(
            after.refits, before.refits,
            "and must not also count as a refit; got {after:?}"
        );
        assert_eq!(
            after.rebuilds,
            before.rebuilds + 1,
            "the reading after it should have rebuilt; got {after:?}"
        );
        assert_eq!(
            after.elements, 16,
            "and rebuilt the whole set; got {after:?}"
        );

        assert_eq!(
            ids_of(&world.overlap_sphere(DVec3::new(3.0, 40.0, 0.0), 0.1)),
            vec![ids[3]],
            "the rebuilt tree must answer at the new place"
        );
    }

    /// **Updates made before there is a tree are counted one by one, and cost
    /// one rebuild between them.**
    ///
    /// The counting rule in one test: the totals only climb, `refits` and
    /// `updates_without_refit` between them account for every `set_*` that
    /// resolved to a live collider, and one that resolved to nothing is counted
    /// by neither.
    #[test]
    fn updates_with_no_tree_yet_are_counted_per_update_not_per_rebuild() {
        let (mut world, ids) = line_of_spheres(16);
        assert!(world.set_sphere(ids[0], Sphere::new(DVec3::new(0.0, 1.0, 0.0), 0.4)));
        assert!(world.set_sphere(ids[1], Sphere::new(DVec3::new(1.0, 1.0, 0.0), 0.4)));

        let stats = world.broadphase_stats();
        assert_eq!(
            stats.updates_without_refit, 2,
            "one per update, with no tree to refit; got {stats:?}"
        );
        assert_eq!(stats.refits, 0, "nothing was refit; got {stats:?}");
        assert_eq!(
            stats.rebuilds, 1,
            "and one rebuild between the two of them; got {stats:?}"
        );

        assert!(world.remove(ids[5]));
        let before = world.broadphase_stats();
        assert!(!world.set_sphere(ids[5], Sphere::new(DVec3::ZERO, 0.4)));
        let after = world.broadphase_stats();
        assert_eq!(
            (after.refits, after.updates_without_refit),
            (before.refits, before.updates_without_refit),
            "a set_* on a stale id is counted by neither; got {after:?}"
        );
    }

    /// **The shared view finds exactly what overlaps, checked against a scan
    /// rather than against the other form.**
    ///
    /// Comparing [`OverlapQueries`] with [`PhysicsWorld::overlap_sphere_into`]
    /// would prove nothing: they are one implementation, and a defect in it
    /// breaks both sides of that comparison equally — measured, not assumed, by
    /// reversing the core's output and watching the comparison stay green. So
    /// the oracle here is an exhaustive scan of every collider in the fixture,
    /// which shares no code with the traversal at all.
    ///
    /// It is a set comparison, because a scan cannot reproduce the tree's
    /// order. The *order* is what a caller reducing over the neighbourhood in
    /// `f64` depends on, and it comes from having one implementation rather than
    /// from this test — which is the reason the two forms were made to share
    /// one, and the reason `apps/horde`'s
    /// `steering_is_bit_identical_however_many_workers_run_it` is where that
    /// property is actually asserted.
    #[test]
    fn the_shared_view_finds_exactly_what_a_scan_would() {
        let mut world = PhysicsWorld::new();
        // A lattice, so a query sphere lands on a neighbourhood rather than on
        // one collider or none, and a descent that pruned a subtree it should
        // not have loses something the scan still finds.
        let mut expected: Vec<(ColliderId, Sphere)> = Vec::new();
        for x in -3..=3 {
            for y in -3..=3 {
                let sphere = Sphere::new(DVec3::new(f64::from(x), f64::from(y), 0.0), 0.4);
                expected.push((world.add_sphere(sphere), sphere));
            }
        }
        // A capsule and a box as well, so every arm of the exact test is
        // exercised rather than only the sphere one.
        let capsule = Capsule::new(DVec3::ZERO, 0.3, 1.0);
        let capsule_id = world.add_capsule(capsule);
        let boxed = BoxCollider::new(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.5));
        let box_id = world.add_box(boxed);

        let centres = [
            DVec3::ZERO,
            DVec3::new(1.2, -0.7, 0.0),
            DVec3::new(-2.5, 2.5, 0.0),
            DVec3::new(50.0, 50.0, 0.0),
        ];
        let mut scratch = QueryScratch::new();
        let mut biggest = 0usize;
        for centre in centres {
            for radius in [0.1, 0.75, 2.0] {
                let probe = Sphere::new(centre, radius);
                // The oracle: every collider, tested directly, with no tree and
                // no traversal between the shapes and the answer.
                let mut scanned: Vec<(ColliderId, OverlapHit)> = expected
                    .iter()
                    .filter_map(|(id, s)| Some((*id, query::sphere_overlap_vs_sphere(&probe, s)?)))
                    .collect();
                if let Some(hit) = query::sphere_overlap_vs_capsule(&probe, &capsule) {
                    scanned.push((capsule_id, hit));
                }
                if let Some(hit) = query::sphere_overlap_vs_aabb(&probe, &boxed.aabb()) {
                    scanned.push((box_id, hit));
                }
                scanned.sort_unstable_by_key(|(id, _)| id.index());

                let mut shared = Vec::new();
                world.overlap_queries().overlap_sphere_into(
                    centre,
                    radius,
                    &mut scratch,
                    &mut shared,
                );
                shared.sort_unstable_by_key(|(id, _)| id.index());

                assert_eq!(scanned, shared, "at {centre} r{radius}");
                biggest = biggest.max(shared.len());
            }
        }
        assert!(
            biggest > 4,
            "the widest query in the fixture found {biggest} colliders, so the \
             comparison above was mostly two empty vectors",
        );
    }

    /// Every probe's answers, from one form or the other, so a whole run
    /// compares in a single `assert_eq!`.
    #[derive(Debug, PartialEq)]
    struct ProbeAnswers {
        rays: Vec<Option<(ColliderId, ShapeHit)>>,
        sweeps: Vec<Option<(ColliderId, ShapeHit)>>,
        excluded_sweeps: Vec<Option<(ColliderId, ShapeHit)>>,
        aabbs: Vec<Vec<ColliderId>>,
    }

    /// The exact ray test for a collider, with no tree and no traversal
    /// between the shape and the answer.
    fn scan_ray_one(ray: &Ray, entry: &ColliderEntry) -> Option<ShapeHit> {
        match entry {
            ColliderEntry::Sphere(s) => query::ray_vs_sphere(ray, s),
            ColliderEntry::Box(b) => query::ray_vs_box(ray, b),
            ColliderEntry::Capsule(c) => query::ray_vs_capsule(ray, &c.capsule),
            ColliderEntry::Mesh(_) | ColliderEntry::Compound(_) => {
                unreachable!("the fixture holds no meshes or compounds")
            }
        }
    }

    /// The exact swept-sphere test for a collider, likewise.
    fn scan_sweep_one(segment: &Segment, radius: f64, entry: &ColliderEntry) -> Option<ShapeHit> {
        match entry {
            ColliderEntry::Sphere(s) => query::swept_sphere_vs_sphere(segment, radius, s),
            ColliderEntry::Box(b) => query::swept_sphere_vs_box(segment, radius, b),
            ColliderEntry::Capsule(c) => {
                query::swept_sphere_vs_capsule(segment, radius, &c.capsule)
            }
            ColliderEntry::Mesh(_) | ColliderEntry::Compound(_) => {
                unreachable!("the fixture holds no meshes or compounds")
            }
        }
    }

    /// **The ray, sweep and AABB queries answer a brute-force scan under a
    /// shared borrow, from every thread asking at once.**
    ///
    /// The companion to `the_shared_view_finds_exactly_what_a_scan_would`, and
    /// it is held to the same standard for the same reason: comparing
    /// [`OverlapQueries::cast_ray`] with [`PhysicsWorld::cast_ray`] proves
    /// nothing on its own, because they are one implementation and a defect in
    /// it moves both sides of that comparison together. So each answer is also
    /// checked against an exhaustive scan of the fixture, which shares no code
    /// with the traversal.
    ///
    /// What the scan can and cannot pin down:
    ///
    /// * For a ray or a sweep the scan gives the closest `t`, and the query's
    ///   own `t` must equal it exactly — same inputs through the same shape
    ///   functions, so this is not a tolerance question. The *identity* is then
    ///   checked by re-running the exact test on the collider that came back:
    ///   a query that returned a farther collider fails on `t`, and one that
    ///   returned a mislabelled id fails on the re-test.
    /// * For an AABB overlap the scan gives the whole set, compared sorted —
    ///   tree order is not something a scan can reproduce. The order is a
    ///   property of the two forms sharing one traversal, which is why they do.
    ///
    /// The concurrent half is what the shared form exists for: one view, a
    /// [`QueryScratch`] per thread, and every thread must reach the answers the
    /// calling thread reached alone. It guards a future regression — putting
    /// the scratch back inside the view is exactly the change that would break
    /// it — rather than a race in today's code, which holds only shared
    /// references.
    #[test]
    fn the_shared_view_casts_sweeps_and_boxes_like_a_scan_would() {
        let mut world = PhysicsWorld::new();
        // (id, shape, is_trigger): the oracle, and all the scan below reads.
        let mut fixture: Vec<(ColliderId, ColliderEntry, bool)> = Vec::new();
        // A lattice, so a probe lands on a neighbourhood rather than on one
        // collider or none, and a descent that pruned a subtree it should not
        // have loses something the scan still finds.
        let mut row_start = None;
        for x in -3..=3 {
            for y in -3..=3 {
                let sphere = Sphere::new(DVec3::new(f64::from(x), f64::from(y), 0.0), 0.4);
                let id = world.add_sphere(sphere);
                if x == -3 && y == 0 {
                    row_start = Some(id);
                }
                fixture.push((id, ColliderEntry::Sphere(sphere), false));
            }
        }
        let row_start = row_start.expect("the lattice contains (-3, 0, 0)");
        // A capsule and a box as well, so every arm of the exact test is
        // exercised rather than only the sphere one.
        let capsule = Capsule::new(DVec3::new(0.0, 0.0, 3.0), 0.3, 1.0);
        fixture.push((
            world.add_capsule(capsule),
            ColliderEntry::Capsule(TurnedCapsule::upright(capsule)),
            true,
        ));
        let boxed = BoxCollider::new(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.5));
        fixture.push((world.add_box(boxed), ColliderEntry::Box(boxed), false));
        // A trigger standing in front of the first ray's solid hits. Triggers
        // are non-solid, so a cast that reports this one has stopped skipping
        // them — and `the_skipped_trigger_was_in_the_way` below checks that
        // this collider really is in the way, so the skip is a branch the run
        // actually takes.
        let trigger = Sphere::new(DVec3::new(-5.0, 0.0, 0.0), 0.5);
        let trigger_id = world.add_sphere(trigger);
        assert!(world.set_trigger(trigger_id, true), "the trigger was added");
        fixture.push((trigger_id, ColliderEntry::Sphere(trigger), true));

        let rays = [
            // Down the lattice's middle row, through the trigger first.
            Ray::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::X),
            // Another row, no trigger on it.
            Ray::new(DVec3::new(-10.0, 2.0, 0.0), DVec3::X),
            // Along +Z through a lattice sphere and the capsule behind it.
            Ray::new(DVec3::new(0.0, 0.0, -10.0), DVec3::Z),
            // Between the rows, so only the box is wide enough to be hit.
            Ray::new(DVec3::new(-10.0, 1.5, 0.0), DVec3::X),
            // Diagonally across the lattice.
            Ray::new(DVec3::new(-10.0, -10.0, 0.0), DVec3::new(1.0, 1.0, 0.0)),
            // Nowhere near anything.
            Ray::new(DVec3::new(-10.0, 20.0, 0.0), DVec3::X),
            // Bounded short of the first solid collider, so `t_max` decides.
            Ray::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::X).with_bounds(0.0, 5.0),
        ];
        let sweeps = [
            (
                Segment::new(DVec3::new(-10.0, 0.0, 0.0), DVec3::new(10.0, 0.0, 0.0)),
                0.2,
            ),
            // Between two rows, close enough that the swept volume reaches
            // both — the case a centre-line traversal used to drop.
            (
                Segment::new(DVec3::new(-10.0, 0.7, 0.0), DVec3::new(10.0, 0.7, 0.0)),
                0.35,
            ),
            (
                Segment::new(DVec3::new(0.0, 3.0, -10.0), DVec3::new(0.0, 3.0, 10.0)),
                0.1,
            ),
            // Starting inside a collider.
            (
                Segment::new(DVec3::new(0.0, 3.0, 0.0), DVec3::new(0.1, 3.0, 0.0)),
                0.2,
            ),
            // Nowhere near anything.
            (
                Segment::new(DVec3::new(20.0, 20.0, 20.0), DVec3::new(30.0, 30.0, 30.0)),
                0.5,
            ),
        ];
        let aabbs = [
            Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(1.2)),
            Aabb::from_centre_half(DVec3::new(1.5, 1.5, 0.0), DVec3::splat(0.6)),
            Aabb::from_centre_half(DVec3::new(50.0, 50.0, 0.0), DVec3::splat(1.0)),
            Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0)),
        ];

        // ── The exclusive form's answers, before the view borrows the world ──
        let plain_sweeps: Vec<Option<(ColliderId, ShapeHit)>> = sweeps
            .iter()
            .map(|(segment, radius)| world.sweep_sphere(segment, *radius))
            .collect();
        // The same sweeps with the collider each one actually hits left out —
        // the query a body sweeping its own path runs, and the only form of it
        // where the exclusion is guaranteed to change the answer. The last
        // entry is the opposite case: excluding a collider that sweep never
        // reaches, which must change nothing.
        let mut excluded_sweeps: Vec<(Segment, f64, ColliderId)> = sweeps
            .iter()
            .zip(&plain_sweeps)
            .filter_map(|((segment, radius), hit)| hit.map(|(id, _)| (*segment, *radius, id)))
            .collect();
        excluded_sweeps.push((sweeps[2].0, sweeps[2].1, row_start));

        let exclusive = ProbeAnswers {
            rays: rays.iter().map(|ray| world.cast_ray(ray)).collect(),
            sweeps: plain_sweeps,
            excluded_sweeps: excluded_sweeps
                .iter()
                .map(|(segment, radius, skip)| {
                    world.sweep_sphere_excluding(segment, *radius, Some(*skip))
                })
                .collect(),
            aabbs: aabbs
                .iter()
                .map(|aabb| {
                    let mut ids = world.overlap_aabb(aabb);
                    ids.sort_unstable_by_key(|id| id.index());
                    ids
                })
                .collect(),
        };

        // ── The scan, which shares no code with the traversal ─────────────
        let solid = |skip: Option<ColliderId>| {
            fixture
                .iter()
                .filter(move |(id, _, is_trigger)| !is_trigger && Some(*id) != skip)
        };
        let closest =
            |hits: &mut dyn Iterator<Item = ShapeHit>| hits.map(|hit| hit.t).min_by(f64::total_cmp);
        let entry_of = |wanted: ColliderId| {
            fixture
                .iter()
                .find(|(id, _, _)| *id == wanted)
                .map(|(_, entry, is_trigger)| (entry.clone(), *is_trigger))
                .expect("the query named a collider the fixture does not hold")
        };

        let mut rays_that_hit = 0usize;
        for (ray, answer) in rays.iter().zip(&exclusive.rays) {
            let scanned =
                closest(&mut solid(None).filter_map(|(_, entry, _)| scan_ray_one(ray, entry)));
            assert_eq!(
                answer.map(|(_, hit)| hit.t),
                scanned,
                "the closest solid hit along {ray:?}",
            );
            if let Some((id, hit)) = answer {
                let (entry, is_trigger) = entry_of(*id);
                assert!(!is_trigger, "a cast reported a trigger: {ray:?}");
                assert_eq!(
                    scan_ray_one(ray, &entry),
                    Some(*hit),
                    "the collider the cast named does not produce the hit it reported",
                );
                rays_that_hit += 1;
            }
        }
        assert!(
            rays_that_hit >= 4 && rays_that_hit < rays.len(),
            "{rays_that_hit} of {} ray probes hit, so the comparison above was \
             mostly empty on one side or never exercised a miss",
            rays.len(),
        );

        // The trigger is genuinely in the way of the first ray, so skipping it
        // is a branch this run takes rather than one it never reaches.
        let with_triggers = closest(
            &mut fixture
                .iter()
                .filter_map(|(_, entry, _)| scan_ray_one(&rays[0], entry)),
        );
        assert!(
            with_triggers < exclusive.rays[0].map(|(_, hit)| hit.t),
            "the trigger is not in front of the first ray's solid hits, so \
             nothing here would notice if triggers stopped being skipped",
        );

        let mut sweeps_that_hit = 0usize;
        for ((segment, radius), answer) in sweeps.iter().zip(&exclusive.sweeps) {
            let scanned = closest(
                &mut solid(None)
                    .filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
            );
            assert_eq!(
                answer.map(|(_, hit)| hit.t),
                scanned,
                "the closest solid hit sweeping r{radius} along {segment:?}",
            );
            if let Some((id, hit)) = answer {
                let (entry, is_trigger) = entry_of(*id);
                assert!(!is_trigger, "a sweep reported a trigger: {segment:?}");
                assert_eq!(
                    scan_sweep_one(segment, *radius, &entry),
                    Some(*hit),
                    "the collider the sweep named does not produce the hit it reported",
                );
                sweeps_that_hit += 1;
            }
        }
        assert!(
            sweeps_that_hit >= 3 && sweeps_that_hit < sweeps.len(),
            "{sweeps_that_hit} of {} sweep probes hit, so the comparison above \
             was mostly empty on one side or never exercised a miss",
            sweeps.len(),
        );

        let mut exclusion_mattered = 0usize;
        let mut exclusion_was_moot = 0usize;
        for ((segment, radius, skip), answer) in
            excluded_sweeps.iter().zip(&exclusive.excluded_sweeps)
        {
            let scanned = closest(
                &mut solid(Some(*skip))
                    .filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
            );
            assert_eq!(
                answer.map(|(_, hit)| hit.t),
                scanned,
                "the closest hit excluding {skip:?}, sweeping r{radius} along {segment:?}",
            );
            assert_ne!(
                answer.map(|(id, _)| id),
                Some(*skip),
                "the excluded collider came back anyway",
            );
            // Whether the exclusion was load-bearing is the scan's to say, not
            // the query's: it is whether the closest solid hit moved when that
            // collider left the fixture.
            let unexcluded = closest(
                &mut solid(None)
                    .filter_map(|(_, entry, _)| scan_sweep_one(segment, *radius, entry)),
            );
            if unexcluded == scanned {
                exclusion_was_moot += 1;
            } else {
                exclusion_mattered += 1;
            }
        }
        assert!(
            exclusion_mattered >= 3 && exclusion_was_moot >= 1,
            "{exclusion_mattered} exclusions changed the answer and \
             {exclusion_was_moot} did not, so one of the two cases never ran",
        );

        let mut widest = 0usize;
        for (aabb, answer) in aabbs.iter().zip(&exclusive.aabbs) {
            let mut scanned: Vec<ColliderId> = fixture
                .iter()
                .filter(|(_, entry, _)| entry.aabb().intersects(aabb))
                .map(|(id, _, _)| *id)
                .collect();
            scanned.sort_unstable_by_key(|id| id.index());
            assert_eq!(&scanned, answer, "the AABBs meeting {aabb:?}");
            widest = widest.max(answer.len());
        }
        assert!(
            widest > 4,
            "the widest AABB probe found {widest} colliders, so the comparison \
             above was mostly two empty vectors",
        );

        // ── The same answers under a shared borrow, from several threads ──
        // One scratch and one output buffer for the whole run, which is how a
        // `par_for` chunk holds them — and what makes a query that forgot to
        // clear its output visible here.
        let ask = |queries: &OverlapQueries<'_>| {
            let mut scratch = QueryScratch::new();
            let mut ids = Vec::new();
            ProbeAnswers {
                rays: rays
                    .iter()
                    .map(|ray| queries.cast_ray(ray, &mut scratch))
                    .collect(),
                sweeps: sweeps
                    .iter()
                    .map(|(segment, radius)| queries.sweep_sphere(segment, *radius, &mut scratch))
                    .collect(),
                excluded_sweeps: excluded_sweeps
                    .iter()
                    .map(|(segment, radius, skip)| {
                        queries.sweep_sphere_excluding(segment, *radius, Some(*skip), &mut scratch)
                    })
                    .collect(),
                aabbs: aabbs
                    .iter()
                    .map(|aabb| {
                        queries.overlap_aabb_into(aabb, &mut scratch, &mut ids);
                        let mut found = ids.clone();
                        found.sort_unstable_by_key(|id| id.index());
                        found
                    })
                    .collect(),
            }
        };

        let queries = world.overlap_queries();
        assert_eq!(ask(&queries), exclusive, "the calling thread's own answers");

        std::thread::scope(|scope| {
            let handles: Vec<_> = (0..4).map(|_| scope.spawn(|| ask(&queries))).collect();
            for handle in handles {
                assert_eq!(
                    handle.join().expect("a query thread panicked"),
                    exclusive,
                    "a thread sharing the view disagreed with the scan",
                );
            }
        });
    }

    /// **A sphere overlap is shape-aware: the query radius is expanded by each
    /// collider's own radius.**
    ///
    /// `overlap_sphere(centre, R)` returns every collider whose *shape* overlaps
    /// the query sphere, so a sphere collider of radius `r_b` is returned iff
    /// its centre is within `R + r_b` of the query's — on every axis by the
    /// broadphase prefilter (whose leaf AABBs carry the collider's own extent),
    /// and off-axis by the exact shape test, which trims the prefilter's square
    /// back to the circle. The contract matters to `apps/horde`: its separation
    /// query passes `r_self + slack` and expects neighbours out to
    /// `r_self + slack + r_b`, which is only right because of this expansion —
    /// the guard for that lives here rather than in the consumer.
    ///
    /// The two families of cases exercise the two layers separately: the
    /// on-axis ones are decided by the broadphase, the 45° ones (in the z = 0
    /// plane) are admitted by the broadphase and decided by the exact shape
    /// test.
    #[test]
    fn a_sphere_overlap_is_expanded_by_the_colliders_own_radius() {
        let mut world = PhysicsWorld::new();
        let body = world.add_sphere(Sphere::new(DVec3::ZERO, 0.5));
        let mut scratch = QueryScratch::new();
        let mut out = Vec::new();
        let queries = world.overlap_queries();

        let query_radius = 1.0;
        let boundary = query_radius + 0.5; // the body's radius

        // On the query's own axis, the broadphase's AABB admission decides.
        queries.overlap_sphere_into(
            DVec3::new(boundary - 0.01, 0.0, 0.0),
            query_radius,
            &mut scratch,
            &mut out,
        );
        assert_eq!(
            ids_of(&out),
            vec![body],
            "a body whose centre is inside R + r_b is returned"
        );

        queries.overlap_sphere_into(
            DVec3::new(boundary + 0.01, 0.0, 0.0),
            query_radius,
            &mut scratch,
            &mut out,
        );
        assert!(
            out.is_empty(),
            "a body whose centre is outside R + r_b is not returned"
        );

        // The boundary is R + r_b, not R: a query radius alone, with the body's
        // centre at R + r_b/2, must still find it.
        queries.overlap_sphere_into(
            DVec3::new(query_radius + 0.25, 0.0, 0.0),
            query_radius,
            &mut scratch,
            &mut out,
        );
        assert_eq!(
            ids_of(&out),
            vec![body],
            "the query radius is expanded by the collider's own radius, not used raw"
        );

        // At 45° in the z = 0 plane, the AABB prefilter still admits both
        // (axis offsets below R + r_b), so the exact shape test decides: the
        // boundary is the circle of radius R + r_b, not the square.
        // (R + r_b)/√2 ≈ 1.0607.
        queries.overlap_sphere_into(
            DVec3::new(1.05, 1.05, 0.0),
            query_radius,
            &mut scratch,
            &mut out,
        );
        assert_eq!(
            ids_of(&out),
            vec![body],
            "a body within the circle of radius R + r_b is returned even off-axis"
        );

        queries.overlap_sphere_into(
            DVec3::new(1.07, 1.07, 0.0),
            query_radius,
            &mut scratch,
            &mut out,
        );
        assert!(
            out.is_empty(),
            "a body outside the circle of radius R + r_b is not returned, \
             even where the broadphase AABB would admit it"
        );
    }

    /// One scratch, many queries: the buffers carry nothing between calls.
    ///
    /// The whole point of handing the caller the scratch is that it is reused,
    /// so a query that read a stale `candidates` from the call before it would
    /// be a defect this API introduced and the owning form cannot have.
    #[test]
    fn a_reused_scratch_does_not_leak_one_query_into_the_next() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::ZERO, 0.5));
        world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 0.5));

        let mut scratch = QueryScratch::new();
        let mut out = Vec::new();
        let queries = world.overlap_queries();

        queries.overlap_sphere_into(DVec3::ZERO, 1.0, &mut scratch, &mut out);
        assert_eq!(out.len(), 1);
        queries.overlap_sphere_into(DVec3::new(0.0, 100.0, 0.0), 1.0, &mut scratch, &mut out);
        assert!(out.is_empty(), "a stale candidate survived the next query");
        queries.overlap_sphere_into(DVec3::new(20.0, 0.0, 0.0), 1.0, &mut scratch, &mut out);
        assert_eq!(out.len(), 1);
    }

    #[test]
    fn adding_and_removing_a_collider_leaves_the_world_empty_again() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        assert_eq!(world.len(), 1);
        assert!(!world.is_empty());
        assert!(world.remove(id));
        assert!(world.is_empty());
    }

    #[test]
    fn remove_invalid_id_returns_false() {
        let mut world = PhysicsWorld::new();
        assert!(!world.remove(ColliderId::new(999, 0)));
        // A double remove is the same stale-id case.
        let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        assert!(world.remove(id));
        assert!(!world.remove(id));
    }

    #[test]
    fn add_sphere_then_cast_ray_hits() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        let result = world.cast_ray(&ray);
        assert!(result.is_some());
        let (_id, hit) = result.unwrap();
        assert!((hit.t - 4.0).abs() < 0.001);
    }

    #[test]
    fn cast_ray_misses_when_no_colliders() {
        let mut world = PhysicsWorld::new();
        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        assert!(world.cast_ray(&ray).is_none());
    }

    #[test]
    fn add_multiple_and_cast_ray_finds_closest() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
        let close = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        let (id, hit) = world.cast_ray(&ray).unwrap();
        assert_eq!(id, close);
        assert!((hit.t - 4.0).abs() < 0.001);
    }

    /// **The excluded collider is dropped before the winner is picked, so the
    /// next-closest hit survives.**
    ///
    /// `near` sits where the swept sphere reaches it first and `far` behind it,
    /// so an implementation that ran the ordinary sweep and threw the answer
    /// away when it named `near` would report nothing at all. Excluding `near`
    /// has to return `far`, and excluding an id the world never issued has to
    /// return `near` again.
    #[test]
    fn sweep_sphere_excluding_keeps_the_next_closest_hit() {
        let mut world = PhysicsWorld::new();
        let near = world.add_sphere(Sphere::new(DVec3::new(0.0, 0.0, 0.0), 1.0));
        let far = world.add_sphere(Sphere::new(DVec3::new(3.0, 0.0, 0.0), 1.0));
        let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));

        let (id, _) = world.sweep_sphere(&seg, 0.5).expect("the sweep hits both");
        assert_eq!(id, near, "the unfiltered sweep answers the closest");

        let (id, hit) = world
            .sweep_sphere_excluding(&seg, 0.5, Some(near))
            .expect("the one behind it is still there");
        assert_eq!(id, far, "excluding the closest must not lose the rest");
        assert!(
            (hit.t - 0.65).abs() < 0.001,
            "expected ~0.65, got {}",
            hit.t
        );

        let (id, _) = world
            .sweep_sphere_excluding(&seg, 0.5, Some(ColliderId::new(999, 0)))
            .expect("an id the world never issued excludes nothing");
        assert_eq!(id, near);

        // **The dangerous stale id is the one whose slot is still live.** An id
        // the world never issued names no slot at all, so ignoring it is easy;
        // an id whose index was reused names a slot that *is* occupied, by
        // something else. Excluding on the index alone would take the new
        // occupant out of the sweep, which is a hit silently lost rather than a
        // filter that did nothing.
        assert!(world.remove(near), "the collider was live");
        let reused = world.add_sphere(Sphere::new(DVec3::new(0.0, 0.0, 0.0), 1.0));
        assert_eq!(
            reused.index, near.index,
            "this test only says anything while the slot is actually reused"
        );
        assert_ne!(
            reused.generation, near.generation,
            "and the id has moved on"
        );
        let (id, _) = world
            .sweep_sphere_excluding(&seg, 0.5, Some(near))
            .expect("the stale id must not hide the collider that took its slot");
        assert_eq!(
            id, reused,
            "a generation that has moved on excludes nothing, so the sweep still \
             answers the shape occupying that slot"
        );
    }

    #[test]
    fn sweep_sphere_hits_box() {
        let mut world = PhysicsWorld::new();
        world.add_box(BoxCollider::new(DVec3::ZERO, DVec3::splat(1.0)));
        let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
        let result = world.sweep_sphere(&seg, 0.5);
        assert!(result.is_some());
        let (_id, hit) = result.unwrap();
        // t should be (distance from start to inflated box near plane) / segment length
        // start=-5, sphere_r=0.5, box half=1.0, near=-1.5, distance=3.5, segment=10
        assert!(
            (hit.t - 0.35).abs() < 0.001,
            "expected ~0.35, got {}",
            hit.t
        );
        assert_eq!(hit.normal, DVec3::NEG_X);
    }

    /// A sphere whose *centre* never enters the box still touches it, and the
    /// sweep has to say so.
    ///
    /// The broadphase used to traverse the centre line as a ray, so a box the
    /// sphere overlaps by anything less than its radius was dropped before the
    /// exact test ran. Every case below is a real contact: the centre line
    /// passes 0.3 above a box whose top is at y = 0, with a sphere of radius
    /// 0.5, so the sphere is 0.2 deep at its closest.
    #[test]
    fn sweep_sphere_hits_a_box_its_centre_line_misses() {
        let mut world = PhysicsWorld::new();
        world.add_box(BoxCollider::new(
            DVec3::new(0.0, -1.0, 0.0),
            DVec3::splat(1.0),
        ));

        // Along the top face, never crossing it.
        let along = Segment::new(DVec3::new(-5.0, 0.3, 0.0), DVec3::new(5.0, 0.3, 0.0));
        let (_, hit) = world
            .sweep_sphere(&along, 0.5)
            .expect("a sphere grazing the top face touches it");
        assert!(hit.point.y <= 0.0 + 1e-9, "contact on the box: {hit:?}");

        // Coming down onto it and stopping short: the surfaces meet, the
        // centres do not.
        let onto = Segment::new(DVec3::new(0.0, 1.0, 0.0), DVec3::new(0.0, 0.3, 0.0));
        let (_, hit) = world
            .sweep_sphere(&onto, 0.5)
            .expect("a sphere landing on the face touches it");
        assert!(hit.normal.y > 0.5, "the top face's normal: {hit:?}");

        // And a genuine miss is still a miss: 0.6 clear of a 0.5 sphere.
        let clear = Segment::new(DVec3::new(-5.0, 0.6, 0.0), DVec3::new(5.0, 0.6, 0.0));
        assert!(
            world.sweep_sphere(&clear, 0.5).is_none(),
            "a sphere that does not reach the box must not report a hit",
        );
    }

    #[test]
    fn rebuilding_after_the_last_removal_leaves_nothing_for_a_ray_to_hit() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
        world.remove(id);
        world.rebuild(); // no panics
        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        assert!(world.cast_ray(&ray).is_none());
    }

    #[test]
    fn churn_after_the_first_query_keeps_the_tree() {
        // The behaviour the asteroids sample turns on: once the tree exists,
        // spawning and killing colliders updates it in place. If either path
        // dropped the tree instead, `bvh_cached` would read false right after
        // the mutation and every frame would pay a rebuild.
        let mut world = PhysicsWorld::new();
        let keep = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
        assert!(world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).is_some());
        assert!(format!("{world:?}").contains("bvh_cached: true"));

        let bullet = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 0.5));
        assert!(
            format!("{world:?}").contains("bvh_cached: true"),
            "adding a collider threw the tree away"
        );
        // The new collider is in the tree, not merely in the slot array: the
        // ray now stops at it rather than at the one it used to reach.
        let (hit_id, _) = world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).unwrap();
        assert_eq!(hit_id, bullet);

        assert!(world.remove(bullet));
        assert!(
            format!("{world:?}").contains("bvh_cached: true"),
            "removing a collider threw the tree away"
        );
        let (hit_id, _) = world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).unwrap();
        assert_eq!(hit_id, keep, "the removed collider still answers queries");
        assert_eq!(world.len(), 1);
    }

    #[test]
    fn churn_through_a_recycled_slot_tracks_the_right_element() {
        // Collider slots and BVH element indices are two independent recycling
        // schemes. If the mapping between them went stale, the new occupant of
        // a slot would refit the *old* occupant's leaf — a collider that moves
        // when a different one is moved.
        let mut world = PhysicsWorld::new();
        let far = world.add_sphere(Sphere::new(DVec3::new(100.0, 0.0, 0.0), 1.0));
        let doomed = world.add_sphere(Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0));
        assert!(world.cast_ray(&Ray::new(DVec3::ZERO, DVec3::X)).is_some());

        assert!(world.remove(doomed));
        let reused = world.add_sphere(Sphere::new(DVec3::new(30.0, 0.0, 0.0), 1.0));
        assert_eq!(reused.index(), doomed.index(), "the slot must be recycled");

        // Move the new occupant, then ask a *local* question about where it
        // landed. A local query is the one that can tell: it only descends
        // into leaves whose bounds reach the query, so a refit applied to some
        // other collider's leaf leaves this one still sitting at its old
        // bounds and out of reach. A long ray would not catch it — the ray
        // would pass through the stale bounds anyway and the narrow phase
        // would re-read the correct shape and paper over the mistake.
        assert!(world.set_sphere(reused, Sphere::new(DVec3::new(3.0, 0.0, 0.0), 1.0)));
        assert_eq!(
            ids_of(&world.overlap_sphere(DVec3::new(3.0, 0.0, 0.0), 0.5)),
            vec![reused],
            "the refit did not move the collider that was asked to move"
        );
        // And nothing else moved with it.
        assert!(
            world
                .overlap_sphere(DVec3::new(30.0, 0.0, 0.0), 0.5)
                .is_empty()
        );
        assert_eq!(
            world.aabb_of(far).unwrap().centre(),
            DVec3::new(100.0, 0.0, 0.0)
        );
    }

    #[test]
    fn aabb_of_returns_correct_bounds() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::new(1.0, 2.0, 3.0), 0.5));
        let aabb = world.aabb_of(id).unwrap();
        assert_eq!(aabb.min, DVec3::new(0.5, 1.5, 2.5));
        assert_eq!(aabb.max, DVec3::new(1.5, 2.5, 3.5));
    }

    #[test]
    fn aabb_of_unknown_id_returns_none() {
        let world = PhysicsWorld::new();
        assert!(world.aabb_of(ColliderId::new(42, 0)).is_none());
    }

    #[test]
    fn stale_id_does_not_address_the_slot_s_new_occupant() {
        // ABA: remove a collider, add another that recycles the same slot, and
        // check the retained id resolves to nothing rather than to the new
        // occupant.
        let mut world = PhysicsWorld::new();
        let old = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        assert!(world.remove(old));

        let new = world.add_sphere(Sphere::new(DVec3::new(9.0, 0.0, 0.0), 2.0));
        assert_eq!(new.index(), old.index(), "the slot must be recycled");
        assert_ne!(new, old, "but the id must not be");

        assert!(world.aabb_of(old).is_none());
        assert!(!world.remove(old));
        assert!(!world.set_trigger(old, true));
        assert!(!world.is_trigger(old));
        assert!(!world.set_sphere(old, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));

        // The new occupant is untouched by any of the above.
        let aabb = world.aabb_of(new).unwrap();
        assert_eq!(aabb.centre(), DVec3::new(9.0, 0.0, 0.0));
        assert_eq!(world.len(), 1);
    }

    #[test]
    fn the_worlds_debug_output_reports_how_many_colliders_it_holds() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        let s = format!("{world:?}");
        assert!(s.contains("collider_count: 1"));
    }

    // ── Overlap tests ─────────────────────────────────────────────────

    #[test]
    fn overlap_sphere_finds_sphere() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
        let results = world.overlap_sphere(DVec3::ZERO, 4.0);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn overlap_sphere_misses_distant() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(10.0, 0.0, 0.0), 1.0));
        let results = world.overlap_sphere(DVec3::ZERO, 2.0);
        assert!(results.is_empty());
    }

    #[test]
    fn overlap_sphere_finds_box() {
        let mut world = PhysicsWorld::new();
        world.add_box(BoxCollider::new(DVec3::ZERO, DVec3::splat(1.0)));
        let results = world.overlap_sphere(DVec3::new(2.0, 0.0, 0.0), 1.5);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn overlap_sphere_finds_capsule() {
        let mut world = PhysicsWorld::new();
        world.add_capsule(Capsule::new(DVec3::ZERO, 0.5, 2.0));
        let results = world.overlap_sphere(DVec3::new(0.0, 0.0, 0.0), 3.0);
        assert_eq!(results.len(), 1);
    }

    #[test]
    fn overlap_sphere_finds_multiple() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
        world.add_sphere(Sphere::new(DVec3::new(-2.0, 0.0, 0.0), 1.0));
        world.add_sphere(Sphere::new(DVec3::new(0.0, 6.0, 0.0), 1.0));
        let results = world.overlap_sphere(DVec3::ZERO, 4.0);
        assert_eq!(results.len(), 2); // only the two on x-axis
    }

    #[test]
    fn overlap_aabb_finds_all_intersecting() {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
        world.add_sphere(Sphere::new(DVec3::new(-2.0, 0.0, 0.0), 1.0));
        world.add_sphere(Sphere::new(DVec3::new(0.0, 10.0, 0.0), 1.0));
        let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(3.0));
        let results = world.overlap_aabb(&query);
        assert_eq!(results.len(), 2);
    }

    #[test]
    fn overlap_aabb_empty_world() {
        let mut world = PhysicsWorld::new();
        let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(10.0));
        assert!(world.overlap_aabb(&query).is_empty());
    }

    // ── Dynamic update (refit) tests ────────────────────────────────────

    #[test]
    fn set_sphere_moves_collider_in_ray_cast() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
        // Initially hits.
        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        assert!(world.cast_ray(&ray).is_some());

        // Move the sphere far away via set_sphere.
        assert!(world.set_sphere(id, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));

        // Should no longer hit with +X ray.
        assert!(world.cast_ray(&ray).is_none());
    }

    #[test]
    fn set_box_updates_overlap_query() {
        let mut world = PhysicsWorld::new();
        let id = world.add_box(BoxCollider::new(
            DVec3::new(5.0, 0.0, 0.0),
            DVec3::splat(1.0),
        ));

        // Overlap near origin should not find it.
        let results = world.overlap_sphere(DVec3::ZERO, 2.0);
        assert!(results.is_empty());

        // Move it to origin.
        assert!(world.set_box(
            id,
            BoxCollider::new(DVec3::new(1.0, 0.0, 0.0), DVec3::splat(1.0))
        ));

        // Now overlap should find it.
        let results = world.overlap_sphere(DVec3::ZERO, 3.0);
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].0, id);
    }

    #[test]
    fn set_sphere_on_invalid_id_returns_false() {
        let mut world = PhysicsWorld::new();
        assert!(!world.set_sphere(ColliderId::new(999, 0), Sphere::new(DVec3::ZERO, 1.0)));
    }

    #[test]
    fn set_sphere_refits_the_right_leaf_when_colliders_are_not_centroid_ordered() {
        // The BVH sorts each range by centroid while building, so the leaf
        // order differs from the order colliders were added.  Moving slot 0
        // must move the collider at x = 20, not the one at x = 5.
        let mut world = PhysicsWorld::new();
        let far = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));
        let near = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));

        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        let (id, hit) = world
            .cast_ray(&ray)
            .expect("the near sphere is ahead of the ray");
        assert_eq!(id, near);
        assert!((hit.t - 4.0).abs() < 1e-9, "t = {}", hit.t);

        // Move the *far* sphere behind the ray origin.  The near one must
        // still be found, at the same distance.
        assert!(world.set_sphere(far, Sphere::new(DVec3::new(-50.0, 0.0, 0.0), 1.0)));
        let (id, hit) = world
            .cast_ray(&ray)
            .expect("the untouched sphere must not vanish");
        assert_eq!(id, near);
        assert!((hit.t - 4.0).abs() < 1e-9, "t = {}", hit.t);
    }

    #[test]
    fn set_capsule_refits_bvh() {
        let mut world = PhysicsWorld::new();
        let id = world.add_capsule(Capsule::new(DVec3::new(5.0, 0.0, 0.0), 0.5, 1.0));
        let ray = Ray::new(DVec3::ZERO, DVec3::X);

        // Initially hits.
        assert!(world.cast_ray(&ray).is_some());

        // Move it.
        assert!(world.set_capsule(id, Capsule::new(DVec3::new(-30.0, 30.0, 0.0), 0.5, 1.0)));

        // Should miss with +X ray.
        assert!(world.cast_ray(&ray).is_none());
    }

    #[test]
    fn set_sphere_after_removal_fails() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        world.remove(id);
        assert!(!world.set_sphere(id, Sphere::new(DVec3::new(1.0, 0.0, 0.0), 1.0)));
    }

    #[test]
    fn sweep_sphere_hits_capsule_exact() {
        let mut world = PhysicsWorld::new();
        world.add_capsule(Capsule::new(DVec3::ZERO, 0.5, 2.0));
        let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
        let result = world.sweep_sphere(&seg, 0.5);
        assert!(result.is_some());
    }

    #[test]
    fn sweep_sphere_misses_distant_capsule() {
        let mut world = PhysicsWorld::new();
        world.add_capsule(Capsule::new(DVec3::new(100.0, 0.0, 0.0), 0.5, 2.0));
        let seg = Segment::new(DVec3::new(-5.0, 0.0, 0.0), DVec3::new(5.0, 0.0, 0.0));
        assert!(world.sweep_sphere(&seg, 0.5).is_none());
    }

    // ── Trigger tests ──────────────────────────────────────────────────

    #[test]
    fn trigger_defaults_to_false() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        assert!(!world.is_trigger(id));
    }

    #[test]
    fn set_trigger_toggles_flag() {
        let mut world = PhysicsWorld::new();
        let id = world.add_sphere(Sphere::new(DVec3::ZERO, 1.0));
        assert!(world.set_trigger(id, true));
        assert!(world.is_trigger(id));
        assert!(world.set_trigger(id, false));
        assert!(!world.is_trigger(id));
    }

    #[test]
    fn set_trigger_on_invalid_id_returns_false() {
        let mut world = PhysicsWorld::new();
        assert!(!world.set_trigger(ColliderId::new(42, 0), true));
    }

    #[test]
    fn trigger_is_transparent_to_rays_and_sweeps() {
        let mut world = PhysicsWorld::new();
        let trigger = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
        assert!(world.set_trigger(trigger, true));

        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        assert!(
            world.cast_ray(&ray).is_none(),
            "a trigger must not stop a bullet"
        );

        let seg = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));
        assert!(world.sweep_sphere(&seg, 0.5).is_none());
    }

    #[test]
    fn trigger_still_shows_up_in_overlap_queries() {
        let mut world = PhysicsWorld::new();
        let trigger = world.add_sphere(Sphere::new(DVec3::new(2.0, 0.0, 0.0), 1.0));
        assert!(world.set_trigger(trigger, true));

        assert_eq!(
            ids_of(&world.overlap_sphere(DVec3::ZERO, 4.0)),
            vec![trigger]
        );
        let query = Aabb::from_centre_half(DVec3::ZERO, DVec3::splat(4.0));
        assert_eq!(world.overlap_aabb(&query), vec![trigger]);
    }

    #[test]
    fn solid_collider_behind_a_trigger_is_still_hit() {
        let mut world = PhysicsWorld::new();
        let trigger = world.add_sphere(Sphere::new(DVec3::new(5.0, 0.0, 0.0), 1.0));
        world.set_trigger(trigger, true);
        let solid = world.add_sphere(Sphere::new(DVec3::new(20.0, 0.0, 0.0), 1.0));

        let ray = Ray::new(DVec3::ZERO, DVec3::X);
        let (id, hit) = world.cast_ray(&ray).expect("the solid sphere is behind it");
        assert_eq!(id, solid);
        assert!((hit.t - 19.0).abs() < 1e-9, "t = {}", hit.t);
    }

    // ── Swept capsule ──────────────────────────────────────────────────

    /// **The broadphase bounds of a capsule sweep reach as high as the
    /// capsule.** A ledge above the sphere's bounds and below the capsule's is
    /// never offered to the narrow phase if the traversal box is only inflated
    /// by the radius — the exact test that would have caught it never runs.
    #[test]
    fn a_capsule_sweeps_broadphase_reaches_a_ledge_the_sphere_sweeps_does_not() {
        let (radius, half_height) = (0.4, 1.5);
        let mut world = PhysicsWorld::new();
        // Sits above the radius the sphere sweep inflates by, and well inside
        // the `radius + half_height` the capsule sweep needs.
        let ledge = world.add_box(BoxCollider::new(
            DVec3::new(2.0, 1.1, 0.0),
            DVec3::new(1.0, 0.1, 1.0),
        ));
        let segment = Segment::new(DVec3::new(-3.0, 0.0, 0.0), DVec3::new(3.0, 0.0, 0.0));

        assert!(
            world.sweep_sphere(&segment, radius).is_none(),
            "the sphere passes under the ledge, or the capsule reaching it proves nothing",
        );
        let (id, hit) = world
            .sweep_capsule(&segment, radius, half_height)
            .expect("the capsule's shoulder is level with the ledge");
        assert_eq!(id, ledge);
        assert_eq!(hit.normal, DVec3::NEG_X);
    }

    /// A character registered in the world sits on the start of every segment
    /// it sweeps. Excluding it in the narrow phase keeps the *next* hit — the
    /// wall it was walking into — which a caller discarding a self-hit
    /// afterwards has already lost.
    #[test]
    fn a_capsule_sweep_excluding_its_own_collider_keeps_the_wall_behind_it() {
        let (radius, half_height) = (0.4, 0.9);
        let mut world = PhysicsWorld::new();
        let character = world.add_capsule(Capsule::new(DVec3::ZERO, radius, half_height));
        let wall = world.add_box(BoxCollider::new(
            DVec3::new(3.0, 0.0, 0.0),
            DVec3::new(0.5, 5.0, 5.0),
        ));
        let segment = Segment::new(DVec3::ZERO, DVec3::new(4.0, 0.0, 0.0));

        let (self_id, self_hit) = world
            .sweep_capsule(&segment, radius, half_height)
            .expect("without the exclusion the character finds itself");
        assert_eq!(self_id, character);
        assert_eq!(self_hit.t, 0.0);

        let (id, hit) = world
            .sweep_capsule_excluding(&segment, radius, half_height, Some(character))
            .expect("the wall survives the exclusion");
        assert_eq!(id, wall);
        // Wall's -X face at x = 2.5, the flank meets it at x = 2.1 along a 4 m path.
        assert!((hit.t - 0.525).abs() < 1e-12, "t = {}", hit.t);
    }

    /// A trigger is non-solid for the capsule sweep exactly as it is for the
    /// sphere sweep — the two share one candidate loop, and this is what says
    /// the capsule path goes through it.
    #[test]
    fn a_capsule_sweep_passes_through_a_trigger_to_the_solid_behind_it() {
        let (radius, half_height) = (0.4, 0.9);
        let mut world = PhysicsWorld::new();
        let trigger = world.add_box(BoxCollider::new(
            DVec3::new(2.0, 0.0, 0.0),
            DVec3::new(0.5, 5.0, 5.0),
        ));
        assert!(world.set_trigger(trigger, true));
        let solid = world.add_box(BoxCollider::new(
            DVec3::new(6.0, 0.0, 0.0),
            DVec3::new(0.5, 5.0, 5.0),
        ));
        let segment = Segment::new(DVec3::ZERO, DVec3::new(10.0, 0.0, 0.0));

        let (id, hit) = world
            .sweep_capsule(&segment, radius, half_height)
            .expect("the solid slab is behind the trigger");
        assert_eq!(
            id, solid,
            "the trigger is in the way and must be passed through"
        );
        // Solid's -X face at x = 5.5, flank meets it at x = 5.1 along a 10 m path.
        assert!((hit.t - 0.51).abs() < 1e-12, "t = {}", hit.t);
    }
}

#[cfg(test)]
#[path = "world/ray_exclusion_tests.rs"]
mod ray_exclusion_tests;

#[cfg(test)]
#[path = "world/query_filter_tests.rs"]
mod query_filter_tests;

#[cfg(test)]
#[path = "world/overlap_hit_tests.rs"]
mod overlap_hit_tests;

#[cfg(test)]
#[path = "world/lying_capsule_tests.rs"]
mod lying_capsule_tests;

#[cfg(test)]
#[path = "world/turned_box_tests.rs"]
mod turned_box_tests;

#[cfg(test)]
#[path = "world/candidate_sweep_tests.rs"]
mod candidate_sweep_tests;

#[cfg(test)]
#[path = "world/query_digest_tests.rs"]
mod query_digest_tests;

#[cfg(test)]
#[path = "world/turned_body_tests.rs"]
mod turned_body_tests;

#[cfg(test)]
#[path = "world/compound_tests.rs"]
mod compound_tests;

#[cfg(test)]
#[path = "world/turned_capsule_tests.rs"]
mod turned_capsule_tests;

#[cfg(test)]
#[path = "world/arc_selection_tests.rs"]
mod arc_selection_tests;
#[cfg(test)]
#[path = "world/arc_sweep_tests.rs"]
mod arc_sweep_tests;