ghast-client 0.5.4

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, 26.2 and 26.3)
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
//! The client's block predictions and the server's answers to them:
//! 26.x `BlockStatePredictionHandler` (`block_changed_ack`) and 1.16.5
//! `ClientPlayerInteractionManager.processPlayerActionResponse` (`acknowledge_player_digging`).

use super::tests::{Script, engine, join};
use super::*;
use crate::common::{DigStatus, Teleport};
use crate::version::ClientVersion;
use ghast_protocol::{BlockPos, RawPacket};

/// Where the player of `join` stands.
const FEET: Vec3 = Vec3::new(8.5, 64.0, 8.5);

fn modern_versions() -> Vec<GameVersion> {
    let mut v = vec![GameVersion::V26_1];
    #[cfg(feature = "v26_2")]
    v.push(GameVersion::V26_2);
    #[cfg(feature = "v26_3")]
    v.push(GameVersion::V26_3);
    v
}

/// A block state id by name.
fn state(v: GameVersion, name: &str) -> u16 {
    match v {
        #[cfg(feature = "v26_2")]
        GameVersion::V26_2 => ghast_data::v26_2::BlockState::parse(name).unwrap().id(),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => ghast_data::v26_3::BlockState::parse(name).unwrap().id(),
        _ => ghast_data::v26_1::BlockState::parse(name).unwrap().id(),
    }
}

/// `block_changed_ack`.
fn ack(v: GameVersion, sequence: i32) -> RawPacket {
    match v {
        #[cfg(feature = "v26_2")]
        GameVersion::V26_2 => RawPacket::from_packet(
            &ghast_protocol::v26_2::play::clientbound::AcknowledgePlayerDigging {
                sequence_id: sequence,
            },
        ),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => RawPacket::from_packet(
            &ghast_protocol::v26_3::play::clientbound::AcknowledgePlayerDigging {
                sequence_id: sequence,
            },
        ),
        _ => RawPacket::from_packet(
            &ghast_protocol::v26_1::play::clientbound::AcknowledgePlayerDigging {
                sequence_id: sequence,
            },
        ),
    }
    .unwrap()
}

/// `block_update`.
fn block_update(v: GameVersion, pos: BlockPos, s: u16) -> RawPacket {
    match v {
        #[cfg(feature = "v26_2")]
        GameVersion::V26_2 => {
            RawPacket::from_packet(&ghast_protocol::v26_2::play::clientbound::BlockChange {
                location: pos,
                r#type: i32::from(s),
            })
        }
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            RawPacket::from_packet(&ghast_protocol::v26_3::play::clientbound::BlockChange {
                location: pos,
                r#type: i32::from(s),
            })
        }
        _ => RawPacket::from_packet(&ghast_protocol::v26_1::play::clientbound::BlockChange {
            location: pos,
            r#type: i32::from(s),
        }),
    }
    .unwrap()
}

/// `section_blocks_update` of the section holding the first position.
fn section_update(v: GameVersion, changes: &[(BlockPos, u16)]) -> RawPacket {
    let p0 = changes[0].0;
    let records: Vec<i64> = changes
        .iter()
        .map(|&(p, s)| {
            assert_eq!(
                (p.x >> 4, p.y >> 4, p.z >> 4),
                (p0.x >> 4, p0.y >> 4, p0.z >> 4)
            );
            i64::from(s) << 12 | i64::from((p.x & 15) << 8 | (p.z & 15) << 4 | (p.y & 15))
        })
        .collect();
    match v {
        #[cfg(feature = "v26_2")]
        GameVersion::V26_2 => {
            use ghast_protocol::v26_2::play::clientbound as cb;
            RawPacket::from_packet(&cb::MultiBlockChange {
                chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                    x: p0.x >> 4,
                    z: p0.z >> 4,
                    y: p0.y >> 4,
                },
                records,
            })
        }
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            use ghast_protocol::v26_3::play::clientbound as cb;
            RawPacket::from_packet(&cb::MultiBlockChange {
                chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                    x: p0.x >> 4,
                    z: p0.z >> 4,
                    y: p0.y >> 4,
                },
                records,
            })
        }
        _ => {
            use ghast_protocol::v26_1::play::clientbound as cb;
            RawPacket::from_packet(&cb::MultiBlockChange {
                chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                    x: p0.x >> 4,
                    z: p0.z >> 4,
                    y: p0.y >> 4,
                },
                records,
            })
        }
    }
    .unwrap()
}

fn block(e: &Engine<Box<dyn Sim>>, p: BlockPos) -> Option<u32> {
    e.sim.raw_block(p.x, p.y, p.z)
}

/// The client broke `p` in prediction `sequence` (as the engine reports a finish).
fn predict(e: &mut Engine<Box<dyn Sim>>, p: BlockPos, sequence: i32) {
    e.sim.dig_sent(p, DigStatus::Finish, true, sequence, FEET);
}

/// A joined modern engine with the stone layer at y = 63.
fn modern(v: GameVersion) -> Engine<Box<dyn Sim>> {
    let mut e = engine(v);
    join(&mut e);
    e
}

const A: BlockPos = BlockPos::new(3, 63, 3);
const B: BlockPos = BlockPos::new(5, 63, 6);
const C: BlockPos = BlockPos::new(12, 63, 1);

/// The server refuses the break and sends no block update: the ack alone restores it.
#[test]
fn ack_without_update_restores_the_block() {
    for v in modern_versions() {
        let mut e = modern(v);
        let stone = u32::from(state(v, "stone"));
        assert_eq!(block(&e, A), Some(stone));
        predict(&mut e, A, 1);
        assert_eq!(block(&e, A), Some(0), "{v:?}");
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, A), Some(stone), "{v:?}");
        // Ended: a later update applies at once.
        e.sim.world_packet(&block_update(v, A, 0)).unwrap();
        assert_eq!(block(&e, A), Some(0), "{v:?}");
    }
}

/// A block update for a predicted block only replaces the remembered server state; at the
/// ack that state wins (whatever the client predicted).
#[test]
fn update_during_prediction_waits_for_the_ack() {
    for v in modern_versions() {
        let mut e = modern(v);
        let dirt = state(v, "dirt");
        predict(&mut e, A, 1);
        e.sim.world_packet(&block_update(v, A, dirt)).unwrap();
        assert_eq!(block(&e, A), Some(0), "deferred: {v:?}");
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, A), Some(u32::from(dirt)), "{v:?}");

        // The approved break: the server's air arrives before the ack, nothing changes.
        predict(&mut e, B, 2);
        e.sim.world_packet(&block_update(v, B, 0)).unwrap();
        e.sim.world_packet(&ack(v, 2)).unwrap();
        assert_eq!(block(&e, B), Some(0), "{v:?}");
    }
}

/// `endPredictionsUpTo`: an ack ends the predictions up to its sequence only.
#[test]
fn lower_ack_keeps_later_predictions() {
    for v in modern_versions() {
        let mut e = modern(v);
        let stone = u32::from(state(v, "stone"));
        predict(&mut e, A, 1);
        predict(&mut e, B, 2);
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, A), Some(stone), "{v:?}");
        assert_eq!(block(&e, B), Some(0), "{v:?}");
        // B still waits: its update is deferred.
        let dirt = state(v, "dirt");
        e.sim.world_packet(&block_update(v, B, dirt)).unwrap();
        assert_eq!(block(&e, B), Some(0), "{v:?}");
        e.sim.world_packet(&ack(v, 2)).unwrap();
        assert_eq!(block(&e, B), Some(u32::from(dirt)), "{v:?}");
        // Breaking air again changes nothing (destroyBlock: nothing for air), so the record
        // keeps its sequence.
        predict(&mut e, C, 3);
        e.sim.dig_sent(C, DigStatus::Finish, true, 4, FEET);
        e.sim.world_packet(&ack(v, 3)).unwrap();
        assert_eq!(block(&e, C), Some(stone), "{v:?}");
    }
}

