crcbl-phys 0.11.0

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
//! Capsule character controller: sweep-based movement against the world.
//!
//! [`CharacterController`] moves a Y-aligned capsule through a
//! [`PhysicsWorld`], sliding along what it hits, walking up slopes it is
//! allowed to and over steps it can reach, staying attached to the ground it
//! walks off the edge of, and pushing itself out of anything it wakes up
//! inside. It is kinematic: nothing integrates it, and it moves exactly as far
//! as the caller asks minus what the world takes away.
//!
//! A prone body is the same controller moving a [`LyingCapsule`] whose head is
//! its position instead: [`CharacterController::move_lying`] sweeps the whole
//! body with the same slide and lays it along the ground, and
//! [`CharacterController::turn_lying`] turns it about its head as far as it
//! fits.
//!
//! # It does not know which camera is watching
//!
//! [`CharacterController::move_and_slide`] takes a **world-space
//! displacement** and nothing else. It holds no camera, no view basis and no
//! yaw, and it never derives a direction from one. Turning a stick vector into
//! a world direction is the caller's job, because that is the only step that
//! genuinely differs between a first-person rig (intent is relative to the
//! view) and a third-person one (intent is relative to the camera while the
//! body turns toward it over time).
//!
//! **Facing is not here either.** There is no orientation on this type. A
//! first-person game pins the character's facing to its view; a third-person
//! game turns the body toward the direction it is moving, over time, and reads
//! that direction from [`MoveOutcome::motion`]. A controller that stored one
//! yaw and used it for both could not do the second without fighting the first,
//! which is where the two styles usually get forked into two controllers.
//!
//! Camera collision, follow logic and spring arms are the camera's, and
//! `docs/plan/30-player-kit.md` puts those on the client as presentation while
//! movement runs as a server system.
//!
//! Jump buffering, coyote time, sprint multipliers, acceleration curves and
//! input mapping are not here either. They are a layer above this one, and they
//! reach it through the displacement they ask for.
//!
//! # The approach, and where it comes from
//!
//! The move is a **collect-and-slide loop over a plane set**, which is the
//! shape every engine converges on:
//!
//! * Quake's `SV_FlyMove` / `PM_SlideMove` sweeps, records each blocking
//!   plane, and clips the velocity against the *set* rather than the last one —
//!   picking the plane whose clipped result does not drive into any other, and
//!   falling back to the crease (the cross product of two planes) when no
//!   single plane frees it. It stops dead when the clipped velocity opposes the
//!   original, which is what keeps a sloping corner from oscillating. That
//!   loop, its bump count ([`CharacterConfig::max_slides`]) and its plane
//!   budget ([`MAX_PLANES`]) are reproduced here.
//! * Godot's `CharacterBody3D::move_and_slide` contributes the iteration cap as
//!   a tunable, the walkable-floor angle as the one thing that decides what
//!   ground is, and `floor_snap_length` — staying attached to a surface that
//!   drops away under you.
//! * Unreal's `UCharacterMovementComponent` contributes the two pieces Quake
//!   has no equivalent of: `StepUp`'s rise / advance / drop with a *validated*
//!   landing, and `ComputeGroundMovementDelta`'s rule that a grounded move
//!   keeps its horizontal length and takes its rise from the ramp — so walking
//!   up a slope is not slower than walking on the flat.
//!
//! One deliberate difference from the Quake lineage: its `ClipVelocity` takes
//! an `overbounce` factor, which Quake III passes slightly above one to nudge
//! off the plane it just clipped against. This backs the capsule off by
//! [`CharacterConfig::skin_width`] instead. The gap is then a distance the
//! reader can name, and the next sweep starts outside the surface rather than
//! exactly on it.
//!
//! # Failure modes
//!
//! Handled, each with the mechanism that handles it:
//!
//! * **A crease between two planes sliding you into geometry.** Clipping
//!   against the plane *set* and falling back to the crease direction, from
//!   `SV_FlyMove`. A third simultaneous plane is a corner and stops the
//!   character rather than squeezing it through.
//! * **Oscillating in a sloping corner.** The clipped displacement is dropped
//!   when it opposes the one the move started with.
//! * **Creeping down a slope while standing still.** A grounded move takes its
//!   rise from the ramp and *discards* the vertical it was asked for rather
//!   than clipping it against the slope, so a request with no horizontal part
//!   becomes no movement at all. Godot spends `floor_stop_on_slope` on the same
//!   problem. The ground probe is what holds the character on.
//! * **Climbing a wall by facing into a corner.** Three things refuse it: the
//!   step-up needs the advance after rising to make real progress, it needs the
//!   drop afterwards to land on walkable ground, and it may happen at most once
//!   per call so a character cannot ratchet up a wall within one tick. The
//!   ground probe is a fourth — it pulls the capsule back down onto whatever it
//!   is actually standing on.
//! * **Tunnelling at speed.** Every probe is a swept capsule, never a
//!   teleport-and-test.
//! * **Waking up inside geometry.** [`Penetration`] depths, resolved deepest
//!   first before the move.
//!
//! Not handled, and known:
//!
//! * **A step-up that clips the wall it stepped over.** The advance is swept at
//!   the raised height and the drop is swept straight down, but the corner
//!   between them is not. A capsule that lands touching the riser is pushed out
//!   by the next call's depenetration rather than being placed clear by this
//!   one.
//! * **Moving geometry.** Nothing here reads a collider's velocity, so a
//!   character standing on a platform does not ride it and a platform closing
//!   on a character resolves as a penetration rather than as a push.
//! * **Ceilings while stepping up.** The rise stops under an overhead
//!   obstruction, so a low ceiling shortens the step rather than cancelling it;
//!   whether the shortened step then lands is left to the same landing check as
//!   any other.
//! * **More than two simultaneous planes.** Stopping dead is Quake's answer and
//!   it is this one; Quake III tries the remaining pairs before giving up.

use glam::DVec3;

use crate::broadphase::{Ray, Segment};
use crate::collider::{Capsule, LyingCapsule};
use crate::query::{Penetration, ShapeHit};
use crate::world::{
    ALL_LAYERS, ColliderId, OverlapQueries, PhysicsWorld, QueryFilter, QueryScratch,
};

mod lying;
mod preview;
mod skin;
mod slide_contact;

pub use lying::{LyingMoveOutcome, LyingTurnOutcome};
pub use preview::UprightPreview;
pub use slide_contact::SlideContact;

/// The world's up axis. `crcbl` is right-handed with `+Y` up, and
/// [`Capsule`] is Y-aligned, so a character controller has exactly one.
const UP: DVec3 = DVec3::Y;

/// A displacement shorter than this is not worth a sweep: the capsule is
/// already where it was going, and sweeping it would only cost a broadphase
/// traversal to be told so.
///
/// For the same reason an advance no longer than this has not covered ground,
/// and the slide keeps the planes it has already collected across it.
const MIN_MOVE: f64 = 1e-9;

/// How many blocking planes one move may collect before the character is
/// declared stuck and stopped.
///
/// Quake's `MAX_CLIP_PLANES`, and reaching it is its "this shouldn't really
/// happen": a character that has found this many distinct surfaces without
/// covering any ground is wedged rather than on a path. It is a different limit
/// from the one `clip_to_planes` enforces, which is that only two planes have a
/// crease to run along.
pub const MAX_PLANES: usize = 5;

/// How many [`CharacterConfig::skin_width`]s of slack a downward probe carries
/// beyond the distance it is actually asking about.
///
/// A settled capsule sits exactly one skin width of *vertical* travel above its
/// ground, so a probe with no slack would find that ground only by touching it,
/// and a sweep that ends exactly at contact is a knife edge. Two skin widths is
/// the shortest slack that clears it. Unreal spends its `MAX_FLOOR_DIST` the
/// same way.
const GROUND_PROBE_SKINS: f64 = 2.0;

// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------

/// The shape of a character and the limits it moves under.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct CharacterConfig {
    /// Radius of the capsule.
    pub radius: f64,
    /// Half the length of the capsule's cylindrical section, as
    /// [`Capsule::half_height`] means it: the standing height is
    /// `2 * (half_height + radius)`.
    pub half_height: f64,
    /// The smallest `normal · +Y` a surface can have and still be ground the
    /// character stands and walks on — the **cosine** of the steepest walkable
    /// slope, not the angle.
    ///
    /// A cosine and not an angle because this crate is a determinism-bearing
    /// one and `cos` is a platform transcendental: see the determinism rule in
    /// `docs/notes/simulation.md`. Authoring an angle is the caller's job, done
    /// once, outside the tick. This is the same runtime form Quake's
    /// `normal[2] > 0.7` and Unreal's `WalkableFloorZ` keep.
    ///
    /// Where the behaviour actually flips is measured by
    /// `tests::the_slope_the_controller_stops_walking_up_is_the_one_it_was_configured_with`.
    pub min_ground_normal_y: f64,
    /// The tallest ledge the character walks up without leaving the ground.
    ///
    /// Also how far it will drop to stay attached to ground that falls away
    /// under it, which is Godot's `floor_snap_length` and the reason walking
    /// down stairs does not become a series of falls.
    ///
    /// The rise is taken with a [`skin_width`](Self::skin_width) to spare, so a
    /// step of exactly this height is climbed and the true cut-off is up to one
    /// skin width above it. The band is measured by
    /// `tests::the_step_the_controller_stops_climbing_is_the_offset_it_was_configured_with`.
    pub step_offset: f64,
    /// The gap kept between the capsule and every surface it touches.
    ///
    /// Every sweep of a move stops this far short of its contact, measured
    /// along the surface's normal, and one that met a surface already nearer
    /// than this backs off to it. The next sweep then starts outside the
    /// surface instead of on it, where a touching start would be reported as
    /// an overlap and a sweep with a tolerance can meet the surface again for
    /// motion along it. Unity's `CharacterController`
    /// calls the same quantity `skinWidth`; Unreal spends it as
    /// `MAX_FLOOR_DIST`.
    /// A move whose physical sweep misses also checks the skin envelope, so
    /// subdividing an approach into sub-skin requests cannot consume the gap.
    /// The envelope only blocks incoming motion, not parallel or departing moves.
    pub skin_width: f64,
    /// How many times one move may be clipped and redirected before it stops.
    ///
    /// Quake's `numbumps` and Godot's `max_slides`.
    pub max_slides: u32,
    /// How many times the move may push the capsule out of what it overlaps
    /// before giving up and moving anyway.
    ///
    /// One pass resolves one contact completely, so this is the number of
    /// *distinct* surfaces a character can be dug out of in a single call — a
    /// corner needs two, a hole in a wall three.
    pub depenetration_passes: u32,
}

