ghast-client 0.5.6

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 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
//! The sign editor on every version, from real packet bodies: `open_sign_entity` is encoded
//! with the version's generated codec and decoded by its wire layer; the answer is written
//! by the version's `write_play` and read back with the generated serverbound codec. The
//! expected values are the vanilla clients' rules (see `crate::sign`).

use super::tests::{Script, engine, join, names};
use super::*;
use crate::sign::{SignCloseReason, SignEditor, SignError, SignEvent};
use crate::version::ClientVersion;
use ghast_protocol::frame::{FrameDecoder, FrameEncoder};
use ghast_protocol::{BlockPos, RawPacket};

/// Every version the client engine runs.
fn versions() -> Vec<GameVersion> {
    let mut v = vec![
        GameVersion::V1_8_9,
        GameVersion::V1_12_2,
        GameVersion::V1_16_5,
        GameVersion::V26_1,
        GameVersion::V26_2,
    ];
    #[cfg(feature = "v26_3")]
    v.push(GameVersion::V26_3);
    v
}

const SIGN: BlockPos = BlockPos::new(9, 64, 9);

fn raw<P: ghast_protocol::Packet>(p: &P) -> RawPacket {
    RawPacket::from_packet(p).unwrap()
}

/// The version's `open_sign_entity` body.
fn open_packet(v: GameVersion, pos: BlockPos, front: bool) -> RawPacket {
    match v {
        GameVersion::V1_8_9 => {
            raw(&ghast_protocol::v1_8::play::clientbound::OpenSignEntity { location: pos })
        }
        GameVersion::V1_12_2 => {
            raw(&ghast_protocol::v1_12_2::play::clientbound::OpenSignEntity { location: pos })
        }
        GameVersion::V1_16_5 => {
            raw(&ghast_protocol::v1_16_5::play::clientbound::OpenSignEntity { location: pos })
        }
        GameVersion::V26_1 => raw(&ghast_protocol::v26_1::play::clientbound::OpenSignEntity {
            location: pos,
            is_front_text: front,
        }),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            use ghast_protocol::v26_3::play::clientbound as cb;
            raw(&cb::OpenSignEntity {
                location: pos,
                side: if front {
                    cb::OpenSignEntitySide::FRONT
                } else {
                    cb::OpenSignEntitySide::BACK
                },
            })
        }
        _ => raw(&ghast_protocol::v26_2::play::clientbound::OpenSignEntity {
            location: pos,
            is_front_text: front,
        }),
    }
}

/// Decodes `raw` with the version's wire layer (it must pass the default filter) and hands
/// it to the engine.
fn feed(e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket) {
    let v = e.core.opts.caps.version;
    let i = Interests::default();
    let (pass, p) = match v {
        GameVersion::V1_8_9 => (
            crate::version::V1_8::play_filter(i).contains(raw.id),
            crate::version::V1_8::decode_play(raw, &mut ()),
        ),
        GameVersion::V1_12_2 => (
            crate::version::V1_12_2::play_filter(i).contains(raw.id),
            crate::version::V1_12_2::decode_play(raw, &mut Default::default()),
        ),
        GameVersion::V1_16_5 => (
            crate::version::V1_16_5::play_filter(i).contains(raw.id),
            crate::version::V1_16_5::decode_play(raw, &mut ()),
        ),
        GameVersion::V26_1 => (
            crate::version::V26_1::play_filter(i).contains(raw.id),
            crate::version::V26_1::decode_play(raw, &mut Default::default()),
        ),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => (
            crate::version::V26_3::play_filter(i).contains(raw.id),
            crate::version::V26_3::decode_play(raw, &mut Default::default()),
        ),
        _ => (
            crate::version::V26_2::play_filter(i).contains(raw.id),
            crate::version::V26_2::decode_play(raw, &mut Default::default()),
        ),
    };
    assert!(pass, "{v:?}: packet {} filtered", raw.id);
    if let Some(p) = p.unwrap() {
        e.handle(p);
    }
}

/// A sign (or stone) block at `pos` through the version's `block_change`.
fn put_block(e: &mut Engine<Box<dyn Sim>>, pos: BlockPos, sign: bool) {
    let v = e.core.opts.caps.version;
    let raw = match v {
        GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::BlockChange {
            location: pos,
            r#type: if sign { 63 << 4 } else { 1 << 4 },
        }),
        GameVersion::V1_12_2 => raw(&ghast_protocol::v1_12_2::play::clientbound::BlockChange {
            location: pos,
            r#type: if sign { 63 << 4 } else { 1 << 4 },
        }),
        GameVersion::V1_16_5 => {
            let b = ghast_data::v1_16_5::Block::from_name(if sign { "oak_sign" } else { "stone" })
                .unwrap();
            raw(&ghast_protocol::v1_16_5::play::clientbound::BlockChange {
                location: pos,
                r#type: i32::from(b.default_state().id()),
            })
        }
        _ => {
            let name = if sign { "oak_sign" } else { "stone" };
            let id = match v {
                GameVersion::V26_1 => ghast_data::v26_1::Block::from_name(name)
                    .unwrap()
                    .default_state()
                    .id(),
                #[cfg(feature = "v26_3")]
                GameVersion::V26_3 => ghast_data::v26_3::Block::from_name(name)
                    .unwrap()
                    .default_state()
                    .id(),
                _ => ghast_data::v26_2::Block::from_name(name)
                    .unwrap()
                    .default_state()
                    .id(),
            };
            raw(&ghast_protocol::v26_1::play::clientbound::BlockChange {
                location: pos,
                r#type: i32::from(id),
            })
        }
    };
    e.sim.world_packet(&raw).unwrap();
}