/// Updates of positions without a prediction apply at once while predictions wait; a
/// section update splits the same way.
#[test]
fn other_positions_and_section_updates() {
    for v in modern_versions() {
        let mut e = modern(v);
        let dirt = state(v, "dirt");
        let glass = state(v, "glass");
        predict(&mut e, A, 1);
        e.sim.world_packet(&block_update(v, C, dirt)).unwrap();
        assert_eq!(block(&e, C), Some(u32::from(dirt)), "{v:?}");
        // A and B share section (0, 3, 0).
        e.sim.collect_block_updates(true);
        e.sim
            .world_packet(&section_update(v, &[(A, glass), (B, glass)]))
            .unwrap();
        assert_eq!(block(&e, A), Some(0), "deferred: {v:?}");
        assert_eq!(block(&e, B), Some(u32::from(glass)), "{v:?}");
        // The behaviour hears every change the server sent.
        let mut seen = Vec::new();
        e.sim.drain_block_updates(&mut seen);
        assert_eq!(
            seen,
            [(A, u32::from(glass)), (B, u32::from(glass))],
            "{v:?}"
        );
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, A), Some(u32::from(glass)), "{v:?}");
    }
}

/// `destroyBlock` leaves the block's fluid: a broken waterlogged block (and seagrass) becomes a
/// water source, a dry one air; a refused break restores the waterlogged state.
#[test]
fn broken_waterlogged_block_leaves_water() {
    for v in modern_versions() {
        let mut e = modern(v);
        let water = u32::from(state(v, "water"));
        for name in [
            "oak_stairs[waterlogged=true]",
            "oak_slab[type=bottom,waterlogged=true]",
            "seagrass",
        ] {
            let s = state(v, name);
            e.sim.world_packet(&block_update(v, A, s)).unwrap();
            predict(&mut e, A, 1);
            assert_eq!(block(&e, A), Some(water), "{v:?} {name}");
            e.sim.world_packet(&ack(v, 1)).unwrap();
            assert_eq!(block(&e, A), Some(u32::from(s)), "{v:?} {name}");
        }
        let dry = state(v, "oak_stairs[waterlogged=false]");
        e.sim.world_packet(&block_update(v, A, dry)).unwrap();
        predict(&mut e, A, 2);
        assert_eq!(block(&e, A), Some(0), "{v:?}");
    }
}

/// `isColliding` uses the player's collision context: scaffolding the player stands inside
/// (not above its top) has no collision shape, so restoring it does not move the player; a
/// full block there does.
#[test]
fn move_back_uses_the_players_collision_context() {
    for v in modern_versions() {
        let mut e = modern(v);
        let at_feet = BlockPos::new(8, 64, 8);
        let back = Vec3::new(8.5, 66.0, 8.5);
        let scaffolding = state(v, "scaffolding[distance=0,bottom=false]");
        e.sim
            .world_packet(&block_update(v, at_feet, scaffolding))
            .unwrap();
        e.sim.dig_sent(at_feet, DigStatus::Finish, true, 1, back);
        e.sim.world_packet(&ack(v, 1)).unwrap();
        e.sync_snap();
        assert_eq!(block(&e, at_feet), Some(u32::from(scaffolding)), "{v:?}");
        assert_eq!(e.core.pose.pos, FEET, "inside scaffolding: {v:?}");
        let stone = state(v, "stone");
        e.sim
            .world_packet(&block_update(v, at_feet, stone))
            .unwrap();
        e.sim.dig_sent(at_feet, DigStatus::Finish, true, 2, back);
        e.sim.world_packet(&ack(v, 2)).unwrap();
        e.sync_snap();
        assert_eq!(e.core.pose.pos, back, "inside stone: {v:?}");
    }
}

/// The wire's numbers for the packets of one tick, as the connection writes them.
fn write_tick<V: ClientVersion>(
    out: &[Outbound],
    wire: &mut V::Wire,
    finishes: &mut Vec<i32>,
) -> Option<i32> {
    let mut enc = ghast_protocol::FrameEncoder::new();
    V::prepare_play(out, wire);
    for o in out {
        V::write_play(&mut enc, o, wire).unwrap();
        if matches!(
            o,
            Outbound::Dig {
                status: DigStatus::Finish,
                ..
            }
        ) {
            finishes.push(V::prediction_sequence(wire).unwrap());
        }
    }
    V::prediction_sequence(wire)
}

/// The left button breaks the block under the feet; the engine numbers the prediction like
/// the wire numbers the finish. The server refuses: its ack restores the block while the
/// player falls into the hole, and the player returns to where it stood (`syncBlockState`).
fn dig_refused<V: ClientVersion>(v: GameVersion)
where
    V::Wire: Default,
{
    let mut e = modern(v);
    let stone = u32::from(state(v, "stone"));
    let under = BlockPos::new(8, 63, 8);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut wire = V::Wire::default();
    // Some predictions before (the numbers do not start at 0).
    for _ in 0..3 {
        let _ = V::write_play(
            &mut ghast_protocol::FrameEncoder::new(),
            &Outbound::UseItem {
                off_hand: false,
                held: None,
            },
            &mut wire,
        );
    }
    e.note_sequence(V::prediction_sequence(&wire));
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        ctx.set_aim(90.0, 89.5);
        let down = ctx.target().is_some_and(|t| t.pos == under);
        ctx.set_buttons(Buttons {
            left: down,
            right: false,
        });
    });
    let mut finishes = Vec::new();
    let mut ticks = 0;
    while finishes.is_empty() {
        e.tick(&mut b, t0);
        let seq = write_tick::<V>(e.outbound(), &mut wire, &mut finishes);
        e.outbound().clear();
        e.note_sequence(seq);
        ticks += 1;
        assert!(ticks < 400, "no finish: {v:?}");
    }
    assert_eq!(block(&e, under), Some(0), "{v:?}");
    // Falling into the hole.
    for _ in 0..3 {
        e.tick(&mut b, t0);
        let seq = write_tick::<V>(e.outbound(), &mut wire, &mut finishes);
        e.outbound().clear();
        e.note_sequence(seq);
    }
    assert!(e.core.pose.pos.y < 64.0, "{v:?} {:?}", e.core.pose.pos);
    let finish = finishes[0];
    // An ack below the finish's number leaves it (the start's prediction broke nothing).
    e.sim.world_packet(&ack(v, finish - 1)).unwrap();
    e.sync_snap();
    assert_eq!(block(&e, under), Some(0), "{v:?}");
    e.sim.world_packet(&ack(v, finish)).unwrap();
    e.sync_snap();
    assert_eq!(block(&e, under), Some(stone), "{v:?}");
    assert_eq!(e.core.pose.pos, FEET, "moved back: {v:?}");
    // The physics continues from there: standing on the stone again.
    e.tick(&mut b, t0);
    assert!(e.core.pose.pos.y >= 64.0, "{v:?} {:?}", e.core.pose.pos);
}

#[test]
fn refused_dig_restores_and_moves_back_26_1() {
    dig_refused::<crate::version::V26_1>(GameVersion::V26_1);
}

#[cfg(feature = "v26_2")]
#[test]
fn refused_dig_restores_and_moves_back_26_2() {
    dig_refused::<crate::version::V26_2>(GameVersion::V26_2);
}
#[cfg(feature = "v26_3")]
#[test]
fn refused_dig_restores_and_moves_back_26_3() {
    dig_refused::<crate::version::V26_3>(GameVersion::V26_3);
}

/// A server teleport after the prediction: the ack restores the block but does not move the
/// player (`lastTeleportSequence < sequence` fails); a block that does not hold the player never
/// moves it.
#[test]
fn teleport_after_prediction_keeps_the_position() {
    for v in modern_versions() {
        let mut e = modern(v);
        let under = BlockPos::new(8, 63, 8);
        e.note_sequence(Some(5));
        predict(&mut e, under, 5);
        let inside = Teleport {
            x: 8.5,
            y: 63.5,
            z: 8.5,
            yaw: 90.0,
            pitch: 0.0,
            flags: 0,
            teleport_id: Some(3),
            ..Default::default()
        };
        e.handle(Inbound::Teleport(inside));
        e.sim.world_packet(&ack(v, 5)).unwrap();
        e.sync_snap();
        assert_ne!(block(&e, under), Some(0), "{v:?}");
        assert_eq!(e.core.pose.pos.y, 63.5, "{v:?}");

        // A later prediction (sequence 6 > the teleport's 5) moves the player back.
        predict(&mut e, C, 6);
        e.sim
            .dig_sent(under, DigStatus::Finish, true, 6, Vec3::new(8.5, 70.0, 8.5));
        e.sim.world_packet(&ack(v, 6)).unwrap();
        e.sync_snap();
        assert_eq!(e.core.pose.pos.y, 70.0, "{v:?}");
        // C did not hold the player: no move for it (none pending any more).
        assert!(e.sim.take_snap().is_none());
    }
}

