ghast-client 0.5.0

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
//! Per-version world and player movement ("simulation"): the chunk store of `ghast-world` and
//! the vanilla-exact movement step of `ghast-physics`, one module per version.
//!
//! The engine is generic over [`Sim`]; the behaviour sees the world through the
//! version-free [`WorldView`].

use ghast_protocol::{BlockPos, DecodeError, RawPacket};
use ghast_world::{WorldConfig, WorldError};

use crate::common::{
    Abilities, Controls, EntityAction, MovePacket, Outbound, Pose, Teleport, Vec3,
};
use crate::hands::{BlockQuery, HeldItem};
use crate::version::DataSet;

#[cfg(feature = "v1_12_2")]
mod place112;
#[cfg(feature = "v1_16_5")]
mod place116;
#[cfg(feature = "v1_8")]
mod place18;
pub(crate) mod predict;
#[cfg(any(ghast_modern, feature = "v1_12_2", feature = "v1_16_5"))]
mod teams;
#[cfg(feature = "v1_12_2")]
mod use112;
#[cfg(feature = "v1_16_5")]
mod use116;
#[cfg(feature = "v1_8")]
mod use18;
#[cfg(feature = "v1_12_2")]
mod v1_12;
#[cfg(feature = "v1_16_5")]
mod v1_16_5;
#[cfg(feature = "v1_8")]
mod v1_8;
#[cfg(feature = "v26_1")]
pub(crate) mod v26_1;
#[cfg(feature = "v26_2")]
pub(crate) mod v26_2;
#[cfg(feature = "v26_3")]
pub(crate) mod v26_3;

#[cfg(feature = "v1_8")]
pub(crate) use v1_8::Sim18;
#[cfg(feature = "v1_12_2")]
pub(crate) use v1_12::Sim12;
#[cfg(feature = "v1_16_5")]
pub(crate) use v1_16_5::Sim16;
#[cfg(feature = "v26_1")]
pub(crate) use v26_1::Sim26;
#[cfg(feature = "v26_2")]
pub(crate) use v26_2::Sim262;
#[cfg(feature = "v26_3")]
pub(crate) use v26_3::Sim263;

/// The crosshair pick's inputs besides the world (vanilla `GameRenderer.updateTargetedEntity`).
#[cfg_attr(
    not(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5")),
    allow(dead_code)
)]
pub(crate) struct PickQuery<'a> {
    /// The eyes (feet + eye height of the pose judged).
    pub eyes: Vec3,
    /// `(yaw, pitch)` of that pose.
    pub rotation: (f32, f32),
    /// The generic look vector (`hands::look_vector`); versions use their own.
    pub look: Vec3,
    /// The main-hand item id (1.16.5+: a held block changes some interaction shapes).
    pub held: Option<u16>,
    /// Pick from the sim's own current state (this tick's key handling: 26.1 eye lerp and
    /// range attributes) instead of `eyes`.
    pub now: bool,
    /// Creative reach (blocks 5, entities 6, no 3-block entity limit).
    pub creative: bool,
    /// The player's bounding box (the entity search box grows from it).
    pub player_bb: ghast_physics::math::Aabb,
    /// The pickable entities near the eyes, in the tracker's order.
    pub entities: &'a [ghast_physics::pick::PickEntity],
}

/// The crosshair target.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) enum Crosshair {
    /// A block, or nothing (a miss, or an entity beyond the 3-block limit).
    Block(Option<crate::BlockHit>),
    /// An entity: index into [`PickQuery::entities`] and the point hit.
    Entity {
        /// Index into the query's entities.
        index: usize,
        /// The point on its (grown) box; the eyes when they are inside it.
        hit: Vec3,
    },
}

/// Why a world packet could not be applied.
#[derive(Debug)]
pub(crate) enum SimError {
    /// The packet itself did not decode.
    Decode(DecodeError),
    /// The chunk data inside it was malformed.
    World(WorldError),
}

impl From<DecodeError> for SimError {
    fn from(e: DecodeError) -> Self {
        SimError::Decode(e)
    }
}

impl From<WorldError> for SimError {
    fn from(e: WorldError) -> Self {
        SimError::World(e)
    }
}

/// Block access for behaviours, independent of the protocol version.
pub trait WorldView {
    /// Whether the chunk column is loaded (sent by the server and not unloaded).
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool;

    /// The block state at a position as the version's raw id: the 1.8 `id << 4 | meta` or the
    /// 1.16 global palette id (decode it with `ghast-data`). `None` when the column is not
    /// loaded — never treat that as air.
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32>;

    /// Number of loaded columns.
    fn loaded_columns(&self) -> usize;

    /// The build height `(min_y, height)` of the current dimension when the version has
    /// dimension-dependent heights (26.1: the overworld is `(-64, 384)`); `None` for the
    /// fixed `0..256` worlds of 1.8.9 – 1.16.5.
    fn build_height(&self) -> Option<(i32, i32)> {
        None
    }

    /// The tracked entities (`None` unless the behaviour asked for [`crate::Interests::ENTITIES`]).
    fn entities(&self) -> Option<&ghast_entity::Entities>;

    /// Dig / place facts of a block (hardness, tool group, ray box); `None` when the column
    /// is not loaded.
    fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery>;

    /// The whole loaded column (sections, light / biomes when kept, see
    /// [`crate::Client::world_config`]) for bulk reads without a call per block. Block states
    /// are the version's raw ids, as in [`WorldView::raw_block`]. `None` when not loaded.
    fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
        let _ = (chunk_x, chunk_z);
        None
    }

    /// The player's last movement step: `(horizontalCollision, verticalCollision)` (`false`
    /// for a view without a player).
    fn collisions(&self) -> (bool, bool) {
        (false, false)
    }

    /// `true` when, in the last tick (its packets and its step), moving blocks ran into a case
    /// the physics model does not cover ([`crate::TickView::piston_uncertain`] lists them). The
    /// simulation goes on with the model's result; the server corrects the rest.
    fn piston_uncertain(&self) -> bool {
        false
    }

    /// The block the crosshair is on from `eyes` with the look `(yaw, pitch)` (`look` is its
    /// unit vector, [`crate::hands::look_vector`]) within `reach`, by the version's ray rules.
    /// `None` when nothing is hit.
    fn crosshair(
        &self,
        eyes: Vec3,
        rotation: (f32, f32),
        look: Vec3,
        reach: f64,
    ) -> Option<crate::BlockHit> {
        let _ = rotation;
        let blocks = |x: i32, y: i32, z: i32| self.block_query(x, y, z);
        crate::hands::pick(&blocks, eyes, look, reach)
    }
}

/// The join / respawn packets of the session (cheap `Bytes` copies).
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
#[derive(Debug, Default)]
pub(super) struct SessionPackets {
    login: Option<RawPacket>,
    respawn: Option<RawPacket>,
}

#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
impl SessionPackets {
    fn note(&mut self, raw: &RawPacket, login: i32, respawn: i32) {
        // Copies: a body shares the receive buffer it arrived in (or the whole inflated
        // packet), which a clone would keep alive for the session.
        let own = || RawPacket::new(raw.id, bytes::Bytes::copy_from_slice(&raw.body));
        if raw.id == login {
            self.login = Some(own());
            self.respawn = None;
        } else if raw.id == respawn {
            self.respawn = Some(own());
        }
    }

    /// Feeds them to a fresh tracker.
    fn replay(&self, mut apply: impl FnMut(&RawPacket)) {
        for r in [&self.login, &self.respawn].into_iter().flatten() {
            apply(r);
        }
    }
}

/// Most block changes kept between two behaviour ticks (a chunk-sized burst is 65536).
pub(super) const MAX_BLOCK_UPDATES: usize = 4096;

/// Block changes buffered for the behaviour.
#[derive(Debug, Default)]
pub(super) struct BlockUpdates {
    on: bool,
    list: Vec<(BlockPos, u32)>,
    dropped: usize,
}

impl BlockUpdates {
    fn push(&mut self, pos: BlockPos, state: u32) {
        if self.on {
            if self.list.len() < MAX_BLOCK_UPDATES {
                self.list.push((pos, state));
            } else {
                self.dropped += 1;
            }
        }
    }
}

/// What [`Sim::pre_tick`] gets each tick.
#[derive(Debug, Clone, Copy)]
// Read by the 26.1 sim only.
#[cfg_attr(not(ghast_modern), allow(dead_code))]
pub(crate) struct PreTick {
    /// The use in progress: (off hand, item id).
    pub(crate) using: Option<(bool, u16)>,
    /// This tick's key handling released a use: (off hand, item id, player ticks it lasted).
    pub(crate) released: Option<(bool, u16, u32)>,
    /// The tick's movement keys.
    pub(crate) controls: Controls,
    /// The tick's look (after the mouse turn): a riptide launches along it.
    pub(crate) look: (f32, f32),
}

