ghast-client 0.5.5

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
//! The engine's own tests and the helpers every engine test module shares (`opts`, `engine`,
//! `load`, `join`, `names`, `Script`): join and teleport replies, the tick order of actions and
//! the movement packet, raw packets, the silent-server hold, panics, chat, deaths and respawns,
//! the buttons (dig, place, planting), block updates, flight, held turns, clicks, the planned
//! look, teleport events, windows, swings, the world view and `after_tick`.

use super::*;
use crate::common::Teleport;
use crate::common::{ChatPosition, EntityAction, JoinGame};
use ghast_protocol::RawPacket;

pub(super) fn opts(version: GameVersion) -> CoreOptions {
    CoreOptions {
        name: "test".into(),
        caps: version.caps(),
        settings: ClientSettings::default(),
        brand: Some("vanilla".into()),
        sensitivity: 0.5,
        silent_hold: Duration::from_millis(1500),
        hold_turn_on_action: true,
        accept_required_packs: true,
        entity_push: true,
        turn_rate: (
            crate::rotation::Rotation::MAX_YAW_PER_TICK,
            crate::rotation::Rotation::MAX_PITCH_PER_TICK,
        ),
        gui_releases_keys: true,
        inventory: match version.instance() {
            GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
            GameVersion::V1_12_2 => ghast_inventory::Version::V1_12,
            GameVersion::V26_1 => ghast_inventory::Version::V26_1,
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => ghast_inventory::Version::V26_2,
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => ghast_inventory::Version::V26_3,
            _ => ghast_inventory::Version::V1_16_5,
        },
    }
}

/// A 1.8.9 engine (physics) or a 1.16.5 one (stand-still mover).
pub(super) fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
    let sim: Box<dyn Sim> = match version.instance() {
        GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
        GameVersion::V1_12_2 => Box::new(crate::sim::Sim12::new()),
        GameVersion::V26_1 => Box::new(crate::sim::Sim26::test_overworld()),
        #[cfg(feature = "v26_2")]
        GameVersion::V26_2 => Box::new(crate::sim::Sim262::test_overworld()),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => Box::new(crate::sim::Sim263::test_overworld()),
        _ => Box::new(crate::sim::Sim16::new()),
    };
    Engine::new(opts(version), sim)
}

/// Loads the column of chunk (x, z) the way the connection does.
pub(super) fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
    let raw = match e.core.opts.caps.version.instance() {
        GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
        GameVersion::V1_12_2 => crate::sim::test_chunks::v1_12_2(x, z),
        GameVersion::V26_1 => crate::sim::test_chunks::v26_1(x, z),
        #[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::v1_16_5(x, z),
    };
    e.sim.world_packet(&raw).unwrap();
}

pub(super) fn join(e: &mut Engine<Box<dyn Sim>>) {
    e.handle(Inbound::JoinGame(JoinGame {
        entity_id: 7,
        game_mode: GameMode::Survival,
        dimension: "0".into(),
        hardcore: false,
        dimension_nbt: None,
        respawn_screen: true,
    }));
    // The player's column and its neighbours (1.21.4+ loads the level only with all nine).
    for x in -1..=1 {
        for z in -1..=1 {
            load(e, x, z);
        }
    }
    e.handle(Inbound::Teleport(Teleport {
        x: 8.5,
        y: 64.0,
        z: 8.5,
        yaw: 90.0,
        pitch: 0.0,
        flags: 0,
        teleport_id: None,
        ..Default::default()
    }));
    // 1.21.4+: the server says the level's chunks are coming (game event 13).
    e.handle(Inbound::GameState {
        reason: 13,
        value: 0.0,
    });
    // The nine columns arrived before the previous tick: the level loads on the next one.
    e.core.near_loaded = 1;
    e.outbound().clear();
}

/// Records the tick's packets as names.
pub(super) fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
    let v = out
        .iter()
        .map(|o| match o {
            Outbound::Move(m) => m.trace_id(),
            Outbound::Chat(_) => "chat",
            Outbound::HeldSlot(_) => "held_slot",
            Outbound::Swing => "swing",
            Outbound::EntityAction { .. } | Outbound::RidingJump { .. } => "entity_action",
            Outbound::KeepAlive(_) => "keep_alive",
            Outbound::Transaction { .. } => "transaction",
            Outbound::TeleportConfirm(_) | Outbound::TeleportConfirmPose { .. } => {
                "teleport_confirm"
            }
            Outbound::Punch => "punch",
            Outbound::Respawn => "respawn",
            Outbound::Settings(_) => "settings",
            Outbound::Brand(_) => "brand",
            Outbound::Abilities { .. } => "abilities",
            Outbound::Dig { .. } => "block_dig",
            Outbound::Place { .. } | Outbound::PlaceInside { .. } | Outbound::UseItem { .. } => {
                "block_place"
            }
            Outbound::SwingOffHand => "swing_off",
            Outbound::UseEntity { .. } => "use_entity",
            Outbound::Inventory(_) => "inventory",
            Outbound::PlayerInput(_) => "player_input",
            Outbound::TickEnd => "tick_end",
            Outbound::PlayerLoaded => "player_loaded",
            Outbound::ChatSessionUpdate => "chat_session_update",
            Outbound::ChunkBatchReceived(_) => "chunk_batch_received",
            Outbound::Pong(_) => "pong",
            Outbound::ResourcePackStatus { .. } => "resource_pack",
            Outbound::CookieResponse { .. } => "cookie_response",
            Outbound::LookAnswer { .. } => "C05",
            Outbound::VehicleMove { .. } => "vehicle_move",
            Outbound::SteerBoat { .. } => "steer_boat",
            Outbound::SteerVehicle { .. } => "steer_vehicle",
            Outbound::CustomClickAction { .. } => "custom_click_action",
            Outbound::DialogCommand(_) => "chat_command",
            Outbound::TabComplete { .. } => "tab_complete",
            Outbound::UpdateSign { .. } => "update_sign",
            Outbound::EditBook(_) => "edit_book",
            Outbound::Raw(_) => "raw",
        })
        .collect();
    out.clear();
    v
}

