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
//! The player side of attacks and the movement keys on every version: the attack slow-down
//! (`PlayerEntity.attack`: velocity x/z × 0.6 and `setSprinting(false)` on a hit with
//! knockback), our own entity data's flags byte, the dead player's and an open screen's
//! released keys, the server velocity before the step and the step's collision flags.

use super::tests::{Script, engine, join, names};
use super::*;
use crate::common::EntityAction;
use bytes::BufMut;
use ghast_protocol::RawPacket;
use ghast_protocol::codec::McWrite;

/// Every version the client engine runs.
#[cfg(not(feature = "v26_3"))]
const VERSIONS: [GameVersion; 5] = [
    GameVersion::V1_8_9,
    GameVersion::V1_12_2,
    GameVersion::V1_16_5,
    GameVersion::V26_1,
    GameVersion::V26_2,
];
/// With 26.3.
#[cfg(feature = "v26_3")]
const VERSIONS: [GameVersion; 6] = [
    GameVersion::V1_8_9,
    GameVersion::V1_12_2,
    GameVersion::V1_16_5,
    GameVersion::V26_1,
    GameVersion::V26_2,
    GameVersion::V26_3,
];

/// What an attack target is.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Kind {
    Player,
    Zombie,
}

fn uuid(id: i32) -> uuid::Uuid {
    uuid::Uuid::from_u128(0x7465_7374_0000 + id as u128)
}

/// Spawns a player or a zombie at `pos`, facing south (26.x: a player's tab-list entry first,
/// the client adds no player without one).
pub(super) fn put(e: &mut Engine<Box<dyn Sim>>, id: i32, kind: Kind, pos: Vec3) {
    let v = e.core.opts.caps.version;
    if kind == Kind::Player && v.caps().configuration_state {
        // player_info: actions {add player}, one entry (uuid, name, no properties).
        let mut b = bytes::BytesMut::new();
        b.put_u8(1);
        b.put_varint(1);
        b.put_u128(uuid(id).as_u128());
        b.put_varint(6);
        b.put_slice(b"Target");
        b.put_varint(0);
        let pid = modern_cb_id!(v, PLAYER_INFO);
        e.sim
            .world_packet(&RawPacket::new(pid, b.freeze()))
            .unwrap();
    }
    e.sim.world_packet(&spawn(v, id, kind, pos)).unwrap();
}

/// A stone floor at y 63 under x −15 … 15, z 7 … 9 (1.16.5's test columns are empty).
fn floor(e: &mut Engine<Box<dyn Sim>>) {
    if e.core.opts.caps.version != GameVersion::V1_16_5 {
        return;
    }
    let id = ghast_protocol::v1_16_5::play::clientbound::id::BLOCK_CHANGE;
    for x in -15i64..=15 {
        for z in 7i64..=9 {
            let pos = ((x & 0x3ff_ffff) << 38) | ((z & 0x3ff_ffff) << 12) | 63;
            let mut b = bytes::BytesMut::new();
            b.put_i64(pos);
            b.put_varint(1);
            e.sim.world_packet(&RawPacket::new(id, b.freeze())).unwrap();
        }
    }
}

/// The version's spawn packet of a player or a zombie at `pos`, facing south.
fn spawn(v: GameVersion, id: i32, kind: Kind, pos: Vec3) -> RawPacket {
    let fixed = |d: f64| (d * 32.0).floor() as i32;
    let vel = ghast_protocol::defs::p47::types::Vec3i16 { x: 0, y: 0, z: 0 };
    match v.instance() {
        GameVersion::V1_8_9 => {
            use ghast_protocol::v1_8::play::clientbound as cb;
            match kind {
                Kind::Player => RawPacket::from_packet(&cb::NamedEntitySpawn {
                    entity_id: id,
                    player_uuid: uuid(id),
                    x: fixed(pos.x),
                    y: fixed(pos.y),
                    z: fixed(pos.z),
                    yaw: 0,
                    pitch: 0,
                    current_item: 0,
                    metadata: Vec::new(),
                }),
                Kind::Zombie => RawPacket::from_packet(&cb::SpawnEntityLiving {
                    entity_id: id,
                    r#type: 54,
                    x: fixed(pos.x),
                    y: fixed(pos.y),
                    z: fixed(pos.z),
                    yaw: 0,
                    pitch: 0,
                    head_pitch: 0,
                    velocity: vel,
                    metadata: Vec::new(),
                }),
            }
        }
        GameVersion::V1_12_2 => {
            use ghast_protocol::v1_12_2::play::clientbound as cb;
            match kind {
                Kind::Player => RawPacket::from_packet(&cb::NamedEntitySpawn {
                    entity_id: id,
                    player_uuid: uuid(id),
                    x: pos.x,
                    y: pos.y,
                    z: pos.z,
                    yaw: 0,
                    pitch: 0,
                    metadata: Vec::new(),
                }),
                Kind::Zombie => RawPacket::from_packet(&cb::SpawnEntityLiving {
                    entity_id: id,
                    entity_uuid: uuid(id),
                    r#type: 54,
                    x: pos.x,
                    y: pos.y,
                    z: pos.z,
                    yaw: 0,
                    pitch: 0,
                    head_pitch: 0,
                    velocity: vel,
                    metadata: Vec::new(),
                }),
            }
        }
        GameVersion::V1_16_5 => {
            use ghast_protocol::v1_16_5::play::clientbound as cb;
            match kind {
                Kind::Player => RawPacket::from_packet(&cb::NamedEntitySpawn {
                    entity_id: id,
                    player_uuid: uuid(id),
                    x: pos.x,
                    y: pos.y,
                    z: pos.z,
                    yaw: 0,
                    pitch: 0,
                }),
                Kind::Zombie => RawPacket::from_packet(&cb::SpawnEntityLiving {
                    entity_id: id,
                    entity_uuid: uuid(id),
                    r#type: ghast_data::v1_16_5::entities()
                        .iter()
                        .find(|e| e.name == "zombie")
                        .map(|e| i32::from(e.id))
                        .unwrap(),
                    x: pos.x,
                    y: pos.y,
                    z: pos.z,
                    yaw: 0,
                    pitch: 0,
                    head_pitch: 0,
                    velocity: vel,
                }),
            }
        }
        modern => {
            let name = match kind {
                Kind::Player => "player",
                Kind::Zombie => "zombie",
            };
            let (ty, id_spawn) = (
                modern_entity_type!(modern, name),
                modern_cb_id!(modern, SPAWN_ENTITY),
            );
            let mut b = bytes::BytesMut::new();
            b.put_varint(id);
            b.put_u128(uuid(id).as_u128());
            b.put_varint(i32::from(ty));
            for c in [pos.x, pos.y, pos.z] {
                b.put_f64(c);
            }
            b.put_u8(0);
            b.put_i8(0);
            b.put_i8(0);
            b.put_i8(0);
            b.put_varint(0);
            return RawPacket::new(id_spawn, b.freeze());
        }
    }
    .unwrap()
}