/// World + movement of one version.
pub(crate) trait Sim: WorldView + std::fmt::Debug {
    /// Applies a world packet (chunks, block changes, join / respawn / view changes).
    /// Other packets are ignored.
    fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError>;
    /// A new client player (join, respawn).
    fn reset_player(&mut self);
    /// The held stack's use facts from the stack itself (26.1: its components decide whether
    /// it has a use state and whether it is food); other versions keep the table facts.
    #[inline(always)]
    fn item_use_facts(
        &self,
        stack: &ghast_inventory::Stack,
        off_hand: bool,
        held: HeldItem,
    ) -> HeldItem {
        let _ = (stack, off_hand);
        held
    }
    /// The sim reads per-tick inputs from the inventory and keys (26.1); `false` lets the
    /// engine skip [`Sim::held_use_inputs`] and [`Sim::pre_tick`] without evaluating anything.
    #[inline(always)]
    fn modern_inputs(&self) -> bool {
        false
    }
    /// Before the key handling, while the use key is down or a use runs: what the held stacks'
    /// use depends on (26.1: the tridents' riptide strength, from the synced enchantments).
    #[inline(always)]
    fn held_use_inputs(&mut self, inv: &mut ghast_inventory::Inventory) {
        let _ = inv;
    }
    /// [`Sim::pre_tick`] has something to do even without a use, a release or a jump press
    /// (26.1: attached rockets).
    #[inline(always)]
    fn pre_tick_wanted(&self) -> bool {
        false
    }
    /// Once per tick before the movement: the inputs of the modern movement that come from the
    /// inventory and the keys (26.1: the used stack's `use_effects`, the equipped glider when
    /// jump is pressed, the hand that holds rockets). `using` is the use in progress (off hand,
    /// item id). Returns `false` when that hand no longer holds the item (`updatingUsingItem`:
    /// the use stops). New mechanics read their per-tick inputs here too.
    #[inline(always)]
    fn pre_tick(&mut self, inv: &ghast_inventory::Inventory, t: &PreTick) -> bool {
        let _ = (inv, t);
        true
    }
    /// Test hook: puts the 26.1 player (and its extension state) in place, level loaded.
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_modern(
        &mut self,
        p: ghast_physics::modern::PlayerState,
        x: ghast_physics::modern::PlayerExt,
    ) {
        let _ = (p, x);
    }
    /// Test hook: the 26.1 player's shared flags byte.
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_shared_flags(&self) -> u8 {
        0
    }
    /// Test hook: our entity id for the own-entity packets.
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_own_id(&mut self, id: i32) {
        let _ = id;
    }
    /// The player glides (26.1 elytra, shared flag 7).
    #[inline(always)]
    fn gliding(&self) -> bool {
        false
    }
    /// A weather game event: 1 start raining, 2 stop raining, 7 rain level `value`.
    fn weather(&mut self, reason: u8, value: f32) {
        let _ = (reason, value);
    }
    /// A mount's screen facts (26.1): entity type id, `canUseSlot(SADDLE)`, `canUseSlot(BODY)`.
    fn mount_info(&self, entity_id: i32) -> Option<(i32, bool, bool)> {
        let _ = entity_id;
        None
    }
    /// 1.8 – 1.16.5: a mount screen's slot rules read off the tracked entity `entity_id` like
    /// the client's `HorseScreenHandler` does (`None`: not tracked, not a mount, or the rules
    /// need entity data that is not kept).
    fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
        let _ = entity_id;
        None
    }
    /// The answer a world packet asks for at once (26.1 `move_vehicle`), taken after each one.
    #[inline(always)]
    fn take_reply(&mut self) -> Option<Outbound> {
        None
    }
    /// The packets the sim reads changed since the last call (rebuild the packet filter).
    #[inline(always)]
    fn take_filter_dirty(&mut self) -> bool {
        false
    }
    /// The vehicle the player rides, when the version models riding.
    #[inline(always)]
    fn vehicle(&self) -> Option<crate::common::Vehicle> {
        None
    }
    /// The client's main arm setting (left: `true`) for the parts of movement that read it.
    #[inline(always)]
    fn set_main_arm_left(&mut self, left: bool) {
        let _ = left;
    }
    /// Play → configuration (`start_configuration`): vanilla's `clearClientLevel` drops the
    /// level (chunks, entities) and the player until the next join.
    fn drop_level(&mut self) {
        self.reset_player();
    }
    /// A new client player after a respawn; `keep` is the respawn packet's kept-data bits
    /// (1.20.2+).
    fn respawn_player(&mut self, keep: u8) {
        let _ = keep;
        self.reset_player();
    }
    /// A server teleport: updates the pose like vanilla (the engine sends the reply).
    fn teleport(&mut self, pose: &mut Pose, t: &Teleport);
    /// Server abilities.
    fn abilities(&mut self, a: Abilities);
    /// Food level (sprinting needs more than 6).
    fn food(&mut self, food: i32);
    /// Velocity from the server (entity velocity for our entity, explosion push), in blocks
    /// per tick; `add` adds to the current velocity (explosion) instead of setting it.
    fn velocity(&mut self, v: Vec3, add: bool);
    /// Our movement speed attribute: base and every modifier `(uuid, amount, operation)` in
    /// packet order (the server's list includes the sprint modifier while sprinting; vanilla
    /// replaces the client's set with it).
    fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]);
    /// Our active status effects (id → amplifier).
    fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>);
    /// Boots enchantments that change movement.
    fn boots(&mut self, depth_strider: u8, soul_speed: u8);
    /// The item id in the feet slot (1.17+ powder snow: leather boots).
    fn feet_item(&mut self, id: Option<i32>) {
        let _ = id;
    }
    /// Spectator game mode (no collision).
    fn spectator(&mut self, on: bool);
    /// 26.1: the client player's movement state (see [`crate::TickContext::modern_player`]).
    #[cfg(ghast_modern)]
    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
        None
    }
    /// One movement step: physics, then the sprint / sneak / abilities packets and exactly one
    /// movement packet appended to `out`. Updates `pose`.
    fn step(
        &mut self,
        pose: &mut Pose,
        controls: Controls,
        using_item: bool,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    );
    /// Packet ids the entity tracker wants (empty without tracking).
    fn entity_packet_ids(&self) -> Vec<i32>;
    /// Packet ids the world consumes with its configuration.
    fn world_packet_ids(&self) -> Vec<i32>;
    /// The entity tracking configuration (`None`: not tracking).
    #[cfg_attr(
        not(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5")),
        allow(dead_code)
    )]
    fn entity_config(&self) -> Option<ghast_entity::Config>;
    /// Starts (empty, our entity id and dimension from the session's join / respawn), stops
    /// (frees the store) or reconfigures entity tracking mid-session.
    fn set_entities(&mut self, config: Option<ghast_entity::Config>);
    /// Client-side flight toggle: sets the physics' flying flag and appends the `abilities`
    /// packet when it changes (starting needs "may fly").
    fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>);
    /// Whether block changes are collected for [`Sim::drain_block_updates`].
    fn collect_block_updates(&mut self, on: bool);
    /// Moves the block changes (position, version raw state) received since the last call
    /// into `out`; returns how many were dropped because the buffer was full.
    fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize;
    /// The block was broken on the client (air until the server says otherwise).
    fn predict_air(&mut self, x: i32, y: i32, z: i32);
    /// A dig action packet of this tick, in packet order, with the player's position when it
    /// was sent (before the tick's movement). `broken`: the client broke the block with it
    /// (`breakBlock` / `destroyBlock`: air until the server says otherwise). `sequence`: the
    /// packet's 1.19+ prediction sequence (26.x remembers the server's state per predicted
    /// block until `block_changed_ack`; 1.16.5 remembers start / abort / finish until
    /// `acknowledge_player_digging`). 1.8.9 and 1.12.2 keep no records (the server sends a
    /// block change).
    #[inline]
    fn dig_sent(
        &mut self,
        pos: BlockPos,
        status: crate::common::DigStatus,
        broken: bool,
        sequence: i32,
        player: Vec3,
    ) {
        let _ = (status, sequence, player);
        if broken {
            self.predict_air(pos.x, pos.y, pos.z);
        }
    }
    /// A `block_place` of this tick that used the held block item, in packet order with the
    /// digs ([`Sim::dig_sent`]): the version places the block on the client when it knows the
    /// result exactly (see [`predict::PlaceSent`]); 26.x keeps the server's state until the ack,
    /// older versions take the server's block updates for the clicked block and its neighbour.
    /// Returns whether the block was placed on the client (the item is then used up there too).
    #[inline]
    fn place_sent(&mut self, p: &predict::PlaceSent<'_>) -> bool {
        let _ = p;
        false
    }
    /// 1.8.9 / 1.12.2: the vanilla client writes no `block_place` for a right click with block
    /// item `held` on `face` of `pos` (`BlockItem.canPlaceItemBlock` fails; see
    /// [`predict::legacy_place_suppressed`]). Always `false` from 1.13 on (no such check).
    #[inline]
    fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
        let _ = (pos, face, held);
        false
    }
    /// 1.8.9: the oracle-proven rules of a right click on a block (`ghast_data::v1_8::place`):
    /// whether the packet is written and the click taken, where they decide it.
    #[inline]
    fn place_rules(&self, q: &predict::PlaceQuery<'_>) -> predict::PlaceRules {
        let _ = q;
        predict::PlaceRules::default()
    }
    /// 1.12.2, 1.16.5: the oracle-proven rules of a hand's item use in the air (`interactItem`
    /// after its packet: the stack's `use` on the client); [`predict::AirAnswer::Flags`] where
    /// the held-item flags decide it.
    #[inline]
    fn air_use(&self, q: &predict::AirQuery<'_>) -> predict::AirAnswer {
        let _ = q;
        predict::AirAnswer::Flags
    }
    /// The blocks an item use in the air set on the client ([`Sim::air_use`]; the version's
    /// state ids).
    #[inline]
    fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
        let _ = blocks;
    }
    /// Test hook: an air-use oracle case's facts of the client world (`AirUseDump`: a dimension
    /// whose water vaporizes).
    #[cfg(test)]
    #[allow(dead_code)] // used by the legacy air-use replays
    fn test_air_case(&mut self, case: &serde_json::Value) {
        let _ = case;
    }
    /// Test hook: the entity tracker counts as started before the join (a replay starts it
    /// after its join packet, with no entity spawned before; 1.8 piston bounds).
    #[cfg(test)]
    #[allow(dead_code)] // used by the legacy combat replays
    fn test_tracker_from_join(&mut self) {}
    /// Test hook: moves the sim's player (as a fall between a prediction and its answer would).
    #[cfg(test)]
    #[allow(dead_code)] // used by the all-version prediction tests
    fn set_player_pos(&mut self, p: Vec3) {
        let _ = p;
    }
    /// [`Sim::dig_sent`] wants the dig packets that broke nothing too (1.16.5 records them).
    #[inline(always)]
    fn records_digs(&self) -> bool {
        false
    }
    /// A server teleport arrived while `sequence` was the last prediction sequence sent
    /// (26.x `BlockStatePredictionHandler.onTeleport`).
    #[inline(always)]
    fn teleport_sequence(&mut self, sequence: Option<i32>) {
        let _ = sequence;
    }
    /// After a prediction answer (`block_changed_ack`, 1.16.5 `acknowledge_player_digging`):
    /// the position the player was moved back to when a restored block would hold it.
    #[inline(always)]
    fn take_snap(&mut self) -> Option<Vec3> {
        None
    }
    /// A held item's version facts (tool speeds, block item, usable) from its id.
    fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem;
    /// The crosshair target as vanilla picks it at the start of this tick (before the key
    /// handling) with the player's own eye and ranges; `eyes` / `look` are the generic
    /// approximation (feet + eye height, `hands::look_vector`). `held` is the main-hand item id.
    fn crosshair_now(
        &self,
        eyes: Vec3,
        rotation: (f32, f32),
        look: Vec3,
        held: Option<u16>,
    ) -> Option<crate::BlockHit> {
        let _ = held;
        self.crosshair(eyes, rotation, look, crate::hands::REACH)
    }
    /// Whether the crosshair pick can hit `e` and by how much its box grows (`None`: not
    /// pickable). Default: the engine's 1.8 – 1.16.5 classification.
    fn pick_margin(&self, e: &ghast_entity::Entity) -> Option<f32> {
        crate::engine::legacy_pick_margin(self.entities()?, e)
    }
    /// Where vanilla's entity search meets `e` (the crosshair pick visits entities in this
    /// order): the client view's chunk-section key ([`ghast_entity::Entity::search_order`]).
    fn search_order(&self, e: &ghast_entity::Entity) -> Option<(i32, i32, i32, u32)> {
        e.search_order()
    }
    /// One client tick of the tracked entities (`ClientLevel.tickEntities`), after the tick's
    /// crosshair pick. Versions whose tracker has no client-side motion do nothing.
    fn tick_entities(&mut self, pose: &mut Pose) {
        let _ = pose;
    }
    /// 26.3 `LocalPlayer.sendChanges` after the level's entities and block entities ticked:
    /// the movement packets of a player tick whose packets wait for that phase (among moving
    /// blocks). Earlier versions send them in the step: nothing.
    #[inline(always)]
    fn send_changes(&mut self, entity_id: i32, out: &mut Vec<Outbound>) {
        let _ = (entity_id, out);
    }
    /// An entity event (`entity_status`) of another entity the sim simulates (26.3: the bubble
    /// column events 71 / 72 of the boat the player drives). Default: nothing.
    #[inline(always)]
    fn entity_event(&mut self, entity_id: i32, status: i8) {
        let _ = (entity_id, status);
    }
    /// The entity store, mutable (its clock and event queue); `None` without a tracker.
    fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
        None
    }
    /// Whether entities push the player (`LivingEntity.pushEntities` and the boat's push on
    /// the client player; default on, as in vanilla). Versions whose client never pushes the
    /// player ignore it.
    fn set_entity_push(&mut self, on: bool) {
        let _ = on;
    }
    /// 1.21.4+ level-load gate: the server's `game_event` 13 (`LEVEL_CHUNKS_LOAD_START`).
    fn level_load_start(&mut self) {}
    /// 1.21.4+ level-load gate: the player is alive (`set_health` above 0).
    fn player_alive(&mut self, alive: bool) {
        let _ = alive;
    }
    /// 1.21.4+ level-load gate, once per tick before the key handling: `true` on the tick the
    /// client sends `player_loaded`. `section_compiled`: the engine's readiness signal;
    /// `timed_out`: the client's 30 s wait is over.
    fn load_gate_tick(&mut self, section_compiled: bool, timed_out: bool) -> bool {
        let _ = (section_compiled, timed_out);
        false
    }
    /// 1.21.4+: a tick behind the level-load gate (the player does not tick; only its entity
    /// tick counter runs).
    fn tick_unloaded(&mut self) {}
    /// The whole crosshair target (vanilla `GameRenderer.updateTargetedEntity`): the block
    /// pick unless one of `q.entities` is hit nearer. Versions without an entity pick yet
    /// pick blocks only.
    fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
        Crosshair::Block(if q.now {
            self.crosshair_now(q.eyes, q.rotation, q.look, q.held)
        } else {
            self.crosshair(q.eyes, q.rotation, q.look, crate::hands::REACH)
        })
    }
    /// 1.20.5+ movement attributes of our entity, in packet order.
    fn attributes(&mut self, attributes: &[crate::common::AttributeUpdate]) {
        let _ = attributes;
    }
    /// `chunk_batch_start` arrived (1.20.2+), at `now_nanos` from any fixed origin.
    fn chunk_batch_start(&mut self, now_nanos: i64) {
        let _ = now_nanos;
    }
    /// `chunk_batch_finished` arrived: the chunks per tick to answer with (1.20.2+).
    fn chunk_batch_finished(&mut self, batch_size: i32, now_nanos: i64) -> f32 {
        let _ = (batch_size, now_nanos);
        // ChunkBatchSizeCalculator's initial value: 7 ms / 2 ms.
        3.5
    }
    /// A configuration-state `registry_data` packet (1.20.2+).
    fn registry_data(&mut self, raw: &RawPacket) {
        let _ = raw;
    }
    /// The clock of a [`crate::common::TimeUpdate`] that is the current dimension's day
    /// (26.x: its world clock registry id; `None` for a dimension without a day).
    fn day_clock(&self) -> Option<i32> {
        Some(crate::common::ClockUpdate::LEGACY_DAY)
    }
    /// `entity.damage(..)` / `hurtClient` of an attack target on the client returns `true`
    /// (with `isAttackable()` and no `handleAttack` / `skipAttackInteraction`): the attack's
    /// knockback part then runs on the client. Other players, vehicles, end crystals, … — the
    /// version's own list; a living mob is never hurt on the client.
    fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
        e.is_player()
    }
    /// The player's eye height as its pose has it now (`getEyeHeight` / `getStandingEyeHeight`),
    /// when it can differ from standing / sneaking (1.12 gliding; 1.16.5 swimming, gliding,
    /// riptide). `None`: the standing / sneaking height.
    fn eye_height(&self) -> Option<f64> {
        None
    }
    /// `PlayerEntity.attack` after a hit that [`Sim::attack_hurts`]: with knockback
    /// (`knockback` enchantment level, 26.x: the attribute part, plus 1 for a sprint attack;
    /// 1.9+ only at full strength: `sprint_bonus`) the attacker's `velocity x/z *= 0.6` and
    /// `setSprinting(false)`, before this tick's movement. The target `target` takes the
    /// knockback from the attacker's `yaw` (1.8: a boat drifts by it in the client view).
    fn attack_slow(&mut self, target: i32, yaw: f32, knockback: i32, sprint_bonus: bool) {
        let _ = (target, yaw, knockback, sprint_bonus);
    }
    /// The flags byte (entity data index 0) the server last sent for our entity (`None`
    /// before any).
    fn server_flags(&self) -> Option<u8> {
        None
    }
    /// The absorption amount the server last sent for our entity (player entity data; 0
    /// before any), once after each change (`None` while unchanged).
    fn take_absorption(&mut self) -> Option<f32> {
        None
    }
    /// Our living flags (1.9+ entity data: bit 1 using, bit 2 off hand) when a packet set them
    /// since the last call.
    fn take_living_flags(&mut self) -> Option<u8> {
        None
    }
    /// The player's velocity now (blocks per tick), with server velocity / explosion pushes
    /// applied since the last step.
    fn velocity_now(&self) -> Vec3 {
        Vec3::default()
    }
}