pub(super) struct Script<F: FnMut(&mut TickContext<'_>)>(pub(super) F);
impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        (self.0)(ctx);
    }
}

#[test]
fn join_sends_settings_then_brand() {
    let mut e = engine(GameVersion::V1_8_9);
    e.handle(Inbound::JoinGame(JoinGame {
        entity_id: 1,
        game_mode: GameMode::Creative,
        dimension: "0".into(),
        hardcore: false,
        dimension_nbt: None,
        respawn_screen: true,
    }));
    assert_eq!(names(e.outbound()), ["settings", "brand"]);
}

#[test]
fn nothing_before_the_first_teleport() {
    let mut e = engine(GameVersion::V1_8_9);
    let mut b = Idle;
    let t0 = Instant::now();
    load(&mut e, 0, 0);
    e.outbound().clear();
    for i in 0..5 {
        e.tick(&mut b, t0 + Duration::from_millis(50 * i));
    }
    assert!(e.outbound().is_empty());
}

#[test]
fn teleport_reply_per_version() {
    let mut e = engine(GameVersion::V1_16_5);
    e.handle(Inbound::Teleport(Teleport {
        x: 1.0,
        y: 2.0,
        z: 3.0,
        yaw: 450.0,
        pitch: 100.0,
        flags: 0,
        teleport_id: Some(5),
        ..Default::default()
    }));
    let out = std::mem::take(e.outbound());
    assert_eq!(out[0], Outbound::TeleportConfirm(5));
    match out[1] {
        Outbound::Move(MovePacket::PositionLook {
            yaw,
            pitch,
            on_ground,
            ..
        }) => {
            assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
        }
        ref o => panic!("unexpected {o:?}"),
    }
    let mut e = engine(GameVersion::V1_8_9);
    e.handle(Inbound::Teleport(Teleport {
        x: 1.0,
        y: 2.0,
        z: 3.0,
        yaw: 450.0,
        pitch: 100.0,
        flags: 0,
        teleport_id: None,
        ..Default::default()
    }));
    let out = std::mem::take(e.outbound());
    assert_eq!(out.len(), 1);
    // 1.8 does not clamp the pitch.
    assert!(matches!(
        out[0],
        Outbound::Move(MovePacket::PositionLook {
            yaw: 90.0,
            pitch: 100.0,
            ..
        })
    ));
}

/// The crosshair is one pick (`ghast_physics::pick::v1_8::pick_target`, oracle-proven on
/// `tests/golden/1.8.9/picks.jsonl.gz`) over the tracked entities: a zombie in front is the
/// target and hides the block; one hit beyond 3 blocks but before the block leaves neither
/// (vanilla's miss), so the block behind it is not dug either.
#[test]
fn entity_pick_uses_the_tracker_and_the_proven_pick() {
    use ghast_protocol::v1_8::play::clientbound::id;
    use std::cell::Cell;
    let raw = |id: i32, b: Vec<u8>| RawPacket {
        id,
        body: bytes::Bytes::from(b),
    };
    let zombie = |eid: u8, x: f64| {
        let mut b = vec![eid, 54];
        for v in [x, 64.0, 8.5] {
            b.extend(((v * 32.0) as i32).to_be_bytes());
        }
        b.extend([0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f]);
        raw(id::SPAWN_ENTITY_LIVING, b)
    };
    let mut e = engine(GameVersion::V1_8_9);
    let mut login = 7i32.to_be_bytes().to_vec();
    login.extend([0, 0, 2, 20, 7]);
    login.extend(b"default");
    login.push(0);
    e.sim.world_packet(&raw(id::LOGIN, login)).unwrap();
    e.sim.set_entities(Some(ghast_entity::Config::default()));
    join(&mut e);
    // Stone at (4, 65, 8): its east face is 3.5 blocks west of the eyes (8.5, 65.62, 8.5),
    // which look west (yaw 90).
    let pos: i64 = (4 << 38) | (65 << 26) | 8;
    let mut b = pos.to_be_bytes().to_vec();
    b.push(1 << 4);
    e.sim.world_packet(&raw(id::BLOCK_CHANGE, b)).unwrap();
    let t0 = Instant::now();
    e.note_inbound(t0);
    let seen = Cell::new((None, None));
    let look = |e: &mut Engine<Box<dyn Sim>>| {
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            seen.set((
                ctx.target_entity().map(|h| (h.id, h.distance)),
                ctx.target().map(|t| (t.pos, t.face)),
            ));
        });
        e.tick(&mut b, t0);
        seen.get()
    };
    assert_eq!(
        look(&mut e),
        (
            None,
            Some((ghast_protocol::BlockPos::new(4, 65, 8), crate::Face::East))
        )
    );
    // A zombie 2 blocks west: its box (0.6 wide) grown by the 1.8 margin 0.1 is hit at
    // x = 6.9, 1.6 away; the block behind is not the target.
    e.sim.world_packet(&zombie(50, 6.5)).unwrap();
    let (ent, block) = look(&mut e);
    let (eid, d) = ent.unwrap();
    assert_eq!(eid, 50);
    assert!((d - 1.6).abs() < 1e-6, "{d}");
    assert_eq!(block, None);
    // Gone, and one at x = 5.0 instead: hit at 5.4, 3.1 away (> 3) but before the block.
    e.sim
        .world_packet(&raw(id::ENTITY_DESTROY, vec![1, 50]))
        .unwrap();
    e.sim.world_packet(&zombie(51, 5.0)).unwrap();
    assert_eq!(look(&mut e), (None, None));
}

#[test]
fn actions_precede_the_single_movement_packet() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        if ctx.tick() == 2 {
            ctx.select_slot(3);
            ctx.chat("hello");
            ctx.swing();
            ctx.set_controls(Controls {
                sneak: true,
                ..Controls::default()
            });
        }
    });
    e.tick(&mut b, t0);
    assert_eq!(names(e.outbound()), ["C06"]);
    e.tick(&mut b, t0);
    assert_eq!(
        names(e.outbound()),
        ["held_slot", "chat", "swing", "entity_action", "C03"]
    );
    for _ in 0..100 {
        e.tick(&mut b, t0);
        let n = names(e.outbound());
        assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
    }
}

