ghast-client 0.4.6

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

use super::Rules;
use super::data::BlockState;
use ghast_physics::modern::{self, AttributeKind, ModifierId};
use ghast_protocol::{BlockPos, RawPacket};

use crate::common::{Abilities, AttributeUpdate, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};
use crate::sim::*;

/// A modern version's chunk store and vanilla-exact modern physics.
pub(crate) struct ModernSim {
    world: super::world::World,
    player: modern::PlayerState,
    packets: ghast_physics::Packets,
    /// Block changes since the last drain (position, state id), when collected.
    updates: BlockUpdates,
    /// `mining_efficiency`, `block_break_speed`, `submerged_mining_speed` (digging).
    mining: [modern::Attribute; 3],
    /// Conduit power amplifier (digging).
    conduit_power: Option<i32>,
    /// `block_interaction_range`, `entity_interaction_range` (the crosshair).
    ranges: [modern::Attribute; 2],
    /// `Entity.xo/yo/zo`: the position at the start of the last tick (the pick's eye lerps
    /// from it).
    old_pos: [f64; 3],
    /// The entity tracker, when entities are tracked.
    entities: Option<super::entity::Tracker>,
    /// Join / respawn packets, replayed into a tracker started mid-session.
    session: SessionPackets,
    /// The level-load gate (`player_loaded`), oracle-proven on `joins.jsonl.gz`.
    gate: modern::LoadGate,
    /// `use_effects` of the item in use (see [`ModernSim::use_effects`]).
    use_effects: Option<(bool, f32)>,
    /// Movement state beyond `player`: gliding, attached rockets (and later mechanics).
    ext: modern::PlayerExt,
    /// What the client knows about entities that drive `ext` (own id, rockets).
    own: OwnEntity,
    /// `Level.rainLevel` from the weather game events (1 START_RAINING, 2 STOP_RAINING,
    /// 7 RAIN_LEVEL_CHANGE); the level rains above 0.2.
    rain_level: f32,
    /// The extension state can act this tick (gliding, a glider to start a glide, rockets, the
    /// riptide spin or counter, a launch made before the tick): set wherever `ext` gains such a
    /// state, recomputed after each extended tick. One flag keeps the plain tick's path lean.
    ext_active: bool,
    /// Riptide strength of the trident in the main / off hand (`held_use_inputs`).
    riptide: [f32; 2],
    /// With entity tracking: the boxes the player collides with this tick and the entities
    /// that push it after its tick (buffers kept between ticks).
    around: Around,
    /// With entity tracking: the scoreboard teams' collision rules (`set_player_team`).
    teams: Option<Box<crate::sim::teams::Teams>>,
    /// The player's scoreboard name (its team membership).
    profile_name: Box<str>,
    /// The vehicle the player rides and controls (`set_passengers` naming us).
    riding: Option<Riding>,
    /// Without entity tracking: a tracker of the vehicles only (boats and minecarts the player
    /// may ride), fed their spawn, move and passenger packets.
    vehicles: Option<Box<super::entity::Tracker>>,
    /// The boat the player left: it stays where the player drove it (the client moved it; the
    /// server sends no move for it) until the server moves it.
    parked: Option<Parked>,
    /// The answer to a server packet that goes out at once (`move_vehicle`).
    reply: Option<Outbound>,
    /// Grim compatibility (not vanilla, off by default): send the position on a tick whose
    /// feet height changed although the move stayed under the resend threshold.
    force_step: ForceStepPosition,
    /// Movement recording ([`crate::Client::record`]).
    rec: Option<Box<crate::record::Recorder>>,
    /// 26.2+: a movement attribute of `ext` (friction / air drag modifier, bounciness) is not
    /// at its default, so the extended tick runs (the plain tick reads the defaults).
    movement_attributes: bool,
    /// The packets the sim reads changed (boats appeared / are gone): rebuild the filter.
    filter_dirty: bool,
    /// Entities push the player (vanilla; off only by the client's non-vanilla opt-in).
    entity_push: bool,
    /// The level's `BlockStatePredictionHandler`: blocks broken on the client and the server's
    /// state of them until its `block_changed_ack`.
    predictions: crate::sim::predict::Sequenced<BlockState>,
    /// An ack moved the player back ([`Sim::take_snap`]).
    snapped: bool,
}

/// A vehicle the player rides.
#[derive(Debug)]
enum Riding {
    /// A boat or raft: client-authoritative (`modern::tick_boat`).
    Boat { id: i32, boat: Box<modern::Boat> },
    /// A minecart: the server moves it, the player sits on it (`modern::tick_passenger`).
    Seat { id: i32 },
}

impl Riding {
    fn id(&self) -> i32 {
        match self {
            Riding::Boat { id, .. } | Riding::Seat { id } => *id,
        }
    }
}

/// A boat the player drove and left.
#[derive(Debug, Clone, Copy)]
struct Parked {
    id: i32,
    pos: [f64; 3],
    bb: [f64; 6],
    /// The tracker's position of it when the player left (a different one: the server moved it).
    tracked: Option<[f64; 3]>,
}

impl Parked {
    /// The parked position and box when `e` is the parked boat and the server has not moved it.
    fn of(this: Option<&Parked>, e: &ghast_entity::Entity) -> Option<([f64; 3], [f64; 6])> {
        let p = this?;
        (p.id == e.id() && p.tracked == Some(e.position())).then_some((p.pos, p.bb))
    }
}

/// The vehicle kinds the player can ride with modelled physics.
fn vehicle_kind(name: &str) -> Option<VehicleKind> {
    if let Some(k) = modern::BoatKind::from_entity_name(name) {
        Some(VehicleKind::Boat(k))
    } else if name.ends_with("minecart") {
        Some(VehicleKind::Cart)
    } else {
        None
    }
}

#[derive(Debug, Clone, Copy)]
enum VehicleKind {
    Boat(modern::BoatKind),
    Cart,
}

/// Entity collision and pushing around the player (only with entity tracking).
#[derive(Debug, Default)]
struct Around {
    /// Collidable entity boxes (`canBeCollidedWith`), in `getEntities` section order.
    boxes: Vec<ghast_physics::math::Aabb>,
    /// Pushers of this tick: order key, push.
    pushers: Vec<(i64, modern::Pusher)>,
    /// The player ticked since the last entity tick (pushes come after its tick).
    player_ticked: bool,
    /// The entities near the player that tick before it in the client's tick list (ticked
    /// early: their boxes are post-tick, their pushes come before the player's tick).
    pre: Vec<i32>,
}

/// Per entity type: the player collides with it (the version's `collides`).
const COLLIDES: u8 = 1;
/// Per entity type: its tick pushes the player like a living entity.
const PUSH_LIVING: u8 = 2;
/// Per entity type: its tick pushes the player like a boat.
const PUSH_BOAT: u8 = 4;

/// [`COLLIDES`] / [`PUSH_LIVING`] / [`PUSH_BOAT`] by entity type id.
fn entity_bits(e: &ghast_entity::Entity) -> u8 {
    static BITS: std::sync::OnceLock<Box<[u8]>> = std::sync::OnceLock::new();
    let bits = BITS.get_or_init(|| {
        let types = super::data::entity_types();
        let mut v = vec![
            0u8;
            types
                .iter()
                .map(|t| usize::from(t.id) + 1)
                .max()
                .unwrap_or(0)
        ];
        for t in types {
            let mut b = 0;
            if super::collides(t.name) {
                b |= COLLIDES;
            }
            match super::push_kind(t.name, t.is_living()) {
                Some(modern::PushKind::Living) => b |= PUSH_LIVING,
                Some(modern::PushKind::Boat) => b |= PUSH_BOAT,
                _ => {}
            }
            v[usize::from(t.id)] = b;
        }
        v.into_boxed_slice()
    });
    super::entity::entity_type(e).map_or(0, |t| bits.get(usize::from(t.id)).copied().unwrap_or(0))
}

/// The boxes the player may collide with this tick (`canBeCollidedWith`: boats, rafts, living
/// shulkers; its own vehicle excluded), and while riding the boxes its boat collides with
/// (`canVehicleCollide`: those and every living entity, not the player), near enough for any
/// move of this tick, each in `getEntities` section order. Only with entity tracking.
#[inline(never)]
fn collect_colliders(
    t: Option<&super::entity::Tracker>,
    parked: Option<&Parked>,
    p: &modern::PlayerState,
    vehicle: Option<i32>,
    boxes: &mut Vec<ghast_physics::math::Aabb>,
    boat_boxes: &mut Vec<ghast_physics::math::Aabb>,
) {
    boxes.clear();
    boat_boxes.clear();
    // Farther than any move of one tick can reach (the physics filters exactly); a boat moves
    // up to ~2 blocks a tick on ice.
    let extra = if vehicle.is_some() { 4.0 } else { 3.0 };
    let reach = |v: f64| v.abs() + extra;
    let (rx, ry, rz) = (reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2]));
    let mut found: Vec<((i32, u64), [f64; 6], bool)> = Vec::new();
    // The boat the player left, where it drove it (without the tracker it is the only one).
    if let Some(k) = parked
        && t.is_none_or(|t| t.get(k.id).is_none())
    {
        found.push((section_order(k.pos), k.bb, true));
    }
    for e in t.into_iter().flat_map(|t| t.iter()) {
        let bits = entity_bits(e);
        let living =
            vehicle.is_some() && super::entity::entity_type(e).is_some_and(|t| t.is_living());
        if bits & COLLIDES == 0 && !living {
            continue;
        }
        if Some(e.id()) == vehicle {
            continue;
        }
        let Some((pos, b)) = Parked::of(parked, e).or_else(|| entity_box(e)) else {
            continue;
        };
        if b[3] < p.bb.min_x - rx
            || b[0] > p.bb.max_x + rx
            || b[4] < p.bb.min_y - ry
            || b[1] > p.bb.max_y + ry
            || b[5] < p.bb.min_z - rz
            || b[2] > p.bb.max_z + rz
        {
            continue;
        }
        // isAlive: a dying shulker (health not above 0, NaN included) no longer collides.
        if !super::entity::alive(e) {
            continue;
        }
        found.push((section_order(pos), b, bits & COLLIDES != 0));
    }
    // getEntities walks sections by x, then z / y.
    found.sort_by_key(|f| f.0);
    for (_, b, collides) in found {
        if collides {
            boxes.push(aabb(b));
        }
        if vehicle.is_some() {
            boat_boxes.push(aabb(b));
        }
    }
}

/// `Level.noCollision` without the entity part, for a tracked entity's moved interpolation
/// target: free of blocks and the border.
fn block_free(
    world: &super::world::World,
    level: &modern::LevelInfo,
    e: &ghast_entity::Entity,
    bb: [f64; 6],
) -> bool {
    let pos = e.position();
    modern::no_block_collision::<Rules, _>(
        world,
        level,
        pos,
        bb,
        &modern::CollisionContext {
            feet_y: pos[1],
            ..Default::default()
        },
    )
}

/// `SectionPos` of a position, as `getEntities` orders sections: x, then z, then y.
fn section_order(pos: [f64; 3]) -> (i32, u64) {
    let b = |v: f64| (v.floor() as i32) >> 4;
    let (x, y, z) = (b(pos[0]), b(pos[1]), b(pos[2]));
    (
        x,
        (u64::from(z as u32 & 0x3F_FFFF) << 20) | u64::from(y as u32 & 0xF_FFFF),
    )
}

/// Position and box of an entity, with the shulker's own rules where the tracker has no box (its
/// size follows the peek): `Shulker.setPos` snaps to the block (`floor(x) + 0.5`,
/// `floor(y + 0.5)`, `floor(z) + 0.5`) and the closed shell is the unit cube there
/// (`Shulker.makeBoundingBox` at peek 0, scale 1; an open shell, taller toward its attach face,
/// and a scaled shulker are not modelled).
fn entity_box(e: &ghast_entity::Entity) -> Option<([f64; 3], [f64; 6])> {
    if let Some(b) = e.bounding_box() {
        return Some((e.position(), b));
    }
    let t = super::entity::entity_type(e)?;
    (t.name == "shulker" && e.vehicle().is_none()).then(|| {
        let [x, y, z] = e.position();
        let (x, y, z) = (x.floor() + 0.5, (y + 0.5).floor(), z.floor() + 0.5);
        ([x, y, z], [x - 0.5, y, z - 0.5, x + 0.5, y + 1.0, z + 0.5])
    })
}

fn aabb(b: [f64; 6]) -> ghast_physics::math::Aabb {
    ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5])
}