/// `velocity *= (0.6, 1, 0.6)` and `setSprinting(false)` when an attack has knockback:
/// `knockback + (sprinting && sprint_bonus ? 1 : 0) > 0`. Returns whether it applied.
#[inline]
pub(super) fn attack_knockback_applies(
    knockback: i32,
    sprinting: bool,
    sprint_bonus: bool,
) -> bool {
    knockback + i32::from(sprinting && sprint_bonus) > 0
}

/// Options of the per-version sim.
#[derive(Debug, Clone, Default)]
pub(crate) struct SimOptions {
    /// Write a movement recording there.
    pub record: Option<std::path::PathBuf>,
    /// Grim compatibility (not vanilla): send the position on ticks whose feet height changed
    /// although the move stayed under the 0.03 resend threshold.
    pub force_step_position: ForceStepPosition,
    /// Track entities (and the tab list).
    pub entities: Option<ghast_entity::Config>,
    /// What the world keeps besides block states (default: nothing, see [`config`]).
    pub world: Option<WorldConfig>,
    /// Share section storage through this store (modern versions; the others ignore it).
    pub shared_chunks: Option<ghast_world::SharedChunks>,
    /// The player's scoreboard name (team membership for entity pushes, 1.12.2, 1.16.5 and
    /// 26.1+).
    #[cfg_attr(
        not(any(ghast_modern, feature = "v1_12_2", feature = "v1_16_5")),
        allow(dead_code)
    )]
    pub profile_name: Option<String>,
}