impl Default for CharacterConfig {
    /// An adult-sized character: 1.8 m tall, 0.6 m across, 45° slopes.
    ///
    /// 45° is expressed as [`std::f64::consts::FRAC_1_SQRT_2`] rather than
    /// `(PI / 4.0).cos()` so the default costs no transcendental at all — see
    /// [`min_ground_normal_y`](Self::min_ground_normal_y).
    fn default() -> Self {
        Self {
            radius: 0.3,
            half_height: 0.6,
            min_ground_normal_y: std::f64::consts::FRAC_1_SQRT_2,
            step_offset: 0.4,
            skin_width: 0.01,
            max_slides: 4,
            depenetration_passes: 4,
        }
    }
}

// ---------------------------------------------------------------------------
// Results
// ---------------------------------------------------------------------------

/// The ground a character is standing on.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroundContact {
    /// Upward unit normal of the surface.
    pub normal: DVec3,
    /// Where the capsule meets it.
    pub point: DVec3,
    /// Which collider it is.
    pub collider: ColliderId,
}

/// What a downward capsule probe found: the surface, how far below the capsule
/// it is, and whether the character could stand on it.
///
/// Returned by [`CharacterController::probe_ground`] and
/// [`CharacterController::probe_ground_at`]. The same probe is what ends every
/// [`CharacterController::move_and_slide`], which keeps only a walkable
/// result, as its [`GroundContact`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GroundProbe {
    /// The surface hit, in the form [`CharacterController::ground`] reports it.
    pub contact: GroundContact,
    /// How far the capsule travelled straight down before touching it. A
    /// character settled by a move sits one
    /// [`skin_width`](CharacterConfig::skin_width) above its ground, so this
    /// reads that gap for a settled character; zero means it is already
    /// touching or overlapping.
    pub distance: f64,
    /// Whether the surface passes [`CharacterController::is_walkable`] under
    /// this controller's slope limit.
    pub walkable: bool,
}

/// What one [`CharacterController::move_and_slide`] did.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct MoveOutcome {
    /// The displacement actually applied, which is the requested one minus
    /// whatever the world took away. **This is what a third-person game turns
    /// the body toward**, and it is world-space for the same reason the
    /// request is.
    pub motion: DVec3,
    /// How far the capsule was pushed out of geometry it started inside,
    /// before the move. Zero in the ordinary case.
    pub depenetration: DVec3,
    /// Whether the character is standing on walkable ground now. Agrees with
    /// [`CharacterController::is_grounded`].
    pub grounded: bool,
    /// Whether the move was blocked by a surface too steep to stand on and not
    /// steep enough to be a ceiling.
    pub hit_wall: bool,
    /// Whether the move was blocked by a surface facing downward.
    pub hit_ceiling: bool,
    /// Whether a step was climbed.
    pub stepped_up: bool,
    /// How many times the move was blocked and redirected. Zero means it went
    /// the whole way unobstructed.
    pub slides: u32,
}

/// What the slide loop found, before the ground probe has its say.
#[derive(Debug, Clone, Copy, Default)]
struct SlideReport {
    hit_wall: bool,
    hit_ceiling: bool,
    stepped_up: bool,
    slides: u32,
}

/// The shape a slide sweeps.
#[derive(Debug, Clone, Copy)]
enum Body {
    /// The controller's own upright capsule, centred on its position.
    Upright,
    /// A body lying back from the controller's position, which is its head;
    /// the capsule's own `head` is not read.
    Lying(LyingCapsule),
}

/// The world as a move reads it: a shared view of its colliders, and the
/// buffers that view's queries work in.
///
/// Every phase of a move queries through this and never through
/// `&mut PhysicsWorld`, so the solve has no way to write the world. The one
/// write a move makes, synchronizing its
/// [self collider](CharacterController::with_self_collider), comes after the
/// solve and outside it — which is what lets
/// [`CharacterController::preview_upright`] run the same solve and stop there.
struct WorldReader<'w, 's> {
    view: OverlapQueries<'w>,
    scratch: &'s mut QueryScratch,
}

impl<'w> WorldReader<'w, 'w> {
    /// Read `world` through the view and buffers it keeps for itself.
    fn of(world: &'w mut PhysicsWorld) -> Self {
        let (view, scratch) = world.overlap_queries_with_scratch();
        Self { view, scratch }
    }
}

/// A step-up that survived all three of its checks.
#[derive(Debug, Clone, Copy)]
struct StepUp {
    /// Where the capsule ends up.
    position: DVec3,
    /// The horizontal displacement the advance consumed.
    advance: DVec3,
}

// ---------------------------------------------------------------------------
// Controller
// ---------------------------------------------------------------------------

/// A capsule that walks.
///
/// Drive it one displacement at a time, at the fixed server timestep:
///
/// ```
/// use crcbl_phys::{BoxCollider, CharacterConfig, CharacterController, PhysicsWorld};
/// use glam::DVec3;
///
/// let mut world = PhysicsWorld::new();
/// world.add_box(BoxCollider::new(
///     DVec3::new(0.0, -1.0, 0.0),
///     DVec3::new(50.0, 1.0, 50.0),
/// ));
///
/// let config = CharacterConfig::default();
/// // Feet on the floor: the capsule centre is a radius plus a half-height up.
/// let feet = config.radius + config.half_height;
/// let mut character = CharacterController::new(config, DVec3::new(0.0, feet, 0.0));
///
/// let dt = 1.0 / 60.0;
/// // The caller owns the camera, so the caller owns this direction.
/// let intent = DVec3::new(1.0, 0.0, 0.0);
/// let gravity = DVec3::new(0.0, -9.81 * dt * dt, 0.0);
///
/// for _ in 0..30 {
///     let outcome = character.move_and_slide(&mut world, intent * 4.0 * dt + gravity);
///     assert!(outcome.grounded);
/// }
/// assert!(character.position().x > 1.0);
/// ```
#[derive(Debug, Clone)]
pub struct CharacterController {
    config: CharacterConfig,
    position: DVec3,
    ground: Option<GroundContact>,
    self_collider: Option<ColliderId>,
    /// The layers every world query of this controller looks at.
    query_mask: u32,
    /// Kept across calls so depenetration allocates nothing per tick.
    contacts: Vec<(ColliderId, Penetration)>,
}

impl CharacterController {
    /// Place a character at `position`, which is the **centre** of its capsule
    /// — a character whose feet are on `y = 0` starts at
    /// `radius + half_height`.
    ///
    /// It starts ungrounded whatever is beneath it; the first
    /// [`move_and_slide`](Self::move_and_slide), even with a zero
    /// displacement, is what finds the floor.
    #[must_use]
    pub fn new(config: CharacterConfig, position: DVec3) -> Self {
        Self {
            config,
            position,
            ground: None,
            self_collider: None,
            query_mask: ALL_LAYERS,
            contacts: Vec::new(),
        }
    }

    /// Tell the controller which collider in the world is its own body, so its
    /// sweeps do not find it.
    ///
    /// A character that other things have to collide with is registered in the
    /// world like anything else, and then sits on the start of every segment it
    /// sweeps — see [`PhysicsWorld::sweep_capsule_excluding`]. Given this, each
    /// move also writes the capsule's new position back to that collider, so
    /// the world's copy is never a tick behind.
    ///
    /// A character nothing else collides with does not need it.
    #[must_use]
    pub fn with_self_collider(mut self, collider: ColliderId) -> Self {
        self.set_self_collider(Some(collider));
        self
    }

    /// Change the world-collider binding without changing movement or ground state.
    pub fn set_self_collider(&mut self, collider: Option<ColliderId>) {
        self.self_collider = collider;
    }

    /// Look only at the world's colliders on a layer in `mask`: see
    /// [`PhysicsWorld::set_layers`].
    ///
    /// Every query the controller makes — the move's sweeps, the step-up, the
    /// ground probe that ends a move, [`probe_ground_at`](Self::probe_ground_at)
    /// and depenetration — applies it together with the
    /// [self collider](Self::with_self_collider) exclusion, so a collider
    /// masked out is one the character walks through, stands on nothing of,
    /// and is never pushed out of. The default is
    /// [`ALL_LAYERS`]: every collider is solid.
    #[must_use]
    pub fn with_query_mask(mut self, mask: u32) -> Self {
        self.set_query_mask(mask);
        self
    }

    /// Change the query mask without changing movement or ground state: see
    /// [`with_query_mask`](Self::with_query_mask).
    pub fn set_query_mask(&mut self, mask: u32) {
        self.query_mask = mask;
    }

    /// The layers this controller's queries look at.
    #[inline]
    #[must_use]
    pub fn query_mask(&self) -> u32 {
        self.query_mask
    }

    /// The centre of the capsule.
    #[inline]
    #[must_use]
    pub fn position(&self) -> DVec3 {
        self.position
    }

    /// Teleport. Discards the ground, because the ground under the old position
    /// says nothing about the new one; the next move finds it again.
    pub fn set_position(&mut self, position: DVec3) {
        self.position = position;
        self.ground = None;
    }

    /// The capsule as the world sees it.
    #[inline]
    #[must_use]
    pub fn capsule(&self) -> Capsule {
        Capsule::new(self.position, self.config.radius, self.config.half_height)
    }

    /// The limits this character moves under.
    #[inline]
    #[must_use]
    pub fn config(&self) -> &CharacterConfig {
        &self.config
    }

    /// The ground the character is standing on, if it is standing on any.
    #[inline]
    #[must_use]
    pub fn ground(&self) -> Option<&GroundContact> {
        self.ground.as_ref()
    }

    /// Whether the character is standing on walkable ground.
    #[inline]
    #[must_use]
    pub fn is_grounded(&self) -> bool {
        self.ground.is_some()
    }

    /// Ask the world, now, what is under the capsule where it stands.
    ///
    /// [`probe_ground_at`](Self::probe_ground_at) at the current
    /// [`position`](Self::position); see there.
    #[must_use]
    pub fn probe_ground(&self, world: &mut PhysicsWorld, distance: f64) -> Option<GroundProbe> {
        self.probe_ground_at(world, self.position, distance)
    }