/// The entity packets the modern movement reads without entity tracking: the player's own
/// shared flags and main arm, and firework rockets attached to it. Only those are decoded: a
/// packet is decoded past its entity id only when the id is ours or a rocket's.
#[derive(Debug, Default)]
struct OwnEntity {
    /// Our entity id (from the login packet).
    id: i32,
    /// The main arm per our own entity data (`DATA_PLAYER_MAIN_HAND`), else the client option.
    main_arm_left: bool,
    /// Firework rockets spawned but not (yet) known as attached to us: id, spawn position.
    rockets: Vec<(i32, [f64; 3])>,
    /// Mountable animals with an inventory screen (horses, llamas, nautili …): what their
    /// screen reads off them (`canUseSlot(SADDLE / BODY)`).
    mounts: Vec<Mount>,
}

/// A mount entity's screen facts.
#[derive(Debug, Clone, Copy)]
struct Mount {
    id: i32,
    /// `minecraft:entity_type` registry id.
    ty: i32,
    /// `AgeableMob.DATA_BABY_ID`.
    baby: bool,
    /// Index 18: `AbstractHorse.DATA_ID_FLAGS` (tamed = 2) or `TamableAnimal.DATA_FLAGS_ID`
    /// (tame = 4).
    flags: u8,
}

/// The entity type ids the modern movement reads, resolved by registry name from the version's
/// data set (each version numbers its entity types itself).
#[derive(Debug, Clone, Copy)]
struct EntityIds {
    /// Entity types whose screen is a mount screen: horse, donkey, mule, skeleton / zombie
    /// horse, camel, camel husk (`AbstractHorse`).
    horses: [i32; 7],
    /// llama, trader llama (`Llama`).
    llamas: [i32; 2],
    /// nautilus, zombie nautilus (`AbstractNautilus`).
    nautili: [i32; 2],
    /// `minecraft:firework_rocket`.
    firework_rocket: i32,
}

impl EntityIds {
    /// The ids of this version (`-1`: a type the version does not have).
    fn get() -> &'static EntityIds {
        static IDS: std::sync::OnceLock<EntityIds> = std::sync::OnceLock::new();
        IDS.get_or_init(|| {
            let id = |name: &str| super::data::entity_by_name(name).map_or(-1, |t| i32::from(t.id));
            EntityIds {
                horses: [
                    "horse",
                    "donkey",
                    "mule",
                    "skeleton_horse",
                    "zombie_horse",
                    "camel",
                    "camel_husk",
                ]
                .map(id),
                llamas: ["llama", "trader_llama"].map(id),
                nautili: ["nautilus", "zombie_nautilus"].map(id),
                firework_rocket: id("firework_rocket"),
            }
        })
    }

    #[cfg(test)]
    fn tuple(&self) -> ([i32; 7], [i32; 2], [i32; 2], i32) {
        (self.horses, self.llamas, self.nautili, self.firework_rocket)
    }

    fn is_mount(&self, ty: i32) -> bool {
        self.horses.contains(&ty) || self.llamas.contains(&ty) || self.nautili.contains(&ty)
    }
}

/// Mounts remembered at most (nearest first is not known: the oldest are dropped).
const MAX_MOUNTS: usize = 128;

impl Mount {
    /// `canUseSlot(SADDLE)`, `canUseSlot(BODY)` (alive: the entity is still in the level).
    fn slots(&self, ids: &EntityIds) -> (bool, bool) {
        if ids.llamas.contains(&self.ty) {
            (true, true)
        } else if ids.nautili.contains(&self.ty) {
            let ok = !self.baby && self.flags & 4 != 0;
            (ok, ok)
        } else {
            (!self.baby && self.flags & 2 != 0, true)
        }
    }
}

// Entity data indices of the version (read from its real classes).
use super::meta::{
    ATTACHED_TO_TARGET as DATA_ATTACHED_TO_TARGET, BABY as DATA_BABY,
    LIVING_FLAGS as DATA_LIVING_FLAGS, MOUNT_FLAGS as DATA_MOUNT_FLAGS,
    PLAYER_MAIN_HAND as DATA_PLAYER_MAIN_HAND, SHARED_FLAGS as DATA_SHARED_FLAGS,
};
/// Rockets spawned near us that may still get attached (a bound against a flood of rockets).
const MAX_PENDING_ROCKETS: usize = 32;

/// The interaction ranges with vanilla's defaults and ranges.
fn range_attributes() -> [modern::Attribute; 2] {
    [
        modern::Attribute::new(4.5, 0.0, 64.0),
        modern::Attribute::new(3.0, 0.0, 64.0),
    ]
}

/// The mining attributes with vanilla's defaults and ranges.
fn mining_attributes() -> [modern::Attribute; 3] {
    [
        modern::Attribute::new(0.0, 0.0, 1024.0),
        modern::Attribute::new(1.0, 0.0, 1024.0),
        modern::Attribute::new(0.2, 0.0, 20.0),
    ]
}

impl std::fmt::Debug for ModernSim {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ModernSim")
            .field("world", &self.world)
            .field("pos", &self.player.pos)
            .finish_non_exhaustive()
    }
}

/// `Player.canGlide` equipment part: some equipment slot holds a stack that can glide using that
/// slot (`LivingEntity.canGlideUsing`: the `glider` component, `equippable` naming that slot,
/// the next point of damage will not break it).
fn glider_equipped(inv: &ghast_inventory::Inventory) -> bool {
    use super::inv::{Equip, can_glide_using};
    let slots = [
        (inv.held(), Equip::MainHand),
        (inv.offhand(), Equip::Offhand),
        (inv.armor(0), Equip::Head),
        (inv.armor(1), Equip::Chest),
        (inv.armor(2), Equip::Legs),
        (inv.armor(3), Equip::Feet),
    ];
    slots
        .into_iter()
        .any(|(s, slot)| s.is_some_and(|s| can_glide_using(s, slot)))
}

/// A world with `c`. Tests: `GHAST_TEST_SHARED=1` gives every world of the test binary one
/// shared section store, so the whole suite can be replayed with sharing on.
fn new_world(c: ghast_world::WorldConfig) -> super::world::World {
    #[cfg_attr(not(test), allow(unused_mut))]
    let mut w = super::world::World::new(c);
    #[cfg(test)]
    if std::env::var_os("GHAST_TEST_SHARED").is_some() {
        static STORE: std::sync::OnceLock<ghast_world::SharedChunks> = std::sync::OnceLock::new();
        w.set_shared_chunks(Some(STORE.get_or_init(Default::default).clone()));
    }
    w
}

impl ModernSim {
    /// Something in `ext` acts next tick (see [`ModernSim::ext_active`]).
    #[inline]
    fn ext_wanted(&self) -> bool {
        let x = &self.ext;
        x.fall_flying
            || x.glider
            || x.rocket_count() > 0
            || x.spin_attack
            || x.auto_spin_ticks > 0
            || self.movement_attributes
    }