/// Grim compatibility (**not vanilla**): when to send the position on a tick whose move stayed
/// under vanilla's 0.03-block resend threshold (every version; on 26.x also bounce landings on
/// slime and beds). See `crates/ghast-physics/GRIM_NOTES.md`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ForceStepPosition {
    /// Vanilla: never.
    #[default]
    Off,
    /// Whenever the feet height changed since the last sent position (step-ups and landings).
    Always,
    /// Only step-ups: on ground after the move and the feet went up. Falls, landings and
    /// descents stay vanilla.
    StepUpOnly,
}

/// Grim compatibility: when the tick's movement packet carries no position but the feet height
/// changed since the last sent position (a step-up or landing under the 0.03 threshold),
/// upgrade it to `position` / `position_look` and update the sent bookkeeping.
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
pub(super) fn force_position(
    packets: &mut ghast_physics::Packets,
    cur: [f64; 3],
    sent_pos: &mut [f64; 3],
    ticks_since_pos: &mut i32,
    mode: ForceStepPosition,
) {
    use ghast_physics::Packet as P;
    if mode == ForceStepPosition::Off || cur[1] == sent_pos[1] {
        return;
    }
    let Some(last) = packets.as_slice().last().copied() else {
        return;
    };
    if mode == ForceStepPosition::StepUpOnly {
        let on_ground = matches!(
            last,
            P::Flying { on_ground: true }
                | P::Look {
                    on_ground: true,
                    ..
                }
        );
        if !on_ground || cur[1] <= sent_pos[1] {
            return;
        }
    }
    let new = match last {
        P::Flying { on_ground } => P::Position {
            x: cur[0],
            y: cur[1],
            z: cur[2],
            on_ground,
        },
        P::Look {
            yaw,
            pitch,
            on_ground,
        } => P::PositionLook {
            x: cur[0],
            y: cur[1],
            z: cur[2],
            yaw,
            pitch,
            on_ground,
        },
        _ => return,
    };
    let mut out = ghast_physics::Packets::new();
    let n = packets.len();
    for p in &packets.as_slice()[..n - 1] {
        out.push(*p);
    }
    out.push(new);
    *packets = out;
    *sent_pos = cur;
    *ticks_since_pos = 0;
}

/// 1.16 blocks whose `onUse` succeeds for a plain right click (GUIs, doors,
/// switches, …). Name-based approximation of vanilla's per-block `use` overrides.
#[cfg(any(feature = "v1_16_5", ghast_modern))]
pub(super) fn activates_1_16(name: &str) -> bool {
    const EXACT: &[&str] = &[
        "chest",
        "trapped_chest",
        "ender_chest",
        "crafting_table",
        "furnace",
        "blast_furnace",
        "smoker",
        "barrel",
        "anvil",
        "chipped_anvil",
        "damaged_anvil",
        "enchanting_table",
        "brewing_stand",
        "hopper",
        "dispenser",
        "dropper",
        "repeater",
        "comparator",
        "note_block",
        "jukebox",
        "cake",
        "loom",
        "stonecutter",
        "grindstone",
        "cartography_table",
        "smithing_table",
        "lectern",
        "bell",
        "beacon",
        "daylight_detector",
        "respawn_anchor",
        "composter",
        "lever",
        "command_block",
        "chain_command_block",
        "repeating_command_block",
        "structure_block",
        "jigsaw",
        "dragon_egg",
        "flower_pot",
        "sweet_berry_bush",
    ];
    EXACT.contains(&name)
        || name.ends_with("_shulker_box")
        || name == "shulker_box"
        || name.ends_with("_bed")
        || name.ends_with("_button")
        || name.ends_with("_fence_gate")
        || (name.ends_with("_door") && name != "iron_door")
        || (name.ends_with("_trapdoor") && name != "iron_trapdoor")
        || name.starts_with("potted_")
}

/// A legacy (1.8.9 / 1.12.2) crosshair target as the engine takes it.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(super) fn legacy_crosshair(t: ghast_physics::pick::legacy::Target, eye: [f64; 3]) -> Crosshair {
    use ghast_physics::pick::legacy::Target;
    match t {
        Target::Block(h) => Crosshair::Block(block_hit(&h, eye)),
        Target::Entity(e) => Crosshair::Entity {
            index: e.index,
            hit: Vec3::new(e.location[0], e.location[1], e.location[2]),
        },
        Target::None | Target::TooFar { .. } => Crosshair::Block(None),
    }
}

/// A modern (1.16.5+) crosshair target as the engine takes it.
#[cfg(any(feature = "v1_16_5", ghast_modern))]
pub(super) fn modern_crosshair(t: ghast_physics::pick::Target, eye: [f64; 3]) -> Crosshair {
    use ghast_physics::pick::Target;
    match t {
        Target::Block(h) => Crosshair::Block(block_hit(&h, eye)),
        Target::Entity(e) => Crosshair::Entity {
            index: e.index,
            hit: Vec3::new(e.location[0], e.location[1], e.location[2]),
        },
    }
}

/// A pick result as the hands take it (`None` for a miss).
pub(super) fn block_hit(
    hit: &ghast_physics::pick::BlockHit,
    eye: [f64; 3],
) -> Option<crate::BlockHit> {
    use ghast_physics::pick::Direction;
    if !hit.is_block() {
        return None;
    }
    let face = match hit.face {
        Direction::Down => crate::Face::Down,
        Direction::Up => crate::Face::Up,
        Direction::North => crate::Face::North,
        Direction::South => crate::Face::South,
        Direction::West => crate::Face::West,
        Direction::East => crate::Face::East,
    };
    let [lx, ly, lz] = hit.location;
    let distance = ((lx - eye[0]).powi(2) + (ly - eye[1]).powi(2) + (lz - eye[2]).powi(2)).sqrt();
    Some(crate::BlockHit {
        pos: BlockPos::new(hit.pos[0], hit.pos[1], hit.pos[2]),
        face,
        hit: Vec3::new(lx, ly, lz),
        distance,
    })
}

/// Union of the collision boxes as a ray box (`None` when there is none).
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5", ghast_modern))]
pub(super) fn union(boxes: &[ghast_data::Aabb]) -> Option<[f64; 6]> {
    let mut u = [1.0_f64, 1.0, 1.0, 0.0, 0.0, 0.0];
    for b in boxes {
        u[0] = u[0].min(b.min_x);
        u[1] = u[1].min(b.min_y);
        u[2] = u[2].min(b.min_z);
        u[3] = u[3].max(b.max_x.min(1.0));
        u[4] = u[4].max(b.max_y.min(1.0));
        u[5] = u[5].max(b.max_z.min(1.0));
    }
    (!boxes.is_empty()).then_some(u)
}