    /// Ask the world, now, what is under this controller's capsule if it were
    /// centred at `position`, looking at most `distance` straight down.
    ///
    /// Nothing moves and nothing is recorded: the controller keeps its
    /// position and its [`ground`](Self::ground), and the world is only read.
    /// The sweep is the one [`move_and_slide`](Self::move_and_slide) ends
    /// with — the same capsule, the same [self collider](Self::with_self_collider)
    /// left out of it, the same [query mask](Self::with_query_mask), the same
    /// [`is_walkable`](Self::is_walkable) verdict —
    /// but it reports a surface too steep to stand on as well, with
    /// [`GroundProbe::walkable`] false, where a move treats that as no ground.
    ///
    /// **This is not [`ground`](Self::ground).** That is what the last move
    /// found and keeps saying so until the next one, however the world changed
    /// in between: remove the floor and `ground()` still names it. This sweeps
    /// the world as it is at the call, which is what an action that must start
    /// from real support — a revive, a vault, a mantle — should ask.
    ///
    /// `distance` is how far below the capsule to look. A move leaves a
    /// grounded character one [`skin_width`](CharacterConfig::skin_width)
    /// above its floor, so a probe for "standing on something" needs more than
    /// that; twice the skin width is the slack the move's own probe carries.
    /// The capsule's shape is this controller's [`config`](Self::config), so a
    /// caller that swaps configurations for a crouch probes the crouched shape.
    ///
    /// # Panics
    ///
    /// If `distance` is negative or not finite. A negative distance would
    /// sweep upward and answer a different question.
    #[must_use]
    pub fn probe_ground_at(
        &self,
        world: &mut PhysicsWorld,
        position: DVec3,
        distance: f64,
    ) -> Option<GroundProbe> {
        assert!(
            distance.is_finite() && distance >= 0.0,
            "a ground probe looks a finite, non-negative distance down, not {distance}",
        );
        self.probe_below(&mut WorldReader::of(world), position, distance)
    }

    /// A solid collider a body lying as `capsule` would be inside, or `None`
    /// if it fits there: [`PhysicsWorld::lying_capsule_blocker`] under this
    /// controller's [self collider](Self::with_self_collider) exclusion and
    /// [query mask](Self::with_query_mask), so it sees exactly what the
    /// controller's own moves see.
    ///
    /// Like [`probe_ground_at`](Self::probe_ground_at) it moves nothing and
    /// records nothing. The shape is the caller's and not this controller's
    /// [`config`](Self::config): a prone body is a different shape from the
    /// one the controller walks with, and this is the check to make before
    /// letting a character lie down; [`turn_lying`](Self::turn_lying) makes it
    /// along a turn.
    ///
    /// A capsule whose [`head`](LyingCapsule::head) is this controller's
    /// settled [`position`](Self::position) with its radius sits a
    /// [`skin_width`](CharacterConfig::skin_width) above the floor, and fits;
    /// only a penetration blocks, never a touch.
    #[must_use]
    pub fn lying_blocker(
        &self,
        world: &mut PhysicsWorld,
        capsule: &LyingCapsule,
    ) -> Option<ColliderId> {
        world.lying_capsule_blocker(capsule, self.filter())
    }

    /// Whether a surface with this normal is ground the character can stand on.
    ///
    /// Upward-facing is part of the question and not an assumption: a
    /// [`min_ground_normal_y`](CharacterConfig::min_ground_normal_y) of zero
    /// would otherwise make a vertical wall walkable, and then the ramp
    /// adjustment would divide by its zero rise.
    #[inline]
    #[must_use]
    pub fn is_walkable(&self, normal: DVec3) -> bool {
        let rise = normal.dot(UP);
        rise > 0.0 && rise >= self.config.min_ground_normal_y
    }

    /// Whether a surface with this normal faces down enough to be a ceiling.
    ///
    /// The mirror of [`is_walkable`](Self::is_walkable) through the horizontal,
    /// so every normal is ground, ceiling or wall and nothing is two of them.
    #[inline]
    #[must_use]
    pub fn is_ceiling(&self, normal: DVec3) -> bool {
        let rise = normal.dot(UP);
        rise < 0.0 && -rise >= self.config.min_ground_normal_y
    }

    /// Move by a **world-space** displacement, sliding along whatever gets in
    /// the way.
    ///
    /// `motion` is a displacement for this tick and not a velocity: the caller
    /// has already multiplied by its own timestep, so nothing here reads a
    /// clock and two callers stepping at different rates get the same answer
    /// for the same displacement.
    ///
    /// # What a grounded move does with the vertical part
    ///
    /// While the character is standing on walkable ground and `motion` does not
    /// point upward, the vertical part of `motion` is **replaced** by the rise
    /// or fall the ground itself imposes — Unreal's
    /// `ComputeGroundMovementDelta`. Walking up a ramp therefore covers the
    /// same horizontal distance as walking on the flat, and the gravity a
    /// caller keeps applying does not dig the capsule into the slope. What
    /// holds the character down instead is the ground probe at the end of the
    /// move.
    ///
    /// The moment the ground stops being walkable, or the caller asks to go
    /// up, `motion` is used as given and gravity does what gravity does.
    pub fn move_and_slide(&mut self, world: &mut PhysicsWorld, motion: DVec3) -> MoveOutcome {
        self.move_upright(world, motion, None)
    }

    /// [`move_and_slide`](Self::move_and_slide), writing every sweep that met
    /// something into `contacts` (which is cleared first), in the order the
    /// slide met them.
    ///
    /// The move itself is the same one, to the bit: recording reads what the
    /// slide found and never feeds back into it. See [`SlideContact`] for what
    /// each entry holds, and why its fraction is a distance along one straight
    /// sweep rather than a time.
    ///
    /// `contacts` is the caller's so a game recording every tick reuses one
    /// buffer rather than allocating a list per move; the slide never records
    /// more than [`max_slides`](CharacterConfig::max_slides) of them.
    pub fn move_and_slide_into(
        &mut self,
        world: &mut PhysicsWorld,
        motion: DVec3,
        contacts: &mut Vec<SlideContact>,
    ) -> MoveOutcome {
        contacts.clear();
        self.move_upright(world, motion, Some(contacts))
    }

    /// The one upright move, recording into `contacts` when there are any:
    /// [`solve_upright`](Self::solve_upright), then the self collider
    /// synchronized to where it left the capsule.
    fn move_upright(
        &mut self,
        world: &mut PhysicsWorld,
        motion: DVec3,
        contacts: Option<&mut Vec<SlideContact>>,
    ) -> MoveOutcome {
        let outcome = self.solve_upright(&mut WorldReader::of(world), motion, contacts);
        if let Some(collider) = self.self_collider {
            world.set_capsule(collider, self.capsule());
        }
        outcome
    }

    /// Everything an upright move decides — depenetration, the slide, the
    /// step-up and the ground probe — applied to this controller and to
    /// nothing else: the world is only read.
    ///
    /// [`move_upright`](Self::move_upright) commits the result to the world;
    /// [`preview_upright`](Self::preview_upright) runs it on a copy and keeps
    /// what it found. One solve for both is what makes a preview the move's
    /// answer to the bit rather than a second algorithm's.
    fn solve_upright(
        &mut self,
        world: &mut WorldReader<'_, '_>,
        motion: DVec3,
        contacts: Option<&mut Vec<SlideContact>>,
    ) -> MoveOutcome {
        let depenetration = self.depenetrate(world);
        let start = self.position;
        let was_grounded = self.ground.is_some();

        let adjusted = self.ground_adjusted(motion, was_grounded);
        let report = self.slide(world, adjusted, was_grounded, Body::Upright, contacts);
        self.settle_on_ground(world, was_grounded, motion);

        MoveOutcome {
            motion: self.position - start,
            depenetration,
            grounded: self.ground.is_some(),
            hit_wall: report.hit_wall,
            hit_ceiling: report.hit_ceiling,
            stepped_up: report.stepped_up,
            slides: report.slides,
        }
    }

    // ── Phases ─────────────────────────────────────────────────────────

    /// Push the capsule out of everything it overlaps, deepest contact first.
    ///
    /// One contact per pass, rather than the sum of all of them: two surfaces
    /// sharing a normal would double the push, and a corner's two normals
    /// summed points somewhere neither of them does. Resolving the deepest and
    /// asking again converges on the corner and never overshoots.
    fn depenetrate(&mut self, world: &mut WorldReader<'_, '_>) -> DVec3 {
        let mut total = DVec3::ZERO;
        for _ in 0..self.config.depenetration_passes {
            let capsule = self.capsule();
            let mut contacts = std::mem::take(&mut self.contacts);
            world.view.capsule_penetrations_filtered_into(
                &capsule,
                self.filter(),
                world.scratch,
                &mut contacts,
            );
            let deepest = contacts
                .iter()
                .max_by(|a, b| a.1.depth.total_cmp(&b.1.depth))
                .map(|&(_, penetration)| penetration);
            self.contacts = contacts;

            let Some(penetration) = deepest else {
                break;
            };
            let push = penetration.normal * (penetration.depth + self.config.skin_width);
            self.position += push;
            total += push;
        }
        total
    }

    /// Turn a requested displacement into the one a grounded character
    /// actually makes.
    ///
    /// While the character is on walkable ground and not asking to leave it,
    /// the horizontal part of the request keeps its length and takes its rise
    /// from the ground plane — Unreal's `ComputeGroundMovementDelta` with
    /// `bMaintainHorizontalGroundVelocity`. The vertical part is **discarded**,
    /// not projected.
    ///
    /// Discarding it is what stops a standing character creeping downhill.
    /// Clipping gravity against the slope instead, which is what happens the
    /// moment this does not run, leaves a downhill component behind on every
    /// tick, and Godot spends `floor_stop_on_slope` on the same problem. It
    /// also means a request with no horizontal part becomes no movement at all,
    /// because the ramp form of a zero horizontal is zero.
    fn ground_adjusted(&self, motion: DVec3, was_grounded: bool) -> DVec3 {
        if !was_grounded || motion.dot(UP) > 0.0 {
            return motion;
        }
        let Some(ground) = self.ground else {
            return motion;
        };
        let flat = motion - UP * motion.dot(UP);
        flat - UP * (ground.normal.dot(flat) / ground.normal.dot(UP))
    }