    /// `set_entity_data`, `add_entity`, `remove_entities` for our own entity and attached
    /// rockets (everything else is read only up to the entity id, or the entity type).
    fn own_entity_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        use super::proto::types::EntityMetadataEntryValue as V;
        let mut r = ghast_protocol::Reader::new(&raw.body);
        match raw.id {
            cb::id::ENTITY_METADATA => {
                let id = r.read_varint()?;
                let rocket = self.own.rockets.iter().position(|&(rid, _)| rid == id);
                let mount = self.own.mounts.iter().position(|m| m.id == id);
                if id != self.own.id && rocket.is_none() && mount.is_none() {
                    return Ok(());
                }
                let p: cb::EntityMetadata = raw.decode_as()?;
                for e in &p.metadata {
                    match (&e.value, e.key) {
                        (V::Byte(b), DATA_SHARED_FLAGS) if id == self.own.id => {
                            self.ext.apply_shared_flags(&mut self.player, *b as u8);
                            self.ext_active |= self.ext.fall_flying;
                        }
                        (V::Byte(b), DATA_LIVING_FLAGS) if id == self.own.id => {
                            self.ext.apply_living_flags(*b as u8);
                            self.ext_active |= self.ext.spin_attack;
                        }
                        (V::HumanoidArm(a), DATA_PLAYER_MAIN_HAND) if id == self.own.id => {
                            // HumanoidArm: LEFT 0, RIGHT 1.
                            self.own.main_arm_left = a.0 == 0;
                        }
                        (V::Boolean(b), DATA_BABY) if mount.is_some() => {
                            self.own.mounts[mount.unwrap_or(0)].baby = *b;
                        }
                        (V::Byte(f), DATA_MOUNT_FLAGS) if mount.is_some() => {
                            self.own.mounts[mount.unwrap_or(0)].flags = *f as u8;
                        }
                        (V::OptionalUnsignedInt(v), DATA_ATTACHED_TO_TARGET) => {
                            if let Some(k) = rocket
                                && *v - 1 == self.own.id
                            {
                                let (rid, pos) = self.own.rockets.swap_remove(k);
                                let ok = self.ext.attach_rocket(rid, pos);
                                self.ext_active |= ok;
                                log::debug!("firework rocket {rid} attached to us ({ok})");
                            }
                        }
                        _ => {}
                    }
                }
            }
            cb::id::SPAWN_ENTITY => {
                let id = r.read_varint()?;
                r.skip(16)?; // uuid
                let ty = r.read_varint()?;
                // Vehicles the player may ride (the full tracker knows them when it runs).
                if self.entities.is_none()
                    && u16::try_from(ty)
                        .ok()
                        .and_then(super::data::entity_type)
                        .and_then(|t| vehicle_kind(t.name))
                        .is_some()
                {
                    self.vehicle_tracker_mut().apply(raw)?;
                    return Ok(());
                }
                let ids = EntityIds::get();
                if ids.is_mount(ty) {
                    self.own.mounts.retain(|m| m.id != id);
                    if self.own.mounts.len() >= MAX_MOUNTS {
                        self.own.mounts.remove(0);
                    }
                    self.own.mounts.push(Mount {
                        id,
                        ty,
                        baby: false,
                        flags: 0,
                    });
                    return Ok(());
                }
                if ty != ids.firework_rocket {
                    return Ok(());
                }
                let p: cb::SpawnEntity = raw.decode_as()?;
                if self.own.rockets.len() >= MAX_PENDING_ROCKETS {
                    self.own.rockets.remove(0);
                }
                self.own.rockets.push((id, [p.x, p.y, p.z]));
            }
            cb::id::ENTITY_DESTROY => {
                if self.own.rockets.is_empty()
                    && self.ext.rocket_count() == 0
                    && self.own.mounts.is_empty()
                    && self.vehicles.is_none()
                    && self.riding.is_none()
                {
                    return Ok(());
                }
                let p: cb::EntityDestroy = raw.decode_as()?;
                if let Some(v) = &mut self.vehicles {
                    v.apply(raw)?;
                }
                for id in p.entity_ids {
                    self.own.rockets.retain(|&(rid, _)| rid != id);
                    self.own.mounts.retain(|m| m.id != id);
                    self.ext.remove_rocket(id);
                    // The vehicle is gone: its passenger is off (removePassenger).
                    if self.riding.as_ref().is_some_and(|v| v.id() == id) {
                        self.riding = None;
                    }
                    if self.parked.is_some_and(|p| p.id == id) {
                        self.parked = None;
                    }
                }
                if self.vehicles.as_ref().is_some_and(|v| v.is_empty()) {
                    self.vehicles = None;
                    self.filter_dirty = true;
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// The vehicles-only tracker, started on the first vehicle seen without entity tracking
    /// (from the session's join packets and the loaded columns, like a tracker started late).
    fn vehicle_tracker_mut(&mut self) -> &mut super::entity::Tracker {
        if self.vehicles.is_none() {
            let mut t = super::entity::Tracker::new(
                ghast_entity::Config::default()
                    .with_metadata(false)
                    .with_equipment(false)
                    .with_effects(false)
                    .with_events(false),
            );
            self.session.replay(|r| {
                let _ = t.apply(r);
            });
            for (c, _) in self.world.columns().iter() {
                t.mark_column_loaded(c.x, c.z);
            }
            self.vehicles = Some(Box::new(t));
            self.filter_dirty = true;
        }
        self.vehicles.as_mut().unwrap()
    }

    /// `ClientLevel.tickEntities` up to the player: the entities near it that tick before it
    /// (before its root vehicle when riding) tick now, and their pushes act before its tick.
    #[inline(never)]
    fn tick_before_player(&mut self, pose: &mut Pose) {
        let Some(t) = &mut self.entities else { return };
        let me = self.riding.as_ref().map_or(self.own.id, Riding::id);
        let Some(me_seq) = t.tick_seq(me) else { return };
        let p = &self.player;
        let reach = |v: f64| v.abs() + 4.0;
        let (rx, ry, rz) = (reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2]));
        let pre = &mut self.around.pre;
        pre.clear();
        let mut found: Vec<(u64, i32)> = Vec::new();
        for e in t.iter() {
            let [x, y, z] = e.position();
            if (x - p.pos[0]).abs() > rx + 2.0
                || (y - p.pos[1]).abs() > ry + 2.0
                || (z - p.pos[2]).abs() > rz + 2.0
            {
                continue;
            }
            if entity_bits(e) & (COLLIDES | PUSH_LIVING | PUSH_BOAT) == 0 && self.riding.is_none() {
                continue;
            }
            let Some(seq) = t.tick_seq(e.id()).filter(|&q| q < me_seq) else {
                continue;
            };
            found.push((seq, e.id()));
        }
        if found.is_empty() {
            return;
        }
        found.sort_unstable();
        let (world, level) = (&self.world, &self.player.level);
        for &(_, id) in &found {
            t.tick_early(id, |e, bb| block_free(world, level, e, bb));
            pre.push(id);
        }
        if self.riding.is_none() {
            self.push_player(pose, true);
        }
    }

    /// The parked boat ends when the server moved it (its tracked position changed) or it is
    /// gone.
    fn check_parked(&mut self) {
        if let Some(k) = self.parked {
            let now = self
                .vehicle_tracker()
                .and_then(|t| t.get(k.id))
                .map(|e| e.position());
            if now != k.tracked {
                self.parked = None;
            }
        }
    }

    /// The tracker that knows the vehicles: the full one, else the vehicles-only one.
    fn vehicle_tracker(&self) -> Option<&super::entity::Tracker> {
        self.entities.as_ref().or(self.vehicles.as_deref())
    }

    /// `set_passengers` and `move_vehicle` (the server's vehicle correction).
    fn vehicle_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        if raw.id == cb::id::VEHICLE_MOVE {
            // handleMoveVehicle: only for the vehicle this client controls; answered at once.
            if let Some(Riding::Boat { boat, .. }) = &mut self.riding {
                let p: cb::VehicleMove = raw.decode_as()?;
                if let ghast_physics::Packet::MoveVehicle {
                    pos,
                    yaw,
                    pitch,
                    on_ground,
                } = boat.server_move([p.x, p.y, p.z], p.yaw, p.pitch)
                {
                    self.reply = Some(Outbound::VehicleMove {
                        pos: Vec3::new(pos[0], pos[1], pos[2]),
                        yaw,
                        pitch,
                        on_ground,
                    });
                }
            }
            return Ok(());
        }
        if let Some(v) = &mut self.vehicles {
            v.apply(raw)?;
        }
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let vehicle = r.read_varint()?;
        let riding_it = self.riding.as_ref().is_some_and(|v| v.id() == vehicle);
        let Some(t) = self.vehicle_tracker() else {
            return Ok(());
        };
        if !riding_it && t.get(vehicle).is_none() {
            return Ok(());
        }
        let p: cb::SetPassengers = raw.decode_as()?;
        let on = p.passengers.contains(&self.own.id);
        if on && !riding_it {
            // startRiding, on a vehicle the client knows (position and rotation as it holds
            // them). A vehicle without modelled physics (living mounts) keeps the walking
            // player, as before.
            let ride = t.get(vehicle).and_then(|e| {
                let kind = super::entity::entity_type(e).and_then(|t| vehicle_kind(t.name))?;
                Some(match kind {
                    VehicleKind::Boat(k) => Riding::Boat {
                        id: vehicle,
                        boat: Box::new(modern::Boat::new(k, e.position(), e.yaw(), e.pitch())),
                    },
                    VehicleKind::Cart => Riding::Seat { id: vehicle },
                })
            });
            if let Some(ride) = ride {
                self.parked = None;
                match &ride {
                    Riding::Boat { boat, .. } => boat.board(&mut self.player),
                    Riding::Seat { .. } => modern::Seat::board(&mut self.player),
                }
                log::debug!("riding {vehicle}");
                self.riding = Some(ride);
            }
        } else if !on && riding_it {
            // Off the vehicle (the server teleports the player afterwards).
            log::debug!("left vehicle {vehicle}");
            if let Some(Riding::Boat { id, boat }) = self.riding.take() {
                let b = boat.bounding_box();
                let pos = boat.pos();
                self.parked = Some(Parked {
                    id,
                    pos,
                    bb: [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
                    tracked: self
                        .vehicle_tracker()
                        .and_then(|t| t.get(id))
                        .map(|e| e.position()),
                });
            }
            // The extended tick runs once more (what the ride left in `ext` is read there).
            self.ext_active = true;
        }
        Ok(())
    }

    /// The `use_effects` of the stack in use (`LivingEntity.getUseItem`), set by the engine
    /// each tick from `super::inv::item_use`; the component default without one.
    fn use_effects(&self) -> modern::UseEffects {
        self.use_effects.map_or_else(
            modern::UseEffects::default,
            |(can_sprint, speed_multiplier)| modern::UseEffects {
                can_sprint,
                speed_multiplier,
            },
        )
    }

    #[cfg(all(test, feature = "v1_8", feature = "v1_16_5"))]
    pub(crate) fn use_effects_now(&self) -> Option<(bool, f32)> {
        self.use_effects
    }

    /// The inventory-derived inputs of `ext` (see [`Sim::pre_tick`]): kept out of line, they
    /// matter only on jump presses and while rockets are attached.
    #[cold]
    #[inline(never)]
    fn ext_inputs(&mut self, inv: &ghast_inventory::Inventory, controls: Controls) {
        // The glider is read only when a glide starts (a jump press in the air).
        if controls.jump {
            self.ext.glider = glider_equipped(inv);
            self.ext_active |= self.ext.glider;
        }
        // Entity.getHandHoldingItemAngle(FIREWORK_ROCKET): the main arm, or the other one when
        // only the off hand holds a rocket. Read only while rockets are attached.
        if self.ext.rocket_count() > 0 {
            let rocket = |s: Option<&ghast_inventory::Stack>| {
                s.is_some_and(|s| super::inv::item_name(s.id()) == Some("firework_rocket"))
            };
            let off_only = rocket(inv.offhand()) && !rocket(inv.held());
            self.ext.rocket_arm_left = self.own.main_arm_left != off_only;
        }
    }

    /// `isInWaterOrRain` with the level's rain (biome precipitation is not known: every biome
    /// counts as rainy).
    /// `Entity.isInWaterOrRain`. `Level.isRainingAt` per position (feet and head): rain level
    /// above 0.2, the biome rains there (`Biome.getPrecipitationAt`; an unknown biome counts as
    /// raining: biomes are kept only once a riptide trident was held, or with
    /// `WorldConfig::biomes`), and nothing above blocks motion or holds fluid (the sky check
    /// of the physics; sky light itself is not modelled).
    fn wet(&self) -> bool {
        let p = &self.player;
        let (bx, bz) = (p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        let view = self.world.view(bx, bz);
        let raining = self.rain_level > 0.2;
        if p.touching_water || !raining {
            return modern::in_water_or_rain::<Rules, _>(p, &view, raining);
        }
        let rains = |y: f64| {
            self.world
                .precipitation_at(bx, y.floor() as i32, bz)
                .is_none_or(|r| r == ghast_world::climate::Precipitation::Rain)
        };
        // in_water_or_rain looks at the feet and the head block: keep only the raining ones.
        let mut q = *p;
        match (rains(p.pos[1]), rains(p.bb.max_y)) {
            (false, false) => return false,
            (true, true) => {}
            (true, false) => q.bb.max_y = q.pos[1],
            (false, true) => q.pos[1] = q.bb.max_y,
        }
        modern::in_water_or_rain::<Rules, _>(&q, &view, true)
    }

    /// `releaseUsingItem` → `TridentItem.releaseUsing` with riptide: the launch, before the tick,
    /// along the tick's look (the mouse turned before the key handling).
    fn release_use(
        &mut self,
        inv: &ghast_inventory::Inventory,
        (off, id, ticks): (bool, u16, u32),
        look: (f32, f32),
    ) {
        let stack = if off { inv.offhand() } else { inv.held() };
        let Some(s) = stack.filter(|s| i64::from(s.id()) == i64::from(id)) else {
            return;
        };
        let strength = self.riptide[usize::from(off)];
        if ticks < 10 || strength <= 0.0 || super::inv::next_damage_will_break(s) {
            return;
        }
        let (yaw, pitch) = (self.player.yaw, self.player.pitch);
        self.player.yaw = look.0;
        self.player.pitch = look.1;
        if !self.wet() {
            self.player.yaw = yaw;
            self.player.pitch = pitch;
            return;
        }
        let p = &mut self.player;
        let view = self
            .world
            .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        modern::riptide::<Rules, _>(p, &mut self.ext, &view, strength);
        self.ext_active = true;
    }

    /// The pushes of the entities that ticked after the player (`LivingEntity.pushEntities`,
    /// `AbstractBoat.tick`), each with its box after its own tick.
    #[inline(never)]
    fn push_player(&mut self, pose: &mut Pose, before: bool) {
        if !self.entity_push {
            return;
        }
        let p = &self.player;
        let a = &mut self.around;
        a.pushers.clear();
        let parked = self.parked.as_ref();
        // The boat the player left pushes from where it is (without the tracker, only it).
        if let Some(k) = parked
            && !before
            && self.entities.as_ref().is_none_or(|t| t.get(k.id).is_none())
        {
            a.pushers.push((
                i64::from(k.id),
                modern::Pusher::new(k.pos, aabb(k.bb), modern::PushKind::Boat),
            ));
        }
        for e in self.entities.iter().flat_map(|t| t.iter()) {
            let t = self.entities.as_ref().unwrap();
            // Those that tick before the player pushed it before its tick.
            if before != (!a.pre.is_empty() && a.pre.contains(&e.id())) {
                continue;
            }
            let bits = entity_bits(e);
            if bits & (PUSH_LIVING | PUSH_BOAT) == 0 {
                continue;
            }
            let Some((pos, b)) = Parked::of(parked, e).or_else(|| entity_box(e)) else {
                continue;
            };
            // Boats reach 0.2 farther; nothing else can touch the player.
            let m = 0.25;
            if b[3] < p.bb.min_x - m
                || b[0] > p.bb.max_x + m
                || b[4] < p.bb.min_y - m
                || b[1] > p.bb.max_y + m
                || b[5] < p.bb.min_z - m
                || b[2] > p.bb.max_z + m
            {
                continue;
            }
            // Only ticking entities push (their column is loaded).
            if !t.is_ticking(e) {
                continue;
            }
            // Entity.push: a spectator player has noPhysics (set in its tick) and pushes
            // nothing. A dead or dying pusher still pushes (its aiStep runs until removed).
            if t.is_spectator(e) {
                continue;
            }
            // EntitySelector.pushableBy: the pusher's and the player's team collision rules.
            if let Some(teams) = self.teams.as_deref().filter(|t| t.any_rule()) {
                let mut buf = [0u8; 36];
                if !teams.may_push(scoreboard_name(t, e, &mut buf), &self.profile_name) {
                    continue;
                }
            }
            let kind = if bits & PUSH_BOAT != 0 {
                modern::PushKind::Boat
            } else {
                modern::PushKind::Living
            };
            // In the client's tick order.
            let seq = t.tick_seq(e.id()).map_or(i64::MAX, |q| q as i64);
            a.pushers
                .push((seq, modern::Pusher::new(pos, aabb(b), kind)));
        }
        if a.pushers.is_empty() {
            return;
        }
        a.pushers.sort_by_key(|x| x.0);
        let p = &mut self.player;
        let view = self
            .world
            .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        for (_, pusher) in &a.pushers {
            modern::push_by::<Rules, _>(p, &self.ext, &view, pusher);
        }
        pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
    }

    pub(crate) fn new() -> Self {
        ModernSim {
            world: new_world(config()),
            player: modern::PlayerState::new([0.0; 3], 0.0, 0.0),
            packets: ghast_physics::Packets::new(),
            updates: BlockUpdates::default(),
            mining: mining_attributes(),
            conduit_power: None,
            ranges: range_attributes(),
            old_pos: [0.0; 3],
            entities: None,
            use_effects: None,
            ext: modern::PlayerExt::default(),
            own: OwnEntity::default(),
            rain_level: 0.0,
            ext_active: false,
            riptide: [0.0; 2],
            around: Around::default(),
            teams: None,
            profile_name: "".into(),
            riding: None,
            vehicles: None,
            parked: None,
            reply: None,
            force_step: ForceStepPosition::Off,
            rec: None,
            movement_attributes: false,
            filter_dirty: false,
            session: SessionPackets::default(),
            gate: modern::LoadGate::waiting(),
            entity_push: true,
            predictions: Default::default(),
            snapped: false,
        }
    }

    /// A sim with options (world contents, entity tracking, Grim step compatibility, movement
    /// recording).
    pub(crate) fn with(opts: &SimOptions) -> Self {
        let mut s = Self::new();
        if let Some(c) = opts.world {
            s.world = new_world(c);
        }
        if let Some(cache) = &opts.shared_chunks {
            s.world.set_shared_chunks(Some(cache.clone()));
        }
        if let Some(p) = opts.record.as_deref() {
            match crate::record::Recorder::create(p) {
                Ok(r) => s.rec = Some(Box::new(r)),
                Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
            }
        }
        s.entities = opts.entities.map(super::entity::Tracker::new);
        s.teams = s.entities.is_some().then(Box::default);
        if let Some(n) = &opts.profile_name {
            s.profile_name = n.as_str().into();
        }
        s.force_step = opts.force_step_position;
        s
    }

    /// Test hook: a world in the vanilla nether (registries as with known packs).
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_nether() -> Self {
        let mut s = Self::new();
        s.world.apply_registry(
            "minecraft:dimension_type",
            [
                ("minecraft:overworld", None),
                ("minecraft:the_nether", None),
            ]
            .into_iter(),
        );
        s.world.apply_registry(
            "minecraft:worldgen/biome",
            [("minecraft:plains", None)].into_iter(),
        );
        s.world.enter_dimension("minecraft:the_nether", 1, 8);
        s.sync_level();
        s
    }

    /// Test hook: share the world's sections through `cache` (the engine bench).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_share_chunks(&mut self, cache: Option<ghast_world::SharedChunks>) {
        self.world.set_shared_chunks(cache);
    }

    /// Test hook: a world in the vanilla overworld (registries as with known packs).
    #[cfg(test)]
    pub(crate) fn test_overworld() -> Self {
        Self::test_overworld_with(&SimOptions::default())
    }

    /// Test hook: [`ModernSim::test_overworld`] with options (a recording).
    #[cfg(test)]
    pub(crate) fn test_overworld_with(opts: &SimOptions) -> Self {
        let mut s = Self::with(opts);
        s.world.apply_registry(
            "minecraft:dimension_type",
            [("minecraft:overworld", None)].into_iter(),
        );
        s.world.apply_registry(
            "minecraft:worldgen/biome",
            [("minecraft:plains", None)].into_iter(),
        );
        s.world.enter_dimension("minecraft:overworld", 0, 8);
        s.sync_level();
        s
    }

    /// The level facts movement reads, from the world's dimension.
    fn sync_level(&mut self) {
        if let Some(d) = self.world.dimension() {
            self.player.level = modern::LevelInfo {
                min_y: d.kind.min_y,
                height: d.kind.height,
                fast_lava: d.kind.fast_lava,
            };
        }
    }

    fn state(&self, x: i32, y: i32, z: i32) -> Option<BlockState> {
        self.world.block_state(x, y, z)
    }

    /// `block_update` / `section_blocks_update` while predictions wait
    /// (`ClientLevel.setServerVerifiedBlockState`): a predicted position only remembers the
    /// server's state; the others change at once. The block-update buffer gets every change
    /// the server sent.
    #[cold]
    #[inline(never)]
    fn verified_block_updates(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        if raw.id == cb::id::BLOCK_CHANGE {
            let p: cb::BlockChange = raw.decode_as()?;
            self.updates.push(p.location, p.r#type as u32);
            let s = state_from_wire(i64::from(p.r#type));
            if self.predictions.update(p.location, s) {
                log::debug!(
                    "block update {s} for predicted {:?} waits for the ack",
                    p.location
                );
            } else {
                self.world.apply_block_change(&p);
            }
            return Ok(());
        }
        let mut p: cb::MultiBlockChange = raw.decode_as()?;
        let (cx, cy, cz) = (
            p.chunk_coordinates.x,
            p.chunk_coordinates.y,
            p.chunk_coordinates.z,
        );
        let sy = (cy << 12) >> 12;
        let (updates, predictions) = (&mut self.updates, &mut self.predictions);
        p.records.retain(|&r| {
            let local = (r & 0xFFF) as i32;
            let pos = BlockPos::new(
                cx * 16 + ((local >> 8) & 15),
                sy.wrapping_mul(16).wrapping_add(local & 15),
                cz * 16 + ((local >> 4) & 15),
            );
            let state = ((r as u64) >> 12) as u32;
            updates.push(pos, state);
            !predictions.update(pos, state_from_wire(i64::from(state)))
        });
        self.world.apply_multi_block_change(&p);
        Ok(())
    }

    /// `block_changed_ack` (`BlockStatePredictionHandler.endPredictionsUpTo`): every prediction
    /// up to `ack` ends; `ClientLevel.syncBlockState` puts the server's state back and moves the
    /// player to where it was at the prediction when the restored block would hold it.
    #[cold]
    #[inline(never)]
    fn end_predictions(&mut self, ack: i32) {
        let (world, player) = (&mut self.world, &mut self.player);
        let mut snap = None;
        self.predictions.end_up_to(ack, |pos, state, at| {
            // getBlockState of a column that is not loaded is air.
            let now = world
                .block_state(pos.x, pos.y, pos.z)
                .unwrap_or(BlockState::AIR);
            if now == state {
                log::debug!("block_changed_ack {ack}: {pos:?} stays {now}");
                return;
            }
            log::debug!("block_changed_ack {ack}: {pos:?} {now} back to the server's {state}");
            world.set_block_state(pos.x, pos.y, pos.z, state);
            if let Some(at) = at
                && holds_player(state, pos, player)
            {
                // Entity.absSnapTo: the position and the old position, velocity kept.
                player.set_pos(at[0], at[1], at[2]);
                snap = Some(at);
            }
        });
        if let Some(at) = snap {
            self.old_pos = at;
            self.snapped = true;
        }
    }
}

impl ModernSim {
    /// `MultiPlayerGameMode.performUseItemOn` → `BlockItem.place` on the client, when its result
    /// is known exactly ([`crate::sim::predict::PlaceSent`]): the position and the state placed.
    /// `None` when nothing is predicted (also when vanilla places nothing: the player's box is in
    /// the way).
    fn plain_placement(
        &self,
        p: &crate::sim::predict::PlaceSent<'_>,
    ) -> Option<(BlockPos, BlockState)> {
        let at = p.face.offset(p.pos);
        let state = plain_placement_rule(
            p,
            |q| self.world.block_state(q.x, q.y, q.z),
            self.world
                .dimension()
                .map(|d| (d.kind.min_y, d.kind.height))?,
            &ghast_physics::BlockView::world_border(&self.world),
        )?;
        if holds_player(state, at, &self.player) {
            // BlockItem.canPlace: Level.isUnobstructed fails, nothing is placed.
            return None;
        }
        Some((at, state))
    }
}

/// The block part of [`ModernSim::plain_placement`] (without the player's box): the state
/// placed.
fn plain_placement_rule(
    p: &crate::sim::predict::PlaceSent<'_>,
    block_at: impl Fn(BlockPos) -> Option<BlockState>,
    (min_y, height): (i32, i32),
    border: &ghast_physics::WorldBorder,
) -> Option<BlockState> {
    use super::data::{Block, Item};
    use crate::common::GameMode;
    use ghast_data::modern::state_flags as sf;
    // ItemStack.useOn: adventure needs can_place_on; spectators never place.
    if !matches!(p.game_mode, GameMode::Survival | GameMode::Creative) {
        return None;
    }
    let stack = p.held?;
    // A component patch may carry block_state / block_entity_data (BlockItem.updateBlockStateFromTag).
    if stack.components().is_some() {
        return None;
    }
    let block = Item::from_id(u16::try_from(stack.id()).ok()?)?.block()?;
    let state = block.default_state();
    if block.layout().state_count != 1
        || !state.phys().has(sf::FULL_CUBE)
        || not_plain_placement(block.name())
    {
        return None;
    }
    // useItemOn: the clicked position inside the world border.
    if !crate::sim::predict::border_contains(border, p.pos) {
        return None;
    }
    // A full collision cube is never replaceable (BlockPlaceContext.replaceClicked is false):
    // the block goes next to it.
    let clicked = block_at(p.pos)?;
    if !clicked.phys().has(sf::FULL_CUBE) {
        return None;
    }
    // useItemOn / useWithoutItem of the clicked block, unless sneaking with an item.
    if !(p.sneaking && p.any_item) && activated_full_cube(clicked.block().name()) {
        return None;
    }
    let at = p.face.offset(p.pos);
    if at.y < min_y || at.y >= min_y + height {
        return None;
    }
    // BlockPlaceContext.canPlace: air and fluids are replaceable by any block item.
    let there = block_at(at)?;
    if !(there.is_air() || matches!(there.block(), Block::WATER | Block::LAVA)) {
        return None;
    }
    Some(state)
}

/// Single-state full-cube blocks whose item places them with logic of its own
/// (oracle: `tests/golden/<version>/place.jsonl.gz`): concrete powder hardens next to water,
/// the game-master block needs operator rights.
fn not_plain_placement(name: &str) -> bool {
    name.ends_with("_concrete_powder") || name == "test_instance_block"
}

/// Full-cube blocks a right click may activate (`useItemOn` / `useWithoutItem` consume the click
/// for a block item, then the item is not used). The menus, note blocks, crafters, respawn
/// anchors and vaults are oracle-proven (`place.jsonl.gz`: every full-cube state clicked on its
/// top and a side); blocks whose answer depends on their block entity (which the oracle's level
/// does not have: jukebox records, chiseled bookshelf books, spawners, beehives, operator
/// blocks) are listed without proof and never predicted.
fn activated_full_cube(name: &str) -> bool {
    const LIST: &[&str] = &[
        // Oracle-proven.
        "barrel",
        "beacon",
        "blast_furnace",
        "cartography_table",
        "chiseled_bookshelf",
        "crafter",
        "crafting_table",
        "dispenser",
        "dropper",
        "furnace",
        "loom",
        "note_block",
        "respawn_anchor",
        "smithing_table",
        "smoker",
        "vault",
        // Block entities the answer may read.
        "bee_nest",
        "beehive",
        "chain_command_block",
        "command_block",
        "creaking_heart",
        "jigsaw",
        "jukebox",
        "repeating_command_block",
        "sculk_catalyst",
        "spawner",
        "structure_block",
        "test_block",
        "test_instance_block",
        "trial_spawner",
    ];
    name.ends_with("shulker_box") || LIST.contains(&name)
}

/// What a broken block leaves (`FluidState.createLegacyBlock` of its fluid): a waterlogged
/// block (and kelp, seagrass, bubble columns) leaves a water source, anything else air.
fn fluid_left_behind(old: BlockState) -> BlockState {
    use super::data::Block;
    // The fluid byte's kind bits: 1 water, 2 lava. A block that holds a fluid holds a source.
    match old.phys().fluid() >> 6 {
        1 => Block::WATER.default_state(),
        2 => Block::LAVA.default_state(),
        _ => BlockState::AIR,
    }
}

/// A wire block state id as the world stores it (unknown ids read as air).
fn state_from_wire(v: i64) -> BlockState {
    u16::try_from(v)
        .ok()
        .and_then(BlockState::from_id)
        .unwrap_or(BlockState::AIR)
}

/// `Entity.isColliding(pos, state)`: the state's collision shape at `pos` for the player's
/// context (model offsets, scaffolding, powder snow) overlaps the player's box.
fn holds_player(state: BlockState, pos: BlockPos, p: &modern::PlayerState) -> bool {
    let b = &p.bb;
    modern::state_collides::<Rules>(
        state,
        [pos.x, pos.y, pos.z],
        [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z],
        &modern::CollisionContext {
            feet_y: p.pos[1],
            descending: p.shift(),
            fall_distance: p.fall_distance,
            walks_on_powder_snow: p.leather_boots,
        },
    )
}

/// The union of a shape's boxes as a ray box (block-local).
fn outline_box(s: BlockState) -> Option<[f64; 6]> {
    let shape = s.outline_shape();
    if shape.empty {
        return None;
    }
    union(shape.boxes)
}

impl WorldView for ModernSim {
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        self.world.is_column_loaded(chunk_x, chunk_z)
    }

    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        self.state(x, y, z).map(|s| u32::from(s.id()))
    }

    fn entities(&self) -> Option<&ghast_entity::Entities> {
        self.entities.as_deref()
    }

    fn loaded_columns(&self) -> usize {
        self.world.columns().len()
    }

    fn build_height(&self) -> Option<(i32, i32)> {
        self.world
            .dimension()
            .map(|d| (d.kind.min_y, d.kind.height))
    }

    fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery> {
        let s = self.state(x, y, z)?;
        let d = s.block().data();
        let hardness = if d.diggable {
            d.hardness.unwrap_or(-1.0)
        } else {
            -1.0
        };
        Some(BlockQuery {
            exact: Some(super::exact_dig(crate::hands::ModernDig {
                state: s.id(),
                mining_efficiency: self.mining[0].value(),
                block_break_speed: self.mining[1].value(),
                submerged_mining_speed: self.mining[2].value(),
                conduit_power: self.conduit_power,
            })),
            air: s.is_air(),
            water: s.block().name() == "water",
            block: s.block().default_state().id(),
            hardness,
            // The modern destroy progress replaces tool groups and harvest lists.
            dig_material: None,
            harvest_tools: &[],
            selection: outline_box(s),
            stairs: None,
            activates: activates_1_16(s.block().name()),
        })
    }

    fn crosshair(
        &self,
        eyes: Vec3,
        (yaw, pitch): (f32, f32),
        _look: Vec3,
        reach: f64,
    ) -> Option<crate::BlockHit> {
        use super::pick;
        // The modern look vector (`calculateViewVector`, double-index sine table).
        let view = pick::view_vector(yaw, pitch);
        let eye = [eyes.x, eyes.y, eyes.z];
        // Survival reach on both rays: the entity range (3) is shorter, the block range wins.
        let hit = pick::pick(&self.world, eye, view, reach, 3.0, None);
        block_hit(&hit, eye)
    }
}

impl Sim for ModernSim {
    fn crosshair_now(
        &self,
        _eyes: Vec3,
        (yaw, pitch): (f32, f32),
        _look: Vec3,
        held: Option<u16>,
    ) -> Option<crate::BlockHit> {
        use super::pick;
        let p = &self.player;
        // Minecraft.pick at partial tick 1: the eye lerps from the old position.
        let eye = pick::eye_position(p.pos, self.old_pos, p.dims.eye_height);
        let held_block = held
            .and_then(super::data::Item::from_id)
            .and_then(super::data::Item::block);
        let hit = pick::pick(
            &self.world,
            eye,
            pick::view_vector(yaw, pitch),
            self.ranges[0].value(),
            self.ranges[1].value(),
            held_block,
        );
        block_hit(&hit, eye)
    }

    fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        self.session.note(raw, cb::id::LOGIN, cb::id::RESPAWN);
        match raw.id {
            cb::id::ENTITY_METADATA | cb::id::SPAWN_ENTITY | cb::id::ENTITY_DESTROY => {
                self.own_entity_packet(raw)?;
            }
            cb::id::SET_PASSENGERS | cb::id::VEHICLE_MOVE => self.vehicle_packet(raw)?,
            cb::id::ENTITY_TELEPORT
            | cb::id::SYNC_ENTITY_POSITION
            | cb::id::REL_ENTITY_MOVE
            | cb::id::ENTITY_MOVE_LOOK
            | cb::id::ENTITY_LOOK
                if self.vehicles.is_some() =>
            {
                if let Some(v) = &mut self.vehicles {
                    v.apply(raw)?;
                }
            }
            cb::id::RESPAWN => {
                self.riding = None;
                self.parked = None;
            }
            cb::id::LOGIN => {
                self.riding = None;
                self.parked = None;
                if self.vehicles.take().is_some() {
                    self.filter_dirty = true;
                }
                self.own.id = raw.decode_as::<cb::Login>()?.entity_id;
                // A new play phase: a new client scoreboard.
                if let Some(t) = &mut self.teams {
                    t.clear();
                }
                self.own.rockets.clear();
                self.own.mounts.clear();
            }
            _ => {}
        }
        if raw.id == cb::id::TEAMS {
            if let Some(t) = &mut self.teams
                && !t.apply(&raw.body, super::TEAM_LAYOUT)
            {
                log::debug!("bad set_player_team packet ({} B)", raw.body.len());
            }
            return Ok(());
        }
        // The tracker also reads map_chunk / unload_chunk (which columns tick): the world gets
        // the same packets below.
        if let Some(t) = &mut self.entities
            && t.wants(raw.id)
        {
            t.apply(raw)?;
        }
        // The vehicles-only tracker follows the level and its columns (which entities tick).
        if let Some(v) = &mut self.vehicles
            && matches!(
                raw.id,
                cb::id::LOGIN | cb::id::RESPAWN | cb::id::MAP_CHUNK | cb::id::UNLOAD_CHUNK
            )
        {
            v.apply(raw)?;
        }
        match raw.id {
            // Batch timing needs the arrival time: the engine routes these (Inbound).
            cb::id::CHUNK_BATCH_START | cb::id::CHUNK_BATCH_FINISHED => return Ok(()),
            // ClientLevel.setServerVerifiedBlockState: a predicted block keeps the client's
            // state until the ack.
            cb::id::BLOCK_CHANGE | cb::id::MULTI_BLOCK_CHANGE if !self.predictions.is_empty() => {
                return self.verified_block_updates(raw);
            }
            cb::id::ACKNOWLEDGE_PLAYER_DIGGING => {
                let p: cb::AcknowledgePlayerDigging = raw.decode_as()?;
                self.end_predictions(p.sequence_id);
                return Ok(());
            }
            cb::id::BLOCK_CHANGE if self.updates.on => {
                let p: cb::BlockChange = raw.decode_as()?;
                self.updates.push(p.location, p.r#type as u32);
                self.world.apply_block_change(&p);
                return Ok(());
            }
            cb::id::MULTI_BLOCK_CHANGE if self.updates.on => {
                let p: cb::MultiBlockChange = raw.decode_as()?;
                let c = &p.chunk_coordinates;
                let sy = ((c.y << 12) as i32) >> 12;
                for &r in &p.records {
                    let local = (r & 0xFFF) as i32;
                    let pos = BlockPos::new(
                        c.x * 16 + ((local >> 8) & 15),
                        sy.wrapping_mul(16).wrapping_add(local & 15),
                        c.z * 16 + ((local >> 4) & 15),
                    );
                    self.updates.push(pos, ((r as u64) >> 12) as u32);
                }
                self.world.apply_multi_block_change(&p);
                return Ok(());
            }
            _ => {}
        }
        // Decode only this world packet: the packet-set enum's decode_raw (behind
        // World::handle_raw) would link every decoder of the version into the binary.
        use super::proto::play::clientbound::ClientboundPlayPacket as P;
        use ghast_world::WorldError;
        let d = |r: Result<P, ghast_protocol::DecodeError>| r.map_err(WorldError::Decode);
        let applied = if raw.id == cb::id::MAP_CHUNK {
            self.world.apply_map_chunk_body(&raw.body)
        } else {
            let p = match raw.id {
                cb::id::LOGIN => d(raw.decode_as().map(P::Login))?,
                cb::id::RESPAWN => d(raw.decode_as().map(P::Respawn))?,
                cb::id::UNLOAD_CHUNK => d(raw.decode_as().map(P::UnloadChunk))?,
                cb::id::BLOCK_CHANGE => d(raw.decode_as().map(P::BlockChange))?,
                cb::id::MULTI_BLOCK_CHANGE => d(raw.decode_as().map(P::MultiBlockChange))?,
                cb::id::CHUNK_BIOMES => d(raw.decode_as().map(P::ChunkBiomes))?,
                cb::id::UPDATE_VIEW_POSITION => d(raw.decode_as().map(P::UpdateViewPosition))?,
                cb::id::UPDATE_VIEW_DISTANCE => d(raw.decode_as().map(P::UpdateViewDistance))?,
                cb::id::INITIALIZE_WORLD_BORDER => {
                    d(raw.decode_as().map(P::InitializeWorldBorder))?
                }
                cb::id::WORLD_BORDER_CENTER => d(raw.decode_as().map(P::WorldBorderCenter))?,
                cb::id::WORLD_BORDER_LERP_SIZE => d(raw.decode_as().map(P::WorldBorderLerpSize))?,
                cb::id::WORLD_BORDER_SIZE => d(raw.decode_as().map(P::WorldBorderSize))?,
                cb::id::WORLD_BORDER_WARNING_DELAY => {
                    d(raw.decode_as().map(P::WorldBorderWarningDelay))?
                }
                cb::id::WORLD_BORDER_WARNING_REACH => {
                    d(raw.decode_as().map(P::WorldBorderWarningReach))?
                }
                cb::id::TILE_ENTITY_DATA => d(raw.decode_as().map(P::TileEntityData))?,
                _ => return Ok(()),
            };
            self.world.handle(&p)
        };
        if matches!(raw.id, cb::id::LOGIN | cb::id::RESPAWN) {
            self.sync_level();
            // A new ClientLevel (join; respawn into another dimension): a new prediction
            // handler.
            if raw.id == cb::id::LOGIN || matches!(applied, Ok(ghast_world::Applied::Changed)) {
                self.predictions.clear();
            }
        }
        applied?;
        Ok(())
    }

    fn registry_data(&mut self, raw: &RawPacket) {
        match raw.decode_as::<super::proto::configuration::clientbound::RegistryData>() {
            Ok(p) => {
                self.world.apply_registry_data(&p);
            }
            Err(e) => log::warn!("bad registry_data packet: {e}"),
        }
    }

    fn modern_inputs(&self) -> bool {
        true
    }

    fn held_use_inputs(&mut self, inv: &mut ghast_inventory::Inventory) {
        // EnchantmentHelper.getTridentSpinAttackStrength through the synced registry (None:
        // not computable -> no riptide). Only tridents are looked at.
        let trident = |s: Option<&ghast_inventory::Stack>| {
            s.filter(|s| super::inv::item_name(s.id()) == Some("trident"))
                .cloned()
        };
        let hands = [trident(inv.held()), trident(inv.offhand())];
        for (k, s) in hands.into_iter().enumerate() {
            self.riptide[k] = s
                .and_then(|s| super::inv_trident_strength(inv, &s))
                .unwrap_or(0.0);
        }
        // Riptide works in rain only where the biome rains: keep biomes from now on.
        if self.riptide.iter().any(|&r| r > 0.0) && !self.world.config().biomes {
            self.world.set_biomes(true);
        }
    }

    fn pre_tick_wanted(&self) -> bool {
        self.ext.rocket_count() > 0
    }

    fn item_use_facts(
        &self,
        stack: &ghast_inventory::Stack,
        off_hand: bool,
        mut held: HeldItem,
    ) -> HeldItem {
        // getUseDuration > 0; food only below a full bar unless can_always_eat.
        if let Some(u) = super::inv::item_use(stack) {
            held.usable = u.duration.is_none_or(|d| d > 0);
            held.food = u.food.is_some();
            held.always_edible = u.food.is_some_and(|f| f.can_always_eat);
        }
        // FireworkRocketItem.use: SUCCESS (the server spawns the boosting rocket) only while
        // gliding; otherwise PASS.
        // TridentItem.use: with riptide only in water or rain (else FAIL: no use state).
        if self.riptide[usize::from(off_hand)] > 0.0
            && super::inv::item_name(stack.id()) == Some("trident")
        {
            held.usable = held.usable && self.wet();
        }
        held.swing_on_use =
            self.ext.fall_flying && super::inv::item_name(stack.id()) == Some("firework_rocket");
        held
    }

    fn pre_tick(&mut self, inv: &ghast_inventory::Inventory, t: &crate::sim::PreTick) -> bool {
        if t.controls.jump || self.ext.rocket_count() > 0 {
            self.ext_inputs(inv, t.controls);
        }
        if let Some(released) = t.released {
            self.release_use(inv, released, t.look);
        }
        self.use_effects = None;
        let Some((off, id)) = t.using else {
            return true;
        };
        // updatingUsingItem: the used hand must still hold the same item (useItem follows it).
        let s = if off { inv.offhand() } else { inv.held() };
        let Some(s) = s.filter(|s| i64::from(s.id()) == i64::from(id)) else {
            return false;
        };
        self.use_effects = super::inv::item_use(s).map(|u| (u.can_sprint, u.speed_multiplier));
        true
    }

    fn gliding(&self) -> bool {
        self.ext.fall_flying
    }

    fn weather(&mut self, reason: u8, value: f32) {
        // ClientPacketListener.handleGameEvent: START_RAINING sets the rain level to 0 (the
        // server then raises it with RAIN_LEVEL_CHANGE), STOP_RAINING to 1, RAIN_LEVEL_CHANGE
        // to the value.
        self.rain_level = match reason {
            1 => 0.0,
            2 => 1.0,
            _ => value,
        };
    }

    fn mount_info(&self, entity_id: i32) -> Option<(i32, bool, bool)> {
        let m = self.own.mounts.iter().find(|m| m.id == entity_id)?;
        let (saddle, body) = m.slots(EntityIds::get());
        Some((m.ty, saddle, body))
    }

    #[cfg(all(test, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_modern(&mut self, p: modern::PlayerState, x: modern::PlayerExt) {
        let level = self.player.level;
        self.player = p;
        self.player.level = level;
        self.ext = x;
        self.ext_active = true;
        self.old_pos = p.pos;
        self.gate = modern::LoadGate::loaded();
    }

    #[cfg(all(test, feature = "v1_8", feature = "v1_16_5"))]
    fn test_shared_flags(&self) -> u8 {
        self.ext.shared_flags(&self.player)
    }

    #[cfg(all(test, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_own_id(&mut self, id: i32) {
        self.own.id = id;
    }