/// Our entity data with only the flags byte (index 0).
fn own_flags(v: GameVersion, flags: u8) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    b.put_varint(7);
    let id = match v.instance() {
        GameVersion::V1_8_9 => {
            // type 0 (byte) << 5 | index 0, the byte, the end marker.
            b.put_u8(0);
            b.put_u8(flags);
            b.put_u8(0x7f);
            return RawPacket::new(
                ghast_protocol::v1_8::play::clientbound::id::ENTITY_METADATA,
                b.freeze(),
            );
        }
        GameVersion::V1_12_2 => ghast_protocol::v1_12_2::play::clientbound::id::ENTITY_METADATA,
        GameVersion::V1_16_5 => ghast_protocol::v1_16_5::play::clientbound::id::ENTITY_METADATA,
        v => modern_cb_id!(v, ENTITY_METADATA),
    };
    // index 0, type 0 (byte), the byte, the end marker.
    b.put_u8(0);
    b.put_u8(0);
    b.put_u8(flags);
    b.put_u8(0xff);
    RawPacket::new(id, b.freeze())
}

/// A joined engine with entity tracking, full food (sprinting needs it) and our entity id
/// known to the sim, standing at (8.5, 64, 8.5) facing west.
pub(super) fn setup(v: GameVersion) -> Engine<Box<dyn Sim>> {
    let mut e = engine(v);
    join(&mut e);
    floor(&mut e);
    e.sim.test_set_own_id(7);
    e.sim.set_entities(Some(ghast_entity::Config::default()));
    e.handle(Inbound::Health(Health {
        health: 20.0,
        food: 20,
        saturation: 5.0,
        ..Health::default()
    }));
    e
}

/// One tick with a behaviour closure; returns the tick's packet names.
fn tick(
    e: &mut Engine<Box<dyn Sim>>,
    t0: Instant,
    f: impl FnMut(&mut TickContext<'_>),
) -> Vec<&'static str> {
    e.note_inbound(t0);
    let mut b = Script(f);
    e.tick(&mut b, t0);
    names(e.outbound())
}

/// The tick's sprint actions.
fn sprint_actions(out: &[Outbound]) -> Vec<EntityAction> {
    out.iter()
        .filter_map(|o| match o {
            Outbound::EntityAction { action, .. }
                if matches!(
                    action,
                    EntityAction::StartSprinting | EntityAction::StopSprinting
                ) =>
            {
                Some(*action)
            }
            _ => None,
        })
        .collect()
}

const RUN: Controls = Controls {
    forward: true,
    sprint: true,
    ..Controls::NONE
};
const WALK: Controls = Controls {
    forward: true,
    ..Controls::NONE
};

/// Sprints west for 8 ticks, then walks on with the sprint key up (still sprinting), the
/// target 1.5 blocks ahead of the sent position; returns the engine just before the attack
/// tick.
fn sprinting_at(v: GameVersion, kind: Kind, t0: Instant) -> Engine<Box<dyn Sim>> {
    let mut e = setup(v);
    for _ in 0..8 {
        tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
    }
    tick(&mut e, t0, |ctx| ctx.set_controls(WALK));
    assert!(e.core.pose.sprinting, "{v}: sprinting");
    let s = e.core.sent.pos;
    put(&mut e, 50, kind, Vec3::new(s.x - 1.5, s.y, s.z));
    e
}