/// Raw packets go out in call order with the other actions, before the movement packet,
/// and the wire writes them as given (the same frame as the typed packet).
#[test]
fn raw_packets_keep_the_call_order() {
    use crate::version::ClientVersion;
    for v in [GameVersion::V1_8_9, GameVersion::V26_1] {
        let mut e = engine(v);
        join(&mut e);
        let t0 = Instant::now();
        e.note_inbound(t0);
        let mut refused = None;
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            if ctx.tick() == 3 {
                ctx.swing();
                ctx.send_raw(0x7f, vec![1, 2, 3]);
                ctx.send_packet(&ghast_protocol::v26_1::play::serverbound::ArmAnimation {
                    hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
                })
                .unwrap();
                refused = Some(ctx.send_packet(
                    &ghast_protocol::v26_1::play::clientbound::KeepAlive { keep_alive_id: 1 },
                ));
                ctx.chat("after");
            }
        });
        for _ in 0..2 {
            e.tick(&mut b, t0);
        }
        e.outbound().clear();
        e.tick(&mut b, t0);
        let out = e.outbound().clone();
        let n = names(e.outbound());
        assert_eq!(n[..4], ["swing", "raw", "raw", "chat"], "{v:?} {n:?}");
        let movement = n.iter().position(|x| {
            x.starts_with('C') || x.contains("position") || *x == "flying" || *x == "look"
        });
        assert!(movement.is_none_or(|m| m > 3), "{v:?} {n:?}");
        assert!(refused.unwrap().is_err());
        // The wire writes the raw packet as the typed one.
        let typed = ghast_protocol::v26_1::play::serverbound::ArmAnimation {
            hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
        };
        let mut want = ghast_protocol::FrameEncoder::new();
        want.write_packet(&typed).unwrap();
        let mut got = ghast_protocol::FrameEncoder::new();
        let mut wire = crate::version::Wire26_1::default();
        crate::version::V26_1::write_play(&mut got, &out[2], &mut wire).unwrap();
        assert_eq!(got.take(), want.take());
    }
}

#[test]
fn standing_bot_packets() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let mut b = Idle;
    let t0 = Instant::now();
    e.note_inbound(t0);
    // First tick: the position differs from the fresh player's lastReported (origin).
    e.tick(&mut b, t0);
    let out = std::mem::take(e.outbound());
    assert!(matches!(
        out[..],
        [Outbound::Move(MovePacket::PositionLook {
            on_ground: false,
            ..
        })]
    ));
    // Then flying (on ground) with a position refresh every 21st tick.
    let mut kinds = Vec::new();
    for _ in 0..42 {
        e.tick(&mut b, t0);
        kinds.extend(names(e.outbound()));
    }
    assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
    assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
    assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
    assert!(e.core.sent.on_ground);
}

#[test]
fn silent_server_freezes_behaviour() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut ticks = 0;
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        ticks += 1;
        ctx.set_controls(Controls {
            sneak: true,
            ..Controls::default()
        });
    });
    e.tick(&mut b, t0 + Duration::from_millis(100));
    e.tick(&mut b, t0 + Duration::from_millis(1600));
    // Frozen: keys released, so the sneak stops; still one movement packet.
    let n = names(e.outbound());
    assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
    e.note_inbound(t0 + Duration::from_millis(1700));
    e.tick(&mut b, t0 + Duration::from_millis(1700));
    let _ = b;
    assert_eq!(ticks, 2);
}

#[test]
fn keepalive_answered_transactions_left_to_the_inventory() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    e.handle(Inbound::KeepAlive(42));
    // The engine never answers confirms: the inventory does (exactly once), see the
    // fake-server test.
    e.handle(Inbound::Transaction {
        window_id: 0,
        action: -5,
        accepted: false,
    });
    assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
}

#[test]
fn panicking_behaviour_does_not_stop_the_tick() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        if ctx.tick() == 2 {
            panic!("boom");
        }
    });
    let hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(|_| {}));
    for _ in 0..5 {
        e.tick(&mut b, t0);
    }
    std::panic::set_hook(hook);
    assert!(e.state.failed);
    assert_eq!(names(e.outbound()).len(), 5);
}

#[test]
fn chat_events_reach_the_behaviour_once() {
    let mut e = engine(GameVersion::V1_16_5);
    join(&mut e);
    e.handle(Inbound::Chat(ChatMessage {
        rendered: None,
        json: r#"{"text":"hi"}"#.into(),
        position: ChatPosition::System,
        sender: None,
    }));
    let mut seen = Vec::new();
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
    });
    let t0 = Instant::now();
    e.tick(&mut b, t0);
    e.tick(&mut b, t0);
    let _ = b;
    assert_eq!(seen, ["hi"]);
}