    fn set_main_arm_left(&mut self, left: bool) {
        self.own.main_arm_left = left;
    }

    fn drop_level(&mut self) {
        // ClientPacketListener.handleConfigurationStart → clearClientLevel: no level, no
        // entities until the next login (which enters a new level from the new registries).
        self.world.clear();
        self.session = SessionPackets::default();
        self.updates.list.clear();
        self.updates.dropped = 0;
        if let Some(t) = &mut self.entities {
            *t = super::entity::Tracker::new(t.config());
        }
        self.reset_player();
    }

    fn reset_player(&mut self) {
        // A fresh LocalPlayer; abilities and food are sent again by the server, the level
        // stays (attributes are re-sent too).
        let abilities = self.player.abilities;
        let food = self.player.food_level;
        let level = self.player.level;
        self.player = modern::PlayerState::new([0.0; 3], 0.0, 0.0);
        // A new LocalPlayer: not gliding, no rockets attached, default attributes.
        self.ext = modern::PlayerExt::default();
        self.ext_active = false;
        self.movement_attributes = false;
        self.player.abilities = abilities;
        self.player.food_level = food;
        self.player.level = level;
        self.mining = mining_attributes();
        self.ranges = range_attributes();
        self.old_pos = [0.0; 3];
        // handleLogin / handleRespawn: wait for the level again.
        self.gate = modern::LoadGate::waiting();
        self.sync_level();
    }