/// The attack tick: `attack` decides whether the behaviour attacks entity 50. Returns the
/// tick's sprint actions, the motion after the step and the attack's result.
fn attack_tick(
    e: &mut Engine<Box<dyn Sim>>,
    t0: Instant,
    controls: Controls,
    attack: bool,
) -> (Vec<EntityAction>, Vec3, bool) {
    let mut hit = false;
    e.note_inbound(t0);
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        ctx.set_controls(controls);
        if attack {
            hit = ctx.attack(50);
        }
    });
    e.tick(&mut b, t0);
    let actions = sprint_actions(e.outbound());
    e.outbound().clear();
    (actions, e.core.pose.motion, hit)
}

/// A sprint hit on a player with the sprint key up: the attack unsprints (a stop goes out)
/// and slows; on a zombie (not hurt on the client) nothing happens. Every version.
#[test]
fn sprint_hit_slows_and_unsprints_on_players_only() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = sprinting_at(v, Kind::Player, t0);
        let (actions, _, hit) = attack_tick(&mut e, t0, WALK, true);
        assert!(hit, "{v}: the attack went out");
        assert_eq!(actions, [EntityAction::StopSprinting], "{v}");
        assert!(!e.core.pose.sprinting, "{v}");

        let mut e = sprinting_at(v, Kind::Zombie, t0);
        let (actions, _, hit) = attack_tick(&mut e, t0, WALK, true);
        assert!(hit, "{v}: the attack went out");
        assert!(actions.is_empty(), "{v}: {actions:?}");
        assert!(e.core.pose.sprinting, "{v}");
    }
}

/// With the sprint key held the sprint starts again in the same movement update (no packet)
/// and the step starts from 0.6 × the horizontal velocity: the motion differs from the same
/// tick without the attack by exactly −0.4 × v × the ground friction (0.6 × 0.91).
#[test]
fn sprint_hit_keeps_the_held_sprint_and_slows_by_0_6() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut a = sprinting_at(v, Kind::Player, t0);
        let mut b = sprinting_at(v, Kind::Player, t0);
        let v0 = a.core.pose.motion;
        assert_eq!(v0, b.core.pose.motion, "{v}");
        assert!(v0.x < -0.1, "{v}: running west {v0:?}");
        let (_, plain, _) = attack_tick(&mut a, t0, RUN, false);
        let (actions, slowed, hit) = attack_tick(&mut b, t0, RUN, true);
        assert!(hit, "{v}");
        assert!(actions.is_empty(), "{v}: {actions:?}");
        assert!(b.core.pose.sprinting, "{v}");
        let f = f64::from(0.6f32 * 0.91);
        for (p, s, v0) in [(plain.x, slowed.x, v0.x), (plain.z, slowed.z, v0.z)] {
            let want = p - 0.4 * v0 * f;
            assert!(
                (s - want).abs() < 1e-9,
                "{v}: {s} vs {want} (plain {p}, v0 {v0})"
            );
        }
        assert_eq!(plain.y, slowed.y, "{v}");
    }
}

/// 1.9+: the sprint bonus needs full attack strength (above 0.9). An attack on a zombie resets
/// the cooldown; the player hit on the next tick then has no knockback and changes nothing.
/// 1.8 has no cooldown: the second hit unsprints.
#[test]
fn weak_hit_keeps_the_sprint_on_1_9_plus() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = sprinting_at(v, Kind::Zombie, t0);
        let (actions, _, hit) = attack_tick(&mut e, t0, WALK, true);
        assert!(hit && actions.is_empty(), "{v}: {actions:?}");
        // The zombie is replaced by a player at the same spot.
        let s = e.core.sent.pos;
        let destroy = destroy(v, 50);
        e.sim.world_packet(&destroy).unwrap();
        put(&mut e, 50, Kind::Player, Vec3::new(s.x - 1.5, s.y, s.z));
        let (actions, _, hit) = attack_tick(&mut e, t0, WALK, true);
        assert!(hit, "{v}");
        if v.caps().combat_1_9 {
            assert!(actions.is_empty(), "{v}: {actions:?}");
        } else {
            assert_eq!(actions, [EntityAction::StopSprinting], "{v}");
        }
    }
}

/// The version's packet removing entity `id`.
fn destroy(v: GameVersion, id: i32) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    b.put_varint(1);
    b.put_varint(id);
    let pid = match v.instance() {
        GameVersion::V1_8_9 => ghast_protocol::v1_8::play::clientbound::id::ENTITY_DESTROY,
        GameVersion::V1_12_2 => ghast_protocol::v1_12_2::play::clientbound::id::ENTITY_DESTROY,
        GameVersion::V1_16_5 => ghast_protocol::v1_16_5::play::clientbound::id::ENTITY_DESTROY,
        v => modern_cb_id!(v, ENTITY_DESTROY),
    };
    RawPacket::new(pid, b.freeze())
}