/// Joining already dead (health 0, no death event): with the immediate-respawn rule the
/// tick asks to respawn (vanilla's screen check) until the respawn arrives; with the
/// death screen nothing is sent, the behaviour sees `died` and may call `respawn`.
#[test]
fn joining_dead_respawns_like_vanilla() {
    let mut versions = vec![
        (GameVersion::V1_8_9, false),
        (GameVersion::V1_12_2, false),
        (GameVersion::V1_16_5, true),
        (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, rule) in versions {
        for immediate in [false, true] {
            let mut e = engine(v);
            join(&mut e);
            if rule {
                e.handle(Inbound::GameState {
                    reason: 11,
                    value: if immediate { 1.0 } else { 0.0 },
                });
            }
            e.handle(Inbound::Health(crate::common::Health {
                health: 0.0,
                food: 20,
                saturation: 5.0,
                ..crate::common::Health::default()
            }));
            let t0 = Instant::now();
            e.note_inbound(t0);
            let mut died = false;
            let mut b = Script(|ctx: &mut TickContext<'_>| died |= ctx.events().died);
            let mut respawns = 0;
            for _ in 0..3 {
                e.tick(&mut b, t0);
                respawns += e
                    .outbound()
                    .iter()
                    .filter(|o| matches!(o, Outbound::Respawn))
                    .count();
                e.outbound().clear();
            }
            let _ = b;
            assert!(died, "{v:?}");
            let want = if rule && immediate { 3 } else { 0 };
            assert_eq!(respawns, want, "{v:?} immediate {immediate}");
        }
    }
}

#[test]
fn immediate_respawn_1_16() {
    let mut e = engine(GameVersion::V1_16_5);
    join(&mut e);
    e.handle(Inbound::GameState {
        reason: 11,
        value: 1.0,
    });
    e.handle(Inbound::Died { entity_id: 7 });
    assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
}

/// Left button on the floor: START, swings, FINISH, all before the tick's movement
/// packet; the broken block is predicted air and the player falls into the hole.
#[test]
fn dig_with_the_left_button() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    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 == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
        });
        ctx.set_buttons(Buttons {
            left: down,
            right: false,
        });
    });
    let mut ticks = Vec::new();
    for _ in 0..200 {
        e.tick(&mut b, t0);
        let n = names(e.outbound());
        assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
        assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
        ticks.push(n);
    }
    let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
    assert_eq!(
        flat.iter().filter(|x| **x == "block_dig").count(),
        2,
        "start + finish"
    );
    assert!(e.core.hands.broken == 1);
    // Stone by hand: not harvestable, 1 / 1.5 / 100 per tick -> 151 damage ticks.
    let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
    let finish = ticks
        .iter()
        .rposition(|t| t.contains(&"block_dig"))
        .unwrap();
    assert_eq!(finish - start, 150);
    assert!(e.sim.block_query(8, 63, 8).unwrap().air);
    assert!(
        e.core.pose.pos.y < 64.0,
        "falls into the hole: {:?}",
        e.core.pose.pos
    );
}

/// `TickView::outbound` lists the tick's packets (the left button's dig start among them,
/// ahead of the movement packet); `prediction_sequence` is what the wire reports, and the
/// modern wire counts the predicting packets.
#[test]
fn outbound_visible_to_the_behaviour() {
    use crate::version::ClientVersion;
    struct Watch {
        seen: Vec<Vec<Outbound>>,
        seq: Vec<Option<i32>>,
    }
    impl Behavior for Watch {
        fn tick(&mut self, ctx: &mut TickContext<'_>) {
            self.seq.push(ctx.prediction_sequence());
            ctx.set_aim(90.0, 89.5);
            let down = ctx.target().is_some_and(|t| t.face == crate::Face::Up);
            ctx.set_buttons(Buttons {
                left: down,
                right: false,
            });
        }
        fn after_tick(&mut self, view: &TickView<'_>) {
            self.seen.push(view.outbound().to_vec());
            assert_eq!(view.prediction_sequence(), *self.seq.last().unwrap());
        }
    }
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut b = Watch {
        seen: Vec::new(),
        seq: Vec::new(),
    };
    for t in 0..20 {
        e.note_sequence(Some(t));
        e.tick(&mut b, t0);
        assert_eq!(*e.outbound(), *b.seen.last().unwrap());
        e.outbound().clear();
    }
    assert_eq!(b.seq.last(), Some(&Some(19)));
    let dig = b
        .seen
        .iter()
        .find(|o| o.iter().any(|p| matches!(p, Outbound::Dig { .. })))
        .expect("a dig start");
    assert!(matches!(
        dig.iter()
            .find(|p| matches!(p, Outbound::Dig { .. }))
            .unwrap(),
        Outbound::Dig {
            status: crate::common::DigStatus::Start,
            face: crate::Face::Up,
            ..
        }
    ));
    assert!(matches!(dig.last(), Some(Outbound::Move(_))));
    // 26.1's wire: start and finish take a new number, abort does not.
    let mut wire = crate::version::Wire26_1::default();
    let mut enc = ghast_protocol::FrameEncoder::new();
    let dig = |status| Outbound::Dig {
        status,
        pos: ghast_protocol::BlockPos::new(1, 2, 3),
        face: crate::Face::Up,
    };
    use crate::common::DigStatus;
    assert_eq!(crate::version::V26_1::prediction_sequence(&wire), Some(0));
    for (s, want) in [
        (DigStatus::Start, 1),
        (DigStatus::Abort, 1),
        (DigStatus::Start, 2),
        (DigStatus::Finish, 3),
    ] {
        crate::version::V26_1::write_play(&mut enc, &dig(s), &mut wire).unwrap();
        assert_eq!(
            crate::version::V26_1::prediction_sequence(&wire),
            Some(want)
        );
    }
    assert_eq!(crate::version::V1_8::prediction_sequence(&()), None);
}

/// `dig_speed` is the left button's per-tick progress; `item_facts` the hands' facts.
#[test]
fn dig_speed_and_item_facts() {
    // 1.16.5 facts by name (its test chunk is empty).
    let mut e = engine(GameVersion::V1_16_5);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
        let bread = ctx.item_facts(&ghast_inventory::Stack::new(id("bread"), 3, 0));
        assert!(bread.is_some_and(|f| f.food && f.usable && !f.places_block && f.count == 3));
        let dirt = ctx.item_facts(&ghast_inventory::Stack::new(id("dirt"), 1, 0));
        assert!(dirt.is_some_and(|f| f.places_block && !f.food));
    });
    e.tick(&mut b, t0);

    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    e.note_inbound(t0);
    let got = std::cell::Cell::new(None);
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        let stone = ghast_protocol::BlockPos::new(8, 63, 8);
        let pick = ghast_inventory::Stack::new(278, 1, 0);
        let facts = ctx.item_facts(&pick).unwrap();
        assert!(!facts.places_block && !facts.food);
        got.set(Some((
            ctx.dig_speed(stone, None),
            ctx.dig_speed(stone, Some(&pick)),
            ctx.dig_speed(ghast_protocol::BlockPos::new(8, 64, 8), None),
            ctx.dig_speed(ghast_protocol::BlockPos::new(500, 63, 8), None),
        )));
    });
    // Land first (in the air the progress is ÷5).
    for _ in 0..40 {
        e.tick(&mut b, t0);
    }
    assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
    let (hand, pick, air, unloaded) = got.get().expect("ticked");
    // Stone by hand: not harvestable, 1 / 1.5 / 100 per tick (the 150 ticks of
    // `dig_with_the_left_button`).
    assert_eq!(hand, Some(1.0 / 1.5 / 100.0));
    // Diamond pickaxe: speed 8, harvestable: 8 / 1.5 / 30.
    assert_eq!(pick, Some(8.0 / 1.5 / 30.0));
    assert_eq!(air, Some(0.0));
    assert_eq!(unloaded, None);
}