/// 1.16.5 `acknowledge_player_digging`.
mod v1_16_5 {
    use super::*;
    use ghast_protocol::v1_16_5::play::clientbound as cb;

    const STONE: u16 = 1;
    const START: i32 = 0;
    const FINISH: i32 = 2;

    fn answer(pos: BlockPos, block: u16, status: i32, successful: bool) -> RawPacket {
        RawPacket::from_packet(&cb::AcknowledgePlayerDigging {
            location: pos,
            block: i32::from(block),
            status,
            successful,
        })
        .unwrap()
    }

    fn set(e: &mut Engine<Box<dyn Sim>>, pos: BlockPos, s: u16) {
        e.sim
            .world_packet(
                &RawPacket::from_packet(&cb::BlockChange {
                    location: pos,
                    r#type: i32::from(s),
                })
                .unwrap(),
            )
            .unwrap();
    }

    fn joined() -> Engine<Box<dyn Sim>> {
        let mut e = engine(GameVersion::V1_16_5);
        join(&mut e);
        for p in [A, B, C] {
            set(&mut e, p, STONE);
        }
        e
    }

    /// Refused: the server's state comes back; approved with the same state: nothing to do.
    #[test]
    fn refused_finish_restores() {
        let mut e = joined();
        e.sim.dig_sent(A, DigStatus::Finish, true, 0, FEET);
        assert_eq!(block(&e, A), Some(0));
        e.sim
            .world_packet(&answer(A, STONE, FINISH, false))
            .unwrap();
        assert_eq!(block(&e, A), Some(u32::from(STONE)));

        e.sim.dig_sent(B, DigStatus::Finish, true, 0, FEET);
        e.sim.world_packet(&answer(B, 0, FINISH, true)).unwrap();
        assert_eq!(block(&e, B), Some(0));
        e.sync_snap();
        assert_eq!(e.core.pose.pos, FEET);
    }

    /// `breakBlock` leaves the block's fluid (a waterlogged block: a water source).
    #[test]
    fn broken_waterlogged_block_leaves_water() {
        use ghast_data::v1_16_5::{Block, Property};
        let mut e = joined();
        let stairs = |w: &str| {
            Block::from_name("oak_stairs")
                .unwrap()
                .state_with(&[(Property::from_name("waterlogged").unwrap(), w)])
                .unwrap()
                .id()
        };
        let id = |n: &str| Block::from_name(n).unwrap().default_state().id();
        let wet = stairs("true");
        set(&mut e, A, wet);
        e.sim.dig_sent(A, DigStatus::Finish, true, 0, FEET);
        assert_eq!(block(&e, A), Some(u32::from(id("water"))));
        e.sim.world_packet(&answer(A, wet, FINISH, false)).unwrap();
        assert_eq!(block(&e, A), Some(u32::from(wet)));
        set(&mut e, B, stairs("false"));
        e.sim.dig_sent(B, DigStatus::Finish, true, 0, FEET);
        assert_eq!(block(&e, B), Some(0));
    }

    /// The left button on a waterlogged block: the engine's dig path leaves water too.
    #[test]
    fn left_button_on_a_waterlogged_block_leaves_water() {
        use ghast_data::v1_16_5::{Block, Property};
        let mut e = joined();
        let wet = Block::from_name("oak_stairs")
            .unwrap()
            .state_with(&[(Property::from_name("waterlogged").unwrap(), "true")])
            .unwrap()
            .id();
        let water = Block::from_name("water").unwrap().default_state().id();
        let under = BlockPos::new(8, 63, 8);
        set(&mut e, under, wet);
        let t0 = Instant::now();
        e.note_inbound(t0);
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_aim(90.0, 89.5);
            let down = ctx.target().is_some_and(|t| t.pos == under);
            ctx.set_buttons(Buttons {
                left: down,
                right: false,
            });
        });
        let mut ticks = 0;
        while block(&e, under) == Some(u32::from(wet)) {
            e.tick(&mut b, t0);
            e.outbound().clear();
            ticks += 1;
            assert!(ticks < 400, "no finish");
        }
        assert_eq!(block(&e, under), Some(u32::from(water)));
    }

    /// An approved start the client recorded keeps the client's state (an instant break stays
    /// air although the answer carries the state before); without a record, or refused, the
    /// server's state is set.
    #[test]
    fn approved_start_keeps_the_client_state() {
        let mut e = joined();
        e.sim.dig_sent(A, DigStatus::Start, true, 0, FEET);
        e.sim.world_packet(&answer(A, STONE, START, true)).unwrap();
        assert_eq!(block(&e, A), Some(0));
        // The record is gone: the same answer again sets the state.
        e.sim.world_packet(&answer(A, STONE, START, true)).unwrap();
        assert_eq!(block(&e, A), Some(u32::from(STONE)));

        e.sim.dig_sent(B, DigStatus::Start, true, 0, FEET);
        e.sim.world_packet(&answer(B, STONE, START, false)).unwrap();
        assert_eq!(block(&e, B), Some(u32::from(STONE)));

        // Keyed by action: a finish answer does not match a recorded start.
        e.sim.dig_sent(C, DigStatus::Start, true, 0, FEET);
        e.sim.world_packet(&answer(C, STONE, FINISH, true)).unwrap();
        assert_eq!(block(&e, C), Some(u32::from(STONE)));
    }

    /// A restored block that holds the player moves it to where it was when the action was
    /// sent; a block beside it does not.
    #[test]
    fn restored_block_moves_the_player_back() {
        let mut e = joined();
        let at_feet = BlockPos::new(8, 64, 8);
        let back = Vec3::new(8.5, 66.0, 8.5);
        e.sim.dig_sent(A, DigStatus::Finish, true, 0, back);
        e.sim
            .world_packet(&answer(A, STONE, FINISH, false))
            .unwrap();
        e.sync_snap();
        assert_eq!(e.core.pose.pos, FEET);
        e.sim.dig_sent(at_feet, DigStatus::Abort, false, 0, back);
        e.sim
            .world_packet(&answer(at_feet, STONE, 1, true))
            .unwrap();
        e.sync_snap();
        assert_eq!(block(&e, at_feet), Some(u32::from(STONE)));
        assert_eq!(e.core.pose.pos, back);
    }

    /// The move-back uses the player's collision context: scaffolding the player stands inside
    /// has no shape for it (no move), stone does.
    #[test]
    fn move_back_uses_the_players_collision_context() {
        use ghast_data::v1_16_5::{Block, Property};
        let mut e = joined();
        let at_feet = BlockPos::new(8, 64, 8);
        let back = Vec3::new(8.5, 66.0, 8.5);
        let scaffolding = Block::from_name("scaffolding")
            .unwrap()
            .state_with(&[
                (Property::from_name("distance").unwrap(), "0"),
                (Property::from_name("bottom").unwrap(), "false"),
            ])
            .unwrap()
            .id();
        e.sim.dig_sent(at_feet, DigStatus::Finish, true, 0, back);
        e.sim
            .world_packet(&answer(at_feet, scaffolding, FINISH, false))
            .unwrap();
        e.sync_snap();
        assert_eq!(block(&e, at_feet), Some(u32::from(scaffolding)));
        assert_eq!(e.core.pose.pos, FEET, "inside scaffolding");
        set(&mut e, at_feet, 0);
        e.sim.dig_sent(at_feet, DigStatus::Finish, true, 0, back);
        e.sim
            .world_packet(&answer(at_feet, STONE, FINISH, false))
            .unwrap();
        e.sync_snap();
        assert_eq!(e.core.pose.pos, back, "inside stone");
    }

    /// The left button records its start and finish with the position before the tick's
    /// movement; the refused finish brings the block back under the falling player and
    /// moves it back up.
    #[test]
    fn refused_dig_with_the_left_button() {
        let mut e = joined();
        let under = BlockPos::new(8, 63, 8);
        set(&mut e, under, STONE);
        let t0 = Instant::now();
        e.note_inbound(t0);
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_aim(90.0, 89.5);
            let down = ctx.target().is_some_and(|t| t.pos == under);
            ctx.set_buttons(Buttons {
                left: down,
                right: false,
            });
        });
        let mut ticks = 0;
        while block(&e, under) != Some(0) {
            e.tick(&mut b, t0);
            e.outbound().clear();
            ticks += 1;
            assert!(ticks < 400, "no finish");
        }
        for _ in 0..3 {
            e.tick(&mut b, t0);
            e.outbound().clear();
        }
        assert!(e.core.pose.pos.y < 64.0, "{:?}", e.core.pose.pos);
        // The start's approval changes nothing (the client's air stays).
        e.sim
            .world_packet(&answer(under, STONE, START, true))
            .unwrap();
        e.sync_snap();
        assert_eq!(block(&e, under), Some(0));
        e.sim
            .world_packet(&answer(under, STONE, FINISH, false))
            .unwrap();
        e.sync_snap();
        assert_eq!(block(&e, under), Some(u32::from(STONE)));
        assert_eq!(e.core.pose.pos, FEET);
    }
}