/// A knockback sword slows a walking (not sprinting) attacker on 1.8 – 1.16.5 (the client reads
/// the enchantment); the same hit without the enchantment changes nothing.
#[test]
fn knockback_enchantment_slows_without_sprint() {
    let t0 = Instant::now();
    for v in [
        GameVersion::V1_8_9,
        GameVersion::V1_12_2,
        GameVersion::V1_16_5,
    ] {
        let run = |kb: Option<u8>, attack: bool| {
            let mut e = setup(v);
            if let Some(level) = kb {
                e.inventory_mut()
                    .on_set_slot(0, 36, Some(knockback_sword(v, level)));
            }
            for _ in 0..8 {
                tick(&mut e, t0, |ctx| ctx.set_controls(WALK));
            }
            assert!(!e.core.pose.sprinting, "{v}");
            let s = e.core.sent.pos;
            put(&mut e, 50, Kind::Player, Vec3::new(s.x - 1.5, s.y, s.z));
            let v0 = e.core.pose.motion;
            let (actions, after, hit) = attack_tick(&mut e, t0, WALK, attack);
            assert!(hit == attack && actions.is_empty(), "{v}");
            (v0, after)
        };
        let (v0, plain) = run(Some(1), false);
        let (_, slowed) = run(Some(1), true);
        let f = f64::from(0.6f32 * 0.91);
        let want = plain.x - 0.4 * v0.x * f;
        assert!(
            (slowed.x - want).abs() < 1e-9,
            "{v}: {} vs {want}",
            slowed.x
        );
        let (_, no_kb) = run(None, true);
        assert_eq!(no_kb, plain, "{v}: no knockback, no slow-down");
    }
}

/// A diamond sword with Knockback `level` (1.8 / 1.12 `ench` id 19, 1.16 `minecraft:knockback`).
fn knockback_sword(v: GameVersion, level: u8) -> ghast_inventory::Stack {
    let mut b = vec![10, 0, 0, 9];
    if v == GameVersion::V1_16_5 {
        let id = b"minecraft:knockback";
        b.extend_from_slice(&[0, 12]);
        b.extend_from_slice(b"Enchantments");
        b.push(10);
        b.extend_from_slice(&1i32.to_be_bytes());
        b.extend_from_slice(&[8, 0, 2]);
        b.extend_from_slice(b"id");
        b.extend_from_slice(&(id.len() as u16).to_be_bytes());
        b.extend_from_slice(id);
    } else {
        b.extend_from_slice(&[0, 4]);
        b.extend_from_slice(b"ench");
        b.push(10);
        b.extend_from_slice(&1i32.to_be_bytes());
        b.extend_from_slice(&[2, 0, 2]);
        b.extend_from_slice(b"id");
        b.extend_from_slice(&19i16.to_be_bytes());
    }
    b.extend_from_slice(&[2, 0, 3]);
    b.extend_from_slice(b"lvl");
    b.extend_from_slice(&i16::from(level).to_be_bytes());
    b.extend_from_slice(&[0, 0]);
    let id = match v {
        GameVersion::V1_16_5 => i32::from(
            ghast_data::v1_16_5::Item::from_name("diamond_sword")
                .unwrap()
                .id(),
        ),
        _ => 276,
    };
    ghast_inventory::Stack::new(id, 1, 0).with_nbt(Some(
        ghast_protocol::nbt::RawNbt::from_bytes(bytes::Bytes::from(b)).unwrap(),
    ))
}

/// Our flags byte from the server: the sprint bit sets the flag only. With it cleared while
/// sprinting (sprint key up) the client reports the stop on its next movement update, the
/// accessors show the byte, and an attack then is no sprint attack.
#[test]
fn own_flags_byte_sets_the_sprint_flag() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = setup(v);
        let mut seen = None;
        tick(&mut e, t0, |ctx| seen = Some(ctx.server_flags()));
        assert_eq!(seen, Some(None), "{v}");
        for _ in 0..8 {
            tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
        }
        e.sim.world_packet(&own_flags(v, 0x08)).unwrap();
        let mut seen = (None, false);
        tick(&mut e, t0, |ctx| {
            ctx.set_controls(WALK);
            seen = (ctx.server_flags(), ctx.server_sprinting());
        });
        assert_eq!(seen, (Some(0x08), true), "{v}");
        assert!(e.core.pose.sprinting, "{v}");
        e.sim.world_packet(&own_flags(v, 0)).unwrap();
        e.note_inbound(t0);
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_controls(WALK);
            seen = (ctx.server_flags(), ctx.server_sprinting());
        });
        e.tick(&mut b, t0);
        let actions = sprint_actions(e.outbound());
        e.outbound().clear();
        assert_eq!(seen, (Some(0), false), "{v}");
        assert_eq!(actions, [EntityAction::StopSprinting], "{v}");
        assert!(!e.core.pose.sprinting, "{v}");
        // Not ours: ignored.
        let mut other = bytes::BytesMut::from(&own_flags(v, 0x08).body[..]);
        other[0] = 8;
        let id = own_flags(v, 0).id;
        e.sim
            .world_packet(&RawPacket::new(id, other.freeze()))
            .unwrap();
        tick(&mut e, t0, |ctx| {
            seen = (ctx.server_flags(), ctx.server_sprinting())
        });
        assert_eq!(seen, (Some(0), false), "{v}");
        // A new client player forgets it.
        e.sim.reset_player();
        tick(&mut e, t0, |ctx| {
            seen = (ctx.server_flags(), ctx.server_sprinting())
        });
        assert_eq!(seen, (None, false), "{v}");
    }
}