    fn respawn_player(&mut self, keep: u8) {
        // ClientPacketListener.handleRespawn: KEEP_ATTRIBUTE_MODIFIERS (1) keeps the attributes,
        // KEEP_ENTITY_DATA (2) the last sent input and sprinting.
        let old = self.player;
        let old_mining = self.mining;
        let old_ranges = self.ranges;
        let old_moves = (self.ext.attributes, self.movement_attributes);
        self.reset_player();
        if keep & 1 != 0 {
            self.player.attributes = old.attributes;
            (self.ext.attributes, self.movement_attributes) = old_moves;
            self.ext_active |= self.movement_attributes;
            self.mining = old_mining;
            self.ranges = old_ranges;
        }
        if keep & 2 != 0 {
            self.player.sent.input = old.sent.input;
            self.player.sent.sprinting = old.sent.sprinting;
        }
    }

    fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
        // The engine keeps the look (its rotation may have moved it since the last tick).
        self.player.yaw = pose.yaw;
        self.player.pitch = pose.pitch;
        // handleMovePlayer: the old position follows the teleport (relative axes keep their
        // offset from it).
        let before = self.player.pos;
        let _reply = self.player.apply_teleport(
            [t.x, t.y, t.z],
            [t.delta.x, t.delta.y, t.delta.z],
            t.yaw,
            t.pitch,
            t.relative,
        );
        if let Some(r) = &mut self.rec {
            r.teleport_modern(
                [t.x, t.y, t.z],
                [t.delta.x, t.delta.y, t.delta.z],
                t.yaw,
                t.pitch,
                t.relative as i32,
                t.teleport_id.unwrap_or(0),
            );
        }
        let now = self.player.pos;
        for (i, old) in self.old_pos.iter_mut().enumerate() {
            *old = if t.relative & (1 << i) != 0 {
                *old + (now[i] - before[i])
            } else {
                now[i]
            };
        }
        sync_pose_26(pose, &self.player);
    }

    fn abilities(&mut self, a: Abilities) {
        let a = physics_abilities(a);
        if let Some(r) = &mut self.rec {
            r.abilities(&a);
        }
        self.player.apply_abilities(a);
    }

    fn food(&mut self, food: i32) {
        self.player.food_level = food;
    }

    fn velocity(&mut self, v: Vec3, add: bool) {
        if let Some(r) = &mut self.rec {
            if add {
                r.note("explosion push not representable");
            } else {
                r.motion([v.x, v.y, v.z]);
            }
        }
        let p = &mut self.player;
        if add {
            p.apply_velocity([p.vel[0] + v.x, p.vel[1] + v.y, p.vel[2] + v.z]);
        } else {
            p.apply_velocity([v.x, v.y, v.z]);
        }
    }

    fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
        // Modern attributes arrive as [`Sim::attributes`].
        let _ = (base, modifiers);
    }

    fn attributes(&mut self, attributes: &[AttributeUpdate]) {
        for a in attributes {
            if let Some(r) = &mut self.rec {
                let mods = a
                    .modifiers
                    .iter()
                    .map(|(id, amount, op)| (id.to_string(), *amount, *op))
                    .collect();
                r.attribute(a.name, a.base, mods);
            }
            let mods: Vec<(ModifierId, f64, u8)> = a
                .modifiers
                .iter()
                .map(|(id, amount, op)| (ModifierId::new(id), *amount, *op as u8))
                .collect();
            let mining = match a.name {
                "mining_efficiency" => Some(0),
                "block_break_speed" => Some(1),
                "submerged_mining_speed" => Some(2),
                _ => None,
            };
            let range = match a.name {
                "block_interaction_range" => Some(0),
                "entity_interaction_range" => Some(1),
                _ => None,
            };
            if let Some(m) = self.ext.attributes.get_mut(a.name) {
                m.apply_packet(a.base, &mods);
                let d = modern::MovementAttributes::default();
                let x = &self.ext.attributes;
                self.movement_attributes = x.friction_modifier.value()
                    != d.friction_modifier.value()
                    || x.air_drag_modifier.value() != d.air_drag_modifier.value()
                    || x.bounciness.value() != d.bounciness.value();
                self.ext_active |= self.movement_attributes;
            } else if let Some(i) = mining {
                self.mining[i].apply_packet(a.base, &mods);
            } else if let Some(i) = range {
                self.ranges[i].apply_packet(a.base, &mods);
            } else if let Some(kind) = AttributeKind::from_name(a.name) {
                self.player.apply_attribute(kind, a.base, &mods);
            }
        }
    }

    fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>) {
        // The engine keeps classic 1-based effect numbers (the version's `minecraft:mob_effect`
        // registry id + 1).
        if let Some(r) = &mut self.rec {
            r.effects(effects);
        }
        use super::effects as fx;
        let e = &mut self.player.effects;
        e.jump_boost = effects.get(&fx::JUMP_BOOST).map(|a| i32::from(*a));
        e.blindness = effects.contains_key(&fx::BLINDNESS);
        e.levitation = effects.get(&fx::LEVITATION).map(|a| i32::from(*a));
        e.slow_falling = effects.contains_key(&fx::SLOW_FALLING);
        e.dolphins_grace = effects.contains_key(&fx::DOLPHINS_GRACE);
        e.weaving = effects.contains_key(&fx::WEAVING);
        self.conduit_power = effects.get(&fx::CONDUIT_POWER).map(|a| i32::from(*a));
    }

    fn boots(&mut self, depth_strider: u8, soul_speed: u8) {
        // Depth strider and soul speed arrive as attributes.
        let _ = (depth_strider, soul_speed);
    }

    fn feet_item(&mut self, id: Option<i32>) {
        let leather = super::data::Item::from_name("leather_boots");
        self.player.leather_boots = id
            .and_then(|i| u16::try_from(i).ok())
            .and_then(super::data::Item::from_id)
            == leather;
    }

    fn spectator(&mut self, on: bool) {
        self.player.spectator = on;
    }

    fn modern_player(&self) -> Option<&modern::PlayerState> {
        Some(&self.player)
    }

    fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>) {
        let a = &mut self.player.abilities;
        if a.flying == flying || (flying && !a.allow_flying) {
            return;
        }
        a.flying = flying;
        let a = *a;
        out.push(Outbound::Abilities {
            flags: abilities_flags(&a),
            flying_speed: a.fly_speed,
            walking_speed: a.walk_speed,
        });
    }

    fn collect_block_updates(&mut self, on: bool) {
        self.updates.on = on;
        if !on {
            self.updates.list.clear();
        }
    }

    fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize {
        out.append(&mut self.updates.list);
        std::mem::take(&mut self.updates.dropped)
    }

    fn world_packet_ids(&self) -> Vec<i32> {
        use super::proto::play::clientbound as cb;
        // Our own entity data and attached rockets (gliding), decoded only when they concern us.
        let own = [
            cb::id::ENTITY_METADATA,
            cb::id::SPAWN_ENTITY,
            cb::id::ENTITY_DESTROY,
            // The vehicle the player rides.
            cb::id::SET_PASSENGERS,
            cb::id::VEHICLE_MOVE,
            // block_changed_ack: the server's answer to the client's block predictions.
            cb::id::ACKNOWLEDGE_PLAYER_DIGGING,
        ];
        // Moves of the boats the player may board, only while some are known without the
        // tracker (entity moves are frequent: not decoded otherwise).
        let boats: &[i32] = if self.entities.is_none() && self.vehicles.is_some() {
            &[
                cb::id::ENTITY_TELEPORT,
                cb::id::SYNC_ENTITY_POSITION,
                cb::id::REL_ENTITY_MOVE,
                cb::id::ENTITY_MOVE_LOOK,
                cb::id::ENTITY_LOOK,
            ]
        } else {
            &[]
        };
        self.world
            .packet_ids()
            .chain(own)
            .chain(boats.iter().copied())
            .collect()
    }

    fn take_reply(&mut self) -> Option<Outbound> {
        self.reply.take()
    }

    fn take_filter_dirty(&mut self) -> bool {
        std::mem::take(&mut self.filter_dirty)
    }

    fn vehicle(&self) -> Option<crate::common::Vehicle> {
        match self.riding.as_ref()? {
            Riding::Seat { id } => {
                let e = self.vehicle_tracker()?.get(*id)?;
                let [x, y, z] = e.position();
                Some(crate::common::Vehicle {
                    entity_id: *id,
                    pos: Vec3::new(x, y, z),
                    yaw: e.yaw(),
                    pitch: e.pitch(),
                    on_ground: e.on_ground(),
                    controlled: false,
                })
            }
            Riding::Boat { id, boat } => {
                let [x, y, z] = boat.pos();
                Some(crate::common::Vehicle {
                    entity_id: *id,
                    pos: Vec3::new(x, y, z),
                    yaw: boat.yaw(),
                    pitch: boat.pitch(),
                    on_ground: boat.on_ground(),
                    controlled: true,
                })
            }
        }
    }

    fn entity_config(&self) -> Option<ghast_entity::Config> {
        self.entities.as_ref().map(|t| t.config())
    }

    fn set_entities(&mut self, config: Option<ghast_entity::Config>) {
        if self.entity_config() == config {
            return;
        }
        self.entities = config.map(|c| {
            let mut t = super::entity::Tracker::new(c);
            self.session.replay(|r| {
                if let Err(e) = t.apply(r) {
                    log::debug!("entity tracker: session packet 0x{:02x}: {e}", r.id);
                }
            });
            // The columns already loaded tick their entities.
            for (c, _) in self.world.columns().iter() {
                t.mark_column_loaded(c.x, c.z);
            }
            t
        });
        // Teams sent before tracking started are not known (all pushes then allowed).
        self.teams = self.entities.is_some().then(Box::default);
        // The tracker knows the boats from now on (it starts empty: boats spawned before are
        // known again once the server resends them).
        if self.entities.is_some() && self.vehicles.take().is_some() {
            self.filter_dirty = true;
        }
    }

    fn entity_packet_ids(&self) -> Vec<i32> {
        self.entities
            .as_ref()
            .map(|t| {
                t.packet_ids()
                    .chain([super::proto::play::clientbound::id::TEAMS])
                    .collect()
            })
            .unwrap_or_default()
    }

    fn pick_margin(&self, e: &ghast_entity::Entity) -> Option<f32> {
        let t = self.entities.as_ref()?;
        t.pickable(e).then(|| super::entity::pick_radius(e))
    }

    fn level_load_start(&mut self) {
        self.gate.level_chunks_load_start();
    }

    fn player_alive(&mut self, alive: bool) {
        self.gate.player_alive(alive);
    }

    fn load_gate_tick(&mut self, section_compiled: bool, timed_out: bool) -> bool {
        if timed_out {
            self.gate.time_out();
        }
        self.gate.tick(&self.player, section_compiled)
    }

    fn tick_unloaded(&mut self) {
        // LoadGate::step before the gate: only the entity tick counter.
        self.player.age += 1;
    }

    fn set_entity_push(&mut self, on: bool) {
        self.entity_push = on;
    }

    fn tick_entities(&mut self, pose: &mut Pose) {
        // ClientLevel.tickEntities; a moved interpolation target must be free of blocks and
        // the border (Level.noCollision without the entity part).
        let (world, level) = (&self.world, &self.player.level);
        if let Some(t) = &mut self.entities {
            t.tick_with(|e, bb| block_free(world, level, e, bb));
        }
        if let Some(v) = &mut self.vehicles {
            v.tick_with(|e, bb| block_free(world, level, e, bb));
        }
        self.check_parked();
        if std::mem::take(&mut self.around.player_ticked)
            && (self.entities.is_some() || self.parked.is_some())
        {
            self.push_player(pose, false);
        }
        self.around.pre.clear();
        // ClientLevel.tick: the world border steps after the entities (the player included).
        self.world.tick();
    }

    fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
        // The oracle-verified LocalPlayer.pick: block ray to the longer range, then the
        // entity ray, each filtered to its range attribute.
        use super::pick;
        let held_block = q
            .held
            .and_then(super::data::Item::from_id)
            .and_then(super::data::Item::block);
        let eye = if q.now {
            let p = &self.player;
            pick::eye_position(p.pos, self.old_pos, p.dims.eye_height)
        } else {
            [q.eyes.x, q.eyes.y, q.eyes.z]
        };
        let view = pick::view_vector(q.rotation.0, q.rotation.1);
        let (block_range, entity_range) = (self.ranges[0].value(), self.ranges[1].value());
        if q.entities.is_empty() {
            // pick_target without entities is the block pick.
            let hit = pick::pick(
                &self.world,
                eye,
                view,
                block_range,
                entity_range,
                held_block,
            );
            return Crosshair::Block(block_hit(&hit, eye));
        }
        let t = pick::pick_target(
            &self.world,
            &q.player_bb,
            eye,
            view,
            block_range,
            entity_range,
            held_block,
            q.entities,
        );
        modern_crosshair(t, eye)
    }

    fn predict_air(&mut self, x: i32, y: i32, z: i32) {
        self.world.set_block_state(x, y, z, BlockState::AIR);
    }

    fn dig_sent(
        &mut self,
        pos: BlockPos,
        _status: crate::common::DigStatus,
        broken: bool,
        sequence: i32,
        player: Vec3,
    ) {
        if !broken {
            return;
        }
        // MultiPlayerGameMode.destroyBlock (nothing for air), ClientLevel.setBlock while
        // predicting: the block's state before is the server's until the ack.
        let Some(old) = self.world.block_state(pos.x, pos.y, pos.z) else {
            return;
        };
        if old.is_air() {
            return;
        }
        if self
            .world
            .set_block_state(pos.x, pos.y, pos.z, fluid_left_behind(old))
        {
            log::debug!("predicted the break of {old} at {pos:?} (sequence {sequence})");
            self.predictions
                .retain(pos, old, sequence, [player.x, player.y, player.z]);
        }
    }

    fn place_sent(&mut self, p: &crate::sim::predict::PlaceSent<'_>) {
        let Some((at, state)) = self.plain_placement(p) else {
            return;
        };
        // BlockItem.place: ClientLevel.setBlock while predicting keeps the server's state.
        let Some(old) = self.world.block_state(at.x, at.y, at.z) else {
            return;
        };
        if self.world.set_block_state(at.x, at.y, at.z, state) {
            log::debug!("predicted {state} at {at:?} (sequence {})", p.sequence);
            self.predictions
                .retain(at, old, p.sequence, [p.player.x, p.player.y, p.player.z]);
        }
    }

    #[cfg(test)]
    fn set_player_pos(&mut self, p: Vec3) {
        self.player.set_pos(p.x, p.y, p.z);
    }

    fn teleport_sequence(&mut self, sequence: Option<i32>) {
        self.predictions.on_teleport(sequence.unwrap_or(0));
    }

    fn take_snap(&mut self) -> Option<Vec3> {
        if !std::mem::take(&mut self.snapped) {
            return None;
        }
        let p = self.player.pos;
        Some(Vec3::new(p[0], p[1], p[2]))
    }

    fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
        held_item_facts(id, count, efficiency)
    }

    fn chunk_batch_start(&mut self, now_nanos: i64) {
        self.world.on_chunk_batch_start(now_nanos);
    }

    fn chunk_batch_finished(&mut self, batch_size: i32, now_nanos: i64) -> f32 {
        self.world.on_chunk_batch_finished(batch_size, now_nanos)
    }

    fn step(
        &mut self,
        pose: &mut Pose,
        controls: Controls,
        using_item: bool,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    ) {
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            using_item,
        };
        self.packets.clear();
        self.player.use_effects = if using_item {
            self.use_effects()
        } else {
            modern::UseEffects::default()
        };
        // Entity.setOldPosAndRot at the start of the entity tick.
        self.old_pos = self.player.pos;
        if self.rec.is_some() {
            self.record_start();
        }
        if self.entities.is_some() {
            self.tick_before_player(pose);
        }
        if let Some(Riding::Seat { id }) = self.riding {
            // The vehicle ticks before its passenger: its position after this tick.
            let (world, level) = (&self.world, &self.player.level);
            let t = match (&mut self.entities, &mut self.vehicles) {
                (Some(t), _) => Some(t),
                (None, Some(v)) => Some(&mut **v),
                _ => None,
            };
            let pos = t.and_then(|t| t.tick_early(id, |e, bb| block_free(world, level, e, bb)));
            if let Some(pos) = pos {
                if self.entities.is_some() {
                    collect_colliders(
                        self.entities.as_ref(),
                        None,
                        &self.player,
                        Some(id),
                        &mut self.around.boxes,
                        &mut Vec::new(),
                    );
                } else {
                    self.around.boxes.clear();
                }
                let p = &mut self.player;
                let view = self
                    .world
                    .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
                let around = modern::Surroundings::new().with_entities(&self.around.boxes);
                let seat = modern::Seat::new(pos, modern::Seat::MINECART);
                modern::tick_passenger::<Rules, _>(
                    p,
                    &mut self.ext,
                    &around,
                    &seat,
                    &input,
                    &view,
                    &mut self.packets,
                );
                if self.rec.is_some() {
                    self.record_tick(&input, Some("riding not representable"));
                }
                push_packets(&self.packets, entity_id, out);
                sync_pose_26(pose, &self.player);
                return;
            }
            // The vehicle is not known any more: walk on as before.
            self.riding = None;
        }
        if let Some(Riding::Boat { id, boat }) = &mut self.riding {
            // The boat ticks with its passenger (tickNonPassenger -> tickPassenger).
            let id = *id;
            let mut boat_boxes = Vec::new();
            if self.entities.is_some() {
                collect_colliders(
                    self.entities.as_ref(),
                    None,
                    &self.player,
                    Some(id),
                    &mut self.around.boxes,
                    &mut boat_boxes,
                );
            } else {
                self.around.boxes.clear();
            }
            let p = &mut self.player;
            let view = self
                .world
                .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
            let around = modern::Surroundings::new().with_entities(&self.around.boxes);
            modern::tick_boat::<Rules, _>(
                boat,
                p,
                &mut self.ext,
                &around,
                &boat_boxes,
                &input,
                &view,
                &mut self.packets,
            );
            if self.rec.is_some() {
                self.record_tick(&input, Some("riding not representable"));
            }
            push_packets(&self.packets, entity_id, out);
            sync_pose_26(pose, &self.player);
            return;
        }
        if self.entities.is_some() || self.parked.is_some() {
            collect_colliders(
                self.entities.as_ref(),
                self.parked.as_ref(),
                &self.player,
                None,
                &mut self.around.boxes,
                &mut Vec::new(),
            );
        } else {
            self.around.boxes.clear();
        }
        let p = &mut self.player;
        let view = self
            .world
            .view(p.pos[0].floor() as i32, p.pos[2].floor() as i32);
        self.around.player_ticked = true;
        if !self.around.boxes.is_empty() {
            // Entities to collide with: the extended tick with them (tick_in).
            let around = modern::Surroundings::new().with_entities(&self.around.boxes);
            modern::tick_in::<Rules, _>(
                p,
                &mut self.ext,
                &around,
                &input,
                &view,
                &mut self.packets,
            );
            self.ext_active = self.ext_wanted();
        } else if self.ext_active {
            modern::tick_ext::<Rules, _>(p, &mut self.ext, &input, &view, &mut self.packets);
            self.ext_active = self.ext_wanted();
        } else {
            // Nothing of the extension state can act (no glide, no glider to start one, no
            // rocket): the plain tick, which is tick_ext with a default state, folded.
            modern::tick::<Rules, _>(p, &input, &view, &mut self.packets);
        }
        if self.force_step != ForceStepPosition::Off {
            force_modern_position(&mut self.packets, &mut self.player, self.force_step);
        }
        if self.rec.is_some() {
            let note = (!self.around.boxes.is_empty())
                .then_some("entity collisions and pushes not representable");
            self.record_tick(&input, note);
        }
        push_packets(&self.packets, entity_id, out);
        sync_pose_26(pose, &self.player);
    }
}