/// `place` is refused unless the sent look is on the face; then C08 + C0A before the
/// movement packet.
#[test]
fn place_needs_the_sent_look() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let floor = ghast_protocol::BlockPos::new(8, 63, 8);
    let mut results = Vec::new();
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        ctx.set_aim(90.0, 89.5);
        results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
    });
    // Torches in the selected hotbar slot (window 0 slot 36): a full block would go into
    // the player's own box, which the 1.8 client does not even send.
    e.core
        .inv
        .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
    let mut placed_tick = None;
    for i in 0..20 {
        e.tick(&mut b, t0);
        let n = names(e.outbound());
        if n.contains(&"block_place") {
            assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
            placed_tick.get_or_insert(i);
        }
    }
    let _ = b;
    let first = results.iter().position(|r| *r).unwrap();
    assert!(first > 3, "refused while still turning");
    assert_eq!(placed_tick, Some(first));
    assert_eq!(e.core.inv.held().map(|s| s.id()), Some(50));
}

#[test]
fn sneak_action_order() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        ctx.set_controls(Controls {
            sneak: true,
            ..Controls::default()
        });
    });
    e.tick(&mut b, Instant::now());
    let out = std::mem::take(e.outbound());
    assert_eq!(
        out[0],
        Outbound::EntityAction {
            entity_id: 7,
            action: EntityAction::StartSneaking
        }
    );
    assert!(matches!(out[1], Outbound::Move(_)));
}

/// Block changes reach the behaviour once, in arrival order, only when asked for.
#[test]
fn block_updates_per_version() {
    use ghast_protocol::BlockPos;
    for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
        let mut e = engine(v);
        join(&mut e);
        e.sim.collect_block_updates(true);
        let t0 = Instant::now();
        e.note_inbound(t0);
        let raws = match v.instance() {
            GameVersion::V1_8_9 => {
                use ghast_protocol::v1_8::play::clientbound as cb;
                vec![
                    RawPacket::from_packet(&cb::BlockChange {
                        location: BlockPos::new(3, 63, 4),
                        r#type: 59 << 4 | 7,
                    })
                    .unwrap(),
                    RawPacket::from_packet(&cb::MultiBlockChange {
                        chunk_x: 0,
                        chunk_z: 0,
                        records: vec![cb::MultiBlockChangeRecords {
                            horizontal_pos: 5 << 4 | 6,
                            y: 62,
                            block_id: 60 << 4 | 7,
                        }],
                    })
                    .unwrap(),
                ]
            }
            GameVersion::V1_12_2 => {
                use ghast_protocol::v1_12_2::play::clientbound as cb;
                vec![
                    RawPacket::from_packet(&cb::BlockChange {
                        location: BlockPos::new(3, 63, 4),
                        r#type: 59 << 4 | 7,
                    })
                    .unwrap(),
                    RawPacket::from_packet(&cb::MultiBlockChange {
                        chunk_x: 0,
                        chunk_z: 0,
                        records: vec![cb::MultiBlockChangeRecords {
                            horizontal_pos: 5 << 4 | 6,
                            y: 62,
                            block_id: 60 << 4 | 7,
                        }],
                    })
                    .unwrap(),
                ]
            }
            GameVersion::V26_1 => {
                use ghast_protocol::v26_1::play::clientbound as cb;
                // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
                let local = (5 << 8 | 6 << 4 | 14) as i64;
                vec![
                    RawPacket::from_packet(&cb::BlockChange {
                        location: BlockPos::new(3, 63, 4),
                        r#type: 1,
                    })
                    .unwrap(),
                    RawPacket::from_packet(&cb::MultiBlockChange {
                        chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                            x: 0,
                            z: 0,
                            y: -1,
                        },
                        records: vec![9 << 12 | local],
                    })
                    .unwrap(),
                ]
            }
            #[cfg(feature = "v26_2")]
            GameVersion::V26_2 => {
                use ghast_protocol::v26_2::play::clientbound as cb;
                // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
                let local = (5 << 8 | 6 << 4 | 14) as i64;
                vec![
                    RawPacket::from_packet(&cb::BlockChange {
                        location: BlockPos::new(3, 63, 4),
                        r#type: 1,
                    })
                    .unwrap(),
                    RawPacket::from_packet(&cb::MultiBlockChange {
                        chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                            x: 0,
                            z: 0,
                            y: -1,
                        },
                        records: vec![9 << 12 | local],
                    })
                    .unwrap(),
                ]
            }
            #[cfg(feature = "v26_3")]
            GameVersion::V26_3 => {
                use ghast_protocol::v26_3::play::clientbound as cb;
                // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
                let local = (5 << 8 | 6 << 4 | 14) as i64;
                vec![
                    RawPacket::from_packet(&cb::BlockChange {
                        location: BlockPos::new(3, 63, 4),
                        r#type: 1,
                    })
                    .unwrap(),
                    RawPacket::from_packet(&cb::MultiBlockChange {
                        chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                            x: 0,
                            z: 0,
                            y: -1,
                        },
                        records: vec![9 << 12 | local],
                    })
                    .unwrap(),
                ]
            }
            _ => {
                use ghast_protocol::v1_16_5::play::clientbound as cb;
                // Section y = -1 (20-bit two's complement), local x 5 z 6 y 14.
                let local = (5 << 8 | 6 << 4 | 14) as i64;
                vec![
                    RawPacket::from_packet(&cb::BlockChange {
                        location: BlockPos::new(3, 63, 4),
                        r#type: 1,
                    })
                    .unwrap(),
                    RawPacket::from_packet(&cb::MultiBlockChange {
                        chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
                            x: 0,
                            z: 0,
                            y: 0xF_FFFF,
                        },
                        not_trust_edges: false,
                        records: vec![9 << 12 | local],
                    })
                    .unwrap(),
                ]
            }
        };
        for raw in &raws {
            e.sim.world_packet(raw).unwrap();
        }
        let mut seen = Vec::new();
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            seen.push(ctx.events().block_updates.clone());
        });
        e.tick(&mut b, t0);
        e.tick(&mut b, t0);
        let _ = b;
        let want = match v.instance() {
            GameVersion::V1_8_9 | GameVersion::V1_12_2 => vec![
                (BlockPos::new(3, 63, 4), 59 << 4 | 7),
                (BlockPos::new(5, 62, 6), 60 << 4 | 7),
            ],
            _ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
        };
        assert_eq!(seen, [want, Vec::new()], "{v:?}");

        // Not collected when not asked for.
        e.sim.collect_block_updates(false);
        e.sim.world_packet(&raws[0]).unwrap();
        let mut n = usize::MAX;
        let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
        e.tick(&mut b, t0);
        let _ = b;
        assert_eq!(n, 0);
    }
}