/// 1.8 blocks whose client `Block.onUse` answers a right click.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
pub(super) const ACTIVATED_1_8: &[u8] = &[
    23, 25, 26, 54, 58, 61, 62, 64, 69, 71, 77, 84, 92, 93, 94, 96, 107, 116, 117, 118, 120, 130,
    138, 143, 145, 146, 149, 150, 151, 154, 158, 167, 178, 183, 184, 185, 186, 187, 193, 194, 195,
    196, 197,
];

#[cfg(feature = "v1_12_2")]
/// 1.12 items used by holding right click besides food: potion, milk, bow, shield, splash and
/// lingering potions are thrown (not held).
const USABLE_1_12: &[u16] = &[373, 335, 261, 442];

/// 1.8 / 1.12 swords (iron, wood, stone, diamond, gold): in creative they break no block.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
const SWORDS_LEGACY: &[u16] = &[267, 268, 272, 276, 283];

/// 1.8 items used by holding right click besides food: potion, milk, bow, swords.
#[cfg(feature = "v1_8")]
const USABLE_1_8: &[u16] = &[373, 335, 261, 267, 268, 272, 276, 283];

/// The hunger points a food item restores (1.8 – 1.16.5 tables; `None` for other items and
/// versions).
pub(crate) fn food_points(data: DataSet, id: u16) -> Option<u8> {
    // Only read by the legacy tables (a 26.x-only build has none).
    let _ = id;
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => ghast_data::v1_8::item_use::food_points(id),
        #[cfg(feature = "v1_12_2")]
        DataSet::V1_12 => ghast_data::v1_12::food(id).map(|f| f.food_points),
        #[cfg(feature = "v1_16_5")]
        DataSet::V1_16_5 => ghast_data::v1_16_5::food(id).map(|f| f.food_points),
        #[allow(unreachable_patterns)]
        _ => None,
    }
}

/// A held item's version facts (tool speeds, block item, usable) from its id.
pub(crate) fn held_item_facts(data: DataSet, id: u16, count: u8, efficiency: u8) -> HeldItem {
    match data {
        #[cfg(feature = "v1_8")]
        DataSet::V1_8 => HeldItem {
            modern_item: None,
            swing_on_use: false,
            equips: false,
            equip_swings: false,
            creative_keeps_blocks: SWORDS_LEGACY.contains(&id),
            use_succeeds: false,
            id,
            count,
            efficiency,
            places_block: id < 256,
            usable: ghast_data::v1_8::item_use::is_food(id) || USABLE_1_8.contains(&id),
            food: ghast_data::v1_8::item_use::is_food(id),
            always_edible: ghast_data::v1_8::item_use::always_edible(id),
            tool_speed: Some(ghast_data::v1_8::tool_multiplier),
        },
        #[cfg(feature = "v1_12_2")]
        DataSet::V1_12 => HeldItem {
            modern_item: None,
            swing_on_use: false,
            equips: false,
            equip_swings: false,
            creative_keeps_blocks: SWORDS_LEGACY.contains(&id),
            use_succeeds: matches!(id, 332 | 344 | 346 | 384 | 438 | 441),
            id,
            count,
            efficiency,
            places_block: id < 256,
            usable: ghast_data::v1_12::item_use::is_food(id) || USABLE_1_12.contains(&id),
            food: ghast_data::v1_12::item_use::is_food(id),
            always_edible: ghast_data::v1_12::item_use::always_edible(id),
            tool_speed: Some(ghast_data::v1_12::tool_multiplier),
        },
        #[cfg(feature = "v1_16_5")]
        DataSet::V1_16_5 => HeldItem {
            modern_item: None,
            // SUCCESS on the client with a swing (`TypedActionResult.success(stack,
            // world.isClient)`): thrown items, the fishing rod, the empty map.
            swing_on_use: ghast_data::v1_16_5::Item::from_id(id).is_some_and(|i| {
                matches!(
                    i.info().name,
                    "snowball"
                        | "egg"
                        | "ender_pearl"
                        | "experience_bottle"
                        | "splash_potion"
                        | "lingering_potion"
                        | "fishing_rod"
                        | "map"
                )
            }),
            equips: false,
            equip_swings: false,
            creative_keeps_blocks: ghast_data::v1_16_5::Item::from_id(id)
                .is_some_and(|i| i.info().name.ends_with("_sword") || i.info().name == "trident"),
            use_succeeds: false,
            id,
            count,
            efficiency,
            places_block: ghast_data::v1_16_5::Item::from_id(id)
                .is_some_and(|i| ghast_data::v1_16_5::Block::from_name(i.info().name).is_some()),
            usable: ghast_data::v1_16_5::item_use::is_food(id)
                || ghast_data::v1_16_5::Item::from_id(id).is_some_and(|i| {
                    matches!(
                        i.info().name,
                        "potion"
                            | "milk_bucket"
                            | "honey_bottle"
                            | "bow"
                            | "crossbow"
                            | "shield"
                            | "trident"
                    )
                }),
            food: ghast_data::v1_16_5::item_use::is_food(id),
            always_edible: ghast_data::v1_16_5::item_use::always_edible(id),
            tool_speed: Some(ghast_data::v1_16_5::tool_multiplier),
        },
        #[cfg(feature = "v26_1")]
        DataSet::V26_1 => v26_1::held_item_facts(id, count, efficiency),
        #[cfg(feature = "v26_2")]
        DataSet::V26_2 => v26_2::held_item_facts(id, count, efficiency),
        #[cfg(feature = "v26_3")]
        DataSet::V26_3 => v26_3::held_item_facts(id, count, efficiency),
        // A data set this build does not include: an item without known facts.
        #[allow(unreachable_patterns)]
        _ => HeldItem {
            modern_item: None,
            swing_on_use: false,
            equips: false,
            equip_swings: false,
            creative_keeps_blocks: false,
            use_succeeds: false,
            id,
            count,
            efficiency,
            places_block: false,
            usable: false,
            food: false,
            always_edible: false,
            tool_speed: None,
        },
    }
}

pub(super) fn config() -> WorldConfig {
    // The bot needs block states only: no biomes, no light.
    WorldConfig::default()
        .with_biomes(false)
        .with_light(false)
        .with_block_entities(false)
}

pub(super) fn abilities_flags(a: &ghast_physics::Abilities) -> i8 {
    let mut f = 0;
    if a.invulnerable {
        f |= 1;
    }
    if a.flying {
        f |= 2;
    }
    if a.allow_flying {
        f |= 4;
    }
    if a.creative {
        f |= 8;
    }
    f
}

/// The physics' packets of a tick, in order, as wire packets.
pub(super) fn push_packets(
    packets: &ghast_physics::Packets,
    entity_id: i32,
    out: &mut Vec<Outbound>,
) {
    for p in packets {
        use ghast_physics::Packet as P;
        let action = |action| Outbound::EntityAction { entity_id, action };
        let wire = match *p {
            P::StartSneaking => action(EntityAction::StartSneaking),
            P::StopSneaking => action(EntityAction::StopSneaking),
            P::StartSprinting => action(EntityAction::StartSprinting),
            P::StopSprinting => action(EntityAction::StopSprinting),
            P::StartFallFlying => action(EntityAction::StartFallFlying),
            P::Abilities(a) => Outbound::Abilities {
                flags: abilities_flags(&a),
                flying_speed: a.fly_speed,
                walking_speed: a.walk_speed,
            },
            P::Flying { on_ground } => Outbound::Move(MovePacket::Flying {
                horizontal_collision: false,
                on_ground,
            }),
            P::Position { x, y, z, on_ground } => Outbound::Move(MovePacket::Position {
                horizontal_collision: false,
                pos: Vec3::new(x, y, z),
                on_ground,
            }),
            P::Look {
                yaw,
                pitch,
                on_ground,
            } => Outbound::Move(MovePacket::Look {
                horizontal_collision: false,
                yaw,
                pitch,
                on_ground,
            }),
            P::PositionLook {
                x,
                y,
                z,
                yaw,
                pitch,
                on_ground,
            } => Outbound::Move(MovePacket::PositionLook {
                horizontal_collision: false,
                pos: Vec3::new(x, y, z),
                yaw,
                pitch,
                on_ground,
            }),
            // The modern physics (1.21.2+): one move packet with optional parts, held keys.
            P::Move {
                pos,
                look,
                on_ground,
                horizontal_collision,
            } => Outbound::Move(match (pos, look) {
                (Some([x, y, z]), Some((yaw, pitch))) => MovePacket::PositionLook {
                    pos: Vec3::new(x, y, z),
                    yaw,
                    pitch,
                    on_ground,
                    horizontal_collision,
                },
                (Some([x, y, z]), None) => MovePacket::Position {
                    pos: Vec3::new(x, y, z),
                    on_ground,
                    horizontal_collision,
                },
                (None, Some((yaw, pitch))) => MovePacket::Look {
                    yaw,
                    pitch,
                    on_ground,
                    horizontal_collision,
                },
                (None, None) => MovePacket::Flying {
                    on_ground,
                    horizontal_collision,
                },
            }),
            P::MoveVehicle {
                pos,
                yaw,
                pitch,
                on_ground,
            } => Outbound::VehicleMove {
                pos: Vec3::new(pos[0], pos[1], pos[2]),
                yaw,
                pitch,
                on_ground,
            },
            P::PaddleBoat { left, right } => Outbound::SteerBoat { left, right },
            P::SteerVehicle {
                sideways,
                forward,
                jump,
                sneak,
            } => Outbound::SteerVehicle {
                sideways,
                forward,
                jump,
                sneak,
            },
            P::PlayerInput(k) => Outbound::PlayerInput(Controls {
                forward: k.forward,
                back: k.back,
                left: k.left,
                right: k.right,
                jump: k.jump,
                sneak: k.sneak,
                sprint: k.sprint,
            }),
            // A physics packet added later without a wire form here.
            _ => {
                debug_assert!(false, "physics packet without a wire form: {p:?}");
                continue;
            }
        };
        out.push(wire);
    }
}