/// The serverbound packet `o` as the version writes it.
fn written<V: ClientVersion>(o: &Outbound) -> RawPacket
where
    V::Wire: Default,
{
    let mut enc = FrameEncoder::new();
    V::write_play(&mut enc, o, &mut V::Wire::default()).unwrap();
    let mut dec = FrameDecoder::new();
    dec.push(&enc.take());
    dec.next_packet().unwrap().unwrap()
}

/// `(pos, front, lines)` of the version's `update_sign` for `o`.
fn sign_bytes(v: GameVersion, o: &Outbound) -> (BlockPos, Option<bool>, [String; 4]) {
    let s = |b: &ghast_protocol::types::ByteString| b.to_string();
    match v {
        GameVersion::V1_8_9 => {
            let p: ghast_protocol::v1_8::play::serverbound::UpdateSign =
                written::<crate::version::V1_8>(o).decode_as().unwrap();
            (
                p.location,
                None,
                [s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
            )
        }
        GameVersion::V1_12_2 => {
            let p: ghast_protocol::v1_12_2::play::serverbound::UpdateSign =
                written::<crate::version::V1_12_2>(o).decode_as().unwrap();
            (
                p.location,
                None,
                [s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
            )
        }
        GameVersion::V1_16_5 => {
            let p: ghast_protocol::v1_16_5::play::serverbound::UpdateSign =
                written::<crate::version::V1_16_5>(o).decode_as().unwrap();
            (
                p.location,
                None,
                [s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
            )
        }
        GameVersion::V26_1 => {
            let p: ghast_protocol::v26_1::play::serverbound::UpdateSign =
                written::<crate::version::V26_1>(o).decode_as().unwrap();
            (
                p.location,
                Some(p.is_front_text),
                [s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
            )
        }
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            use ghast_protocol::v26_3::play::serverbound as sb;
            let p: sb::UpdateSign = written::<crate::version::V26_3>(o).decode_as().unwrap();
            (
                p.location,
                Some(p.side == sb::UpdateSignSide::FRONT),
                [s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
            )
        }
        _ => {
            let p: ghast_protocol::v26_2::play::serverbound::UpdateSign =
                written::<crate::version::V26_2>(o).decode_as().unwrap();
            (
                p.location,
                Some(p.is_front_text),
                [s(&p.text1), s(&p.text2), s(&p.text3), s(&p.text4)],
            )
        }
    }
}

fn sign_engine(v: GameVersion) -> Engine<Box<dyn Sim>> {
    let mut e = engine(v);
    join(&mut e);
    e.note_inbound(Instant::now());
    // settle the join (settings, brand, the level-load gate)
    for _ in 0..3 {
        e.tick(&mut Idle, Instant::now());
    }
    e.outbound().clear();
    e
}

fn modern(v: GameVersion) -> bool {
    v.caps().configuration_state
}

/// Opens the editor (the sign placed first), writes the lines in the behaviour tick: one
/// `update_sign` with the vanilla bytes, before the movement packet; keys released while open.
#[test]
fn write_sign_every_version() {
    for v in versions() {
        let mut e = sign_engine(v);
        put_block(&mut e, SIGN, true);
        // the back side on 26.x (legacy signs have only the front)
        let front = !modern(v);
        feed(&mut e, &open_packet(v, SIGN, front));
        let ed = SignEditor::new(SIGN, front);
        let mut seen = (Vec::new(), None, None);
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                seen.0 = ctx.events().signs().to_vec();
                seen.1 = ctx.sign_editor();
                seen.2 = Some(ctx.write_sign(&["Hi§x", "a<b", "", "\u{7f}c\"d"]));
                // closed: a second answer is refused
                assert_eq!(ctx.close_sign(), Err(SignError::NotOpen));
            }),
            Instant::now(),
        );
        assert_eq!(seen.0, vec![SignEvent::Opened(ed)], "{v:?}");
        assert_eq!(seen.1, Some(ed), "{v:?}");
        assert_eq!(seen.2, Some(Ok(())), "{v:?}");
        let out = e.outbound().clone();
        let at = |f: fn(&Outbound) -> bool| out.iter().position(f);
        let us = at(|o| matches!(o, Outbound::UpdateSign { .. })).expect("update_sign");
        // 1.9+ sends no movement packet for a player standing still
        if let Some(mv) = at(|o| matches!(o, Outbound::Move(_))) {
            assert!(us < mv, "{v:?}: the sign after the movement packet");
        } else {
            assert_ne!(v, GameVersion::V1_8_9);
        }
        let n = names(&mut out.clone());
        assert_eq!(
            n.iter().filter(|x| **x == "update_sign").count(),
            1,
            "{v:?}"
        );
        let o = out
            .iter()
            .find(|o| matches!(o, Outbound::UpdateSign { .. }))
            .unwrap();
        let (pos, side, lines) = sign_bytes(v, o);
        assert_eq!(pos, SIGN, "{v:?}");
        assert_eq!(side, modern(v).then_some(ed.front), "{v:?}");
        if v == GameVersion::V1_8_9 {
            // Text.Serializer / Gson: literal strings, HTML-safe escapes
            assert_eq!(lines, ["\"Hix\"", "\"a\\u003cb\"", "\"\"", "\"c\\\"d\""]);
        } else {
            assert_eq!(lines, ["Hix", "a<b", "", "c\"d"].map(String::from), "{v:?}");
        }
        assert!(e.core.sign.is_none());
    }
}

/// The screen takes the keyboard: no movement while the editor is open.
#[test]
fn editor_releases_the_keys() {
    for v in versions() {
        let mut e = sign_engine(v);
        put_block(&mut e, SIGN, true);
        feed(&mut e, &open_packet(v, SIGN, true));
        let walk = Controls {
            forward: true,
            ..Controls::NONE
        };
        let before = e.core.pose.pos;
        for _ in 0..3 {
            e.note_inbound(Instant::now());
            e.tick(
                &mut Script(|ctx: &mut TickContext<'_>| ctx.set_controls(walk)),
                Instant::now(),
            );
        }
        // (the 1.16.5 test chunk lets the player fall: compare the horizontal position)
        let flat = |p: Vec3| (p.x, p.z);
        assert_eq!(
            flat(e.core.pose.pos),
            flat(before),
            "{v:?}: walked with the editor open"
        );
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                ctx.close_sign().unwrap();
                ctx.set_controls(walk);
            }),
            Instant::now(),
        );
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| ctx.set_controls(walk)),
            Instant::now(),
        );
        assert_ne!(
            flat(e.core.pose.pos),
            flat(before),
            "{v:?}: no walk after closing"
        );
    }
}