/// Holds 16 of `item` in hotbar slot 0, right-clicks the top of the floor block two blocks in
/// front with [`TickContext::place`] and returns the engine with the placement written.
fn place_on_floor(v: GameVersion, item_id: i32) -> (Engine<Box<dyn Sim>>, BlockPos) {
    place_on_floor_in(v, item_id, false)
}

/// [`place_on_floor`], in creative mode with `creative`.
fn place_on_floor_in(
    v: GameVersion,
    item_id: i32,
    creative: bool,
) -> (Engine<Box<dyn Sim>>, BlockPos) {
    let mut e = engine(v);
    join(&mut e);
    if creative {
        e.handle(Inbound::GameState {
            reason: 3,
            value: 1.0,
        });
    }
    let support = BlockPos::new(8, 63, 10);
    if v == GameVersion::V1_16_5 {
        // The 1.16.5 test chunks are empty: a floor under the player and the support.
        for z in 7..=10 {
            legacy_set(&mut e, v, BlockPos::new(8, 63, z), 1);
        }
    }
    e.inventory_mut()
        .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item_id, 16, 0)));
    let t0 = Instant::now();
    e.note_inbound(t0);
    let hit = Vec3::new(8.5, 64.0, 10.5);
    let mut placed = false;
    for _ in 0..40 {
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_aim(0.0, 39.0);
            if ctx.place(support, crate::common::Face::Up, hit) {
                ctx.set_aim(0.0, 39.0);
            }
        });
        e.tick(&mut b, t0);
        placed = e
            .outbound()
            .iter()
            .any(|o| matches!(o, Outbound::Place { pos, .. } if *pos == support));
        e.outbound().clear();
        if placed {
            break;
        }
    }
    assert!(placed, "no placement: {v:?}");
    (e, BlockPos::new(8, 64, 10))
}

/// A placement the server refuses with its ack alone: the block shows at once and goes when
/// the ack comes; an accepted one (the server's update, then the ack) never flickers.
#[test]
fn placed_block_is_predicted_and_settled_by_the_ack() {
    for v in modern_versions() {
        let stone_item = match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => {
                i32::from(ghast_data::v26_2::Item::from_name("stone").unwrap().id())
            }
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => {
                i32::from(ghast_data::v26_3::Item::from_name("stone").unwrap().id())
            }
            _ => i32::from(ghast_data::v26_1::Item::from_name("stone").unwrap().id()),
        };
        let stone = state(v, "stone");
        let (mut e, at) = place_on_floor(v, stone_item);
        assert_eq!(block(&e, at), Some(u32::from(stone)), "predicted: {v:?}");
        // Refused: the ack alone restores the air.
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, at), Some(0), "{v:?}");

        let (mut e, at) = place_on_floor(v, stone_item);
        e.sim.world_packet(&block_update(v, at, stone)).unwrap();
        assert_eq!(block(&e, at), Some(u32::from(stone)), "{v:?}");
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, at), Some(u32::from(stone)), "{v:?}");
        // Not a block item: nothing predicted.
        let stick = match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => {
                i32::from(ghast_data::v26_2::Item::from_name("stick").unwrap().id())
            }
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => {
                i32::from(ghast_data::v26_3::Item::from_name("stick").unwrap().id())
            }
            _ => i32::from(ghast_data::v26_1::Item::from_name("stick").unwrap().id()),
        };
        let (e, at) = place_on_floor(v, stick);
        assert_eq!(block(&e, at), Some(0), "{v:?}");
        // Oak logs place along the clicked face's axis (the top: y).
        let log = match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => {
                i32::from(ghast_data::v26_2::Item::from_name("oak_log").unwrap().id())
            }
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => {
                i32::from(ghast_data::v26_3::Item::from_name("oak_log").unwrap().id())
            }
            _ => i32::from(ghast_data::v26_1::Item::from_name("oak_log").unwrap().id()),
        };
        let (e, at) = place_on_floor(v, log);
        assert_eq!(block(&e, at), Some(u32::from(state(v, "oak_log"))), "{v:?}");
    }
}

/// A server block change on 1.8.9 – 1.16.5 (raw `id << 4 | meta` there, a state id on 1.16.5).
fn legacy_set(e: &mut Engine<Box<dyn Sim>>, v: GameVersion, pos: BlockPos, s: u32) {
    let raw = match v {
        GameVersion::V1_8_9 => {
            RawPacket::from_packet(&ghast_protocol::v1_8::play::clientbound::BlockChange {
                location: pos,
                r#type: s as i32,
            })
        }
        GameVersion::V1_12_2 => {
            RawPacket::from_packet(&ghast_protocol::v1_12_2::play::clientbound::BlockChange {
                location: pos,
                r#type: s as i32,
            })
        }
        _ => RawPacket::from_packet(&ghast_protocol::v1_16_5::play::clientbound::BlockChange {
            location: pos,
            r#type: s as i32,
        }),
    };
    e.sim.world_packet(&raw.unwrap()).unwrap();
}

/// 1.8.9 – 1.16.5: the placed block shows at once; the server's block change for it settles
/// it (refused: back to air; accepted: the same block, no flicker). Logs place along the
/// clicked face's axis (the top: y); wool (variants) too (the oracle-proven rules,
/// `ghast_data::v1_8::place`, `v1_12::place`).
#[test]
fn placed_block_is_predicted_on_legacy_versions() {
    let cases: [(GameVersion, i32, u32, &[i32]); 6] = [
        // cobblestone item 4 → raw 4 << 4; stick 280: not predicted.
        (GameVersion::V1_8_9, 4, 4 << 4, &[280]),
        (GameVersion::V1_12_2, 4, 4 << 4, &[280]),
        // logs 17: axis y = meta 0
        (GameVersion::V1_8_9, 17, 17 << 4, &[]),
        (GameVersion::V1_12_2, 17, 17 << 4, &[]),
        (
            GameVersion::V1_16_5,
            i32::from(
                ghast_data::v1_16_5::Item::from_name("oak_log")
                    .unwrap()
                    .id(),
            ),
            u32::from(
                ghast_data::v1_16_5::Block::from_name("oak_log")
                    .unwrap()
                    .default_state()
                    .id(),
            ),
            &[],
        ),
        (
            GameVersion::V1_16_5,
            i32::from(
                ghast_data::v1_16_5::Item::from_name("cobblestone")
                    .unwrap()
                    .id(),
            ),
            u32::from(
                ghast_data::v1_16_5::Block::from_name("cobblestone")
                    .unwrap()
                    .default_state()
                    .id(),
            ),
            &[
                i32::from(
                    ghast_data::v1_16_5::Item::from_name("grass_block")
                        .unwrap()
                        .id(),
                ),
                i32::from(ghast_data::v1_16_5::Item::from_name("stick").unwrap().id()),
            ],
        ),
    ];
    for (v, item, placed, others) in cases {
        let (mut e, at) = place_on_floor(v, item);
        assert_eq!(block(&e, at), Some(placed), "predicted: {v:?}");
        legacy_set(&mut e, v, at, 0);
        assert_eq!(block(&e, at), Some(0), "refused: {v:?}");
        let (mut e, at) = place_on_floor(v, item);
        legacy_set(&mut e, v, at, placed);
        assert_eq!(block(&e, at), Some(placed), "accepted: {v:?}");
        for &o in others {
            let (e, at) = place_on_floor(v, o);
            assert_eq!(block(&e, at), Some(0), "{v:?} item {o}");
        }
    }
}