    /// The collect-and-slide loop, after `SV_FlyMove`, sweeping `body`.
    ///
    /// Only an upright body steps up; a grounded lying one meets a wall as
    /// though the wall were upright.
    ///
    /// Each sweep that meets something is pushed onto `contacts`, when given,
    /// once the slide has decided what to do about it. Nothing read back from
    /// a contact steers the loop, so recording cannot change the move.
    fn slide(
        &mut self,
        world: &mut WorldReader<'_, '_>,
        motion: DVec3,
        was_grounded: bool,
        body: Body,
        mut contacts: Option<&mut Vec<SlideContact>>,
    ) -> SlideReport {
        let mut record = |contact| {
            if let Some(contacts) = contacts.as_deref_mut() {
                contacts.push(contact);
            }
        };
        let mut report = SlideReport::default();
        let primal = motion;
        let mut remaining = motion;
        // Quake's `original_velocity`: what the plane set is asked to clip.
        // It is only re-read once the capsule has actually covered ground,
        // because a plane found without moving has to be added to the ones
        // already there rather than replacing them.
        let mut clip_from = motion;
        let mut planes = [DVec3::ZERO; MAX_PLANES];
        let mut plane_count = 0usize;

        for _ in 0..self.config.max_slides {
            let distance = remaining.length();
            if distance <= MIN_MOVE {
                return report;
            }
            let direction = remaining / distance;
            let target = self.position + remaining;

            let Some(sweep) = self.sweep_body(world, body, remaining) else {
                self.position = target;
                return report;
            };
            let (collider, hit) = (sweep.collider, sweep.hit);
            report.slides += 1;
            let mut contact = SlideContact {
                collider,
                normal: hit.normal,
                requested: remaining,
                fraction: hit.t,
                started_inside: hit.started_inside,
                clearance_only: sweep.clearance.is_some(),
                applied: DVec3::ZERO,
                remaining: DVec3::ZERO,
                stepped_up: false,
            };

            let wall = !self.is_ceiling(hit.normal) && !self.is_walkable(hit.normal);
            let mut plane = hit.normal;
            if wall && was_grounded && matches!(body, Body::Lying(_)) {
                // Unreal's `SlideAlongSurface`: a grounded body is not pushed
                // up a wall. A lying body meets the edge of a riser with its
                // round end, whose normal leans up, and clipping against that,
                // or backing off along it, lifts it a little every tick until
                // it is on top; against the wall made upright, it stops. The
                // upright capsule is not given the rule here: it steps up, and
                // its sweep meets a box's edge square
                // (`query::swept_capsule_vs_aabb`), not leaning.
                let flat = (plane - UP * plane.dot(UP)).normalize_or_zero();
                if flat != DVec3::ZERO {
                    plane = flat;
                }
            }

            let along = hit.t * distance;
            let mut back_off = DVec3::ZERO;
            let travel = if sweep.clearance.is_some() {
                (!hit.started_inside).then_some(along)
            } else {
                self.skin_short(along, direction, plane)
            };
            if let Some(travel) = travel {
                let travel = travel.min(distance);
                let step = direction * travel;
                self.position += step;
                remaining -= step;
                contact.applied = step;
                // Only real ground covered makes the planes already found
                // stale. A sweep that touches within rounding of the skin
                // width advances by noise, and dropping the set on that
                // would lose the crease: a capsule falling into a corner
                // would keep only the second wall, clip against it alone,
                // and stop dead every tick.
                if travel > MIN_MOVE {
                    clip_from = remaining;
                    plane_count = 0;
                }
            } else {
                // The contact is no further than the skin width, so clipping
                // alone would leave the next sweep starting that near too,
                // and a sweep with a tolerance can meet the same surface
                // again for motion along it: conservative advancement divides
                // a gap of rounding size by a closing speed of rounding size,
                // and a capsule hovering 1e-16 off a turned box hung in
                // mid-air on it. A capsule set down exactly on the floor
                // arrives here too, started inside, and must still be able to
                // walk. Back off along the normal to the gap every other
                // sweep keeps — unless the gap already is that, to within
                // rounding: a character resting a skin off a wall it keeps
                // walking into meets it here every tick, and a back-off of
                // rounding size moved it an ulp along the normal each time
                // it was asked to stand still.
                let approach = (along * -direction.dot(plane)).max(0.0);
                let short = sweep.clearance.unwrap_or(self.config.skin_width - approach);
                if short > MIN_MOVE {
                    back_off = plane * short;
                }
            }

            if self.is_ceiling(hit.normal) {
                report.hit_ceiling = true;
            } else if wall {
                report.hit_wall = true;
                if was_grounded
                    && !report.stepped_up
                    && matches!(body, Body::Upright)
                    && let Some(step) = self.try_step_up(world, remaining)
                {
                    contact.applied += step.position - self.position;
                    self.position = step.position;
                    remaining -= step.advance;
                    clip_from = remaining;
                    plane_count = 0;
                    report.stepped_up = true;
                    record(SlideContact {
                        remaining,
                        stepped_up: true,
                        ..contact
                    });
                    continue;
                }
            }

            // A valid step can cross a riser's clearance envelope. Backing
            // away before trying it would cancel a shorter forward move on
            // every tick, preventing the capsule from reaching the landing.
            self.position += back_off;
            contact.applied += back_off;

            if plane_count == MAX_PLANES {
                record(contact);
                return report;
            }
            planes[plane_count] = plane;
            plane_count += 1;

            remaining = clip_to_planes(clip_from, &planes[..plane_count], remaining);
            if remaining.dot(primal) <= 0.0 {
                record(contact);
                return report;
            }
            record(SlideContact {
                remaining,
                ..contact
            });
        }
        report
    }

    /// Rise, advance, drop — Unreal's `StepUp`, with its landing check.
    ///
    /// The three refusals stop three different things. The **advance** check is
    /// what makes a corner not a step: after rising, a corner is still a wall
    /// in both directions and nothing was stepped onto. The **landing** check
    /// keeps the capsule off thin air when the drop finds nothing under it. The
    /// **walkable** test keeps it off a surface it is not allowed to stand on
    /// and would slide straight back off.
    ///
    /// They are not the last line: the ground probe that ends every move pulls
    /// the capsule back down onto whatever it is really standing on, so a step
    /// that rose without earning it is undone anyway. All four have to be gone
    /// at once before a character in a corner actually gains height, which is
    /// what `tests::a_character_pressed_into_a_corner_does_not_climb_it` was
    /// checked against.
    fn try_step_up(&self, world: &mut WorldReader<'_, '_>, remaining: DVec3) -> Option<StepUp> {
        if self.config.step_offset <= 0.0 {
            return None;
        }
        let forward = remaining - UP * remaining.dot(UP);
        let forward_distance = forward.length();
        if forward_distance <= MIN_MOVE {
            return None;
        }
        let forward_direction = forward / forward_distance;

        // Rise. A settled capsule is already a skin width off its floor, and
        // that gap is what lets a step of exactly `step_offset` clear its own
        // top rather than starting the advance in contact with it. An overhead
        // obstruction shortens the rise instead of cancelling it.
        let rise = self.clear_travel(world, self.position, UP * self.config.step_offset);
        if rise <= MIN_MOVE {
            return None;
        }
        let raised = self.position + UP * rise;

        // Advance. No progress up here means this is a wall and not a step.
        let advance = self.clear_travel(world, raised, forward);
        if advance <= MIN_MOVE {
            return None;
        }
        // Drop, far enough to actually reach what it is landing on: the rise
        // it is undoing plus the gap it started from, or a step of no height at
        // all comes back as a sweep that ends exactly at contact and is
        // reported as a miss. Unreal spends the same two floor distances on it.
        let drop = rise + self.config.skin_width * GROUND_PROBE_SKINS;
        let land = |world: &mut WorldReader<'_, '_>, advance: f64| {
            let over = raised + forward_direction * advance;
            let (_, landing) = world.view.sweep_upright_where(
                &Capsule::new(over, self.config.radius, self.config.half_height),
                over - UP * drop,
                self.filter(),
                world.scratch,
                |hit| hit.normal.dot(UP) > MIN_MOVE,
            )?;
            (!landing.started_inside).then_some((advance, over, landing))
        };
        let (advance, over, landing) = land(world, advance)?;
        if !self.is_walkable(landing.normal)
            && !self.perches_on(world, landing.point, over, forward_direction)
        {
            return None;
        }
        // The step is as high as what it lands on, not as high as the capsule
        // rose: a round capsule on a rounded edge sits lower than the edge's
        // top, and would otherwise climb a step a little higher than the
        // offset. `feet` rest a skin above the floor, so this allows the
        // offset above the floor and that skin.
        let feet = self.position.y - self.config.radius - self.config.half_height;
        if landing.point.y - feet > self.config.step_offset {
            return None;
        }
        let fall = (landing.t * drop - self.config.skin_width).clamp(0.0, drop);

        Some(StepUp {
            position: over - UP * fall,
            advance: forward_direction * advance,
        })
    }

    /// Find the ground, and drop onto it if it fell away under the character.
    ///
    /// The probe is what makes the ground authoritative: a walkable plane the
    /// slide loop happened to graze is not standing on it, and a character that
    /// walked off a lip is still standing on the floor below. Snapping only
    /// happens to a character that was already walking and is not asking to go
    /// up, so a jump is not swallowed by the floor it just left.
    fn settle_on_ground(
        &mut self,
        world: &mut WorldReader<'_, '_>,
        was_grounded: bool,
        motion: DVec3,
    ) {
        self.ground = None;
        // An explicit ascent leaves support even inside the ground probe's
        // reach. Use requested motion here: walking uphill also rises, but
        // that rise belongs to the ground adjustment and must stay supported.
        if motion.dot(UP) > 0.0 {
            return;
        }
        let probe = self.settle_reach(was_grounded, motion);

        let Some(mut found) = self.probe_below(world, self.position, probe) else {
            return;
        };
        let ahead = DVec3::new(motion.x, 0.0, motion.z).normalize_or_zero();
        let perched = !found.walkable
            && was_grounded
            && self.perches_on(
                world,
                found.contact.point,
                self.position - UP * found.distance,
                ahead,
            );
        if perched {
            // Stood on as a step's corner is, flat: the edge's own normal
            // steepens towards horizontal at its rim, and ground-following
            // along it would climb without bound. The next move's sweep meets
            // the edge ahead and steps on.
            found.contact.normal = UP;
            found.walkable = true;
        }
        if !found.walkable {
            // A walking character over an edge too steep to stand on, and not
            // stepping onto it, slides off it, down its tangent, onto what is
            // below within the same reach: a lip walked off lands on the
            // floor beneath, while a character that was not walking has only
            // the probe's slack to slide and falls.
            let Some((landed, below)) = self.slide_off_edge(world, probe, &found) else {
                return;
            };
            self.position = landed;
            found = below;
        }
        // Signed, and so it corrects in both directions: a capsule that ended
        // the move *closer* to the floor than a skin width — set down on it, or
        // walked onto it — is lifted back off, which is what keeps the next
        // horizontal sweep from starting on the floor's surface and being told
        // it is already in contact. Unreal spends `AdjustFloorHeight` on the
        // same correction. The lift is capped at the gap it is restoring;
        // anything deeper than that is a penetration, and the next move's
        // depenetration is what owns it.
        let fall = (found.distance - self.config.skin_width).clamp(-self.config.skin_width, probe);
        self.position -= UP * fall;
        self.ground = Some(found.contact);
    }