/// `close_sign` sends four empty lines; a second editor replaces the first (which sends).
#[test]
fn close_and_replace() {
    for v in versions() {
        let mut e = sign_engine(v);
        let other = BlockPos::new(10, 64, 9);
        put_block(&mut e, SIGN, true);
        put_block(&mut e, other, true);
        feed(&mut e, &open_packet(v, SIGN, true));
        feed(&mut e, &open_packet(v, other, true));
        let mut ev = Vec::new();
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                ev = ctx.events().signs().to_vec();
                ctx.close_sign().unwrap();
            }),
            Instant::now(),
        );
        let a = SignEditor::new(SIGN, true);
        let b = SignEditor::new(other, true);
        assert_eq!(
            ev,
            vec![
                SignEvent::Opened(a),
                SignEvent::Closed(a, SignCloseReason::Replaced),
                SignEvent::Opened(b)
            ],
            "{v:?}"
        );
        let sent: Vec<_> = e
            .outbound()
            .iter()
            .filter_map(|o| match o {
                Outbound::UpdateSign { pos, lines, .. } => Some((*pos, lines.clone())),
                _ => None,
            })
            .collect();
        assert_eq!(sent.len(), 2, "{v:?}");
        assert_eq!((sent[0].0, sent[1].0), (SIGN, other));
        assert!(sent.iter().all(|s| s.1.iter().all(String::is_empty)));
        let empty = if v == GameVersion::V1_8_9 { "\"\"" } else { "" };
        let o = e
            .outbound()
            .iter()
            .find(|o| matches!(o, Outbound::UpdateSign { .. }))
            .unwrap()
            .clone();
        assert_eq!(sign_bytes(v, &o).2, [empty; 4].map(String::from), "{v:?}");
    }
}

/// Where the client has no sign: 1.8 / 1.12 open anyway (and stay open), 1.16.5 opens and
/// closes on the screen's first tick (sending), 26.x ignores the packet.
#[test]
fn editor_without_a_sign() {
    for v in versions() {
        let mut e = sign_engine(v);
        put_block(&mut e, SIGN, false);
        feed(&mut e, &open_packet(v, SIGN, true));
        let mut ev = Vec::new();
        let mut open = None;
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                ev = ctx.events().signs().to_vec();
                open = ctx.sign_editor();
            }),
            Instant::now(),
        );
        let ed = SignEditor::new(SIGN, true);
        let sent = names(e.outbound()).contains(&"update_sign");
        match v {
            GameVersion::V1_8_9 | GameVersion::V1_12_2 => {
                assert_eq!(ev, vec![SignEvent::Opened(ed)], "{v:?}");
                assert_eq!(open, Some(ed));
                assert!(!sent);
            }
            GameVersion::V1_16_5 => {
                assert_eq!(
                    ev,
                    vec![
                        SignEvent::Opened(ed),
                        SignEvent::Closed(ed, SignCloseReason::BlockGone)
                    ]
                );
                assert_eq!(open, None);
                assert!(sent);
            }
            _ => {
                assert_eq!(ev, vec![SignEvent::Ignored(ed)], "{v:?}");
                assert_eq!(open, None);
                assert!(!sent);
            }
        }
    }
}