/// `set_flying` sends the abilities packet before the move, only when allowed and changed.
#[test]
fn set_flying_needs_may_fly() {
    for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
        let mut e = engine(v);
        join(&mut e);
        let t0 = Instant::now();
        e.note_inbound(t0);
        // In the air (flight ends on landing, like vanilla).
        e.handle(Inbound::Teleport(Teleport {
            x: 8.5,
            y: 70.0,
            z: 8.5,
            yaw: 90.0,
            pitch: 0.0,
            flags: 0,
            teleport_id: Some(2),
            ..Default::default()
        }));
        e.outbound().clear();
        let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
        e.tick(&mut b, t0);
        assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
        assert!(!e.core.pose.flying);
        e.handle(Inbound::Abilities(Abilities {
            flags: 4,
            ..Abilities::default()
        }));
        e.tick(&mut b, t0);
        let out = std::mem::take(e.outbound());
        assert_eq!(
            out[0],
            Outbound::Abilities {
                flags: 6,
                flying_speed: 0.05,
                walking_speed: 0.1
            },
            "{v:?}"
        );
        assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
        assert!(e.core.pose.flying && e.core.sent.flying);
        // Already flying: nothing more.
        e.tick(&mut b, t0);
        assert!(!names(e.outbound()).contains(&"abilities"));
        let _ = b;
    }
}

/// 1.12.2 runs the vanilla-exact physics: the player is added to its chunk on the first
/// tick (nothing sent), then walks on the stone floor and sends its moves; standing still
/// sends no idle on-ground packets (1.9+).
#[test]
fn v1_12_2_walks_with_physics() {
    let mut e = engine(GameVersion::V1_12_2);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut idle = Script(|_: &mut TickContext<'_>| {});
    e.tick(&mut idle, t0);
    assert!(
        !names(e.outbound())
            .iter()
            .any(|n| matches!(*n, "C04" | "C06"))
    );
    for _ in 0..5 {
        e.tick(&mut idle, t0);
    }
    e.outbound().clear();
    let start = e.core.pose.pos;
    assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
    let mut walk = Script(|ctx: &mut TickContext<'_>| {
        ctx.set_controls(crate::common::Controls {
            forward: true,
            ..Default::default()
        });
    });
    for _ in 0..10 {
        e.tick(&mut walk, t0);
    }
    let _ = walk;
    let moved = names(e.outbound());
    assert!(
        moved.iter().any(|n| matches!(*n, "C04" | "C06")),
        "{moved:?}"
    );
    // Yaw 90 faces -X.
    assert!(e.core.pose.pos.x < start.x - 0.5, "{:?}", e.core.pose.pos);
    assert_eq!(e.core.pose.pos.y, 64.0);
    let mut stop = Script(|ctx: &mut TickContext<'_>| {
        ctx.set_controls(crate::common::Controls::default());
    });
    for _ in 0..30 {
        e.tick(&mut stop, t0);
    }
    e.outbound().clear();
    for _ in 0..5 {
        e.tick(&mut stop, t0);
    }
    let _ = (idle, stop);
    // No idle on-ground packets; at most the position refresh every 20 ticks.
    let still = names(e.outbound());
    assert!(still.len() <= 1 && !still.contains(&"C03"), "{still:?}");
}

/// A behaviour that reports `running() == false` is not ticked again.
#[test]
fn finished_behaviour_is_not_ticked() {
    struct Three(std::rc::Rc<std::cell::Cell<u32>>);
    impl Behavior for Three {
        fn tick(&mut self, _ctx: &mut TickContext<'_>) {
            self.0.set(self.0.get() + 1);
        }
        fn running(&self) -> bool {
            self.0.get() < 3
        }
    }
    let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
    for _ in 0..10 {
        e.tick(&mut b, t0);
        // The player keeps sending its movement packet.
        let out = std::mem::take(e.outbound());
        assert!(
            out.iter().any(|o| matches!(o, Outbound::Move(_))),
            "{out:?}"
        );
    }
    assert_eq!(
        ticks.get(),
        3,
        "not ticked after running() == false (through the Box)"
    );
}

/// A turn that would take the crosshair off a block placed this tick waits one tick.
#[test]
fn turn_held_on_a_place_tick() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    e.core
        .inv
        .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
    let floor = ghast_protocol::BlockPos::new(8, 63, 8);
    let mut tick = 0;
    let mut placed_at = None;
    let mut pitches = Vec::new();
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        tick += 1;
        if placed_at.is_none() {
            ctx.set_aim(90.0, 89.5);
            if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
                placed_at = Some(tick);
                // Look up on the same tick: held back.
                ctx.set_aim(90.0, -60.0);
            }
        } else {
            ctx.set_aim(90.0, -60.0);
        }
        pitches.push(ctx.pose().pitch);
    });
    for _ in 0..30 {
        e.tick(&mut b, t0);
        e.outbound().clear();
    }
    let _ = b;
    let p = placed_at.expect("placed");
    assert_eq!(e.core.held_turns, 1);
    // Pose at the start of the tick after the place: still the place look.
    assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
    assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
}