    /// Whether a capsule centred at `centre`, moving horizontally along
    /// `ahead`, perches on an edge it touches at `point` that is too steep to
    /// stand on: when the edge is ahead of it, so it is stepping onto it, no
    /// higher above its feet than the step offset, and **the rim of a walkable
    /// top**, which a ray dropped a skin beyond the contact finds within a
    /// skin of its height. A steep slope has no top there, only more slope,
    /// and is refused: perching on it would climb it a step at a time.
    /// Standing still, or moving away, a capsule has nothing ahead, and slides
    /// off.
    fn perches_on(
        &self,
        world: &mut WorldReader<'_, '_>,
        point: DVec3,
        centre: DVec3,
        ahead: DVec3,
    ) -> bool {
        let feet = centre.y - self.config.radius - self.config.half_height;
        let toward = DVec3::new(point.x - centre.x, 0.0, point.z - centre.z);
        if toward.dot(ahead) <= MIN_MOVE || point.y - feet > self.config.step_offset {
            return false;
        }
        let skin = self.config.skin_width;
        let ray = Ray::new(point + ahead * skin + UP * skin, -UP).with_bounds(0.0, 2.0 * skin);
        world
            .view
            .cast_ray_filtered(&ray, self.filter(), world.scratch)
            .is_some_and(|(_, top)| !top.started_inside && self.is_walkable(top.normal))
    }

    /// Where a capsule resting `found.distance` above an edge too steep to
    /// stand on comes to rest sliding off it with the rest of `reach`, and
    /// the walkable ground it finds there, or `None` if it finds none: the
    /// slide follows the edge's surface downward, as far as falls the rest of
    /// the reach, and ends a skin short of whatever it meets.
    fn slide_off_edge(
        &self,
        world: &mut WorldReader<'_, '_>,
        reach: f64,
        found: &GroundProbe,
    ) -> Option<(DVec3, GroundProbe)> {
        let normal = found.contact.normal;
        let down = (-UP + normal * normal.dot(UP)).normalize_or_zero();
        let remaining = reach - found.distance;
        if down.dot(UP) > -MIN_MOVE || remaining <= MIN_MOVE {
            return None;
        }
        let start = self.position - UP * found.distance;
        let length = remaining / -down.dot(UP);
        // Only surfaces the slide closes on stop it: the edge it slides along
        // is tangent to it and holds nothing back.
        let travel = match world.view.sweep_upright_where(
            &Capsule::new(start, self.config.radius, self.config.half_height),
            start + down * length,
            self.filter(),
            world.scratch,
            |hit| down.dot(hit.normal) < -MIN_MOVE,
        ) {
            None => length,
            Some((_, hit)) => self.skin_short(hit.t * length, down, hit.normal)?,
        };
        let end = start + down * travel;
        let below = self.probe_below(world, end, self.config.skin_width * GROUND_PROBE_SKINS)?;
        below.walkable.then_some((end, below))
    }

    /// How far below itself a move's closing ground probe looks: the
    /// [`step_offset`](CharacterConfig::step_offset) it snaps down by, for a
    /// character that was walking and is not asking to go up, and the probe's
    /// slack either way.
    fn settle_reach(&self, was_grounded: bool, motion: DVec3) -> f64 {
        let snap = if was_grounded && motion.dot(UP) <= 0.0 {
            self.config.step_offset
        } else {
            0.0
        };
        snap + self.config.skin_width * GROUND_PROBE_SKINS
    }

    /// Sweep the capsule straight down `distance` from `from`, and describe
    /// the first surface it touches.
    ///
    /// The one ground probe: [`settle_on_ground`](Self::settle_on_ground) and
    /// the public [`probe_ground_at`](Self::probe_ground_at) both ask it, so
    /// the two cannot disagree about what counts as ground.
    fn probe_below(
        &self,
        world: &mut WorldReader<'_, '_>,
        from: DVec3,
        distance: f64,
    ) -> Option<GroundProbe> {
        let found = world.view.sweep_upright_where(
            &Capsule::new(from, self.config.radius, self.config.half_height),
            from - UP * distance,
            self.filter(),
            world.scratch,
            |hit| hit.normal.dot(UP) > MIN_MOVE,
        )?;
        let probe = self.ground_probe(found, distance);
        if probe.walkable {
            return Some(probe);
        }
        Some(self.wedged_footing(world, from - UP * probe.distance, probe))
    }

    /// `probe`, a surface too steep to stand on alone, as footing when the
    /// capsule at `at` is held up by more than one surface whose normals
    /// together point up within the slope limit: a capsule wedged in the
    /// V-crease of two steep faces stands in it, as EW asked (2026-10-23).
    /// The ground it reports is the normals' normalized sum, so slope
    /// projection runs along the crease, and a crease too steep along its own
    /// length still sums to a normal the limit refuses, and slides.
    ///
    /// The surfaces are the ones within the probe's slack of the capsule,
    /// where the slide loop leaves a resting character a skin off each of
    /// them, and only those facing up: a wall beside the capsule holds
    /// nothing up. One supporting surface is `probe` itself, refused as it
    /// was.
    fn wedged_footing(
        &self,
        world: &mut WorldReader<'_, '_>,
        at: DVec3,
        probe: GroundProbe,
    ) -> GroundProbe {
        let reach = Capsule::new(
            at,
            self.config.radius + self.config.skin_width * GROUND_PROBE_SKINS,
            self.config.half_height,
        );
        let mut normals = Vec::new();
        world
            .view
            .capsule_contact_normals_into(&reach, self.filter(), world.scratch, &mut normals);
        let (count, sum) = normals
            .iter()
            .filter(|normal| normal.dot(UP) > MIN_MOVE)
            .fold((0_usize, DVec3::ZERO), |(count, sum), normal| {
                (count + 1, sum + *normal)
            });
        let combined = sum.normalize_or_zero();
        if count < 2 || !self.is_walkable(combined) {
            return probe;
        }
        GroundProbe {
            contact: GroundContact {
                normal: combined,
                ..probe.contact
            },
            walkable: true,
            ..probe
        }
    }

    /// A downward sweep of `distance` that met `found`, described as ground.
    fn ground_probe(&self, (collider, hit): (ColliderId, ShapeHit), distance: f64) -> GroundProbe {
        GroundProbe {
            contact: GroundContact {
                normal: hit.normal,
                point: hit.point,
                collider,
            },
            distance: hit.t * distance,
            walkable: self.is_walkable(hit.normal),
        }
    }

    // ── Sweeping ───────────────────────────────────────────────────────

    /// How far along `delta` the skin envelope can go. Parallel and departing
    /// surfaces do not obstruct the step's rise or forward travel.
    fn clear_travel(&self, world: &mut WorldReader<'_, '_>, from: DVec3, delta: DVec3) -> f64 {
        let distance = delta.length();
        if distance <= MIN_MOVE {
            return 0.0;
        }
        world
            .view
            .sweep_upright_where(
                &Capsule::new(
                    from,
                    self.config.radius + self.config.skin_width,
                    self.config.half_height,
                ),
                from + delta,
                self.filter(),
                world.scratch,
                |hit| delta.dot(hit.normal) < -MIN_MOVE,
            )
            .map_or(distance, |(_, hit)| hit.t * distance)
    }

    /// How far along `direction` the capsule can go toward a contact `along`
    /// ahead of it, with surface normal `normal`, and stay a
    /// [`skin_width`](CharacterConfig::skin_width) off the surface's plane:
    /// `None` when it is already no further than that.
    ///
    /// The gap is measured along the normal, as a gap is. Measured along the
    /// move instead, an oblique approach is left nearer than a skin; the
    /// slide backs that off along the normal on its next sweep, and the two
    /// then fight — a capsule in a crease bounced between its walls rather
    /// than falling down it. The step-up's advance measures it the same way,
    /// or a character the slide left a skin off both walls of a corner is
    /// offered the diagonal between the two measures as a step.
    fn skin_short(&self, along: f64, direction: DVec3, normal: DVec3) -> Option<f64> {
        let closing = -direction.dot(normal);
        (along * closing > self.config.skin_width).then(|| along - self.config.skin_width / closing)
    }

    /// The capsule's own sweep, with the character's body and every collider
    /// off its query mask left out of it.
    fn sweep(
        &self,
        world: &mut WorldReader<'_, '_>,
        from: DVec3,
        to: DVec3,
    ) -> Option<(ColliderId, ShapeHit)> {
        world.view.sweep_capsule_filtered(
            &Segment::new(from, to),
            self.config.radius,
            self.config.half_height,
            self.filter(),
            world.scratch,
        )
    }

    /// The filter every world query of this controller runs under.
    fn filter(&self) -> QueryFilter {
        QueryFilter::excluding(self.self_collider).with_mask(self.query_mask)
    }
}