/// 1.16.5 sends the editor before the placed sign's block update (the vanilla client predicted
/// the sign; ghast does not for signs): air at the position keeps the editor open, and the
/// block update that follows confirms it.
#[test]
fn v1_16_5_editor_before_its_block() {
    let v = GameVersion::V1_16_5;
    let mut e = sign_engine(v);
    feed(&mut e, &open_packet(v, SIGN, true));
    e.note_inbound(Instant::now());
    e.tick(&mut Idle, Instant::now());
    assert!(e.core.sign.is_some(), "closed over air");
    put_block(&mut e, SIGN, true);
    e.tick(&mut Idle, Instant::now());
    assert!(e.core.sign.is_some());
    assert!(!names(e.outbound()).contains(&"update_sign"));
}

/// 26.x: the screen's tick closes the editor when the sign is broken or the player is
/// farther than the interaction range + 4 from it; older versions keep it open.
#[test]
fn modern_editor_closes_itself() {
    for v in versions() {
        // the sign is broken
        let mut e = sign_engine(v);
        put_block(&mut e, SIGN, true);
        feed(&mut e, &open_packet(v, SIGN, true));
        put_block(&mut e, SIGN, false);
        let mut ev = Vec::new();
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| ev = ctx.events().signs().to_vec()),
            Instant::now(),
        );
        let ed = SignEditor::new(SIGN, true);
        if modern(v) {
            assert_eq!(
                ev,
                vec![
                    SignEvent::Opened(ed),
                    SignEvent::Closed(ed, SignCloseReason::BlockGone)
                ],
                "{v:?}"
            );
            assert!(names(e.outbound()).contains(&"update_sign"));
        } else {
            // 1.16.5: the screen's block entity keeps the state it read at the start
            assert_eq!(ev, vec![SignEvent::Opened(ed)], "{v:?}");
            assert!(e.core.sign.is_some());
        }
        // too far: 8.5 blocks from the eyes to the sign's box closes it (4.5 + 4)
        let mut e = sign_engine(v);
        put_block(&mut e, SIGN, true);
        feed(&mut e, &open_packet(v, SIGN, true));
        for (z, closes) in [(18.4, false), (18.6, true)] {
            e.handle(Inbound::Teleport(crate::common::Teleport {
                x: 9.5,
                y: 64.0,
                z,
                flags: 0,
                ..Default::default()
            }));
            let mut ev = Vec::new();
            e.note_inbound(Instant::now());
            e.tick(
                &mut Script(|ctx: &mut TickContext<'_>| ev = ctx.events().signs().to_vec()),
                Instant::now(),
            );
            let closed = ev.contains(&SignEvent::Closed(ed, SignCloseReason::TooFar));
            assert_eq!(closed, closes && modern(v), "{v:?} z {z}: {ev:?}");
        }
    }
}

#[test]
fn too_many_lines() {
    let mut e = sign_engine(GameVersion::V1_8_9);
    feed(&mut e, &open_packet(GameVersion::V1_8_9, SIGN, true));
    e.note_inbound(Instant::now());
    e.tick(
        &mut Script(|ctx: &mut TickContext<'_>| {
            assert_eq!(
                ctx.write_sign(&["1", "2", "3", "4", "5"]),
                Err(SignError::TooManyLines)
            );
            // still open
            assert!(ctx.sign_editor().is_some());
        }),
        Instant::now(),
    );
    assert!(!names(e.outbound()).contains(&"update_sign"));
}

// ---- books ----

/// What a version wrote for an `Outbound::EditBook`.
#[derive(Debug, Default)]
struct BookSent {
    /// 1.8 / 1.12: the custom payload channel.
    channel: Option<String>,
    /// 1.16.5+: the slot.
    slot: Option<i32>,
    /// 1.16.5: the signing flag.
    signing: Option<bool>,
    /// 1.8 – 1.16.5: the stack.
    stack: Option<ghast_inventory::Stack>,
    /// 26.x: the pages and title.
    pages: Option<Vec<String>>,
    title: Option<Option<String>>,
}