/// A placement predicted on the client also uses one item of the held stack there (vanilla
/// `BlockItem.place` / `ItemBlock.onItemUse`), on every version; one left to the server keeps
/// the count until the server's `set_slot`, and creative keeps the stack.
#[test]
fn predicted_placement_uses_the_item() {
    let item = |v: GameVersion, name: &str| -> i32 {
        match v {
            GameVersion::V1_8_9 | GameVersion::V1_12_2 => match name {
                "cobblestone" => 4,
                _ => 2,
            },
            GameVersion::V1_16_5 => {
                i32::from(ghast_data::v1_16_5::Item::from_name(name).unwrap().id())
            }
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => i32::from(ghast_data::v26_2::Item::from_name(name).unwrap().id()),
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => i32::from(ghast_data::v26_3::Item::from_name(name).unwrap().id()),
            _ => i32::from(ghast_data::v26_1::Item::from_name(name).unwrap().id()),
        }
    };
    let held = |e: &Engine<Box<dyn Sim>>| e.core.inv.held().map(ghast_inventory::Stack::count);
    let mut versions = vec![
        GameVersion::V1_8_9,
        GameVersion::V1_12_2,
        GameVersion::V1_16_5,
    ];
    versions.extend(modern_versions());
    for v in versions {
        let (e, at) = place_on_floor(v, item(v, "cobblestone"));
        assert_ne!(block(&e, at), Some(0), "predicted: {v:?}");
        assert_eq!(held(&e), Some(15), "{v:?}");
        // a grass block (1.8.9: an enchanting table, its rules place grass): not predicted,
        // the count waits for the server
        let unpredicted = if v == GameVersion::V1_8_9 {
            116
        } else {
            item(v, "grass_block")
        };
        let (e, at) = place_on_floor(v, unpredicted);
        assert_eq!(block(&e, at), Some(0), "{v:?}");
        assert_eq!(held(&e), Some(16), "{v:?}");
        // creative: placed, the stack stays
        let (e, at) = place_on_floor_in(v, item(v, "cobblestone"), true);
        assert_eq!(e.core.game_mode, GameMode::Creative, "{v:?}");
        assert_ne!(block(&e, at), Some(0), "creative predicted: {v:?}");
        assert_eq!(held(&e), Some(16), "creative: {v:?}");
    }
}

/// 1.8.9 / 1.12.2 logs: the item's variant (`damage & 3`) with the clicked face's axis in the
/// meta (`BlockLog.onBlockPlaced`); a variant the block does not have is left to the server.
#[test]
fn legacy_logs_take_the_face_axis_and_variant() {
    use crate::common::Face;
    for v in [GameVersion::V1_8_9, GameVersion::V1_12_2] {
        let mut e = engine(v);
        join(&mut e);
        let clicked = BlockPos::new(8, 65, 12);
        // (item, damage, face) -> raw placed
        let cases: [(i32, i16, Face, Option<u32>); 6] = [
            (17, 2, Face::East, Some(17 << 4 | 2 | 4)),
            (17, 6, Face::North, Some(17 << 4 | 2 | 8)),
            (17, 1, Face::Down, Some(17 << 4 | 1)),
            (162, 1, Face::West, Some(162 << 4 | 1 | 4)),
            (162, 2, Face::East, None),
            (170, 3, Face::South, Some(170 << 4 | 8)),
        ];
        for (item, damage, face, want) in cases {
            let at = face.offset(clicked);
            legacy_set(&mut e, v, clicked, 1 << 4);
            legacy_set(&mut e, v, at, 0);
            let held = ghast_inventory::Stack::new(item, 8, damage);
            let placed = e.sim.place_sent(&crate::sim::predict::PlaceSent {
                pos: clicked,
                face,
                held: Some(&held),
                sneaking: false,
                any_item: true,
                game_mode: GameMode::Survival,
                sequence: 0,
                player: e.core.pose.pos,
                cursor: [0.5, 1.0, 0.5],
                yaw: 0.0,
            });
            assert_eq!(placed, want.is_some(), "{v:?} {item}:{damage} {face:?}");
            assert_eq!(
                block(&e, at),
                Some(want.unwrap_or(0)),
                "{v:?} {item}:{damage} {face:?}"
            );
        }
    }
}

/// Switching to spectator stops an item use only on 26.x (the server's `stopUsingItem`);
/// 1.8.9 – 1.16.5 keep it until release or finish.
#[test]
fn spectator_switch_stops_a_use_only_on_26_x() {
    let mut versions = vec![
        (GameVersion::V1_8_9, false),
        (GameVersion::V1_12_2, false),
        (GameVersion::V1_16_5, false),
        (GameVersion::V26_1, true),
    ];
    #[cfg(feature = "v26_2")]
    versions.push((GameVersion::V26_2, true));
    #[cfg(feature = "v26_3")]
    versions.push((GameVersion::V26_3, true));
    for (v, stops) in versions {
        let mut e = engine(v);
        join(&mut e);
        e.core.hands.test_start_using(1);
        assert!(e.core.hands.using_item(), "{v:?}");
        e.handle(Inbound::GameState {
            reason: 3,
            value: 3.0,
        });
        assert_eq!(e.core.game_mode, GameMode::Spectator, "{v:?}");
        assert_eq!(e.core.hands.using_item(), !stops, "{v:?}");
    }
}

/// 1.8.9 / 1.12.2 `canPlaceItemBlock` before the block packet: decided for a spot that is not
/// replaceable and for a full-cube block in the player's box; anvils, slabs and non-block items
/// are left alone. `ctx.place` then sends nothing.
#[test]
fn legacy_client_suppresses_unplaceable_blocks() {
    use crate::common::Face;
    for v in [GameVersion::V1_8_9, GameVersion::V1_12_2] {
        let mut e = engine(v);
        join(&mut e);
        let under = BlockPos::new(8, 63, 8);
        let ahead = BlockPos::new(8, 63, 10);
        // Into the player's own box (cobblestone 4, stone 1 with its variants).
        assert!(e.sim.place_suppressed(under, Face::Up, 4), "{v:?}");
        assert!(e.sim.place_suppressed(under, Face::Up, 1), "{v:?}");
        // Free air.
        assert!(!e.sim.place_suppressed(ahead, Face::Up, 4), "{v:?}");
        // The spot next to the face is stone: no block item fits (torch 50 too).
        assert!(e.sim.place_suppressed(ahead, Face::North, 4), "{v:?}");
        assert!(e.sim.place_suppressed(ahead, Face::North, 50), "{v:?}");
        // Not decided: anvil, stone slab; not a block item: stick.
        assert!(!e.sim.place_suppressed(ahead, Face::North, 145), "{v:?}");
        assert!(!e.sim.place_suppressed(ahead, Face::North, 44), "{v:?}");
        assert!(!e.sim.place_suppressed(ahead, Face::North, 280), "{v:?}");
        // A torch has no collision box: it may go into the player's box.
        assert!(!e.sim.place_suppressed(under, Face::Up, 50), "{v:?}");
        // Tall grass is replaced itself: the spot is the grass, not the block above.
        legacy_set(&mut e, v, BlockPos::new(8, 64, 10), 31 << 4 | 1);
        assert!(
            !e.sim
                .place_suppressed(BlockPos::new(8, 64, 10), Face::Up, 4),
            "{v:?}"
        );
    }
    // 1.16.5 has no such check.
    let mut e = engine(GameVersion::V1_16_5);
    join(&mut e);
    assert!(!e.sim.place_suppressed(BlockPos::new(8, 63, 8), Face::Up, 1));
}