/// A dead player's keys do nothing (`isMovementBlocked`); after the respawn they apply again.
#[test]
fn dead_player_does_not_walk() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = setup(v);
        tick(&mut e, t0, |ctx| ctx.set_controls(WALK));
        e.handle(Inbound::Health(Health {
            health: 0.0,
            food: 20,
            saturation: 0.0,
            ..Health::default()
        }));
        let x0 = e.core.pose.pos.x;
        for _ in 0..20 {
            tick(&mut e, t0, |ctx| ctx.set_controls(WALK));
        }
        // The walk's motion runs out (0.546 friction): far less than 20 ticks of walking.
        let moved = x0 - e.core.pose.pos.x;
        assert!(moved < 0.25, "{v}: moved {moved}");
        assert!(e.core.pose.motion.x.abs() < 1e-3, "{v}");
    }
}

/// An open screen releases the keys (the sprint and the sneak end); with the option off the
/// controls apply through it.
#[test]
fn open_inventory_releases_the_keys() {
    let t0 = Instant::now();
    for v in VERSIONS {
        for release in [true, false] {
            let mut e = setup(v);
            e.core.opts.gui_releases_keys = release;
            for _ in 0..8 {
                tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
            }
            assert!(e.core.pose.sprinting, "{v}");
            e.note_inbound(t0);
            let mut b = Script(|ctx: &mut TickContext<'_>| {
                ctx.set_controls(RUN);
                ctx.open_inventory().unwrap();
            });
            e.tick(&mut b, t0);
            let actions = sprint_actions(e.outbound());
            e.outbound().clear();
            if release {
                assert_eq!(actions, [EntityAction::StopSprinting], "{v}");
            } else {
                assert!(actions.is_empty(), "{v}: {actions:?}");
            }
            let x0 = e.core.pose.pos.x;
            for _ in 0..20 {
                tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
            }
            let moved = x0 - e.core.pose.pos.x;
            assert_eq!(moved < 0.5, release, "{v}: moved {moved}");
            // Closed: the held keys apply again.
            tick(&mut e, t0, |ctx| {
                ctx.set_controls(RUN);
                ctx.close_window().unwrap();
            });
            let x1 = e.core.pose.pos.x;
            for _ in 0..5 {
                tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
            }
            assert!(x1 - e.core.pose.pos.x > 0.5, "{v}");
        }
    }
}

/// 1.16.5's own inventory passes keys pressed while it is open (`InventoryScreen.passEvents`):
/// the keys held through the opening stay released, let go and pressed again they walk and
/// sprint. The other versions' screens take every key.
#[test]
fn own_inventory_passes_new_presses_on_1_16_5() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let passes = v.caps().own_inventory_passes_keys;
        assert_eq!(passes, v == GameVersion::V1_16_5, "{v}");
        let mut e = setup(v);
        for _ in 0..8 {
            tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
        }
        tick(&mut e, t0, |ctx| {
            ctx.set_controls(RUN);
            ctx.open_inventory().unwrap();
        });
        // Held through the opening: released.
        let x0 = e.core.pose.pos.x;
        for _ in 0..20 {
            tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
        }
        let moved = x0 - e.core.pose.pos.x;
        assert!(moved < 0.5, "{v}: moved {moved}");
        assert!(!e.core.pose.sprinting, "{v}");
        // Let go for a tick, then pressed again with the screen still open.
        tick(&mut e, t0, |ctx| ctx.set_controls(Controls::NONE));
        e.outbound().clear();
        let x1 = e.core.pose.pos.x;
        for _ in 0..10 {
            tick(&mut e, t0, |ctx| ctx.set_controls(RUN));
        }
        let moved = x1 - e.core.pose.pos.x;
        assert_eq!(moved > 1.0, passes, "{v}: moved {moved}");
        assert_eq!(e.core.pose.sprinting, passes, "{v}");
        assert!(e.core.inv.inventory_open(), "{v}");
        // A newly pressed key next to one held through the opening: only the new one applies.
        tick(&mut e, t0, |ctx| {
            ctx.set_controls(Controls::NONE);
            ctx.close_window().unwrap();
        });
        for _ in 0..8 {
            tick(&mut e, t0, |ctx| ctx.set_controls(WALK));
        }
        tick(&mut e, t0, |ctx| {
            ctx.set_controls(WALK);
            ctx.open_inventory().unwrap();
        });
        let strafe = Controls { left: true, ..WALK };
        let z0 = e.core.pose.pos.z;
        let x2 = e.core.pose.pos.x;
        for _ in 0..20 {
            tick(&mut e, t0, |ctx| ctx.set_controls(strafe));
        }
        let (dx, dz) = (x2 - e.core.pose.pos.x, z0 - e.core.pose.pos.z);
        assert!(dx.abs() < 0.5, "{v}: forward stays released, moved {dx}");
        assert_eq!(dz.abs() > 1.0, passes, "{v}: strafe {dz}");
    }
}