/// Redirect `motion` so it runs along the planes it has collected, after
/// `SV_FlyMove`'s plane-set rule.
///
/// The first plane whose clipped result does not drive into any of the others
/// wins. When none does, two planes have a crease to run along — their cross
/// product — and anything more is a corner with nowhere to go.
///
/// `current` is the displacement as the last clip left it, which is what the
/// crease is measured against; Quake takes it from the same place.
fn clip_to_planes(motion: DVec3, planes: &[DVec3], current: DVec3) -> DVec3 {
    for (i, &plane) in planes.iter().enumerate() {
        let clipped = motion - plane * motion.dot(plane);
        if planes
            .iter()
            .enumerate()
            .all(|(j, &other)| j == i || clipped.dot(other) >= 0.0)
        {
            return clipped;
        }
    }
    if let [first, second] = planes {
        // Normalised, where Quake leaves the cross product at the sine of the
        // angle between the planes and quietly shortens the move by it. Quake
        // III normalises for the same reason.
        let crease = first.cross(*second).normalize_or_zero();
        return crease * crease.dot(current);
    }
    DVec3::ZERO
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::collider::{BoxCollider, Sphere};

    /// A ramp big enough that its curvature does not move the slope under the
    /// character: over the tenth of a metre these tests walk, the contact angle
    /// changes by the travel over this radius.
    const DOME_RADIUS: f64 = 1000.0;

    /// The centre a capsule needs so its feet are at `feet`.
    fn centre_for_feet(config: &CharacterConfig, feet: f64) -> f64 {
        feet + config.radius + config.half_height
    }

    /// A floor whose top is `y = 0`, wide enough that nothing in these tests
    /// reaches its edge.
    fn flat_world() -> PhysicsWorld {
        let mut world = PhysicsWorld::new();
        world.add_box(BoxCollider::new(
            DVec3::new(0.0, -1.0, 0.0),
            DVec3::new(50.0, 1.0, 50.0),
        ));
        world
    }

    /// A character standing on `flat_world`'s floor at the origin, already
    /// grounded — the zero move is what finds the floor.
    fn standing(world: &mut PhysicsWorld, config: CharacterConfig) -> CharacterController {
        let mut character =
            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0));
        character.move_and_slide(world, DVec3::ZERO);
        assert!(character.is_grounded(), "the fixture starts on the floor");
        character
    }

    /// A dome whose summit is `y = 0`, so a character on it stands on a slope
    /// of whatever angle `on_dome` places it at.
    pub(super) fn dome_world() -> PhysicsWorld {
        let mut world = PhysicsWorld::new();
        world.add_sphere(Sphere::new(DVec3::new(0.0, -DOME_RADIUS, 0.0), DOME_RADIUS));
        world
    }

    /// The capsule centre that touches the dome exactly where its surface
    /// normal is `angle` from vertical, leaning toward `+X`.
    ///
    /// Exact rather than approximate: a capsule against a sphere is its centre
    /// against that sphere grown along Y (see `query`'s swept-capsule note), so
    /// the contact normal is the radial direction from the grown shape's top
    /// cap, which is what this offsets from.
    pub(super) fn on_dome(config: &CharacterConfig, angle: f64) -> DVec3 {
        let normal = DVec3::new(
            crcbl_core::trig::sin(angle),
            crcbl_core::trig::cos(angle),
            0.0,
        );
        DVec3::new(0.0, -DOME_RADIUS + config.half_height, 0.0)
            + normal * (DOME_RADIUS + config.radius)
    }

    /// A floor over `x < 0` whose top is `y = 0`, and a second one over
    /// `x > 0` whose top is `y = height`.
    pub(super) fn stepped_world(height: f64) -> PhysicsWorld {
        let mut world = PhysicsWorld::new();
        world.add_box(BoxCollider::new(
            DVec3::new(-25.0, -1.0, 0.0),
            DVec3::new(25.0, 1.0, 5.0),
        ));
        world.add_box(BoxCollider::new(
            DVec3::new(25.0, (height - 2.0) * 0.5, 0.0),
            DVec3::new(25.0, (height + 2.0) * 0.5, 5.0),
        ));
        world
    }

    fn feet_of(character: &CharacterController) -> f64 {
        character.position().y - character.config().radius - character.config().half_height
    }

    // ── The unobstructed case ──────────────────────────────────────────

    #[test]
    fn an_unobstructed_move_covers_the_whole_displacement_and_slides_none() {
        let mut world = flat_world();
        let mut character = standing(&mut world, CharacterConfig::default());
        let outcome = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, -0.1));

        assert_eq!(outcome.slides, 0, "nothing was in the way");
        assert!(
            (outcome.motion - DVec3::new(0.2, 0.0, -0.1)).length() < 1e-12,
            "asked for (0.2, 0, -0.1) and got {:?}",
            outcome.motion,
        );
        assert!(outcome.grounded);
        assert!(!outcome.hit_wall && !outcome.hit_ceiling && !outcome.stepped_up);
    }

    // ── Walls ──────────────────────────────────────────────────────────

    /// **Walking into a wall at an angle keeps the speed along it.** Stopping
    /// dead against a wall the character is only grazing is the failure this
    /// guards; the tangential half of the displacement has to survive intact,
    /// not merely mostly.
    #[test]
    fn walking_into_a_wall_at_an_angle_keeps_the_whole_speed_along_it() {
        let mut world = flat_world();
        // Its -X face is x = 0, so a capsule centred at x = -0.35 has 0.05 of
        // clear approach in front of its flank.
        world.add_box(BoxCollider::new(
            DVec3::new(4.5, 2.0, 0.0),
            DVec3::new(4.5, 3.0, 10.0),
        ));
        let config = CharacterConfig::default();
        let mut character = standing(&mut world, config);
        character.set_position(DVec3::new(-0.35, centre_for_feet(&config, 0.0), 0.0));
        character.move_and_slide(&mut world, DVec3::ZERO);

        let asked = DVec3::new(0.1, 0.0, 0.1);
        let outcome = character.move_and_slide(&mut world, asked);

        assert!(outcome.hit_wall, "the wall's -X face is 0.05 away");
        assert!(
            outcome.motion.x < asked.x,
            "the wall must have taken something off the approach, and x moved {}",
            outcome.motion.x,
        );
        assert!(
            (outcome.motion.z - asked.z).abs() < 1e-12,
            "the speed along the wall is {} and was asked to be {}",
            outcome.motion.z,
            asked.z,
        );
    }

    /// **A move far longer than the obstacle is thick still stops at it.**
    /// The whole point of sweeping rather than stepping-and-testing.
    #[test]
    fn a_move_far_longer_than_the_obstacle_does_not_pass_through_it() {
        let mut world = flat_world();
        let pane_x = 5.0;
        let pane_half_thickness = 0.005;
        world.add_box(BoxCollider::new(
            DVec3::new(pane_x, 2.0, 0.0),
            DVec3::new(pane_half_thickness, 3.0, 10.0),
        ));
        let config = CharacterConfig::default();
        let mut character = standing(&mut world, config);

        let outcome = character.move_and_slide(&mut world, DVec3::new(50.0, 0.0, 0.0));

        assert!(outcome.hit_wall);
        let front = pane_x - pane_half_thickness - config.radius;
        assert!(
            character.position().x <= front,
            "the capsule's flank is at {} and the pane's near face at {front}",
            character.position().x + config.radius,
        );
    }

    // ── Slopes ─────────────────────────────────────────────────────────

    /// **The slope the controller stops walking is the one it was configured
    /// with**, measured rather than assumed.
    ///
    /// The sweep: place a character on a dome at every tenth of a degree from
    /// `0°` to `89.9°`, ground it, then hand it sixty ticks of pure gravity and
    /// no horizontal intent at all, and record how far it drifted sideways. On
    /// ground it can stand on the answer is exactly zero — that is
    /// `ground_adjusted`'s refusal to creep. On ground it cannot, gravity is
    /// clipped to the surface and the character slides down it.
    ///
    /// Measured with [`CharacterConfig::default`]: the drift stays at zero up
    /// to the configured limit and is non-zero one step past it, which brackets
    /// the limit to within the sweep's own step. The comparison is `>=`, so a
    /// slope exactly at the limit is walkable.
    ///
    /// **The bracket is closed at both ends, and it has to be.** Which of the
    /// two adjacent samples the limit lands on is not portable: the dome's
    /// surface normal arrives through `sin`/`cos`, those are platform
    /// transcendentals, and a last-ulp difference moves a slope that sits
    /// exactly on the threshold to either side of it. Linux measures the limit
    /// as the last still sample and Windows as the first creeping one, from the
    /// same source. Asserting an open end pins the measurement finer than the
    /// sweep's step can resolve, which is a claim about a libm rather than
    /// about this controller.
    #[test]
    fn the_slope_the_controller_stops_walking_is_the_one_it_was_configured_with() {
        let config = CharacterConfig::default();
        let step_degrees = 0.1;
        // Big enough to cross the skin gap in one tick: a fall shorter than
        // that never touches the ground and the ground never gets a say.
        let gravity = DVec3::new(0.0, -0.05, 0.0);

        let mut last_still: Option<f64> = None;
        let mut first_creep: Option<f64> = None;
        for tenth in 0..900 {
            let degrees = f64::from(tenth) * step_degrees;
            let mut world = dome_world();
            let mut character =
                CharacterController::new(config, on_dome(&config, degrees.to_radians()));
            character.move_and_slide(&mut world, DVec3::ZERO);
            let start = character.position();
            for _ in 0..60 {
                character.move_and_slide(&mut world, gravity);
            }
            let drift = (character.position() - start).x;
            if first_creep.is_none() {
                if drift == 0.0 {
                    last_still = Some(degrees);
                } else {
                    first_creep = Some(degrees);
                }
            }
        }

        let (Some(last_still), Some(first_creep)) = (last_still, first_creep) else {
            panic!(
                "the sweep never crossed a boundary: {last_still:?} was the last still \
                 slope and {first_creep:?} the first creeping one",
            );
        };
        #[expect(
            clippy::disallowed_methods,
            reason = "the platform's arccosine is the oracle"
        )]
        let limit = config.min_ground_normal_y.acos().to_degrees();
        assert!(
            last_still <= limit && limit <= first_creep,
            "the boundary was measured at {last_still}° still / {first_creep}° creeping, \
             and the configured limit is {limit}° — the two samples are one \
             {step_degrees}° step apart, so the limit has to fall between them",
        );
    }

    /// **A surface exactly at the limit is walkable**, which the sweep above
    /// cannot say.
    ///
    /// That sweep brackets the boundary to a tenth of a degree and no finer,
    /// and which of its two adjacent samples the limit lands on moves with the
    /// platform's `sin`/`cos` — so flipping `is_walkable`'s comparison from
    /// `>=` to `>` shifts it by exactly the amount a different libm does, and
    /// the sweep cannot tell the two apart. This can: the normal is built
    /// **from** [`CharacterConfig::min_ground_normal_y`] rather than from an
    /// angle, so its rise is that number bit for bit on every target, and no
    /// transcendental stands between the configuration and the answer.
    #[test]
    fn a_surface_exactly_at_the_limit_is_walkable() {
        let config = CharacterConfig::default();
        let character = CharacterController::new(config, DVec3::ZERO);
        let rise = config.min_ground_normal_y;
        // Unit length, and its Y component is `rise` exactly — the `sqrt` only
        // ever touches the horizontal lane.
        let exactly = DVec3::new((1.0 - rise * rise).sqrt(), rise, 0.0);

        assert_eq!(
            exactly.y, rise,
            "the test's own normal must carry the configured rise unrounded"
        );
        assert!(
            character.is_walkable(exactly),
            "a surface whose rise is exactly {rise} must be walkable, because the \
             comparison is `>=` and the limit is the last slope you can stand on"
        );
    }

    /// **Walking up a walkable slope covers the same horizontal ground as
    /// walking on the flat**, which is Unreal's
    /// `bMaintainHorizontalGroundVelocity` and the reason a ramp does not feel
    /// like treacle.
    #[test]
    #[expect(
        clippy::disallowed_methods,
        reason = "the platform's tangent is the oracle"
    )]
    fn a_walkable_slope_is_climbed_without_losing_horizontal_ground() {
        let config = CharacterConfig::default();
        let angle = 30.0_f64.to_radians();
        let mut world = dome_world();
        let mut character = CharacterController::new(config, on_dome(&config, angle));
        character.move_and_slide(&mut world, DVec3::ZERO);
        assert!(character.is_grounded(), "30° is inside the default limit");

        // Uphill is -X: the character is on the +X flank of the dome.
        let asked = DVec3::new(-0.05, 0.0, 0.0);
        let before = character.position();
        let outcome = character.move_and_slide(&mut world, asked);
        let moved = character.position() - before;

        assert!(
            (moved.x - asked.x).abs() < 1e-6,
            "the horizontal ground covered was {} and the request was {}",
            moved.x,
            asked.x,
        );
        assert!(
            (moved.y - asked.x.abs() * angle.tan()).abs() < 1e-4,
            "climbing 0.05 m of a 30° slope should rise {}, and it rose {}",
            asked.x.abs() * angle.tan(),
            moved.y,
        );
        assert!(outcome.grounded);
    }

    // ── Steps ──────────────────────────────────────────────────────────

    /// **The step the controller stops climbing is the offset it was
    /// configured with**, measured rather than assumed.
    ///
    /// The sweep: build a floor and a raised second floor at every millimetre
    /// from `0` to `0.6 m`, walk a grounded character into the join for thirty
    /// ticks of 0.05 m, and record whether it ended up on top.
    ///
    /// Measured with [`CharacterConfig::default`]: every step through `0.409 m`
    /// is climbed and `0.410 m` is the first that is not. The band above the
    /// configured offset is one [`CharacterConfig::skin_width`] wide, because
    /// a settled capsule already floats that far off its floor and the rise
    /// starts from there.
    #[test]
    fn the_step_the_controller_stops_climbing_is_the_offset_it_was_configured_with() {
        let config = CharacterConfig::default();
        let step_metres = 0.001;

        let mut last_climbed: Option<f64> = None;
        let mut first_blocked: Option<f64> = None;
        for milli in 0..=600 {
            let height = f64::from(milli) * step_metres;
            let mut world = stepped_world(height);
            let mut character = CharacterController::new(
                config,
                DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0),
            );
            character.move_and_slide(&mut world, DVec3::ZERO);
            for _ in 0..30 {
                character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0));
            }
            let climbed =
                character.position().x > 0.2 && (feet_of(&character) - height).abs() < 0.02;
            if first_blocked.is_none() {
                if climbed {
                    last_climbed = Some(height);
                } else {
                    first_blocked = Some(height);
                }
            }
        }

        let last_climbed = last_climbed.expect("a zero-height step is walked straight over");
        let first_blocked = first_blocked.expect("a 0.6 m step is not a step");
        assert!(
            last_climbed >= config.step_offset,
            "a step of exactly the configured offset must be climbed, and the last \
             one climbed was {last_climbed}",
        );
        assert!(
            first_blocked <= config.step_offset + config.skin_width + step_metres,
            "the first step refused was {first_blocked}, which is more than one skin \
             width above the configured offset of {}",
            config.step_offset,
        );
    }

    /// **Walking off a lip inside the step offset keeps the character on the
    /// ground**, rather than dropping it into a one-tick fall on every stair.
    #[test]
    fn walking_off_a_lip_within_the_step_offset_never_leaves_the_ground() {
        let config = CharacterConfig::default();
        let drop = 0.3;
        let mut world = stepped_world(-drop);
        let mut character =
            CharacterController::new(config, DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0));
        character.move_and_slide(&mut world, DVec3::ZERO);

        for tick in 0..30 {
            let outcome = character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0));
            assert!(
                outcome.grounded,
                "tick {tick} left the ground at x = {}, y = {}",
                character.position().x,
                character.position().y,
            );
        }
        assert!(character.position().x > 0.2, "it walked past the lip");
        assert!(
            (feet_of(&character) + drop).abs() < config.skin_width * 2.0,
            "it should be standing on the lower floor at {}, and its feet are at {}",
            -drop,
            feet_of(&character),
        );
    }

    /// The other half of the snap: a drop deeper than the step offset is a
    /// fall, and the character has to leave the ground for it.
    #[test]
    fn walking_off_a_drop_past_the_step_offset_leaves_the_ground() {
        let config = CharacterConfig::default();
        let mut world = stepped_world(-(config.step_offset * 2.0));
        let mut character =
            CharacterController::new(config, DVec3::new(-1.0, centre_for_feet(&config, 0.0), 0.0));
        character.move_and_slide(&mut world, DVec3::ZERO);

        let mut left_the_ground = false;
        for _ in 0..30 {
            left_the_ground |= !character
                .move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.0))
                .grounded;
        }
        assert!(
            left_the_ground,
            "the character walked over a {} m drop without ever falling",
            config.step_offset * 2.0,
        );
    }

    /// **A character pressed into a corner does not climb it.** The step-up's
    /// advance is what refuses: after rising, a corner is still a wall in both
    /// directions, so there is nowhere to step onto and the whole step is
    /// reverted rather than leaving the capsule up in the air.
    #[test]
    fn a_character_pressed_into_a_corner_does_not_climb_it() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        world.add_box(BoxCollider::new(
            DVec3::new(5.5, 2.0, 0.0),
            DVec3::new(5.0, 3.0, 10.0),
        ));
        world.add_box(BoxCollider::new(
            DVec3::new(0.0, 2.0, 5.5),
            DVec3::new(10.0, 3.0, 5.0),
        ));
        let mut character = standing(&mut world, config);
        let resting_feet = feet_of(&character);

        let mut planes_at_once = 0;
        for _ in 0..60 {
            let outcome = character.move_and_slide(&mut world, DVec3::new(0.05, 0.0, 0.05));
            planes_at_once = planes_at_once.max(outcome.slides);
            assert!(
                feet_of(&character) <= resting_feet + config.skin_width,
                "the character rose to {} from {resting_feet}",
                feet_of(&character),
            );
            assert!(
                !outcome.stepped_up,
                "a corner is not a step, and it was climbed at y = {}",
                character.position().y,
            );
        }
        assert!(
            character.position().x > 0.1 && character.position().z > 0.1,
            "the character should have slid along both walls before wedging, and \
             stopped at {:?}",
            character.position(),
        );
        assert!(
            planes_at_once >= 2,
            "the corner never presented two planes in one move, so the clipping \
             this is about never ran",
        );
    }

    // ── Depenetration ──────────────────────────────────────────────────

    /// **A capsule that wakes up inside a box leaves through the nearest
    /// face**, by the depth it is in by, and not by a teleport to somewhere
    /// convenient.
    #[test]
    fn a_capsule_that_starts_inside_a_box_is_pushed_out_of_the_nearest_face() {
        let config = CharacterConfig::default();
        let mut world = PhysicsWorld::new();
        let half = DVec3::new(1.0, 1.0, 1.0);
        world.add_box(BoxCollider::new(DVec3::ZERO, half));

        // Buried 0.2 m short of the +X face and dead centre on the others, so
        // +X is the only shortest way out.
        let inside = DVec3::new(half.x - 0.2, 0.0, 0.0);
        let mut character = CharacterController::new(config, inside);
        let outcome = character.move_and_slide(&mut world, DVec3::ZERO);

        let mut still_inside = Vec::new();
        world.capsule_penetrations_into(&character.capsule(), None, &mut still_inside);
        assert!(
            still_inside.is_empty(),
            "the capsule is still inside {still_inside:?} after being pushed out",
        );
        let expected = DVec3::X * (config.radius + 0.2 + config.skin_width);
        assert!(
            (outcome.depenetration - expected).length() < 1e-12,
            "expected a push of {expected:?} and got {:?}",
            outcome.depenetration,
        );
    }

    /// The push has to converge: a character standing clear of everything must
    /// not be shoved on every tick for ever.
    #[test]
    fn a_capsule_clear_of_the_world_is_not_pushed_at_all() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        // Set down at the gap a settled capsule keeps, so it is touching
        // nothing — and the move must leave it exactly where it is.
        let mut character = CharacterController::new(
            config,
            DVec3::new(0.0, centre_for_feet(&config, config.skin_width), 0.0),
        );

        let outcome = character.move_and_slide(&mut world, DVec3::ZERO);

        assert_eq!(
            outcome.depenetration,
            DVec3::ZERO,
            "a capsule a skin width clear of its floor is inside nothing",
        );
        assert!(
            outcome.grounded,
            "and it is standing on the floor it is clear of"
        );
    }

    // ── Jumping and the ground snap ────────────────────────────────────

    /// An upward move is used exactly as it was asked for: the ground
    /// adjustment stands aside the moment the character asks to leave the
    /// ground, or a jump would be flattened into a walk.
    #[test]
    fn an_upward_move_covers_its_whole_rise() {
        let mut world = flat_world();
        let mut character = standing(&mut world, CharacterConfig::default());
        let before = character.position().y;

        character.move_and_slide(&mut world, DVec3::new(0.0, 0.2, 0.0));

        assert!(
            (character.position().y - before - 0.2).abs() < 1e-12,
            "asked to rise 0.2 and rose {}",
            character.position().y - before,
        );
    }

    /// And the ground snap does not reach up after it. The snap is for a
    /// character that was walking and stayed down, not for one that jumped.
    #[test]
    fn an_upward_move_is_not_pulled_back_by_the_ground_snap() {
        let config = CharacterConfig::default();
        for rise in [config.skin_width * 0.1, 0.2] {
            let mut world = flat_world();
            let mut character = standing(&mut world, config);
            for _ in 0..2 {
                let motion = DVec3::new(0.005, rise, 0.0);
                let outcome = character.move_and_slide(&mut world, motion);
                assert!(
                    !outcome.grounded,
                    "the floor reached up and took the jump back: rise={rise}"
                );
                assert!((outcome.motion - motion).length() < 1e-12);
            }
        }
    }

    /// **A grounded character asked for nothing but gravity does not move.**
    /// On the flat that is trivial; on a slope it is the whole of
    /// `floor_stop_on_slope`, because gravity clipped against a 40° face has a
    /// downhill component on every single tick.
    #[test]
    fn gravity_alone_does_not_walk_a_grounded_character_down_a_slope() {
        let config = CharacterConfig::default();
        let mut world = dome_world();
        let mut character =
            CharacterController::new(config, on_dome(&config, 40.0_f64.to_radians()));
        character.move_and_slide(&mut world, DVec3::ZERO);
        assert!(character.is_grounded(), "40° is inside the default limit");

        let before = character.position();
        for tick in 0..60 {
            let outcome = character.move_and_slide(&mut world, DVec3::new(0.0, -0.05, 0.0));
            assert_eq!(
                (outcome.motion.x, outcome.motion.z),
                (0.0, 0.0),
                "tick {tick} walked sideways",
            );
            assert!(outcome.grounded, "tick {tick} left the slope");
        }
        let drift = character.position() - before;
        assert_eq!(
            (drift.x, drift.z),
            (0.0, 0.0),
            "it ended up downhill by {drift:?}"
        );
        assert!(
            drift.y.abs() < config.skin_width,
            "it sank {} into the slope, which is more than the gap it settles to",
            -drift.y,
        );
    }

    // ── The character's own collider ───────────────────────────────────

    #[test]
    fn clearing_self_collider_preserves_ground_and_movement_state() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        let mut character =
            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0));
        character.move_and_slide(&mut world, DVec3::ZERO);
        assert!(character.is_grounded());
        let position = character.position();
        let ground = character.ground().cloned();
        let body = world.add_capsule(character.capsule());
        character.set_self_collider(Some(body));
        assert_eq!(character.self_collider, Some(body));
        assert_eq!(character.position(), position);
        assert_eq!(character.ground(), ground.as_ref());
        character.set_self_collider(None);
        assert_eq!(character.self_collider, None);
        assert_eq!(character.position(), position);
        assert_eq!(character.ground(), ground.as_ref());
        assert!(world.remove(body));
        let moved = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, 0.0));
        assert!((moved.motion.x - 0.2).abs() < 1e-12);
        assert!(moved.grounded);
    }

    #[test]
    fn a_character_registered_in_the_world_is_left_out_of_its_own_sweeps() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        let body = world.add_capsule(Capsule::new(
            DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0),
            config.radius,
            config.half_height,
        ));
        let mut character =
            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0))
                .with_self_collider(body);

        character.move_and_slide(&mut world, DVec3::ZERO);

        let outcome = character.move_and_slide(&mut world, DVec3::new(0.2, 0.0, 0.0));
        assert!(
            (outcome.motion.x - 0.2).abs() < 1e-12,
            "its own body blocked it: it moved {}",
            outcome.motion.x,
        );
        let aabb = world.aabb_of(body).expect("the body is still registered");
        assert!(
            (aabb.centre() - character.position()).length() < 1e-12,
            "the world's copy is at {:?} and the character at {:?}",
            aabb.centre(),
            character.position(),
        );
    }

    // ── The public ground probe ────────────────────────────────────────

    /// The probe length a caller asks "is it standing on something" with: the
    /// move's own slack.
    fn standing_probe(config: &CharacterConfig) -> f64 {
        config.skin_width * GROUND_PROBE_SKINS
    }

    #[test]
    fn a_probe_under_a_settled_character_finds_its_floor_a_skin_width_down() {
        let config = CharacterConfig::default();
        let mut world = PhysicsWorld::new();
        let floor = world.add_box(BoxCollider::new(
            DVec3::new(0.0, -1.0, 0.0),
            DVec3::new(50.0, 1.0, 50.0),
        ));
        let character = standing(&mut world, config);

        let found = character
            .probe_ground(&mut world, standing_probe(&config))
            .expect("a settled character is standing on its floor");

        assert_eq!(found.contact.collider, floor);
        assert!(
            (found.contact.normal - DVec3::Y).length() < 1e-12,
            "the floor faces up, and the probe reported {:?}",
            found.contact.normal,
        );
        assert!(
            (found.distance - config.skin_width).abs() < 1e-9,
            "a settled capsule floats one skin width ({}) up, and the probe \
             measured {}",
            config.skin_width,
            found.distance,
        );
        assert!(found.walkable);
        assert_eq!(
            Some(&found.contact),
            character.ground(),
            "the move and the probe share one sweep, so they name the same contact",
        );
    }

    #[test]
    fn a_probe_from_above_its_distance_finds_nothing() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        let height = 1.0;
        let character = CharacterController::new(
            config,
            DVec3::new(0.0, centre_for_feet(&config, height), 0.0),
        );

        assert_eq!(
            character.probe_ground(&mut world, standing_probe(&config)),
            None,
            "the floor is {height} m down and the probe looked {} m",
            standing_probe(&config),
        );
        // And the miss is the distance, not a probe that cannot see the floor.
        let far = character
            .probe_ground(&mut world, height * 2.0)
            .expect("a long enough probe reaches the floor");
        assert!(
            (far.distance - height).abs() < 1e-9,
            "the floor is {height} m below the feet and the probe measured {}",
            far.distance,
        );
    }

    #[test]
    fn a_probe_on_a_slope_past_the_limit_reads_as_not_walkable() {
        let config = CharacterConfig::default();
        let mut world = dome_world();
        let at = |degrees: f64| on_dome(&config, degrees.to_radians()) + UP * config.skin_width;
        let character = CharacterController::new(config, DVec3::ZERO);

        let steep = character
            .probe_ground_at(&mut world, at(60.0), standing_probe(&config))
            .expect("the dome is a skin width under the capsule");
        assert!(
            !steep.walkable,
            "60° is past the default 45° limit, and the probe called it walkable \
             with normal {:?}",
            steep.contact.normal,
        );
        assert!(steep.contact.normal.y < config.min_ground_normal_y);

        let gentle = character
            .probe_ground_at(&mut world, at(30.0), standing_probe(&config))
            .expect("the dome is a skin width under the capsule");
        assert!(gentle.walkable, "30° is inside the default limit");
    }

    #[test]
    fn a_probe_leaves_the_controller_and_its_world_body_where_they_were() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        let body = world.add_capsule(Capsule::new(
            DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0),
            config.radius,
            config.half_height,
        ));
        let mut character =
            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.0), 0.0))
                .with_self_collider(body);
        character.move_and_slide(&mut world, DVec3::ZERO);
        let position = character.position();
        let ground = character.ground().copied();
        let aabb = world.aabb_of(body);
        assert!(ground.is_some(), "the fixture starts on the floor");

        let here = character.probe_ground(&mut world, standing_probe(&config));
        let aloft = character.probe_ground_at(
            &mut world,
            DVec3::new(3.0, centre_for_feet(&config, 2.0), 0.0),
            standing_probe(&config),
        );

        assert_ne!(
            here.map(|found| found.contact.collider),
            Some(body),
            "the probe found the character's own body",
        );
        assert!(here.is_some_and(|found| found.walkable));
        assert_eq!(aloft, None);
        assert_eq!(character.position(), position);
        assert_eq!(character.ground().copied(), ground);
        assert_eq!(world.aabb_of(body), aabb);
    }

    /// **`ground()` is the last move's answer; the probe is the world's
    /// current one.** Ported from EW's
    /// `support_refresh_rejects_removed_floor_without_advancing_stamina_clocks`:
    /// take the floor away and the recorded ground still names it, while a
    /// fresh probe finds nothing and moves nothing.
    #[test]
    fn a_probe_sees_a_removed_floor_that_ground_still_reports() {
        let config = CharacterConfig::default();
        let mut world = PhysicsWorld::new();
        let floor = world.add_box(BoxCollider::new(
            DVec3::new(0.0, -1.0, 0.0),
            DVec3::new(50.0, 1.0, 50.0),
        ));
        let character = standing(&mut world, config);
        assert!(
            character
                .probe_ground(&mut world, standing_probe(&config))
                .is_some_and(|found| found.walkable)
        );
        let position = character.position();

        assert!(world.remove(floor));

        assert!(
            character.is_grounded(),
            "ground() is the last move's record"
        );
        assert_eq!(
            character.probe_ground(&mut world, standing_probe(&config)),
            None
        );
        assert_eq!(character.position(), position);
    }

    /// Ported from EW's `unsupported_spawn_cannot_begin_revival_even_with_valid_reach`:
    /// a character placed 0.1 m over its floor has no support within the
    /// move's slack.
    #[test]
    fn a_character_spawned_a_tenth_of_a_metre_up_has_no_support() {
        let config = CharacterConfig::default();
        let mut world = flat_world();
        let character =
            CharacterController::new(config, DVec3::new(0.0, centre_for_feet(&config, 0.1), 0.0));

        assert_eq!(
            character.probe_ground(&mut world, standing_probe(&config)),
            None
        );
    }

    #[test]
    #[should_panic(expected = "non-negative distance")]
    fn a_probe_refuses_a_negative_distance() {
        let mut world = flat_world();
        let character = standing(&mut world, CharacterConfig::default());
        let _ = character.probe_ground(&mut world, -0.1);
    }
}

#[cfg(test)]
#[path = "character/query_mask_tests.rs"]
mod query_mask_tests;

#[cfg(test)]
#[path = "character/lying_tests.rs"]
mod lying_tests;

#[cfg(test)]
#[path = "character/lying_move_tests.rs"]
mod lying_move_tests;

#[cfg(test)]
#[path = "character/lying_turn_tests.rs"]
mod lying_turn_tests;

#[cfg(test)]
#[path = "character/lying_contact_tests.rs"]
mod lying_contact_tests;

#[cfg(test)]
#[path = "character/slide_contact_tests.rs"]
mod slide_contact_tests;

#[cfg(test)]
#[path = "character/crease_tests.rs"]
mod crease_tests;

#[cfg(test)]
#[path = "character/edge_tests.rs"]
mod edge_tests;

#[cfg(test)]
#[path = "character/rest_tests.rs"]
mod rest_tests;

#[cfg(test)]
#[path = "character/skin_tests.rs"]
mod skin_tests;

#[cfg(test)]
#[path = "character/preview_tests.rs"]
mod preview_tests;