/// 1.12.2 with entity tracking: a cow standing in the spot (client position) makes vanilla's
/// `hasEntityIn` fail, so no block packet; without tracking the cow is unknown and the packet
/// is sent as before. 1.8.9 never decides other entities.
#[test]
fn tracked_entity_in_the_spot_suppresses_on_1_12_2() {
    use crate::common::Face;
    use ghast_protocol::v1_12_2::play::clientbound as cb;
    let cow = |id: i32| {
        RawPacket::from_packet(&cb::SpawnEntityLiving {
            entity_id: id,
            entity_uuid: uuid::Uuid::from_u128(0x636f_7700 + id as u128),
            r#type: 92,
            x: 8.5,
            y: 64.0,
            z: 10.5,
            yaw: 0,
            pitch: 0,
            head_pitch: 0,
            velocity: ghast_protocol::defs::p47::types::Vec3i16 { x: 0, y: 0, z: 0 },
            metadata: Vec::new(),
        })
        .unwrap()
    };
    let ahead = BlockPos::new(8, 63, 10);
    let mut e = engine(GameVersion::V1_12_2);
    join(&mut e);
    e.sim.world_packet(&cow(50)).unwrap();
    assert!(!e.sim.place_suppressed(ahead, Face::Up, 4), "tracking off");
    e.sim.set_entities(Some(ghast_entity::Config::default()));
    e.sim.world_packet(&cow(51)).unwrap();
    assert!(e.sim.place_suppressed(ahead, Face::Up, 4));
    // A torch has no collision box: the cow does not matter.
    assert!(!e.sim.place_suppressed(ahead, Face::Up, 50));
    // The cow's box ends at x 8.95: the spot west of it is free.
    assert!(
        !e.sim
            .place_suppressed(BlockPos::new(9, 63, 10), Face::Up, 4)
    );

    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    e.sim.set_entities(Some(ghast_entity::Config::default()));
    let raw = RawPacket::from_packet(
        &ghast_protocol::v1_8::play::clientbound::SpawnEntityLiving {
            entity_id: 51,
            r#type: 92,
            x: 8 * 32 + 16,
            y: 64 * 32,
            z: 10 * 32 + 16,
            yaw: 0,
            pitch: 0,
            head_pitch: 0,
            velocity: ghast_protocol::defs::p47::types::Vec3i16 { x: 0, y: 0, z: 0 },
            metadata: Vec::new(),
        },
    )
    .unwrap();
    e.sim.world_packet(&raw).unwrap();
    assert!(
        !e.sim.place_suppressed(ahead, Face::Up, 4),
        "1.8.9: not decided"
    );
}

/// `ctx.place` into the player's own box on 1.8.9 / 1.12.2 writes nothing and reports it.
#[test]
fn legacy_place_into_the_player_is_refused() {
    for v in [GameVersion::V1_8_9, GameVersion::V1_12_2] {
        let mut e = engine(v);
        join(&mut e);
        e.inventory_mut()
            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(4, 16, 0)));
        let t0 = Instant::now();
        e.note_inbound(t0);
        let under = BlockPos::new(8, 63, 8);
        let mut tried = 0;
        let mut accepted = false;
        for _ in 0..20 {
            let mut b = Script(|ctx: &mut TickContext<'_>| {
                ctx.set_aim(0.0, 90.0);
                if ctx.target().is_some_and(|t| t.pos == under) {
                    tried += 1;
                    accepted |=
                        ctx.place(under, crate::common::Face::Up, Vec3::new(8.5, 64.0, 8.5));
                }
            });
            e.tick(&mut b, t0);
            assert!(
                !e.outbound()
                    .iter()
                    .any(|o| matches!(o, Outbound::Place { .. })),
                "{v:?}"
            );
            e.outbound().clear();
        }
        assert!(tried > 0 && !accepted, "{v:?}");
    }
}

/// Replays of the oracle's right clicks (`tests/golden/<version>/place.jsonl.gz`, the real
/// client's `MultiPlayerGameMode.useItemOn` and its prediction records): every placement this
/// client predicts is the vanilla one, and after the server's answer (an ack alone, a block
/// update then the ack, or the client's own state then the ack, with the player moved in
/// between) the clicked block, the target block and the player's position are vanilla's.
mod place_golden {
    use super::*;
    use serde_json::Value;
    use std::io::BufRead;

    /// The golden's player stands at (0.5, 64, 0.5); the test engine's at (8.5, 64, 8.5).
    const SHIFT: i32 = 8;

    fn f64_of(v: &Value) -> f64 {
        let bits = v[1].as_str().expect("hex bits");
        f64::from_bits(u64::from_str_radix(bits, 16).expect("hex"))
    }

    fn pos_of(v: &Value) -> BlockPos {
        BlockPos::new(
            v[0].as_i64().unwrap() as i32 + SHIFT,
            v[1].as_i64().unwrap() as i32,
            v[2].as_i64().unwrap() as i32 + SHIFT,
        )
    }

    fn vec_of(v: &Value) -> Vec3 {
        Vec3::new(
            f64_of(&v[0]) + f64::from(SHIFT),
            f64_of(&v[1]),
            f64_of(&v[2]) + f64::from(SHIFT),
        )
    }