/// `ctx.velocity()` shows the server's velocity before the step; the step's collisions show
/// the floor.
#[test]
fn velocity_and_collisions() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = setup(v);
        for _ in 0..3 {
            tick(&mut e, t0, |_| {});
        }
        let mut seen = (Vec3::default(), false, false);
        tick(&mut e, t0, |ctx| {
            seen = (
                ctx.velocity(),
                ctx.horizontal_collision(),
                ctx.vertical_collision(),
            );
        });
        assert!(!seen.1 && seen.2, "{v}: standing on the floor {seen:?}");
        assert_eq!(seen.0, e.core.pose.motion, "{v}");
        let push = Vec3::new(0.25, 0.375, -0.125);
        e.handle(Inbound::Velocity {
            entity_id: 7,
            motion: push,
        });
        tick(&mut e, t0, |ctx| seen.0 = ctx.velocity());
        assert_eq!(seen.0, push, "{v}");
    }
}

/// A tick that attacks keeps its look: the server judges the attack with the movement packet
/// after it, and a vanilla client's pick look is always that packet's look (1.8 Grim checks the
/// reach with it only). The aimed turn follows on the next tick. Every version.
#[test]
fn an_attack_tick_holds_the_turn() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = sprinting_at(v, Kind::Player, t0);
        let before = (e.core.pose.yaw, e.core.pose.pitch);
        let aim = (before.0 + 20.0, 30.0);
        let mut hit = false;
        e.note_inbound(t0);
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_controls(WALK);
            ctx.set_aim(aim.0, aim.1);
            hit = ctx.attack(50);
        });
        e.tick(&mut b, t0);
        assert!(hit, "{v}: the attack went out");
        assert_eq!(
            (e.core.pose.yaw, e.core.pose.pitch),
            before,
            "{v}: the turn was held"
        );
        let looks: Vec<(f32, f32)> = e
            .outbound()
            .iter()
            .filter_map(|o| match o {
                Outbound::Move(
                    MovePacket::Look { yaw, pitch, .. }
                    | MovePacket::PositionLook { yaw, pitch, .. },
                ) => Some((*yaw, *pitch)),
                _ => None,
            })
            .collect();
        assert!(
            looks.is_empty(),
            "{v}: no new look on the attack tick: {looks:?}"
        );
        e.outbound().clear();
        // The next tick turns.
        let mut b = Script(|ctx: &mut TickContext<'_>| {
            ctx.set_controls(WALK);
            ctx.set_aim(aim.0, aim.1);
        });
        e.tick(&mut b, t0);
        assert_ne!(
            (e.core.pose.yaw, e.core.pose.pitch),
            before,
            "{v}: turned a tick later"
        );
    }
}

/// `sprinting()` is the sim's flag after this tick's packets: a sprint-off flags byte clears it
/// at once (while the pose still shows the last step's sprint), `attack_slows` then says no and
/// the attack indeed changes nothing. Without the packet both say yes, and after a first hit in
/// the tick `attack_slows` says no. Every version.
#[test]
fn sprint_queries_follow_the_server_flags() {
    let t0 = Instant::now();
    for v in VERSIONS {
        // Sprinting, no packet: a sprint hit slows; the second one in the tick does not.
        let mut e = sprinting_at(v, Kind::Player, t0);
        let mut seen = Vec::new();
        tick(&mut e, t0, |ctx| {
            ctx.set_controls(WALK);
            seen.push((ctx.sprinting(), ctx.attack_slows(50)));
            assert!(ctx.attack(50));
            seen.push((ctx.sprinting(), ctx.attack_slows(50)));
            // A mob or an unknown entity never slows.
            seen.push((ctx.pose().sprinting, ctx.attack_slows(999)));
        });
        assert_eq!(seen, [(true, true), (true, false), (true, false)], "{v}");
        assert!(!e.core.pose.sprinting, "{v}: the hit ended the sprint");

        // The server's sprint-off flags byte before the attack tick.
        let run = |attack: bool| {
            let mut e = sprinting_at(v, Kind::Player, t0);
            e.sim.world_packet(&own_flags(v, 0x08)).unwrap();
            tick(&mut e, t0, |ctx| ctx.set_controls(WALK));
            e.sim.world_packet(&own_flags(v, 0)).unwrap();
            let mut seen = None;
            tick(&mut e, t0, |ctx| {
                ctx.set_controls(WALK);
                seen = Some((ctx.pose().sprinting, ctx.sprinting(), ctx.attack_slows(50)));
                if attack {
                    assert!(ctx.attack(50));
                }
            });
            (seen, e.core.pose.motion)
        };
        let (plain_seen, plain) = run(false);
        let (seen, hit) = run(true);
        assert_eq!(seen, Some((true, false, false)), "{v}");
        assert_eq!(plain_seen, seen, "{v}");
        assert_eq!(hit, plain, "{v}: no slow-down");
    }
}