fn book_sent(v: GameVersion, o: &Outbound) -> BookSent {
    let legacy = |channel: &ghast_protocol::types::ByteString, data: &bytes::Bytes| {
        let slot: ghast_protocol::types::slot::legacy::Slot =
            ghast_protocol::Decode::decode(&mut ghast_protocol::Reader::new(data)).unwrap();
        BookSent {
            channel: Some(channel.to_string()),
            stack: ghast_inventory::from_legacy_slot(slot),
            ..BookSent::default()
        }
    };
    let pages = |p: &[ghast_protocol::types::ByteString]| p.iter().map(|s| s.to_string()).collect();
    match v {
        GameVersion::V1_8_9 => {
            let p: ghast_protocol::v1_8::play::serverbound::CustomPayload =
                written::<crate::version::V1_8>(o).decode_as().unwrap();
            legacy(&p.channel, &p.data)
        }
        GameVersion::V1_12_2 => {
            let p: ghast_protocol::v1_12_2::play::serverbound::CustomPayload =
                written::<crate::version::V1_12_2>(o).decode_as().unwrap();
            legacy(&p.channel, &p.data)
        }
        GameVersion::V1_16_5 => {
            let p: ghast_protocol::v1_16_5::play::serverbound::EditBook =
                written::<crate::version::V1_16_5>(o).decode_as().unwrap();
            BookSent {
                slot: Some(p.hand),
                signing: Some(p.signing),
                stack: ghast_inventory::from_modern_slot(p.new_book),
                ..BookSent::default()
            }
        }
        GameVersion::V26_1 => {
            let p: ghast_protocol::v26_1::play::serverbound::EditBook =
                written::<crate::version::V26_1>(o).decode_as().unwrap();
            BookSent {
                slot: Some(p.hand),
                pages: Some(pages(&p.pages)),
                title: Some(p.title.map(|t| t.to_string())),
                ..BookSent::default()
            }
        }
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            let p: ghast_protocol::v26_3::play::serverbound::EditBook =
                written::<crate::version::V26_3>(o).decode_as().unwrap();
            BookSent {
                slot: Some(p.hand),
                pages: Some(pages(&p.pages)),
                title: Some(p.title.map(|t| t.to_string())),
                ..BookSent::default()
            }
        }
        _ => {
            let p: ghast_protocol::v26_2::play::serverbound::EditBook =
                written::<crate::version::V26_2>(o).decode_as().unwrap();
            BookSent {
                slot: Some(p.hand),
                pages: Some(pages(&p.pages)),
                title: Some(p.title.map(|t| t.to_string())),
                ..BookSent::default()
            }
        }
    }
}

/// `(pages, author, title)` of a legacy book stack's NBT.
fn book_nbt(s: &ghast_inventory::Stack) -> (Vec<String>, Option<String>, Option<String>) {
    use ghast_protocol::nbt::Tag;
    let root = s.nbt().unwrap().parse().unwrap().unwrap().tag;
    let c = root.as_compound().unwrap();
    let pages = match c.get("pages") {
        Some(Tag::List(l)) => l
            .items
            .iter()
            .map(|t| match t {
                Tag::String(s) => s.clone(),
                o => panic!("{o:?}"),
            })
            .collect(),
        _ => Vec::new(),
    };
    let s = |k: &str| match c.get(k) {
        Some(Tag::String(s)) => Some(s.clone()),
        _ => None,
    };
    (pages, s("author"), s("title"))
}

fn the_edit(e: &mut Engine<Box<dyn Sim>>) -> Outbound {
    let o = e
        .outbound()
        .iter()
        .find(|o| matches!(o, Outbound::EditBook(_)))
        .expect("edit_book")
        .clone();
    e.outbound().clear();
    o
}

/// Done, then Sign, on every version: the packet each version's screen sends and the held
/// stack it leaves.
#[test]
fn edit_and_sign_a_book_every_version() {
    for v in versions() {
        let mut e = sign_engine(v);
        let (writable, written_id) = crate::book::book_items(v.caps().data).unwrap();
        e.core
            .inv
            .set_hand(false, Some(ghast_inventory::Stack::new(writable, 1, 0)));
        let me = e.core.opts.name.to_string();
        // Done: two pages typed, one empty page at the end
        let mut r = None;
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                r = Some(ctx.edit_book(false, &["Hel§lo", "two\nlines", ""], None));
            }),
            Instant::now(),
        );
        assert_eq!(r, Some(Ok(())), "{v:?}");
        let s = book_sent(v, &the_edit(&mut e));
        let held = e.core.inv.held().cloned().unwrap();
        let want = vec!["Hello".to_owned(), "two\nlines".to_owned()];
        match v {
            GameVersion::V1_8_9 | GameVersion::V1_12_2 => {
                assert_eq!(s.channel.as_deref(), Some("MC|BEdit"), "{v:?}");
                let st = s.stack.unwrap();
                assert_eq!(st.id(), writable);
                assert_eq!(book_nbt(&st), (want.clone(), None, None), "{v:?}");
                assert_eq!(book_nbt(&held), (want.clone(), None, None), "{v:?}");
            }
            GameVersion::V1_16_5 => {
                assert_eq!((s.slot, s.signing), (Some(0), Some(false)));
                assert_eq!(book_nbt(&s.stack.unwrap()), (want.clone(), None, None));
                assert_eq!(book_nbt(&held), (want.clone(), None, None));
            }
            _ => {
                assert_eq!(s.slot, Some(0), "{v:?}");
                assert_eq!(s.pages.as_ref(), Some(&want), "{v:?}");
                assert_eq!(s.title, Some(None), "{v:?}");
                // updateLocalCopy: the held book carries the pages
                let ty = if v.caps().protocol >= 777 { 56 } else { 54 };
                let c = held.components().expect("components");
                let b = c.get(ty).expect("writable_book_content");
                // 2 pages: "Hello" (5) + no filter, "two\nlines" (9) + no filter
                let mut x = vec![2u8, 5];
                x.extend_from_slice(b"Hello");
                x.extend_from_slice(&[0, 9]);
                x.extend_from_slice(b"two\nlines");
                x.push(0);
                assert_eq!(&b[..], &x[..], "{v:?}");
            }
        }
        // Sign: a title with spaces around it, an empty trailing page
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                r = Some(ctx.edit_book(false, &["A<", ""], Some(" T ")));
            }),
            Instant::now(),
        );
        assert_eq!(r, Some(Ok(())), "{v:?}");
        let s = book_sent(v, &the_edit(&mut e));
        let after = e.core.inv.held().cloned().unwrap();
        let t = Some("T".to_owned());
        match v {
            GameVersion::V1_8_9 => {
                assert_eq!(s.channel.as_deref(), Some("MC|BSign"));
                let st = s.stack.unwrap();
                // the client already made it a written book with JSON pages
                assert_eq!(st.id(), written_id);
                let n = (vec!["\"A\\u003c\"".to_owned()], Some(me.clone()), t.clone());
                assert_eq!(book_nbt(&st), n);
                assert_eq!((after.id(), book_nbt(&after)), (written_id, n));
            }
            GameVersion::V1_12_2 => {
                assert_eq!(s.channel.as_deref(), Some("MC|BSign"));
                let st = s.stack.unwrap();
                assert_eq!(st.id(), writable);
                let n = (vec!["A<".to_owned()], Some(me.clone()), t.clone());
                assert_eq!(book_nbt(&st), n);
                assert_eq!(book_nbt(&after), n);
            }
            GameVersion::V1_16_5 => {
                assert_eq!((s.slot, s.signing), (Some(0), Some(true)));
                let n = (vec!["A<".to_owned()], Some(me.clone()), t.clone());
                assert_eq!(book_nbt(&s.stack.unwrap()), n);
                assert_eq!(book_nbt(&after), n);
            }
            _ => {
                // BookSignScreen sends the edit screen's pages as they are
                assert_eq!(s.pages, Some(vec!["A<".to_owned(), String::new()]), "{v:?}");
                assert_eq!(s.title, Some(t.clone()));
                // and changes nothing in the hand
                assert_eq!(after, held, "{v:?}");
            }
        }
    }
}