    fn item_id(v: GameVersion, name: &str) -> i32 {
        match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => i32::from(ghast_data::v26_2::Item::from_name(name).unwrap().id()),
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => i32::from(ghast_data::v26_3::Item::from_name(name).unwrap().id()),
            _ => i32::from(ghast_data::v26_1::Item::from_name(name).unwrap().id()),
        }
    }

    fn block_name(v: GameVersion, id: u32) -> String {
        match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => ghast_data::v26_2::BlockState::from_id(id as u16)
                .unwrap()
                .block()
                .name()
                .to_string(),
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => ghast_data::v26_3::BlockState::from_id(id as u16)
                .unwrap()
                .block()
                .name()
                .to_string(),
            _ => ghast_data::v26_1::BlockState::from_id(id as u16)
                .unwrap()
                .block()
                .name()
                .to_string(),
        }
    }

    fn replay(v: GameVersion, label: &str) {
        let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("../../tests/golden")
            .join(label)
            .join("place.jsonl.gz");
        let Ok(file) = std::fs::File::open(&path) else {
            panic!("missing {}", path.display());
        };
        let lines = std::io::BufReader::new(flate2::read::GzDecoder::new(file)).lines();
        let mut e = modern(v);
        let mut n = 0;
        let mut predicted = 0;
        let mut vanilla_placed = 0;
        let mut missed: std::collections::BTreeMap<String, u32> = Default::default();
        let mut sequence = 0;
        let mut bad = Vec::new();
        // Predictions where vanilla also changed neighbours (shape updates).
        let mut extra: std::collections::BTreeMap<String, u32> = Default::default();
        for line in lines {
            let c: Value = serde_json::from_str(&line.unwrap()).unwrap();
            n += 1;
            let k = c["k"].as_i64().unwrap();
            let clicked = pos_of(&c["clicked"]);
            let face = crate::common::Face::from_id(c["face"].as_i64().unwrap() as i8).unwrap();
            let target = face.offset(clicked);
            let (cs, ts) = (
                c["clicked_state"].as_u64().unwrap() as u16,
                c["target_state"].as_u64().unwrap() as u16,
            );
            // Nothing predicted from the case before; the case's blocks.
            sequence += 1;
            e.sim.world_packet(&ack(v, i32::MAX >> 1)).unwrap();
            let _ = e.sim.take_snap();
            for p in [clicked, target] {
                let d = (p.x - SHIFT).abs().max((p.z - SHIFT).abs());
                let floor = if p.y == 63 && d <= 4 {
                    state(v, "stone")
                } else {
                    0
                };
                e.sim.world_packet(&block_update(v, p, floor)).unwrap();
            }
            e.sim.world_packet(&block_update(v, clicked, cs)).unwrap();
            e.sim.world_packet(&block_update(v, target, ts)).unwrap();
            let player = vec_of(&c["player"]);
            e.sim.set_player_pos(player);
            let held = c["held"].as_str().map(|name| {
                ghast_inventory::Stack::new(
                    item_id(v, name),
                    c["count"].as_i64().unwrap() as i32,
                    0,
                )
            });
            let game_mode = match c["mode"].as_str().unwrap() {
                "survival" => GameMode::Survival,
                "creative" => GameMode::Creative,
                "adventure" => GameMode::Adventure,
                _ => GameMode::Spectator,
            };
            e.sim.place_sent(&crate::sim::predict::PlaceSent {
                pos: clicked,
                face,
                held: held.as_ref(),
                sneaking: c["sneaking"].as_bool().unwrap(),
                any_item: held.is_some(),
                game_mode,
                sequence,
                player,
                cursor: [0.5, 1.0, 0.5],
                yaw: 0.0,
            });
            let ours = block(&e, target).unwrap();
            let changed: Vec<(BlockPos, u32)> = c["changed"]
                .as_array()
                .unwrap()
                .iter()
                .map(|x| (pos_of(&x[0]), x[1].as_u64().unwrap() as u32))
                .collect();
            let vanilla_target = changed.iter().find(|x| x.0 == target).map(|x| x.1);
            if vanilla_target.is_some() {
                vanilla_placed += 1;
            }
            let we_predicted = ours != u32::from(ts);
            if we_predicted {
                predicted += 1;
                // the client uses the item as vanilla does (the engine consumes it)
                let count = c["count"].as_i64().unwrap();
                let ours_after =
                    count - i64::from(crate::sim::predict::placing_uses_item(game_mode));
                assert_eq!(
                    ours_after,
                    c["count_after"].as_i64().unwrap(),
                    "case {k} count after: {c}"
                );
                if vanilla_target != Some(ours) || c["result"] != "Success" {
                    bad.push(format!(
                        "case {k}: predicted {} at {target:?} clicking {}, vanilla {:?} ({}): {c}",
                        block_name(v, ours),
                        block_name(v, u32::from(cs)),
                        vanilla_target.map(|s| block_name(v, s)),
                        c["result"]
                    ));
                    continue;
                }
            } else if let Some(s) = vanilla_target {
                *missed
                    .entry(format!(
                        "{} on {}",
                        block_name(v, s),
                        block_name(v, u32::from(cs))
                    ))
                    .or_default() += 1;
            }
            if we_predicted && changed.len() > 1 {
                *extra
                    .entry(format!(
                        "{} next to {:?}",
                        block_name(v, ours),
                        changed
                            .iter()
                            .filter(|x| x.0 != target)
                            .map(|x| block_name(v, x.1))
                            .collect::<Vec<_>>()
                    ))
                    .or_default() += 1;
            }
            // The answer: comparable when the client changed what vanilla changed.
            let same = changed.is_empty() && !we_predicted || we_predicted && changed.len() == 1;
            if !same {
                continue;
            }
            e.sim.set_player_pos(Vec3::new(
                player.x,
                player.y - f64_of(&c["moved"]),
                player.z,
            ));
            let update = c["update"].as_i64().unwrap();
            if update >= 0 {
                e.sim
                    .world_packet(&block_update(v, target, update as u16))
                    .unwrap();
            }
            if c["sequence"].as_i64().unwrap() >= 0 {
                e.sim.world_packet(&ack(v, sequence)).unwrap();
            }
            assert_eq!(
                block(&e, target),
                Some(c["target_after"].as_u64().unwrap() as u32),
                "case {k} target after the answer: {c}"
            );
            assert_eq!(
                block(&e, clicked),
                Some(c["clicked_after"].as_u64().unwrap() as u32),
                "case {k} clicked after the answer: {c}"
            );
            let after = vec_of(&c["player_after"]);
            let now = e.sim.take_snap().unwrap_or(Vec3::new(
                player.x,
                player.y - f64_of(&c["moved"]),
                player.z,
            ));
            assert_eq!(now, after, "case {k} player after the answer: {c}");
        }
        assert!(n > 0);
        for b in bad.iter().take(12) {
            eprintln!("{b}");
        }
        assert!(
            bad.is_empty(),
            "{label}: {} predictions differ from vanilla",
            bad.len()
        );
        eprintln!("{label}: neighbours vanilla changed too: {extra:?}");
        let mut top: Vec<_> = missed.into_iter().collect();
        top.sort_by_key(|x| std::cmp::Reverse(x.1));
        eprintln!(
            "{label}: {n} clicks, vanilla placed {vanilla_placed}, predicted {predicted} (all \
             vanilla); not predicted (top): {:?}",
            &top[..top.len().min(25)]
        );
    }

    #[test]
    fn place_golden_26_1() {
        replay(GameVersion::V26_1, "26.1");
    }

    #[cfg(feature = "v26_2")]
    #[test]
    fn place_golden_26_2() {
        replay(GameVersion::V26_2, "26.2");
    }
    #[cfg(feature = "v26_3")]
    #[test]
    fn place_golden_26_3() {
        replay(GameVersion::V26_3, "26.3");
    }
}

/// Ghost-block checks of 26.x placement predictions (`BlockStatePredictionHandler`,
/// `ClientLevel.syncBlockState`): whatever the server does with a `use_item_on` (it always acks
/// it once the client has loaded), the predicted block ends as the server's state.
mod placement_rollback {
    use super::*;
    use crate::common::Face;