/// `set_turn_rate` changes the aim's cap from this tick's turn on and stays; `turn_rate` reads
/// it; a bad value keeps the axis's cap.
#[test]
fn turn_rate_changes_mid_session() {
    let t0 = Instant::now();
    let v = VERSIONS[0];
    let mut e = setup(v);
    tick(&mut e, t0, |_| {});
    let y0 = e.core.pose.yaw;
    let mut rate = (0.0, 0.0);
    tick(&mut e, t0, |ctx| {
        rate = ctx.turn_rate();
        ctx.set_aim(y0 + 90.0, 0.0);
    });
    assert_eq!(rate, (14.0, 10.5));
    let d1 = e.core.pose.yaw - y0;
    assert!(d1 > 13.0 && d1 < 14.5, "{d1}");
    tick(&mut e, t0, |ctx| {
        ctx.set_turn_rate(40.0, f64::NAN);
        rate = ctx.turn_rate();
        ctx.set_aim(y0 + 90.0, 0.0);
    });
    assert_eq!(rate, (40.0, 10.5));
    let d2 = e.core.pose.yaw - y0 - d1;
    assert!(d2 > 39.0 && d2 < 41.0, "{d2}");
    // Kept on the next ticks.
    tick(&mut e, t0, |ctx| {
        rate = ctx.turn_rate();
        ctx.set_aim(y0 + 90.0, 0.0);
    });
    assert_eq!(rate, (40.0, 10.5));
    assert!((e.core.pose.yaw - y0 - 90.0).abs() < 0.2);
}

// ---- queued presses (`TickContext::press`) ----

/// A player 2.5 blocks west of the bot (eye level), the bot looking at `look`, the entity's
/// drawn position settled.
fn facing(v: GameVersion, look: (f32, f32), t0: Instant) -> Engine<Box<dyn Sim>> {
    let mut e = setup(v);
    tick(&mut e, t0, |_| {});
    let s = e.core.pose.pos;
    put(&mut e, 50, Kind::Player, Vec3::new(s.x - 2.5, s.y, s.z));
    e.core.forced_look = Some(look);
    for _ in 0..4 {
        tick(&mut e, t0, |_| {});
    }
    assert_eq!((e.core.pose.yaw, e.core.pose.pitch), look, "{v}");
    e
}

/// The tick's hand packets in order: `swing` (a swing or a 26.3 punch), `attack`, others left
/// out. Asserts that they all come before the tick's movement packets.
fn hand_order(out: &[Outbound]) -> Vec<&'static str> {
    let last_hand = out.iter().rposition(|o| {
        matches!(
            o,
            Outbound::Swing | Outbound::Punch | Outbound::UseEntity { .. }
        )
    });
    let first_move = out.iter().position(|o| matches!(o, Outbound::Move(_)));
    if let (Some(h), Some(m)) = (last_hand, first_move) {
        assert!(h < m, "hand packets after the movement: {out:?}");
    }
    out.iter()
        .filter_map(|o| match o {
            Outbound::Swing | Outbound::Punch => Some("swing"),
            Outbound::UseEntity {
                target: 50,
                action: crate::common::EntityUse::Attack,
                ..
            } => Some("attack"),
            Outbound::UseEntity { .. } => Some("other use_entity"),
            _ => None,
        })
        .collect()
}

/// One tick: `presses` queued left presses after `f`; returns the tick's packets.
fn press_tick(
    e: &mut Engine<Box<dyn Sim>>,
    t0: Instant,
    presses: usize,
    mut f: impl FnMut(&mut TickContext<'_>),
) -> Vec<Outbound> {
    e.note_inbound(t0);
    let mut b = Script(|ctx: &mut TickContext<'_>| {
        f(ctx);
        for _ in 0..presses {
            assert!(ctx.press(hands::Button::Left));
        }
    });
    e.tick(&mut b, t0);
    std::mem::take(e.outbound())
}

/// N presses in one tick are N attacks on the crosshair's entity in the key handling, each with
/// its swing in the version's order (1.8: swing first; 1.9+: after the attack), all before the
/// movement packet; 1.9+ resets the cooldown on each. A right press is not queued.
#[test]
fn queued_presses_attack_in_the_version_order() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = facing(v, (90.0, 0.0), t0);
        let mut right = true;
        let out = press_tick(&mut e, t0, 2, |ctx| {
            right = ctx.press(hands::Button::Right);
        });
        assert!(!right, "{v}: the right button is not queued");
        let want: &[&str] = if v.caps().combat_1_9 {
            &["attack", "swing", "attack", "swing"]
        } else {
            &["swing", "attack", "swing", "attack"]
        };
        assert_eq!(hand_order(&out), want, "{v}");
        if v.caps().combat_1_9 {
            assert_eq!(e.core.hands.ticks_since_swing, 0, "{v}: cooldown reset");
        }
        // The presses were this tick's only: the next tick clicks nothing.
        let out = press_tick(&mut e, t0, 0, |_| {});
        assert_eq!(hand_order(&out), [] as [&str; 0], "{v}");
    }
}

/// Two sprint hits in one tick: the first unsprints and slows, the second (no sprint, no
/// knockback item) does not slow again; one stop goes out.
#[test]
fn queued_sprint_hits_slow_once() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = sprinting_at(v, Kind::Player, t0);
        let out = press_tick(&mut e, t0, 2, |ctx| ctx.set_controls(WALK));
        assert_eq!(
            hand_order(&out).iter().filter(|&&n| n == "attack").count(),
            2,
            "{v}: {out:?}"
        );
        assert_eq!(sprint_actions(&out), [EntityAction::StopSprinting], "{v}");
        assert!(!e.core.pose.sprinting, "{v}");
    }
}