#[cfg(any(feature = "v1_12_2", feature = "v1_16_5", ghast_modern))]
pub(super) fn physics_abilities(a: Abilities) -> ghast_physics::Abilities {
    ghast_physics::Abilities {
        invulnerable: a.flags & 1 != 0,
        flying: a.flags & 2 != 0,
        allow_flying: a.flags & 4 != 0,
        creative: a.flags & 8 != 0,
        fly_speed: a.flying_speed,
        walk_speed: a.walking_speed,
    }
}

pub(super) fn keys(c: Controls) -> ghast_physics::Keys {
    ghast_physics::Keys {
        forward: c.forward,
        back: c.back,
        left: c.left,
        right: c.right,
        jump: c.jump,
        sneak: c.sneak,
        sprint: c.sprint,
    }
}

#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
pub(super) fn rel_flags(flags: i8) -> [bool; 5] {
    use crate::common::teleport_flags as fl;
    [
        flags & fl::X != 0,
        flags & fl::Y != 0,
        flags & fl::Z != 0,
        flags & fl::YAW != 0,
        flags & fl::PITCH != 0,
    ]
}

#[cfg(test)]
impl WorldView for Box<dyn Sim> {
    fn column(&self, chunk_x: i32, chunk_z: i32) -> Option<&ghast_world::Column> {
        (**self).column(chunk_x, chunk_z)
    }
    fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
        (**self).is_column_loaded(chunk_x, chunk_z)
    }
    fn raw_block(&self, x: i32, y: i32, z: i32) -> Option<u32> {
        (**self).raw_block(x, y, z)
    }
    fn entities(&self) -> Option<&ghast_entity::Entities> {
        (**self).entities()
    }
    fn loaded_columns(&self) -> usize {
        (**self).loaded_columns()
    }
    fn collisions(&self) -> (bool, bool) {
        (**self).collisions()
    }

    fn block_query(&self, x: i32, y: i32, z: i32) -> Option<BlockQuery> {
        (**self).block_query(x, y, z)
    }

    fn crosshair(
        &self,
        eyes: Vec3,
        rotation: (f32, f32),
        look: Vec3,
        reach: f64,
    ) -> Option<crate::BlockHit> {
        (**self).crosshair(eyes, rotation, look, reach)
    }
}

#[cfg(test)]
impl Sim for Box<dyn Sim> {
    fn world_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        (**self).world_packet(raw)
    }
    fn reset_player(&mut self) {
        (**self).reset_player();
    }
    fn respawn_player(&mut self, keep: u8) {
        (**self).respawn_player(keep);
    }
    fn teleport(&mut self, pose: &mut Pose, t: &Teleport) {
        (**self).teleport(pose, t);
    }
    fn abilities(&mut self, a: Abilities) {
        (**self).abilities(a);
    }
    fn food(&mut self, food: i32) {
        (**self).food(food);
    }
    fn velocity(&mut self, v: Vec3, add: bool) {
        (**self).velocity(v, add);
    }
    fn step(
        &mut self,
        pose: &mut Pose,
        controls: Controls,
        using_item: bool,
        entity_id: i32,
        out: &mut Vec<Outbound>,
    ) {
        (**self).step(pose, controls, using_item, entity_id, out);
    }
    fn set_flying(&mut self, flying: bool, out: &mut Vec<Outbound>) {
        (**self).set_flying(flying, out);
    }
    fn collect_block_updates(&mut self, on: bool) {
        (**self).collect_block_updates(on);
    }
    fn drain_block_updates(&mut self, out: &mut Vec<(BlockPos, u32)>) -> usize {
        (**self).drain_block_updates(out)
    }
    fn world_packet_ids(&self) -> Vec<i32> {
        (**self).world_packet_ids()
    }
    fn entity_config(&self) -> Option<ghast_entity::Config> {
        (**self).entity_config()
    }
    fn set_entities(&mut self, config: Option<ghast_entity::Config>) {
        (**self).set_entities(config);
    }
    fn entity_packet_ids(&self) -> Vec<i32> {
        (**self).entity_packet_ids()
    }
    fn predict_air(&mut self, x: i32, y: i32, z: i32) {
        (**self).predict_air(x, y, z);
    }
    fn dig_sent(
        &mut self,
        pos: BlockPos,
        status: crate::common::DigStatus,
        broken: bool,
        sequence: i32,
        player: Vec3,
    ) {
        (**self).dig_sent(pos, status, broken, sequence, player);
    }
    fn records_digs(&self) -> bool {
        (**self).records_digs()
    }
    fn place_sent(&mut self, p: &predict::PlaceSent<'_>) -> bool {
        (**self).place_sent(p)
    }
    fn place_suppressed(&self, pos: BlockPos, face: crate::common::Face, held: u16) -> bool {
        (**self).place_suppressed(pos, face, held)
    }
    fn place_rules(&self, q: &predict::PlaceQuery<'_>) -> predict::PlaceRules {
        (**self).place_rules(q)
    }
    fn air_use(&self, q: &predict::AirQuery<'_>) -> predict::AirAnswer {
        (**self).air_use(q)
    }
    fn air_use_sent(&mut self, blocks: &[(BlockPos, u32)]) {
        (**self).air_use_sent(blocks);
    }
    fn set_player_pos(&mut self, p: Vec3) {
        (**self).set_player_pos(p);
    }
    fn teleport_sequence(&mut self, sequence: Option<i32>) {
        (**self).teleport_sequence(sequence);
    }
    fn take_snap(&mut self) -> Option<Vec3> {
        (**self).take_snap()
    }
    fn movement_speed(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
        (**self).movement_speed(base, modifiers);
    }
    fn status_effects(&mut self, effects: &std::collections::BTreeMap<i8, i8>) {
        (**self).status_effects(effects);
    }
    fn boots(&mut self, depth_strider: u8, soul_speed: u8) {
        (**self).boots(depth_strider, soul_speed);
    }
    fn feet_item(&mut self, id: Option<i32>) {
        (**self).feet_item(id);
    }
    fn spectator(&mut self, on: bool) {
        (**self).spectator(on);
    }
    fn held_item(&self, id: u16, count: u8, efficiency: u8) -> HeldItem {
        (**self).held_item(id, count, efficiency)
    }
    fn item_use_facts(
        &self,
        stack: &ghast_inventory::Stack,
        off_hand: bool,
        held: HeldItem,
    ) -> HeldItem {
        (**self).item_use_facts(stack, off_hand, held)
    }
    fn modern_inputs(&self) -> bool {
        (**self).modern_inputs()
    }
    fn held_use_inputs(&mut self, inv: &mut ghast_inventory::Inventory) {
        (**self).held_use_inputs(inv);
    }
    fn pre_tick_wanted(&self) -> bool {
        (**self).pre_tick_wanted()
    }
    fn pre_tick(&mut self, inv: &ghast_inventory::Inventory, t: &PreTick) -> bool {
        (**self).pre_tick(inv, t)
    }
    fn gliding(&self) -> bool {
        (**self).gliding()
    }
    fn weather(&mut self, reason: u8, value: f32) {
        (**self).weather(reason, value);
    }
    fn mount_info(&self, entity_id: i32) -> Option<(i32, bool, bool)> {
        (**self).mount_info(entity_id)
    }
    fn mount_rules(&self, entity_id: i32) -> Option<ghast_inventory::MountRules> {
        (**self).mount_rules(entity_id)
    }
    #[cfg(ghast_modern)]
    fn modern_player(&self) -> Option<&ghast_physics::modern::PlayerState> {
        (**self).modern_player()
    }
    fn take_reply(&mut self) -> Option<Outbound> {
        (**self).take_reply()
    }
    fn take_filter_dirty(&mut self) -> bool {
        (**self).take_filter_dirty()
    }
    fn vehicle(&self) -> Option<crate::common::Vehicle> {
        (**self).vehicle()
    }
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_modern(
        &mut self,
        p: ghast_physics::modern::PlayerState,
        x: ghast_physics::modern::PlayerExt,
    ) {
        (**self).test_set_modern(p, x);
    }
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_shared_flags(&self) -> u8 {
        (**self).test_shared_flags()
    }
    #[cfg(all(test, ghast_modern, feature = "v1_8", feature = "v1_16_5"))]
    fn test_set_own_id(&mut self, id: i32) {
        (**self).test_set_own_id(id);
    }
    fn set_main_arm_left(&mut self, left: bool) {
        (**self).set_main_arm_left(left);
    }
    fn crosshair_now(
        &self,
        eyes: Vec3,
        rotation: (f32, f32),
        look: Vec3,
        held: Option<u16>,
    ) -> Option<crate::BlockHit> {
        (**self).crosshair_now(eyes, rotation, look, held)
    }
    fn crosshair_target(&self, q: &PickQuery<'_>) -> Crosshair {
        (**self).crosshair_target(q)
    }
    fn pick_margin(&self, e: &ghast_entity::Entity) -> Option<f32> {
        (**self).pick_margin(e)
    }
    fn search_order(&self, e: &ghast_entity::Entity) -> Option<(i32, i32, i32, u32)> {
        (**self).search_order(e)
    }
    fn tick_entities(&mut self, pose: &mut Pose) {
        (**self).tick_entities(pose);
    }
    fn send_changes(&mut self, entity_id: i32, out: &mut Vec<Outbound>) {
        (**self).send_changes(entity_id, out);
    }
    fn entity_event(&mut self, entity_id: i32, status: i8) {
        (**self).entity_event(entity_id, status);
    }
    fn entities_mut(&mut self) -> Option<&mut ghast_entity::Entities> {
        (**self).entities_mut()
    }
    fn set_entity_push(&mut self, on: bool) {
        (**self).set_entity_push(on);
    }
    fn level_load_start(&mut self) {
        (**self).level_load_start();
    }
    fn player_alive(&mut self, alive: bool) {
        (**self).player_alive(alive);
    }
    fn load_gate_tick(&mut self, section_compiled: bool, timed_out: bool) -> bool {
        (**self).load_gate_tick(section_compiled, timed_out)
    }
    fn tick_unloaded(&mut self) {
        (**self).tick_unloaded();
    }
    fn attributes(&mut self, attributes: &[crate::common::AttributeUpdate]) {
        (**self).attributes(attributes);
    }
    fn chunk_batch_start(&mut self, now_nanos: i64) {
        (**self).chunk_batch_start(now_nanos);
    }
    fn chunk_batch_finished(&mut self, batch_size: i32, now_nanos: i64) -> f32 {
        (**self).chunk_batch_finished(batch_size, now_nanos)
    }
    fn registry_data(&mut self, raw: &RawPacket) {
        (**self).registry_data(raw);
    }
    fn day_clock(&self) -> Option<i32> {
        (**self).day_clock()
    }
    fn attack_hurts(&self, e: &ghast_entity::Entity) -> bool {
        (**self).attack_hurts(e)
    }
    fn eye_height(&self) -> Option<f64> {
        (**self).eye_height()
    }
    fn attack_slow(&mut self, target: i32, yaw: f32, knockback: i32, sprint_bonus: bool) {
        (**self).attack_slow(target, yaw, knockback, sprint_bonus);
    }
    fn server_flags(&self) -> Option<u8> {
        (**self).server_flags()
    }
    fn take_living_flags(&mut self) -> Option<u8> {
        (**self).take_living_flags()
    }
    fn take_absorption(&mut self) -> Option<f32> {
        (**self).take_absorption()
    }
    fn velocity_now(&self) -> Vec3 {
        (**self).velocity_now()
    }
}