#[test]
fn book_refusals_and_the_off_hand() {
    for v in versions() {
        let mut e = sign_engine(v);
        let (writable, _) = crate::book::book_items(v.caps().data).unwrap();
        let mut r = Vec::new();
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                r.push(ctx.edit_book(false, &["x"], None));
            }),
            Instant::now(),
        );
        assert_eq!(r, vec![Err(crate::book::BookError::NoBook)], "{v:?}");
        assert!(!names(e.outbound()).contains(&"edit_book"));
        e.core
            .inv
            .set_hand(true, Some(ghast_inventory::Stack::new(writable, 1, 0)));
        let mut r = None;
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                r = Some(ctx.edit_book(true, &["x"], None));
            }),
            Instant::now(),
        );
        if v == GameVersion::V1_8_9 {
            assert_eq!(r, Some(Err(crate::book::BookError::OffHand)));
            continue;
        }
        assert_eq!(r, Some(Ok(())), "{v:?}");
        let s = book_sent(v, &the_edit(&mut e));
        if v != GameVersion::V1_12_2 {
            assert_eq!(s.slot, Some(40), "{v:?}");
        }
    }
}

/// The new state stays out of the per-packet enum.
#[test]
fn inbound_size_unchanged() {
    assert!(
        std::mem::size_of::<Inbound>() <= 104,
        "{}",
        std::mem::size_of::<Inbound>()
    );
}

// ---- sleeping ----

const BED: BlockPos = BlockPos::new(9, 64, 9);
const ME: i32 = 7;

/// A bed (1.8 / 1.12: head half facing south, meta 8) at `BED`.
fn put_bed(e: &mut Engine<Box<dyn Sim>>) {
    let v = e.core.opts.caps.version;
    let raw = match v {
        GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::BlockChange {
            location: BED,
            r#type: 26 << 4 | 8,
        }),
        GameVersion::V1_12_2 => raw(&ghast_protocol::v1_12_2::play::clientbound::BlockChange {
            location: BED,
            r#type: 26 << 4 | 8,
        }),
        GameVersion::V1_16_5 => raw(&ghast_protocol::v1_16_5::play::clientbound::BlockChange {
            location: BED,
            r#type: i32::from(
                ghast_data::v1_16_5::Block::from_name("red_bed")
                    .unwrap()
                    .default_state()
                    .id(),
            ),
        }),
        _ => {
            let id = match v {
                GameVersion::V26_1 => ghast_data::v26_1::Block::from_name("red_bed")
                    .unwrap()
                    .default_state()
                    .id(),
                #[cfg(feature = "v26_3")]
                GameVersion::V26_3 => ghast_data::v26_3::Block::from_name("red_bed")
                    .unwrap()
                    .default_state()
                    .id(),
                _ => ghast_data::v26_2::Block::from_name("red_bed")
                    .unwrap()
                    .default_state()
                    .id(),
            };
            raw(&ghast_protocol::v26_1::play::clientbound::BlockChange {
                location: BED,
                r#type: i32::from(id),
            })
        }
    };
    e.sim.world_packet(&raw).unwrap();
}