impl ModernSim {
    /// Recording: the setup at the first movement step, then the columns around the player.
    #[cold]
    fn record_start(&mut self) {
        let Some(r) = self.rec.as_deref_mut() else {
            return;
        };
        if !r.started() {
            r.start_modern(&self.player, super::GAME.name(), |id| {
                super::data::BlockState::from_id(u16::try_from(id).ok()?).map(|s| s.to_string())
            });
        }
        let w = &self.world;
        r.observe(self.player.pos, |x, y, z| {
            w.is_column_loaded(x >> 4, z >> 4)
                .then(|| w.block_state(x, y, z).map_or(0, |s| u32::from(s.id())))
        });
    }

    /// Recording: this movement step's input and ghast's result.
    #[cold]
    fn record_tick(&mut self, input: &ghast_physics::TickInput, note: Option<&'static str>) {
        let Some(r) = self.rec.as_deref_mut() else {
            return;
        };
        if let Some(n) = note {
            r.note_once(n);
        }
        r.tick(
            input,
            &crate::record::state_modern(&self.player),
            &self.packets,
        );
    }
}

/// Grim compatibility (see [`ForceStepPosition`]): the tick's movement packet carries no
/// position although the feet height changed since the last sent position (a landing, a bounce
/// or a step-up under the resend threshold): it gets the position, and the sent bookkeeping
/// follows.
#[cold]
#[inline(never)]
fn force_modern_position(
    packets: &mut ghast_physics::Packets,
    p: &mut modern::PlayerState,
    mode: ForceStepPosition,
) {
    use ghast_physics::Packet as P;
    let cur = p.pos;
    if cur[1] == p.sent.pos[1] {
        return;
    }
    let Some(&P::Move {
        pos: None,
        look,
        on_ground,
        horizontal_collision,
    }) = packets
        .as_slice()
        .iter()
        .rev()
        .find(|q| matches!(q, P::Move { .. }))
    else {
        return;
    };
    if mode == ForceStepPosition::StepUpOnly && !(on_ground && cur[1] > p.sent.pos[1]) {
        return;
    }
    let mut out = ghast_physics::Packets::new();
    for q in packets.as_slice() {
        out.push(match *q {
            P::Move { pos: None, .. } => P::Move {
                pos: Some(cur),
                look,
                on_ground,
                horizontal_collision,
            },
            other => other,
        });
    }
    *packets = out;
    p.sent.pos = cur;
    p.sent.position_reminder = 0;
}