/// Chunk packets for tests.
#[cfg(test)]
#[allow(unused_imports, dead_code)] // each helper is used by the tests of its version
pub(crate) mod test_chunks {
    use bytes::{BufMut, Bytes, BytesMut};
    use ghast_protocol::RawPacket;

    #[cfg(feature = "v1_8")]
    /// A 1.8 ground-up chunk with one section (y 48–63) whose top layer (y = 63) is stone.
    pub(crate) fn v1_8(x: i32, z: i32) -> RawPacket {
        let mut d = BytesMut::with_capacity(12_544);
        for i in 0..4096 {
            // Index = y << 8 | z << 4 | x; local y 15 is the top layer. Stone = 1 << 4.
            d.put_u16_le(if i >> 8 == 15 { 1 << 4 } else { 0 });
        }
        d.put_bytes(0, 2048); // block light
        d.put_bytes(0xff, 2048); // sky light
        d.put_bytes(1, 256); // biomes
        RawPacket::from_packet(&ghast_protocol::v1_8::play::clientbound::MapChunk {
            x,
            z,
            ground_up: true,
            bit_map: 1 << 3,
            chunk_data: d.freeze(),
        })
        .unwrap()
    }

    #[cfg(feature = "v1_12_2")]
    /// A 1.12.2 ground-up chunk with one section (y 48–63) whose top layer (y = 63) is stone.
    pub(crate) fn v1_12_2(x: i32, z: i32) -> RawPacket {
        let mut d = BytesMut::new();
        d.put_u8(4); // bits per block: linear palette
        d.put_u8(2); // palette length (VarInt)
        d.put_u8(0); // air
        d.put_u8(1 << 4); // stone (one byte VarInt: 16)
        d.put_u8(0x80); // data length 256 (VarInt)
        d.put_u8(0x02);
        for w in 0..256 {
            // 16 values of 4 bits per word; words 240.. hold y = 15 (index >> 8 == 15).
            d.put_u64(if w >= 240 { 0x1111_1111_1111_1111 } else { 0 });
        }
        d.put_bytes(0, 2048); // block light
        d.put_bytes(0xff, 2048); // sky light
        d.put_bytes(1, 256); // biomes
        RawPacket::from_packet(&ghast_protocol::v1_12_2::play::clientbound::MapChunk {
            x,
            z,
            ground_up: true,
            bit_map: 1 << 3,
            chunk_data: d.freeze(),
            block_entities: Vec::new(),
        })
        .unwrap()
    }

    #[cfg(feature = "v26_1")]
    /// A 26.1 overworld chunk (y −64 … 319) whose layer y = 63 is stone, the rest air.
    pub(crate) fn v26_1(x: i32, z: i32) -> RawPacket {
        v26_1_sections(x, z, 24, 7)
    }

    #[cfg(feature = "v26_1")]
    /// A 26.1 column of `sections` sections with the stone layer at the top of section
    /// `stone` (the nether: 16 sections, stone layer section 3).
    pub(crate) fn v26_1_sections(x: i32, z: i32, sections: usize, stone_at: usize) -> RawPacket {
        use ghast_protocol::McWrite;
        let stone = ghast_data::v26_1::BlockState::parse("stone").unwrap().id();
        let mut d = BytesMut::new();
        for section in 0..sections {
            if section == stone_at {
                // y 48 … 63: a 4-bit linear palette (air, stone), the top layer stone.
                d.put_i16(256);
                d.put_i16(0);
                d.put_u8(4);
                d.put_varint(2);
                d.put_varint(0);
                d.put_varint(i32::from(stone));
                for w in 0..256 {
                    d.put_u64(if w >= 240 { 0x1111_1111_1111_1111 } else { 0 });
                }
            } else {
                d.put_i16(0);
                d.put_i16(0);
                d.put_u8(0);
                d.put_varint(0);
            }
            // Biomes: one value (registry id 0).
            d.put_u8(0);
            d.put_varint(0);
        }
        RawPacket::from_packet(&ghast_protocol::v26_1::play::clientbound::MapChunk {
            x,
            z,
            heightmaps: Vec::new(),
            chunk_data: d.freeze(),
            block_entities: Vec::new(),
            sky_light_mask: Vec::new(),
            block_light_mask: Vec::new(),
            empty_sky_light_mask: Vec::new(),
            empty_block_light_mask: Vec::new(),
            sky_light: Vec::new(),
            block_light: Vec::new(),
        })
        .unwrap()
    }

    #[cfg(feature = "v26_2")]
    /// A 26.2 overworld chunk (y −64 … 319) whose layer y = 63 is stone, the rest air.
    pub(crate) fn v26_2(x: i32, z: i32) -> RawPacket {
        v26_2_sections(x, z, 24, 7)
    }