/// `click` returns the ticket its confirm carries.
#[test]
fn click_ticket_matches_the_confirm() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    e.core
        .inv
        .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
    let mut ticket = None;
    let mut n = 0;
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        n += 1;
        if n == 1 {
            ctx.open_inventory().unwrap();
        } else if ticket.is_none() {
            ticket = ctx
                .click(ghast_inventory::Click::Pickup {
                    slot: 36,
                    right: false,
                })
                .ok();
        }
    });
    for _ in 0..3 {
        e.tick(&mut b, t0);
    }
    let _ = b;
    let t = ticket.expect("click sent");
    assert_eq!(t.window_id, 0);
    assert!(t.matches(&ghast_inventory::ClickResult::new(
        0,
        t.action,
        ghast_inventory::ClickOutcome::Accepted,
    )));
}

/// 1.8 planting uses the seed at once (vanilla `SeedItem.use` on the client), seeds on
/// stone keep the stack; a torch on stone goes on at once too (the 1.8.9 right-click
/// rules, `ghast_data::v1_8::place`).
#[test]
fn planting_uses_the_seed_at_once() {
    use ghast_protocol::v1_8::play::clientbound as cb;
    for (soil, item, used) in [
        (60 << 4 | 7, 295, true),
        (1 << 4, 295, false),
        (1 << 4, 50, true),
    ] {
        let mut e = engine(GameVersion::V1_8_9);
        join(&mut e);
        let t0 = Instant::now();
        e.note_inbound(t0);
        let floor = ghast_protocol::BlockPos::new(8, 63, 8);
        let raw = RawPacket::from_packet(&cb::BlockChange {
            location: floor,
            r#type: soil,
        })
        .unwrap();
        e.sim.world_packet(&raw).unwrap();
        e.core
            .inv
            .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
        let mut done = false;
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_aim(90.0, 89.5);
            if !done {
                done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
            }
        });
        let mut sent = None;
        for _ in 0..20 {
            e.tick(&mut b, t0);
            for o in e.outbound().drain(..) {
                if let Outbound::Place { held, .. } = o {
                    sent = held.map(|h| h.count());
                }
            }
        }
        let _ = b;
        assert_eq!(sent, Some(64), "the packet carries the stack before use");
        let left = e.core.inv.held().map(|s| s.count());
        assert_eq!(
            left,
            Some(if used { 63 } else { 64 }),
            "soil {soil} item {item}"
        );
    }
}

/// `planned_look` is the look the movement step then uses: a plain turn, a turn held on a
/// place tick, no aim; and it leaves the rotation's budget alone.
#[test]
fn planned_look_is_the_next_look() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    e.core
        .inv
        .on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
    let floor = ghast_protocol::BlockPos::new(8, 63, 8);
    let mut n = 0;
    let mut placed = false;
    let mut plans: Vec<(f32, f32)> = Vec::new();
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        n += 1;
        if n % 5 == 0 {
            // No aim this tick: the current look.
        } else if !placed {
            ctx.set_aim(90.0, 89.5);
            if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
                placed = true;
                ctx.set_aim(90.0, -60.0);
            }
        } else {
            ctx.set_aim(150.0, -60.0);
        }
        // Asking twice changes nothing.
        let p = ctx.planned_look();
        assert_eq!(p, ctx.planned_look());
        plans.push(p);
    });
    let mut looks = Vec::new();
    for _ in 0..40 {
        e.tick(&mut b, t0);
        e.outbound().clear();
        looks.push((e.core.pose.yaw, e.core.pose.pitch));
    }
    let _ = b;
    assert!(placed);
    assert_eq!(e.core.test_held_turns(), 1);
    assert_eq!(plans, looks);
}

/// A teleport event keeps the sent pose from before the overwrite, the raw values and the
/// resolved pose.
#[test]
fn teleport_event_has_the_sent_pose_before() {
    for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
        let mut e = engine(v);
        join(&mut e);
        let t0 = Instant::now();
        e.note_inbound(t0);
        let mut seen = Vec::new();
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            seen.extend(ctx.events().teleports.iter().copied());
        });
        e.tick(&mut b, t0);
        let sent = e.core.sent;
        // Relative yaw +30, absolute position.
        let tp = Teleport {
            x: 10.5,
            y: 64.0,
            z: 8.5,
            yaw: 30.0,
            pitch: 0.0,
            flags: crate::common::teleport_flags::YAW,
            teleport_id: Some(9),
            relative: crate::common::teleport_flags::YAW as u32,
            ..Default::default()
        };
        e.handle(Inbound::Teleport(tp));
        e.tick(&mut b, t0);
        e.tick(&mut b, t0);
        let _ = b;
        // The spawn position first (join), then ours, each once.
        assert_eq!(seen.len(), 2, "{v:?}");
        let ev = seen[1];
        assert_eq!(ev.teleport, tp);
        assert_eq!(ev.sent_before, sent);
        assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
        assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
    }
}