/// The server puts us in the bed: 1.8 / 1.12 `bed`, 1.16.5+ our sleeping position in the
/// entity data (`None`: woke up).
fn sleep_packet(v: GameVersion, bed: Option<BlockPos>) -> RawPacket {
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    match v {
        GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::Bed {
            entity_id: ME,
            location: bed.unwrap(),
        }),
        GameVersion::V1_12_2 => raw(&ghast_protocol::v1_12_2::play::clientbound::Bed {
            entity_id: ME,
            location: bed.unwrap(),
        }),
        _ => {
            // index 13 / 14, type OptPosition 10 / OptionalBlockPos 11
            let (index, ty, id) = match v {
                GameVersion::V1_16_5 => (
                    13,
                    10,
                    ghast_protocol::v1_16_5::play::clientbound::id::ENTITY_METADATA,
                ),
                GameVersion::V26_1 => (
                    14,
                    11,
                    ghast_protocol::v26_1::play::clientbound::id::ENTITY_METADATA,
                ),
                #[cfg(feature = "v26_3")]
                GameVersion::V26_3 => (
                    14,
                    11,
                    ghast_protocol::v26_3::play::clientbound::id::ENTITY_METADATA,
                ),
                _ => (
                    14,
                    11,
                    ghast_protocol::v26_2::play::clientbound::id::ENTITY_METADATA,
                ),
            };
            let mut b = bytes::BytesMut::new();
            b.put_varint(ME);
            b.put_u8(index);
            b.put_varint(ty);
            match bed {
                Some(p) => {
                    b.put_u8(1);
                    let x = (i64::from(p.x) & 0x3ff_ffff) << 38;
                    let z = (i64::from(p.z) & 0x3ff_ffff) << 12;
                    b.put_i64(x | z | (i64::from(p.y) & 0xfff));
                }
                None => b.put_u8(0),
            }
            b.put_u8(0xff);
            RawPacket::new(id, b.freeze())
        }
    }
}

/// Feeds a sleep / wake packet the way the connection routes it.
fn feed_sleep(e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket) {
    let v = e.core.opts.caps.version;
    if matches!(v, GameVersion::V1_8_9 | GameVersion::V1_12_2) {
        feed(e, raw);
    } else {
        // our entity data is the sim's (it learns our id from the join packet)
        e.sim.test_set_own_id(ME);
        e.sim.world_packet(raw).unwrap();
    }
}

/// 1.8 / 1.12 `animation` (entity, animation id).
fn animation(v: GameVersion, id: i32, anim: u8) -> RawPacket {
    use bytes::BufMut;
    use ghast_protocol::codec::McWrite;
    let mut b = bytes::BytesMut::new();
    b.put_varint(id);
    b.put_u8(anim);
    let pid = if v == GameVersion::V1_8_9 {
        ghast_protocol::v1_8::play::clientbound::id::ANIMATION
    } else {
        ghast_protocol::v1_12_2::play::clientbound::id::ANIMATION
    };
    RawPacket::new(pid, b.freeze())
}

/// Falling asleep, the client's bed position, the immobile and level-looking sleeper, the
/// timer, Leave Bed and waking up on every version.
#[test]
fn sleeping_every_version() {
    for v in versions() {
        let mut e = sign_engine(v);
        put_bed(&mut e);
        e.core.pose.pitch = 30.0;
        feed_sleep(&mut e, &sleep_packet(v, Some(BED)));
        let mut seen = (Vec::new(), None, 0, false);
        e.note_inbound(Instant::now());
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                seen.0 = ctx.events().sleep().to_vec();
                seen.1 = ctx.sleeping();
                seen.2 = ctx.sleep_ticks();
                ctx.set_controls(Controls {
                    forward: true,
                    jump: true,
                    ..Controls::NONE
                });
                ctx.set_aim(90.0, 45.0);
            }),
            Instant::now(),
        );
        assert_eq!(
            seen.0,
            vec![crate::common::SleepEvent::FellAsleep(BED)],
            "{v:?}"
        );
        assert_eq!((seen.1, seen.2), (Some(BED), 1), "{v:?}");
        // where the client put the player (x / z: the bed's facing on 1.8 / 1.12, in float)
        let p = e.core.pose.pos;
        let (x, z) = match v {
            GameVersion::V1_8_9 => (9.5, f64::from(9f32 + 0.9f32)),
            GameVersion::V1_12_2 => (9.5, f64::from(9f32 + (0.5f32 + 0.4f32))),
            _ => (9.5, 9.5),
        };
        assert_eq!((p.x, p.z), (x, z), "{v:?}");
        // it falls onto the bed's top (0.5625) from 0.6875 like any entity
        assert!(p.y > 64.56 && p.y <= 64.6875, "{v:?} y {}", p.y);
        // no turn; 1.16.5+ levels the pitch
        let pitch = if v.caps().sleep_levels_pitch {
            0.0
        } else {
            30.0
        };
        assert_eq!(e.core.pose.pitch, pitch, "{v:?}");
        for _ in 0..30 {
            e.note_inbound(Instant::now());
            e.tick(&mut Idle, Instant::now());
        }
        let q = e.core.pose.pos;
        assert_eq!((q.x, q.z), (x, z), "{v:?}: moved while asleep");
        let mut r = (0, false, false);
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                r = (ctx.sleep_ticks(), ctx.leave_bed(), false);
            }),
            Instant::now(),
        );
        assert_eq!((r.0, r.1), (32, true), "{v:?}");
        let o = e
            .outbound()
            .iter()
            .find(|o| matches!(o, Outbound::EntityAction { .. }))
            .cloned()
            .expect("entity_action");
        let action = match v {
            GameVersion::V1_8_9 => {
                written::<crate::version::V1_8>(&o)
                    .decode_as::<ghast_protocol::v1_8::play::serverbound::EntityAction>()
                    .unwrap()
                    .action_id
                    .0
            }
            GameVersion::V1_12_2 => {
                written::<crate::version::V1_12_2>(&o)
                    .decode_as::<ghast_protocol::v1_12_2::play::serverbound::EntityAction>()
                    .unwrap()
                    .action_id
                    .0
            }
            GameVersion::V1_16_5 => {
                written::<crate::version::V1_16_5>(&o)
                    .decode_as::<ghast_protocol::v1_16_5::play::serverbound::EntityAction>()
                    .unwrap()
                    .action_id
                    .0
            }
            _ => {
                written::<crate::version::V26_1>(&o)
                    .decode_as::<ghast_protocol::v26_1::play::serverbound::EntityAction>()
                    .unwrap()
                    .action_id
                    .0
            }
        };
        // STOP_SLEEPING: 2 before 1.20 (after the two sneak actions), 0 on 26.x
        assert_eq!(action, if modern(v) { 0 } else { 2 }, "{v:?}");
        e.outbound().clear();
        // still asleep until the server says otherwise; an arm swing is not a wake-up
        if !modern(v) && v != GameVersion::V1_16_5 {
            feed(&mut e, &animation(v, ME, 0));
            feed(&mut e, &animation(v, ME + 1, 2));
            assert!(e.core.sleeping.is_some(), "{v:?}");
            feed(&mut e, &animation(v, ME, 2));
        } else {
            feed_sleep(&mut e, &sleep_packet(v, None));
        }
        let mut seen = (Vec::new(), Some(BED), 9);
        e.tick(
            &mut Script(|ctx: &mut TickContext<'_>| {
                seen = (
                    ctx.events().sleep().to_vec(),
                    ctx.sleeping(),
                    ctx.sleep_ticks(),
                );
                assert!(!ctx.leave_bed());
            }),
            Instant::now(),
        );
        assert_eq!(
            seen,
            (vec![crate::common::SleepEvent::WokeUp], None, 0),
            "{v:?}"
        );
    }
}