    #[cfg(feature = "v26_2")]
    /// A 26.2 column of `sections` sections with the stone layer at the top of section
    /// `stone` (the nether: 16 sections, stone layer section 3).
    pub(crate) fn v26_2_sections(x: i32, z: i32, sections: usize, stone_at: usize) -> RawPacket {
        use ghast_protocol::McWrite;
        let stone = ghast_data::v26_2::BlockState::parse("stone").unwrap().id();
        let mut d = BytesMut::new();
        for section in 0..sections {
            if section == stone_at {
                // y 48 … 63: a 4-bit linear palette (air, stone), the top layer stone.
                d.put_i16(256);
                d.put_i16(0);
                d.put_u8(4);
                d.put_varint(2);
                d.put_varint(0);
                d.put_varint(i32::from(stone));
                for w in 0..256 {
                    d.put_u64(if w >= 240 { 0x1111_1111_1111_1111 } else { 0 });
                }
            } else {
                d.put_i16(0);
                d.put_i16(0);
                d.put_u8(0);
                d.put_varint(0);
            }
            // Biomes: one value (registry id 0).
            d.put_u8(0);
            d.put_varint(0);
        }
        RawPacket::from_packet(&ghast_protocol::v26_2::play::clientbound::MapChunk {
            x,
            z,
            heightmaps: Vec::new(),
            chunk_data: d.freeze(),
            block_entities: Vec::new(),
            sky_light_mask: Vec::new(),
            block_light_mask: Vec::new(),
            empty_sky_light_mask: Vec::new(),
            empty_block_light_mask: Vec::new(),
            sky_light: Vec::new(),
            block_light: Vec::new(),
        })
        .unwrap()
    }

    #[cfg(feature = "v26_3")]
    /// A 26.3 overworld chunk (y −64 … 319) whose layer y = 63 is stone, the rest air.
    pub(crate) fn v26_3(x: i32, z: i32) -> RawPacket {
        v26_3_sections(x, z, 24, 7)
    }

    #[cfg(feature = "v26_3")]
    /// A 26.3 column of `sections` sections with the stone layer at the top of section
    /// `stone` (the nether: 16 sections, stone layer section 3).
    pub(crate) fn v26_3_sections(x: i32, z: i32, sections: usize, stone_at: usize) -> RawPacket {
        use ghast_protocol::McWrite;
        let stone = ghast_data::v26_3::BlockState::parse("stone").unwrap().id();
        let mut d = BytesMut::new();
        for section in 0..sections {
            if section == stone_at {
                // y 48 … 63: a 4-bit linear palette (air, stone), the top layer stone.
                d.put_i16(256);
                d.put_i16(0);
                d.put_u8(4);
                d.put_varint(2);
                d.put_varint(0);
                d.put_varint(i32::from(stone));
                for w in 0..256 {
                    d.put_u64(if w >= 240 { 0x1111_1111_1111_1111 } else { 0 });
                }
            } else {
                d.put_i16(0);
                d.put_i16(0);
                d.put_u8(0);
                d.put_varint(0);
            }
            // Biomes: one value (registry id 0).
            d.put_u8(0);
            d.put_varint(0);
        }
        RawPacket::from_packet(&ghast_protocol::v26_3::play::clientbound::MapChunk {
            x,
            z,
            heightmaps: Vec::new(),
            chunk_data: d.freeze(),
            block_entities: Vec::new(),
            sky_light_mask: Default::default(),
            block_light_mask: Default::default(),
            empty_sky_light_mask: Default::default(),
            empty_block_light_mask: Default::default(),
            sky_light: Vec::new(),
            block_light: Vec::new(),
        })
        .unwrap()
    }

    #[cfg(feature = "v1_16_5")]
    /// A 1.16.5 full chunk without sections (all air).
    pub(crate) fn v1_16_5(x: i32, z: i32) -> RawPacket {
        RawPacket::from_packet(&ghast_protocol::v1_16_5::play::clientbound::MapChunk {
            x,
            z,
            ground_up: true,
            bit_map: 0,
            heightmaps: ghast_protocol::nbt::RawNbt::from_bytes(Bytes::from_static(&[10, 0, 0, 0]))
                .unwrap(),
            biomes: Some(vec![1; 1024]),
            chunk_data: Bytes::new(),
            block_entities: Vec::new(),
        })
        .unwrap()
    }
}

#[cfg(all(test, feature = "v1_8"))]
mod tests {
    use super::*;
    use crate::version::{ClientVersion, V1_8};

    /// The 1.8 physics' teleport matches the version's documented rules.
    #[test]
    fn teleport_rules_agree() {
        let cases = [
            (1.5, 64.0, -2.5, 450.0_f32, 100.0_f32, 0_i8),
            (0.25, -1.0, 0.5, -30.0, -95.0, 0x1f),
            (3.0, 70.0, 3.0, 720.5, 10.0, 0x08),
        ];
        for (x, y, z, yaw, pitch, flags) in cases {
            let t = Teleport {
                x,
                y,
                z,
                yaw,
                pitch,
                flags,
                teleport_id: None,
                ..Default::default()
            };
            let start = Pose {
                pos: Vec3::new(10.0, 65.0, 10.0),
                yaw: 33.0,
                pitch: 5.0,
                motion: Vec3::new(0.1, -0.0784, 0.2),
                ..Pose::default()
            };
            let mut a = start;
            <V1_8 as ClientVersion>::apply_teleport(&mut a, &t);
            let mut sim = Sim18::new();
            let mut b = start;
            sim.player
                .set_position(start.pos.x, start.pos.y, start.pos.z);
            sim.player.vel = [start.motion.x, start.motion.y, start.motion.z];
            sim.teleport(&mut b, &t);
            assert_eq!(
                (a.pos, a.yaw, a.pitch, a.motion),
                (b.pos, b.yaw, b.pitch, b.motion),
                "{t:?}"
            );
        }
    }

    #[test]
    fn force_position_only_on_height_change() {
        use ghast_physics::Packet as P;
        let mut pk = ghast_physics::Packets::new();
        pk.push(P::StopSprinting);
        pk.push(P::Look {
            yaw: 1.0,
            pitch: 2.0,
            on_ground: true,
        });
        let mut sent = [1.0, 3.979, 8.3];
        let mut ticks = 3;
        // Same height: untouched.
        force_position(
            &mut pk,
            [1.01, 3.979, 8.3],
            &mut sent,
            &mut ticks,
            ForceStepPosition::Always,
        );
        assert!(matches!(pk.as_slice()[1], P::Look { .. }));
        // Stepped up: the look becomes a position_look, the bookkeeping follows.
        force_position(
            &mut pk,
            [1.01, 4.0, 8.28],
            &mut sent,
            &mut ticks,
            ForceStepPosition::Always,
        );
        assert_eq!(pk.as_slice()[0], P::StopSprinting);
        assert!(matches!(
            pk.as_slice()[1],
            P::PositionLook {
                y: 4.0,
                on_ground: true,
                ..
            }
        ));
        assert_eq!((sent, ticks), ([1.01, 4.0, 8.28], 0));
    }

    #[test]
    fn force_position_step_up_only() {
        use ghast_physics::Packet as P;
        let look = |on_ground| P::Look {
            yaw: 1.0,
            pitch: 2.0,
            on_ground,
        };
        let mode = ForceStepPosition::StepUpOnly;
        // Feet went down (a landing under the threshold): stays vanilla.
        let mut pk = ghast_physics::Packets::new();
        pk.push(look(true));
        let (mut sent, mut ticks) = ([1.0, 4.0, 8.3], 3);
        force_position(&mut pk, [1.01, 3.979, 8.3], &mut sent, &mut ticks, mode);
        assert!(matches!(pk.as_slice()[0], P::Look { .. }));
        // Went up but airborne: stays vanilla.
        force_position(&mut pk, [1.01, 4.01, 8.3], &mut sent, &mut ticks, mode);
        let mut air = ghast_physics::Packets::new();
        air.push(look(false));
        force_position(&mut air, [1.01, 4.01, 8.3], &mut sent, &mut ticks, mode);
        assert!(matches!(air.as_slice()[0], P::Look { .. }));
        // A step-up (up and on ground): forced.
        let mut up = ghast_physics::Packets::new();
        up.push(look(true));
        let (mut sent, mut ticks) = ([1.0, 3.979, 8.3], 3);
        force_position(&mut up, [1.01, 4.0, 8.28], &mut sent, &mut ticks, mode);
        assert!(matches!(up.as_slice()[0], P::PositionLook { y: 4.0, .. }));
        assert_eq!((sent, ticks), ([1.01, 4.0, 8.28], 0));
    }

    #[test]
    fn physics_stands_on_the_test_floor() {
        let mut sim = Sim18::new();
        sim.world_packet(&test_chunks::v1_8(0, 0)).unwrap();
        let mut pose = Pose::default();
        sim.teleport(
            &mut pose,
            &Teleport {
                x: 8.5,
                y: 64.0,
                z: 8.5,
                yaw: 0.0,
                pitch: 0.0,
                flags: 0,
                teleport_id: None,
                ..Default::default()
            },
        );
        let mut out = Vec::new();
        for _ in 0..30 {
            sim.step(&mut pose, Controls::NONE, false, 1, &mut out);
        }
        assert_eq!(pose.pos, Vec3::new(8.5, 64.0, 8.5));
        assert!(pose.on_ground);
        // Walking forward moves the player.
        for _ in 0..10 {
            sim.step(
                &mut pose,
                Controls {
                    forward: true,
                    ..Controls::NONE
                },
                false,
                1,
                &mut out,
            );
        }
        assert!(pose.pos.z > 9.0, "{pose:?}");
    }
}