fn sync_pose_26(pose: &mut Pose, p: &modern::PlayerState) {
    pose.pos = Vec3::new(p.pos[0], p.pos[1], p.pos[2]);
    pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
    pose.yaw = p.yaw;
    pose.pitch = p.pitch;
    pose.on_ground = p.on_ground;
    pose.flying = p.abilities.flying;
    pose.sneaking = p.shift();
    pose.sprinting = p.sprinting;
}

/// [`held_item_facts`] of this version's data set.
pub(crate) fn held_item_facts(id: u16, count: u8, efficiency: u8) -> HeldItem {
    let item = super::data::Item::from_id(id);
    let name = item.map_or("", super::data::Item::name);
    let food = item.and_then(super::data::Item::food);
    HeldItem {
        id,
        count,
        efficiency,
        places_block: item.is_some_and(|i| i.block().is_some()),
        usable: food.is_some()
            || matches!(
                name,
                "potion"
                    | "milk_bucket"
                    | "honey_bottle"
                    | "bow"
                    | "crossbow"
                    | "shield"
                    | "trident"
                    | "spyglass"
                    | "goat_horn"
            ),
        food: food.is_some(),
        always_edible: food.is_some_and(|f| f.can_always_eat),
        // The modern destroy progress reads the item itself.
        tool_speed: None,
        modern_item: item.map(|_| id),
        swing_on_use: false,
    }
}