    /// The column's test chunk as the server sends it (stone at y = 63, air above).
    fn chunk(v: GameVersion, x: i32, z: i32) -> RawPacket {
        match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => crate::sim::test_chunks::v26_2(x, z),
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => crate::sim::test_chunks::v26_3(x, z),
            _ => crate::sim::test_chunks::v26_1(x, z),
        }
    }

    fn stone_stack(v: GameVersion) -> ghast_inventory::Stack {
        let id = match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => ghast_data::v26_2::Item::from_name("stone").unwrap().id(),
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => ghast_data::v26_3::Item::from_name("stone").unwrap().id(),
            _ => ghast_data::v26_1::Item::from_name("stone").unwrap().id(),
        };
        ghast_inventory::Stack::new(i32::from(id), 32, 0)
    }

    /// Places stone on the top of `clicked` in prediction `sequence`; returns the target.
    fn place(
        e: &mut Engine<Box<dyn Sim>>,
        v: GameVersion,
        clicked: BlockPos,
        sequence: i32,
    ) -> BlockPos {
        let held = stone_stack(v);
        assert!(e.sim.place_sent(&crate::sim::predict::PlaceSent {
            pos: clicked,
            face: Face::Up,
            held: Some(&held),
            sneaking: false,
            any_item: true,
            game_mode: GameMode::Survival,
            sequence,
            player: FEET,
            cursor: [0.5, 1.0, 0.5],
            yaw: 0.0,
        }));
        Face::Up.offset(clicked)
    }

    /// (a) The server's hand held something else (a dirt block): its block update brings the
    /// dirt, the ack keeps it. (b) A refused `use_item_on` (out of reach, the hit point too far
    /// from the block, spawn protection): the ack alone, or the server's updates of the clicked
    /// block and the target, put the air back.
    #[test]
    fn other_item_and_refusals() {
        for v in modern_versions() {
            let stone = u32::from(state(v, "stone"));
            let dirt = state(v, "dirt");
            let mut e = modern(v);
            let t = place(&mut e, v, A, 1);
            assert_eq!(block(&e, t), Some(stone), "{v:?}");
            e.sim.world_packet(&block_update(v, t, dirt)).unwrap();
            assert_eq!(block(&e, t), Some(stone), "deferred: {v:?}");
            e.sim.world_packet(&ack(v, 1)).unwrap();
            assert_eq!(block(&e, t), Some(u32::from(dirt)), "{v:?}");

            let t = place(&mut e, v, B, 2);
            e.sim.world_packet(&ack(v, 2)).unwrap();
            assert_eq!(block(&e, t), Some(0), "ack only: {v:?}");

            let t = place(&mut e, v, C, 3);
            e.sim
                .world_packet(&block_update(v, C, stone as u16))
                .unwrap();
            e.sim.world_packet(&block_update(v, t, 0)).unwrap();
            e.sim.world_packet(&ack(v, 3)).unwrap();
            assert_eq!(block(&e, t), Some(0), "updates + ack: {v:?}");
            assert_eq!(block(&e, C), Some(stone), "{v:?}");
        }
    }

    /// (c, d) A roof row: several placements, the server acks only the last sequence of its
    /// tick; a placement and a break of the same block keep the first server state and the
    /// last sequence (`retainKnownServerState`), so an ack between them ends nothing.
    #[test]
    fn batched_acks_and_one_block_twice() {
        for v in modern_versions() {
            let stone = u32::from(state(v, "stone"));
            let mut e = modern(v);
            let row: Vec<BlockPos> = (0..4)
                .map(|i| place(&mut e, v, BlockPos::new(2 + i, 63, 12), 1 + i))
                .collect();
            // Accepted: the server's stone for the first three, the fourth refused.
            for t in &row[..3] {
                e.sim
                    .world_packet(&block_update(v, *t, stone as u16))
                    .unwrap();
            }
            e.sim.world_packet(&ack(v, 4)).unwrap();
            for t in &row[..3] {
                assert_eq!(block(&e, *t), Some(stone), "{v:?}");
            }
            assert_eq!(block(&e, row[3]), Some(0), "{v:?}");

            let t = place(&mut e, v, A, 5);
            e.sim.dig_sent(t, DigStatus::Finish, true, 6, FEET);
            assert_eq!(block(&e, t), Some(0), "{v:?}");
            e.sim.world_packet(&ack(v, 5)).unwrap();
            assert_eq!(block(&e, t), Some(0), "the break waits: {v:?}");
            // Both refused: the first server state (air) comes back.
            e.sim.world_packet(&ack(v, 6)).unwrap();
            assert_eq!(block(&e, t), Some(0), "{v:?}");
            // Accepted place, refused break: the server's stone, sent during the prediction.
            let t = place(&mut e, v, B, 7);
            e.sim.dig_sent(t, DigStatus::Finish, true, 8, FEET);
            e.sim
                .world_packet(&block_update(v, t, stone as u16))
                .unwrap();
            e.sim.world_packet(&ack(v, 8)).unwrap();
            assert_eq!(block(&e, t), Some(stone), "{v:?}");
        }
    }

    /// (e) A section update between the prediction and the ack is remembered for the
    /// predicted block; a resent chunk replaces the column, and the ack then puts back the
    /// state remembered before (vanilla: the chunk packet does not touch the records).
    #[test]
    fn section_and_chunk_between() {
        for v in modern_versions() {
            let stone = u32::from(state(v, "stone"));
            let glass = state(v, "glass");
            let mut e = modern(v);
            let t = place(&mut e, v, A, 1);
            e.sim
                .world_packet(&section_update(v, &[(t, glass)]))
                .unwrap();
            assert_eq!(block(&e, t), Some(stone), "deferred: {v:?}");
            e.sim.world_packet(&ack(v, 1)).unwrap();
            assert_eq!(block(&e, t), Some(u32::from(glass)), "{v:?}");

            // Refused, the column resent before the ack: air from the chunk, air after the ack.
            let t = place(&mut e, v, B, 2);
            e.sim.world_packet(&chunk(v, 0, 0)).unwrap();
            assert_eq!(block(&e, t), Some(0), "{v:?}");
            e.sim.world_packet(&ack(v, 2)).unwrap();
            assert_eq!(block(&e, t), Some(0), "{v:?}");
        }
    }

    /// Through the engine and the wire: placements on two ticks after some other predicting
    /// packets carry the numbers the engine predicted with, so the server's ack of the last
    /// one ends both (refused: air again).
    fn numbering<V: ClientVersion>(v: GameVersion)
    where
        V::Wire: Default,
    {
        let (mut e, at) = place_on_floor(v, i32::from(stone_stack(v).id() as u16));
        // place_on_floor wrote its packet with sequence 1 (a fresh wire numbers from 1).
        let mut wire = V::Wire::default();
        let mut finishes = Vec::new();
        let first = write_tick::<V>(
            &[Outbound::Place {
                pos: BlockPos::new(8, 63, 10),
                face: Face::Up,
                cursor: Vec3::new(0.5, 1.0, 0.5),
                held: None,
                off_hand: false,
            }],
            &mut wire,
            &mut finishes,
        );
        assert_eq!(first, Some(1), "{v:?}");
        assert_eq!(
            block(&e, at),
            Some(u32::from(state(v, "stone"))),
            "predicted: {v:?}"
        );
        e.sim.world_packet(&ack(v, 1)).unwrap();
        assert_eq!(block(&e, at), Some(0), "{v:?}");
    }

    #[test]
    fn numbering_26_1() {
        numbering::<crate::version::V26_1>(GameVersion::V26_1);
    }

    #[cfg(feature = "v26_2")]
    #[test]
    fn numbering_26_2() {
        numbering::<crate::version::V26_2>(GameVersion::V26_2);
    }
    #[cfg(feature = "v26_3")]
    #[test]
    fn numbering_26_3() {
        numbering::<crate::version::V26_3>(GameVersion::V26_3);
    }
}

/// A right click whose ray starts inside the clicked block's outline (the eyes inside a block)
/// writes `insideBlock` (vanilla `BlockHitResult.isInsideBlock`), on 26.x as on 1.16.5 (whose
/// place oracle covers it, `place_legacy.rs`).
#[test]
fn place_from_inside_a_block_writes_inside_block() {
    use ghast_protocol::frame::{FrameDecoder, FrameEncoder};
    for v in modern_versions() {
        let mut e = modern(v);
        let p = e.core.pose.pos;
        let eyes = BlockPos::new(
            p.x.floor() as i32,
            (p.y + 1.62).floor() as i32,
            p.z.floor() as i32,
        );
        e.sim
            .world_packet(&block_update(v, eyes, state(v, "glass")))
            .unwrap();
        let stone = match v {
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => {
                i32::from(ghast_data::v26_2::Item::from_name("stone").unwrap().id())
            }
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => {
                i32::from(ghast_data::v26_3::Item::from_name("stone").unwrap().id())
            }
            _ => i32::from(ghast_data::v26_1::Item::from_name("stone").unwrap().id()),
        };
        e.inventory_mut()
            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(stone, 16, 0)));
        let t0 = Instant::now();
        e.note_inbound(t0);
        let mut found = None;
        for _ in 0..10 {
            let mut b = Script(|ctx: &mut TickContext<'_>| {
                ctx.set_aim(0.0, 0.0);
                ctx.set_buttons(Buttons {
                    left: false,
                    right: true,
                });
            });
            e.tick(&mut b, t0);
            if let Some(o) = e
                .outbound()
                .iter()
                .find(|o| matches!(o, Outbound::Place { .. } | Outbound::PlaceInside { .. }))
            {
                found = Some(o.clone());
                break;
            }
            e.outbound().clear();
        }
        let o = found.unwrap_or_else(|| panic!("no placement: {v:?}"));
        assert!(
            matches!(o, Outbound::PlaceInside { pos, .. } if pos == eyes),
            "{v:?}: {o:?}"
        );
        // the wire: hand, position, face, cursor, then insideBlock = true
        let mut enc = FrameEncoder::new();
        let mut wire = Default::default();
        crate::version::V26_1::write_play(&mut enc, &o, &mut wire).unwrap();
        let mut dec = FrameDecoder::new();
        dec.push(&enc.take());
        let body = dec.next_packet().unwrap().unwrap().body;
        assert_eq!(body[1 + 8 + 1 + 12], 1, "{v:?}: insideBlock");
    }
}