/// Another entity's bed packet does nothing to us; 26.3 puts the player on the bed only when a
/// bed is there (the client's `setPosToBed`), but it sleeps anyway.
#[test]
fn others_and_missing_beds() {
    for v in versions() {
        let mut e = sign_engine(v);
        if !modern(v) && v != GameVersion::V1_16_5 {
            let p = match v {
                GameVersion::V1_8_9 => raw(&ghast_protocol::v1_8::play::clientbound::Bed {
                    entity_id: ME + 1,
                    location: BED,
                }),
                _ => raw(&ghast_protocol::v1_12_2::play::clientbound::Bed {
                    entity_id: ME + 1,
                    location: BED,
                }),
            };
            feed(&mut e, &p);
            assert!(e.core.sleeping.is_none(), "{v:?}");
            continue;
        }
        let before = e.core.pose.pos;
        feed_sleep(&mut e, &sleep_packet(v, Some(BED)));
        e.note_inbound(Instant::now());
        e.tick(&mut Idle, Instant::now());
        assert_eq!(e.core.sleeping, Some(BED), "{v:?}");
        let p = e.core.pose.pos;
        if v == GameVersion::V26_3 {
            assert_eq!(
                (p.x, p.z),
                (before.x, before.z),
                "{v:?}: moved without a bed"
            );
        } else {
            // 1.16.5's setPositionInBed and 26.1 / 26.2's setPosToBed do not look at the
            // block (oracle `sleep_no_bed`)
            assert_eq!((p.x, p.z), (9.5, 9.5), "{v:?}");
        }
    }
}

/// Each one-tick right click with the book sends its use (vanilla opens the book screen on it;
/// anticheats expect the use before an edit), the edit in between changes nothing about that.
#[test]
fn every_book_press_sends_its_use() {
    for v in versions() {
        let mut e = sign_engine(v);
        let (writable, _) = crate::book::book_items(v.caps().data).unwrap();
        e.core
            .inv
            .set_hand(false, Some(ghast_inventory::Stack::new(writable, 1, 0)));
        let mut log = Vec::new();
        for t in 0..30 {
            e.note_inbound(Instant::now());
            e.tick(
                &mut Script(|ctx: &mut TickContext<'_>| {
                    let right = t == 1 || t == 16;
                    ctx.set_buttons(crate::hands::Buttons { left: false, right });
                    if t == 7 {
                        ctx.edit_book(false, &["a"], None).unwrap();
                    }
                }),
                Instant::now(),
            );
            for x in names(e.outbound()) {
                if matches!(x, "block_place" | "edit_book") {
                    log.push((t, x));
                }
            }
        }
        assert_eq!(
            log,
            vec![(1, "block_place"), (7, "edit_book"), (16, "block_place")],
            "{v:?}"
        );
    }
}