/// `BlockBehaviour.getDestroyProgress` of this version (oracle-verified in its `data::dig`).
pub(crate) fn dig_progress(
    m: &crate::hands::ModernDig,
    held: Option<&HeldItem>,
    f: crate::hands::DigFactors,
) -> f32 {
    use super::data::{BlockState, Item, dig};
    let Some(state) = BlockState::from_id(m.state) else {
        return 0.0;
    };
    let item = held.and_then(|h| h.modern_item).and_then(Item::from_id);
    let c = dig::DigConditions {
        mining_efficiency: m.mining_efficiency,
        block_break_speed: m.block_break_speed,
        submerged_mining_speed: m.submerged_mining_speed,
        haste: (f.haste > 0).then(|| i32::from(f.haste) - 1),
        conduit_power: m.conduit_power,
        mining_fatigue: (f.fatigue > 0).then(|| i32::from(f.fatigue) - 1),
        eye_in_water: f.in_water,
        on_ground: f.on_ground,
    };
    dig::destroy_progress_with(state, item, &c)
}

/// `Entity.getScoreboardName`: a player's profile name (from the tab list), else the UUID.
fn scoreboard_name<'a>(
    t: &'a super::entity::Tracker,
    e: &'a ghast_entity::Entity,
    buf: &'a mut [u8; 36],
) -> &'a str {
    match t.scoreboard_name(e) {
        Some(n) => n,
        None => e.uuid().hyphenated().encode_lower(buf),
    }
}

/// The resolved entity ids (the per-version table tests).
#[cfg(test)]
pub(super) fn entity_ids_for_test() -> ([i32; 7], [i32; 2], [i32; 2], i32) {
    EntityIds::get().tuple()
}

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

    /// `spawn_entity` of type `ty` at `pos` (no rotation, no velocity).
    fn spawn_raw(eid: i32, uuid: u128, ty: &str, pos: [f64; 3]) -> RawPacket {
        use super::super::proto::play::clientbound as cb;
        use bytes::BufMut;
        use ghast_protocol::codec::McWrite;
        let ty = super::super::data::entity_by_name(ty).unwrap().id;
        let mut b = bytes::BytesMut::new();
        b.put_varint(eid);
        b.put_u128(uuid);
        b.put_varint(i32::from(ty));
        for v in pos {
            b.put_f64(v);
        }
        b.put_u8(0);
        b.put_i8(0);
        b.put_i8(0);
        b.put_i8(0);
        b.put_varint(0);
        RawPacket::new(cb::id::SPAWN_ENTITY, b.freeze())
    }

    /// `isAlive` decides whether a shulker collides: a health that is not above 0 (NaN
    /// included) makes it dead.
    #[test]
    fn dead_shulkers_do_not_collide() {
        use super::super::proto::play::clientbound as cb;
        use bytes::BufMut;
        use ghast_protocol::codec::McWrite;
        for (health, collides) in [
            (None, true),
            (Some(10.0f32), true),
            (Some(0.0), false),
            (Some(f32::NAN), false),
        ] {
            let mut s = ModernSim::test_overworld();
            s.set_entities(Some(ghast_entity::Config::default()));
            s.world_packet(&spawn_raw(7, 0x77, "shulker", [1.5, 0.0, 0.5]))
                .unwrap();
            if let Some(h) = health {
                // entity_metadata: LivingEntity health (index 9, float serializer 3).
                let mut b = bytes::BytesMut::new();
                b.put_varint(7);
                b.put_u8(super::super::entity::meta::HEALTH);
                b.put_varint(3);
                b.put_f32(h);
                b.put_u8(0xFF);
                s.world_packet(&RawPacket::new(cb::id::ENTITY_METADATA, b.freeze()))
                    .unwrap();
            }
            let (mut boxes, mut boat) = (Vec::new(), Vec::new());
            let player = modern::PlayerState::new([0.5, 0.0, 0.5], 0.0, 0.0);
            collect_colliders(
                s.entities.as_ref(),
                None,
                &player,
                None,
                &mut boxes,
                &mut boat,
            );
            assert_eq!(boxes.len(), usize::from(collides), "health {health:?}");
        }
    }

    /// `Entity.push`: a spectator player (noPhysics) pushes nothing, a survival one does, and a
    /// dying mob still does (its aiStep runs until it is removed).
    #[test]
    fn spectators_do_not_push_dying_mobs_do() {
        use super::super::proto::play::clientbound as cb;
        use bytes::BufMut;
        use ghast_protocol::codec::McWrite;
        let pushed = |ty: &str, game_mode: Option<i32>, health: Option<f32>| {
            let mut s = ModernSim::test_overworld();
            s.set_entities(crate::client::entity_config(
                crate::Interests::ENTITIES,
                super::super::GAME.caps(),
            ));
            let uuid = 0x55u128;
            if let Some(gm) = game_mode {
                // player_info: add_player + update_game_mode.
                let mut b = bytes::BytesMut::new();
                b.put_u8(0b101);
                b.put_varint(1);
                b.put_u128(uuid);
                b.put_string("Alex").unwrap();
                b.put_varint(0);
                b.put_varint(gm);
                s.world_packet(&RawPacket::new(cb::id::PLAYER_INFO, b.freeze()))
                    .unwrap();
            }
            s.world_packet(&spawn_raw(9, uuid, ty, [0.8, 64.0, 0.5]))
                .unwrap();
            if let Some(h) = health {
                let mut b = bytes::BytesMut::new();
                b.put_varint(9);
                b.put_u8(super::super::entity::meta::HEALTH);
                b.put_varint(3);
                b.put_f32(h);
                b.put_u8(0xFF);
                s.world_packet(&RawPacket::new(cb::id::ENTITY_METADATA, b.freeze()))
                    .unwrap();
            }
            let t = s.entities.as_mut().unwrap();
            assert!(t.get(9).is_some(), "{ty} spawned");
            t.mark_column_loaded(0, 0);
            s.player = modern::PlayerState::new([0.5, 64.0, 0.5], 0.0, 0.0);
            let mut pose = Pose::default();
            s.push_player(&mut pose, false);
            s.player.vel[0] != 0.0
        };
        assert!(pushed("player", Some(0), None));
        assert!(!pushed("player", Some(3), None));
        assert!(pushed("zombie", None, None));
        assert!(pushed("zombie", None, Some(0.0)));
    }

    /// A player that pushes the local player is judged by its team under its profile name,
    /// which comes from the tab list: with entity tracking as the client sets it up for
    /// `Interests::ENTITIES` alone the name must still be known.
    #[test]
    fn pushing_players_are_judged_by_their_profile_name() {
        use super::super::proto::play::clientbound as cb;
        use bytes::BufMut;
        use ghast_protocol::codec::McWrite;
        let mut s = ModernSim::test_overworld();
        s.set_entities(crate::client::entity_config(
            crate::Interests::ENTITIES,
            super::super::GAME.caps(),
        ));
        let uuid = 0x1234_5678_9abc_def0_1122_3344_5566_7788u128;
        // player_info: add_player (action bit 0) for one profile, no properties.
        let mut b = bytes::BytesMut::new();
        b.put_u8(1);
        b.put_varint(1);
        b.put_u128(uuid);
        b.put_string("Steve").unwrap();
        b.put_varint(0);
        let info = RawPacket::new(cb::id::PLAYER_INFO, b.freeze());
        // spawn_entity: a player next to the local one.
        let player = super::super::data::entity_by_name("player").unwrap().id;
        let mut b = bytes::BytesMut::new();
        b.put_varint(42);
        b.put_u128(uuid);
        b.put_varint(i32::from(player));
        b.put_f64(0.5);
        b.put_f64(64.0);
        b.put_f64(0.5);
        b.put_u8(0);
        b.put_i8(0);
        b.put_i8(0);
        b.put_i8(0);
        b.put_varint(0);
        let spawn = RawPacket::new(cb::id::SPAWN_ENTITY, b.freeze());
        // What the client lets through to the sim.
        let wanted = s.entity_packet_ids();
        for raw in [&info, &spawn] {
            if wanted.contains(&raw.id) {
                s.world_packet(raw).unwrap();
            }
        }
        let t = s.entities.as_ref().unwrap();
        let e = t.get(42).expect("the player spawned");
        let mut buf = [0u8; 36];
        assert_eq!(scoreboard_name(t, e, &mut buf), "Steve");
        // The names-only list is not the tab list the behaviour sees (it did not ask for it).
        assert_eq!(t.players().count(), 0);
        // Vanilla skips a player spawn whose profile is not in the tab list.
        s.world_packet(&spawn_raw(43, 0x99, "player", [0.5, 64.0, 0.5]))
            .unwrap();
        assert!(s.entities.as_ref().unwrap().get(43).is_none());
    }

    /// Grim compatibility: a status-only move whose feet height differs from the sent one gets
    /// the position (and the sent bookkeeping follows); off, or with the same height, nothing
    /// changes.
    #[test]
    fn forced_step_position() {
        use ghast_physics::Packet as P;
        let status = P::Move {
            pos: None,
            look: None,
            on_ground: true,
            horizontal_collision: false,
        };
        let mut p = modern::PlayerState::new([0.5, 4.0, 0.5], 0.0, 0.0);
        p.sent.pos = [0.5, 4.000_061_962_301_82, 0.5];
        let mut packets = ghast_physics::Packets::new();
        packets.push(status);
        force_modern_position(&mut packets, &mut p, ForceStepPosition::Always);
        assert_eq!(
            packets.as_slice(),
            [P::Move {
                pos: Some([0.5, 4.0, 0.5]),
                look: None,
                on_ground: true,
                horizontal_collision: false,
            }]
        );
        assert_eq!(p.sent.pos, [0.5, 4.0, 0.5]);
        let mut packets = ghast_physics::Packets::new();
        packets.push(status);
        force_modern_position(&mut packets, &mut p, ForceStepPosition::Always);
        assert_eq!(packets.as_slice(), [status]);
    }

    /// The engine's teleport path (`ModernSim::teleport`, fed from the decoded `Teleport`) lands
    /// exactly where `modern::PlayerState::apply_teleport` does — the function the oracle's
    /// teleport goldens (`tests/golden/26.1/teleports.jsonl.gz`) prove — for random
    /// relative bits, deltas, rotations and prior motion.
    #[test]
    fn teleport_matches_the_proven_physics_call() {
        let mut seed = 0x9E37_79B9_7F4A_7C15u64;
        let mut rnd = move || {
            seed ^= seed << 13;
            seed ^= seed >> 7;
            seed ^= seed << 17;
            (seed >> 11) as f64 / (1u64 << 53) as f64
        };
        for _ in 0..2000 {
            let mut sim = ModernSim::new();
            let start = [rnd() * 64.0 - 32.0, rnd() * 100.0, rnd() * 64.0 - 32.0];
            sim.player.set_pos(start[0], start[1], start[2]);
            sim.player.vel = [rnd() - 0.5, rnd() - 0.5, rnd() - 0.5];
            sim.player.yaw = (rnd() * 720.0 - 360.0) as f32;
            sim.player.pitch = (rnd() * 180.0 - 90.0) as f32;
            let mut pose = Pose::default();
            sync_pose_26(&mut pose, &sim.player);
            let mut direct = sim.player;
            let relative = (rnd() * 512.0) as u32 & 0x1ff;
            let t = Teleport {
                x: rnd() * 40.0 - 20.0,
                y: rnd() * 40.0 - 20.0,
                z: rnd() * 40.0 - 20.0,
                yaw: (rnd() * 720.0 - 360.0) as f32,
                pitch: (rnd() * 200.0 - 100.0) as f32,
                flags: (relative & 0x1f) as i8,
                teleport_id: Some(1),
                relative,
                delta: Vec3::new(
                    rnd() * 40.0 - 20.0,
                    rnd() * 40.0 - 20.0,
                    rnd() * 40.0 - 20.0,
                ),
            };
            sim.teleport(&mut pose, &t);
            let _ = direct.apply_teleport(
                [t.x, t.y, t.z],
                [t.delta.x, t.delta.y, t.delta.z],
                t.yaw,
                t.pitch,
                relative,
            );
            assert_eq!(sim.player, direct, "{t:?}");
            assert_eq!(
                pose.pos,
                Vec3::new(direct.pos[0], direct.pos[1], direct.pos[2])
            );
            assert_eq!((pose.yaw, pose.pitch), (direct.yaw, direct.pitch));
        }
    }
}