/// On a tick with queued presses the turn comes first: the pitch turns onto the target (the old
/// look passes above its head) and the presses attack it, the movement packet carrying the
/// pick's look. The held button's press edge without queued presses picks after the turn too
/// (vanilla's key handling always reads the look the frames turned to before the tick).
#[test]
fn queued_presses_pick_after_the_turn() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = facing(v, (90.0, -10.0), t0);
        let out = press_tick(&mut e, t0, 1, |ctx| ctx.set_aim(90.0, 0.0));
        let want: &[&str] = if v.caps().combat_1_9 {
            &["attack", "swing"]
        } else {
            &["swing", "attack"]
        };
        assert_eq!(hand_order(&out), want, "{v}");
        let now = (e.core.pose.yaw, e.core.pose.pitch);
        assert!(now.0 == 90.0 && now.1.abs() < 0.2, "{v}: turned {now:?}");
        let looks: Vec<(f32, f32)> = out
            .iter()
            .filter_map(|o| match o {
                Outbound::Move(
                    MovePacket::Look { yaw, pitch, .. }
                    | MovePacket::PositionLook { yaw, pitch, .. },
                ) => Some((*yaw, *pitch)),
                _ => None,
            })
            .collect();
        assert_eq!(looks, [now], "{v}: the pick's look goes out");

        // The button edge alone: picked after the turn as well, a hit.
        // The preview and the planned look before the aim describe the old look (a miss),
        // after it the turned one (the hit the key handling then makes).
        let mut e = facing(v, (90.0, -10.0), t0);
        let mut seen = None;
        let out = press_tick(&mut e, t0, 0, |ctx| {
            let before = ctx.press_preview(hands::Button::Left);
            ctx.set_aim(90.0, 0.0);
            seen = Some((
                before,
                ctx.press_preview(hands::Button::Left),
                ctx.planned_look(),
            ));
            ctx.set_buttons(Buttons {
                left: true,
                right: false,
            });
        });
        assert_eq!(hand_order(&out), want, "{v}");
        let (before, after, planned) = seen.unwrap();
        assert!(
            matches!(before, hands::PressOutcome::Nothing),
            "{v}: {before:?}"
        );
        assert!(
            matches!(after, hands::PressOutcome::Entity(_)),
            "{v}: {after:?}"
        );
        assert_eq!(planned, now, "{v}");
        assert_eq!((e.core.pose.yaw, e.core.pose.pitch), now, "{v}");
    }
}

/// 1.8 picks with the head yaw (the yaw before this tick's turn) and every press of the tick
/// acts on that one pick: a yaw turn away from the target still attacks three times. 1.9+ pick
/// with the new yaw: the first press misses, and its miss delay holds back the other two (one
/// swing); with the button up the delay ends with the tick, so the next tick's press swings
/// again. In creative a miss has no delay: three swings.
#[test]
fn queued_presses_share_one_pick_and_the_miss_delay() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = facing(v, (90.0, 0.0), t0);
        let out = press_tick(&mut e, t0, 3, |ctx| ctx.set_aim(102.0, 0.0));
        assert!((e.core.pose.yaw - 102.0).abs() < 0.2, "{v}: turned");
        let order = hand_order(&out);
        if v.caps().combat_1_9 {
            assert_eq!(order, ["swing"], "{v}: one miss");
            assert_eq!(e.core.hands.ticks_since_swing, 0, "{v}: a miss resets");
        } else {
            assert_eq!(
                order,
                ["swing", "attack", "swing", "attack", "swing", "attack"],
                "{v}: one pick (head yaw)"
            );
        }
        // Looking at the sky: one swing per tick however many presses, the delay ends with
        // the tick (the button is up).
        e.core.forced_look = Some((90.0, -60.0));
        tick(&mut e, t0, |_| {});
        for _ in 0..2 {
            let out = press_tick(&mut e, t0, 3, |_| {});
            assert_eq!(hand_order(&out), ["swing"], "{v}");
        }
        // Held: the delay stays, the presses of the next ticks do nothing.
        let held = Buttons {
            left: true,
            right: false,
        };
        let out = press_tick(&mut e, t0, 2, |ctx| ctx.set_buttons(held));
        assert_eq!(hand_order(&out), ["swing"], "{v}");
        let out = press_tick(&mut e, t0, 2, |ctx| ctx.set_buttons(held));
        assert_eq!(hand_order(&out), [] as [&str; 0], "{v}");
        tick(&mut e, t0, |ctx| ctx.set_buttons(Buttons::default()));
        // Creative: no miss delay.
        e.core.game_mode = GameMode::Creative;
        let out = press_tick(&mut e, t0, 3, |_| {});
        assert_eq!(hand_order(&out), ["swing", "swing", "swing"], "{v}");
    }
}

/// An open screen or death drops the presses (and they do not wait for the next tick).
#[test]
fn queued_presses_dropped_behind_a_screen() {
    let t0 = Instant::now();
    for v in VERSIONS {
        let mut e = facing(v, (90.0, 0.0), t0);
        let out = press_tick(&mut e, t0, 2, |ctx| {
            ctx.open_inventory().unwrap();
        });
        assert_eq!(hand_order(&out), [] as [&str; 0], "{v}");
        let out = press_tick(&mut e, t0, 0, |ctx| {
            ctx.close_window().unwrap();
        });
        assert_eq!(hand_order(&out), [] as [&str; 0], "{v}");
    }
}