/// A container the server opened and the behaviour closed (`close_window`) no longer
/// holds the mouse: the left button digs again (both versions). While it is open the
/// buttons are up.
#[test]
fn closed_window_frees_the_buttons() {
    for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
        let mut e = engine(v);
        join(&mut e);
        let t0 = Instant::now();
        e.note_inbound(t0);
        if v.instance() == GameVersion::V1_16_5 {
            // The 1.16 test chunk is all air: put a stone floor under the player.
            use ghast_protocol::v1_16_5::play::clientbound as cb;
            let raw = RawPacket::from_packet(&cb::BlockChange {
                location: ghast_protocol::BlockPos::new(8, 63, 8),
                r#type: 1,
            })
            .unwrap();
            e.sim.world_packet(&raw).unwrap();
        }
        e.core.inv.on_open_window(
            5,
            Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
            "Vault".into(),
        );
        e.handle(Inbound::OpenWindow(5));
        // Something on the cursor: vanilla's client-side close drops it (the server
        // throws it out), so the client forgets it too.
        e.core
            .inv
            .on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
        let mut n = 0;
        let mut closed_at = None;
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            n += 1;
            ctx.set_aim(90.0, 89.5);
            ctx.set_buttons(Buttons {
                left: true,
                right: false,
            });
            if n == 15 {
                assert!(ctx.inventory().cursor().is_some());
                ctx.close_window().unwrap();
                assert_eq!(ctx.open_window(), None);
                let inv = ctx.inventory();
                assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
                closed_at = Some(n);
            }
        });
        let mut first_dig = None;
        for i in 1..=30 {
            e.tick(&mut b, t0);
            let out = std::mem::take(e.outbound());
            if first_dig.is_none()
                && out.iter().any(|o| {
                    matches!(
                        o,
                        Outbound::Dig {
                            status: crate::common::DigStatus::Start,
                            ..
                        }
                    )
                })
            {
                first_dig = Some(i);
            }
        }
        let _ = b;
        assert_eq!(closed_at, Some(15));
        let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
        // The hands run after the behaviour: the closing tick already digs.
        assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
    }
}

/// `swings` counts every arm swing: the behaviour's, an action's and the held button's.
#[test]
fn swings_count_every_arm_swing() {
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut n = 0;
    let mut seen = Vec::new();
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        n += 1;
        ctx.set_aim(90.0, 89.5);
        if n == 1 {
            ctx.swing();
            ctx.swing();
        }
        if n == 20 {
            // Hold the left button on the stone floor: a swing every tick while digging.
            ctx.set_buttons(Buttons {
                left: true,
                right: false,
            });
        }
        seen.push(ctx.swings());
    });
    let mut sent = 0u64;
    for _ in 0..30 {
        e.tick(&mut b, t0);
        sent += count_swings(&std::mem::take(e.outbound()));
    }
    let _ = b;
    assert_eq!(seen[0], 2, "this tick's own swings count at once");
    assert!(sent > 10, "the held button swings: {sent}");
    // The last reading misses only the hands' swing of the last tick.
    assert_eq!(*seen.last().unwrap() + 1, sent);
    assert_eq!(e.core.swings, sent);
}

/// `WorldView::column` gives the stored column; light and biomes only when configured.
#[test]
fn column_view_and_world_config() {
    for config in [
        None,
        Some(
            ghast_world::WorldConfig::default()
                .with_biomes(true)
                .with_light(true),
        ),
    ] {
        let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
            world: config,
            ..crate::sim::SimOptions::default()
        });
        let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
        join(&mut e);
        let w: &dyn WorldView = &e.sim;
        let col = w.column(0, 0).expect("loaded");
        assert_eq!(u32::from(col.raw(8, 63, 8)), w.raw_block(8, 63, 8).unwrap());
        assert_eq!(col.raw(8, 63, 8), 1 << 4);
        assert!(w.column(5, 5).is_none());
        let light = col.sky_light(8, 63, 8);
        assert_eq!(light.is_some(), config.is_some(), "{config:?}");
        let biomes = !matches!(col.biomes(), ghast_world::Biomes::None);
        assert_eq!(biomes, config.is_some(), "{config:?}");
    }
}

/// `after_tick` runs after the movement step with the sent pose, also once the behaviour
/// finished; a panic there stops the behaviour only.
#[test]
fn after_tick_sees_the_sent_pose() {
    struct Obs {
        n: u32,
        views: Vec<(u64, Pose, u64)>,
    }
    impl Behavior for Obs {
        fn tick(&mut self, ctx: &mut TickContext<'_>) {
            self.n += 1;
            ctx.set_aim(150.0, 10.0);
            ctx.set_controls(Controls {
                forward: true,
                ..Controls::default()
            });
        }
        fn running(&self) -> bool {
            self.n < 5
        }
        fn after_tick(&mut self, view: &TickView<'_>) {
            self.views.push((view.tick(), *view.sent(), view.swings()));
            assert!(view.world().is_column_loaded(0, 0));
            assert_eq!(view.version(), GameVersion::V1_8_9);
        }
    }
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    let t0 = Instant::now();
    e.note_inbound(t0);
    let mut b = Obs {
        n: 0,
        views: Vec::new(),
    };
    let mut sent = Vec::new();
    for _ in 0..10 {
        e.tick(&mut b, t0);
        e.outbound().clear();
        sent.push(e.core.sent);
    }
    assert_eq!(b.n, 5);
    assert_eq!(b.views.len(), 10, "also after the behaviour finished");
    for (i, (_, p, _)) in b.views.iter().enumerate() {
        assert_eq!(*p, sent[i]);
    }
    assert_ne!(
        b.views[0].1.yaw, b.views[4].1.yaw,
        "the view follows the turn"
    );
}

/// With block entities on, a 1.8 sign update reaches the column (and the packet passes the
/// filter); off by default.
#[test]
fn block_entities_follow_the_world_config() {
    use ghast_protocol::v1_8::play::clientbound as cb;
    for on in [false, true] {
        let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
            world: on.then(|| ghast_world::WorldConfig::default().with_block_entities(true)),
            ..crate::sim::SimOptions::default()
        });
        assert_eq!(sim.world_packet_ids().contains(&cb::id::UPDATE_SIGN), on);
        let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
        join(&mut e);
        let raw = RawPacket::from_packet(&cb::UpdateSign {
            location: ghast_protocol::BlockPos::new(3, 64, 4),
            text1: "\"Hello\"".into(),
            text2: "\"\"".into(),
            text3: "\"\"".into(),
            text4: "\"\"".into(),
        })
        .unwrap();
        e.sim.world_packet(&raw).unwrap();
        let w: &dyn WorldView = &e.sim;
        let be = w.column(0, 0).unwrap().block_entity(3, 64, 4);
        assert_eq!(be.is_some(), on, "{be:?}");
    }
}