ghast-client 0.4.11

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
//! The version-agnostic layer: what the client core receives from and sends to the server,
//! independent of the protocol version.
//!
//! Each supported version (see [`crate::version`]) maps its generated packets to [`Inbound`]
//! and [`Outbound`] values. Only the packets the core or the behaviour needs are mapped; the
//! rest is dropped by the frame decoder's filter before it is decoded.

use bytes::Bytes;
use ghast_protocol::types::ByteString;
use uuid::Uuid;

/// A position or direction in world space.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Vec3 {
    /// East (+) / west (−).
    pub x: f64,
    /// Up (+) / down (−).
    pub y: f64,
    /// South (+) / north (−).
    pub z: f64,
}

impl Vec3 {
    /// A vector from its components.
    #[must_use]
    pub const fn new(x: f64, y: f64, z: f64) -> Self {
        Vec3 { x, y, z }
    }
}

/// The player's pose: feet position, look, motion and movement flags.
///
/// `yaw` / `pitch` are degrees in vanilla's convention (yaw is an unbounded `f32` like the
/// client's `Entity.yaw`; 0 = south, 90 = west; pitch 90 = straight down).
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Pose {
    /// Feet position (bounding box minimum Y).
    pub pos: Vec3,
    /// Yaw in degrees.
    pub yaw: f32,
    /// Pitch in degrees.
    pub pitch: f32,
    /// Motion per tick.
    pub motion: Vec3,
    /// On ground as the client computes it (and sends it).
    pub on_ground: bool,
    /// Creative / ability flight.
    pub flying: bool,
    /// Sneaking (as sent with `entity_action`).
    pub sneaking: bool,
    /// Sprinting (as sent with `entity_action`).
    pub sprinting: bool,
}

impl Pose {
    /// Eye position: feet + 1.62 (1.54 while sneaking in 1.8; 1.16.5 uses a crouching pose
    /// with eyes at 1.27, see [`crate::GameVersion::sneak_eye_height`]).
    #[must_use]
    pub fn eyes(&self, eye_height: f64) -> Vec3 {
        Vec3::new(self.pos.x, self.pos.y + eye_height, self.pos.z)
    }
}

/// Movement keys held for the next movement step (the keyboard state in vanilla).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
pub struct Controls {
    /// Walk forward (W).
    pub forward: bool,
    /// Walk backward (S).
    pub back: bool,
    /// Strafe left (A).
    pub left: bool,
    /// Strafe right (D).
    pub right: bool,
    /// Jump (space).
    pub jump: bool,
    /// Sneak (shift).
    pub sneak: bool,
    /// Sprint key (ctrl).
    pub sprint: bool,
}

impl Controls {
    /// No key held.
    pub const NONE: Controls = Controls {
        forward: false,
        back: false,
        left: false,
        right: false,
        jump: false,
        sneak: false,
        sprint: false,
    };
}

/// Where a chat message is shown.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ChatPosition {
    /// A player chat message.
    Chat,
    /// A system message (command feedback, server announcements).
    System,
    /// The action bar above the hotbar.
    ActionBar,
    /// A value this client does not know.
    Other(i8),
}

impl ChatPosition {
    /// From the wire byte (same values in every supported version).
    #[must_use]
    pub fn from_wire(v: i8) -> Self {
        match v {
            0 => Self::Chat,
            1 => Self::System,
            2 => Self::ActionBar,
            v => Self::Other(v),
        }
    }
}

/// A chat message from the server. The text stays raw JSON until asked for.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ChatMessage {
    /// The chat component as the server sent it (JSON).
    pub json: ByteString,
    /// Where it is shown.
    pub position: ChatPosition,
    /// Sender UUID (1.16+; `None` on 1.8 and for system messages with the nil UUID).
    pub sender: Option<Uuid>,
    /// 1.20.3+: the text already rendered from the NBT component (`json` is empty then).
    pub(crate) rendered: Option<String>,
}

impl ChatMessage {
    /// A message from its JSON chat component.
    #[must_use]
    pub fn from_json(json: ByteString, position: ChatPosition, sender: Option<Uuid>) -> Self {
        ChatMessage {
            json,
            position,
            sender,
            rendered: None,
        }
    }

    /// A message already rendered to plain text (1.20.3+ NBT components).
    #[must_use]
    pub fn from_text(text: String, position: ChatPosition, sender: Option<Uuid>) -> Self {
        ChatMessage {
            json: ByteString::from_static(""),
            position,
            sender,
            rendered: Some(text),
        }
    }

    /// The message as plain text, with legacy `§` formatting codes kept.
    #[must_use]
    pub fn text(&self) -> String {
        match &self.rendered {
            Some(t) => t.clone(),
            None => ghast_protocol::chat::to_plain_text(&self.json),
        }
    }

    /// The message as plain text without `§` formatting codes.
    #[must_use]
    pub fn plain(&self) -> String {
        ghast_protocol::chat::strip_formatting(&self.text())
    }
}

/// Converts a chat component (JSON) to plain text without formatting codes.
#[must_use]
pub fn chat_to_plain(json: &str) -> String {
    ghast_protocol::chat::strip_formatting(&ghast_protocol::chat::to_plain_text(json))
}

/// Game mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum GameMode {
    /// Survival.
    #[default]
    Survival,
    /// Creative.
    Creative,
    /// Adventure.
    Adventure,
    /// Spectator.
    Spectator,
    /// A value this client does not know.
    Other(u8),
}

impl GameMode {
    /// From the wire value (the hardcore bit 0x08 of 1.8 is ignored).
    #[must_use]
    pub fn from_wire(v: u8) -> Self {
        match v & 0x07 {
            0 => Self::Survival,
            1 => Self::Creative,
            2 => Self::Adventure,
            3 => Self::Spectator,
            _ => Self::Other(v),
        }
    }
}

/// Player abilities (`abilities` packet).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Abilities {
    /// Raw flags: 1 invulnerable, 2 flying, 4 may fly, 8 creative (instant break).
    pub flags: i8,
    /// Flying speed (0.05 by default).
    pub flying_speed: f32,
    /// Walking speed (0.1 by default).
    pub walking_speed: f32,
}

impl Default for Abilities {
    fn default() -> Self {
        Abilities {
            flags: 0,
            flying_speed: 0.05,
            walking_speed: 0.1,
        }
    }
}

impl Abilities {
    /// The server allows flight.
    #[must_use]
    pub fn may_fly(&self) -> bool {
        self.flags & 4 != 0
    }

    /// The server says the player is flying.
    #[must_use]
    pub fn flying(&self) -> bool {
        self.flags & 2 != 0
    }

    /// The server says the player takes no damage (creative, spectator).
    #[must_use]
    pub fn invulnerable(&self) -> bool {
        self.flags & 1 != 0
    }

    /// The server says the player builds as in creative (`abilities.creativeMode`).
    #[must_use]
    pub(crate) fn creative_mode(&self) -> bool {
        self.flags & 8 != 0
    }
}

/// Health, food and saturation (`update_health`).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Health {
    /// Health points (20 = full; ≤ 0 = dead).
    pub health: f32,
    /// Food level 0 … 20.
    pub food: i32,
    /// Food saturation.
    pub saturation: f32,
    /// Absorption hearts (the player entity data's absorption amount; not part of
    /// `update_health`, kept from our own `entity_metadata` on every version without entity
    /// tracking, refreshed once per behaviour tick).
    pub absorption: f32,
}

impl Default for Health {
    fn default() -> Self {
        Health {
            health: 20.0,
            food: 20,
            saturation: 5.0,
            absorption: 0.0,
        }
    }
}

/// The world's time (`update_time`), counted on between the server's updates like the
/// vanilla client does (the server sends one a second).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct WorldTime {
    /// Game time: the ticks the world has run (the packet's `age`).
    pub age: i64,
    /// The dimension's day clock in ticks, days included (`time_of_day + 24000 * day`);
    /// `None` when the dimension has no day (26.x: the nether) or the server sent none.
    pub day_time: Option<i64>,
    /// Day clock ticks per game tick: 1 normally, 0 while the day stands still (the
    /// `doDaylightCycle` / `advance_time` game rule off, or a paused 26.x clock).
    pub day_rate: f32,
}

impl WorldTime {
    /// The time of day, `0..24000` (0 = sunrise, 6000 = noon, 18000 = midnight).
    #[must_use]
    pub fn time_of_day(&self) -> Option<i64> {
        self.day_time.map(|t| t.rem_euclid(24000))
    }

    /// The day number (`day_time / 24000`).
    #[must_use]
    pub fn day(&self) -> Option<i64> {
        self.day_time.map(|t| t.div_euclid(24000))
    }

    /// The day stands still (`day_rate` is 0).
    #[must_use]
    pub fn day_frozen(&self) -> bool {
        self.day_rate == 0.0
    }
}

/// One clock of a [`TimeUpdate`]: a 26.x world clock (its `minecraft:world_clock` network id)
/// or, on 1.8 – 1.16.5, the world's single day ([`ClockUpdate::LEGACY_DAY`]).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct ClockUpdate {
    /// Clock id.
    pub id: i32,
    /// Ticks of the clock.
    pub total_ticks: i64,
    /// Fraction of a tick (rates other than whole numbers).
    pub partial_tick: f32,
    /// Clock ticks per game tick (0 = stands still).
    pub rate: f32,
}

impl ClockUpdate {
    /// The id of the legacy day.
    pub const LEGACY_DAY: i32 = -1;
}

/// `update_time` as the core reads it: the game time and the clocks it sets (at most
/// [`TimeUpdate::MAX_CLOCKS`]; vanilla has two, further ones are dropped).
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct TimeUpdate {
    /// Game time.
    pub age: i64,
    /// The clocks, `clocks[..len]`.
    pub clocks: [ClockUpdate; TimeUpdate::MAX_CLOCKS],
    /// Number of clocks.
    pub len: u8,
}

impl TimeUpdate {
    /// Clocks one update carries.
    pub const MAX_CLOCKS: usize = 3;

    /// 1.8 – 1.16.5: `age` and the day's `time`, negative while the daylight cycle is off
    /// (vanilla's `WorldClient.setWorldTime`).
    #[must_use]
    pub fn legacy(age: i64, time: i64) -> TimeUpdate {
        let mut u = TimeUpdate {
            age,
            ..TimeUpdate::default()
        };
        u.push(ClockUpdate {
            id: ClockUpdate::LEGACY_DAY,
            total_ticks: time.wrapping_abs(),
            partial_tick: 0.0,
            rate: if time < 0 { 0.0 } else { 1.0 },
        });
        u
    }

    /// Adds a clock (dropped when full).
    pub fn push(&mut self, c: ClockUpdate) {
        if let Some(slot) = self.clocks.get_mut(usize::from(self.len)) {
            *slot = c;
            self.len += 1;
        }
    }

    /// 26.x `update_time` body: `age` (long), then a map of world clock (var-int id) to state
    /// (var-long ticks, float partial tick, float rate). Decoded in place, nothing allocated.
    ///
    /// # Errors
    /// A malformed body.
    pub fn decode_modern(body: &bytes::Bytes) -> Result<TimeUpdate, ghast_protocol::DecodeError> {
        let mut r = ghast_protocol::Reader::new(body);
        let mut u = TimeUpdate {
            age: r.read_i64()?,
            ..TimeUpdate::default()
        };
        let n = r.read_varint()?;
        for _ in 0..n.max(0) {
            let c = ClockUpdate {
                id: r.read_varint()?,
                total_ticks: r.read_varlong()?,
                partial_tick: r.read_f32()?,
                rate: r.read_f32()?,
            };
            u.push(c);
        }
        Ok(u)
    }

    /// The clocks.
    #[must_use]
    pub fn clocks(&self) -> &[ClockUpdate] {
        &self.clocks[..usize::from(self.len)]
    }
}

/// The client's clocks (vanilla `ClientClockManager`; the legacy day is one of them).
#[derive(Debug, Clone, Copy, Default)]
pub(crate) struct Clocks {
    known: bool,
    age: i64,
    last: i64,
    len: u8,
    c: [ClockUpdate; Clocks::CAP],
}

impl Clocks {
    const CAP: usize = 4;

    /// One client tick (`ClientLevel.tickTime`): game time + 1, the clocks follow.
    #[inline]
    pub(crate) fn tick(&mut self) {
        if self.known {
            self.age = self.age.wrapping_add(1);
            self.advance();
        }
    }

    /// `ClientClockManager.tick`: each clock moves by the game time passed times its rate.
    fn advance(&mut self) {
        let d = self.age.wrapping_sub(self.last);
        self.last = self.age;
        for c in &mut self.c[..usize::from(self.len)] {
            let t = f64::from(c.partial_tick) + d as f64 * f64::from(c.rate);
            // Mth.floor(double) -> int
            let i = t as i32;
            let whole = if t < f64::from(i) { i - 1 } else { i };
            c.partial_tick = (t - f64::from(whole)) as f32;
            c.total_ticks = c.total_ticks.wrapping_add(i64::from(whole));
        }
    }

    /// `handleSetTime`: the game time, the clocks moved up to it, then the sent states.
    pub(crate) fn apply(&mut self, u: &TimeUpdate) {
        if !self.known {
            self.known = true;
            self.last = u.age;
        }
        self.age = u.age;
        self.advance();
        for s in u.clocks() {
            let n = usize::from(self.len);
            match self.c[..n].iter_mut().find(|c| c.id == s.id) {
                Some(c) => *c = *s,
                None if n < Clocks::CAP => {
                    self.c[n] = *s;
                    self.len += 1;
                }
                None => {}
            }
        }
    }

    /// The time with `day` as the day clock (`None` before the first update).
    pub(crate) fn world_time(&self, day: Option<i32>) -> Option<WorldTime> {
        if !self.known {
            return None;
        }
        let c = day.and_then(|id| self.c[..usize::from(self.len)].iter().find(|c| c.id == id));
        Some(WorldTime {
            age: self.age,
            day_time: c.map(|c| c.total_ticks),
            day_rate: c.map_or(0.0, |c| c.rate),
        })
    }
}

/// Relative-teleport flag bits of the server's position packet.
pub mod teleport_flags {
    /// X is relative.
    pub const X: i8 = 0x01;
    /// Y is relative.
    pub const Y: i8 = 0x02;
    /// Z is relative.
    pub const Z: i8 = 0x04;
    /// Yaw is relative.
    pub const YAW: i8 = 0x08;
    /// Pitch is relative.
    pub const PITCH: i8 = 0x10;
}

/// A server teleport (position packet), before it is applied to the pose.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
#[non_exhaustive]
pub struct Teleport {
    /// X (absolute or relative, see `flags`).
    pub x: f64,
    /// Y.
    pub y: f64,
    /// Z.
    pub z: f64,
    /// Yaw.
    pub yaw: f32,
    /// Pitch.
    pub pitch: f32,
    /// [`teleport_flags`] bits.
    pub flags: i8,
    /// Teleport id to confirm (1.9+).
    pub teleport_id: Option<i32>,
    /// Every relative bit as on the wire: `flags` (bits 0 – 4) plus, from 1.21.2 on, 5 – 7
    /// delta X / Y / Z relative and 8 "rotate the delta".
    pub relative: u32,
    /// The motion the teleport sets (1.21.2+; zero before).
    pub delta: Vec3,
}

/// Login-state packets from the server, common to every version.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum LoginInbound {
    /// The server refused the login (chat JSON).
    Disconnect(ByteString),
    /// Online mode: the server asks for encryption.
    EncryptionRequest {
        /// Server id (usually empty) for the session hash.
        server_id: ByteString,
        /// The server's RSA public key (DER).
        public_key: Bytes,
        /// Token to encrypt and send back.
        verify_token: Bytes,
    },
    /// The server asks for encryption without a session-server check (1.20.5+
    /// `shouldAuthenticate = false`): the client encrypts and skips the `join` call, so an
    /// offline account can answer it too.
    EncryptionRequestUnauthenticated {
        /// Server id (usually empty).
        server_id: ByteString,
        /// The server's RSA public key (DER).
        public_key: Bytes,
        /// Token to encrypt and send back.
        verify_token: Bytes,
    },
    /// Compression starts with the next packet.
    Compress(i32),
    /// Login finished; the connection is in the play state.
    Success {
        /// The player's UUID as the server assigned it.
        uuid: Option<Uuid>,
        /// The player's name.
        username: ByteString,
    },
    /// A login plugin request (1.13+): answered with "not understood".
    PluginRequest {
        /// Message id to answer.
        message_id: i32,
        /// Channel name.
        channel: ByteString,
    },
    /// The server asks for a cookie (1.20.5+): answered with none.
    CookieRequest(ByteString),
}

/// A data pack the server offers as known (configuration `select_known_packs`).
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct KnownPack {
    /// Namespace (`minecraft`).
    pub namespace: ByteString,
    /// Pack id (`core`).
    pub id: ByteString,
    /// Pack version (the game version, e.g. `26.1.2`).
    pub version: ByteString,
}

/// Configuration-state packets from the server the client reacts to (1.20.2+).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ConfigInbound {
    /// Keep-alive to echo.
    KeepAlive(i64),
    /// Ping to answer with a pong.
    Ping(i32),
    /// Configuration is done: answer and enter play.
    Finish,
    /// The server ends the connection (plain text).
    Disconnect(String),
    /// The packs the server can skip sending data for.
    SelectKnownPacks(Vec<KnownPack>),
    /// A registry (`registry_data`), kept raw for the world and the wire layer.
    RegistryData(ghast_protocol::RawPacket),
    /// A server resource pack.
    ResourcePackPush {
        /// Pack id.
        id: Uuid,
        /// The server requires it.
        required: bool,
    },
    /// The server asks for a cookie.
    CookieRequest(ByteString),
    /// The server's code of conduct (26.x): the player accepts it to continue.
    CodeOfConduct(String),
    /// The server sends the client to another server (`host:port`): the session ends with
    /// [`crate::SessionEnd::Transferred`] (followed with [`crate::Client::follow_transfers`]).
    Transfer(String),
    /// The server shows a dialog (26.1+, see [`crate::dialog`]).
    ShowDialog(Box<crate::dialog::Dialog>),
    /// The server closes the open dialog.
    ClearDialog,
}

/// Configuration-state packets the client writes (1.20.2+).
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum ConfigOutbound {
    /// Keep-alive answer.
    KeepAlive(i64),
    /// Pong.
    Pong(i32),
    /// Acknowledge the end of configuration.
    Finish,
    /// The packs the client knows too.
    SelectKnownPacks(Vec<KnownPack>),
    /// Resource pack status (see [`Outbound::ResourcePackStatus`]).
    ResourcePackStatus {
        /// Pack id.
        id: Uuid,
        /// Status.
        result: i32,
    },
    /// Cookie answer.
    CookieResponse {
        /// Key.
        key: ByteString,
    },
    /// Accept the code of conduct.
    AcceptCodeOfConduct,
    /// The client brand.
    Brand(String),
    /// Client settings.
    Settings(ClientSettings),
    /// A dialog button's custom action (26.1+, see [`Outbound::CustomClickAction`]).
    CustomClickAction {
        /// Action id.
        id: String,
        /// Payload tag.
        payload: Option<ghast_protocol::nbt::AnonNbt>,
    },
}

/// Static information from the join game packet.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct JoinGame {
    /// The player's entity id.
    pub entity_id: i32,
    /// Game mode.
    pub game_mode: GameMode,
    /// Dimension: the 1.8 id (−1 nether, 0 overworld, 1 end) as a string, or the 1.16 world
    /// name (e.g. `minecraft:overworld`).
    pub dimension: String,
    /// Hardcore world.
    pub hardcore: bool,
    /// 1.16: the dimension codec and dimension type NBT, kept raw (not parsed).
    pub dimension_nbt: Option<(ghast_protocol::nbt::RawNbt, ghast_protocol::nbt::RawNbt)>,
    /// 1.16: the respawn screen is shown (false = immediate respawn gamerule).
    pub respawn_screen: bool,
}

/// Clientbound play packets the core understands, common to every version.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Inbound {
    /// Keep-alive to echo.
    KeepAlive(i64),
    /// Join game (also sent again on a proxy server switch).
    JoinGame(JoinGame),
    /// Respawn / dimension change.
    Respawn {
        /// Dimension key (see [`JoinGame::dimension`]).
        dimension: String,
        /// Game mode after the respawn.
        game_mode: GameMode,
        /// 1.20.2+ data kept from the old player: bit 1 attributes, bit 2 entity data (the
        /// last sent input and sprinting); 0 before.
        keep: u8,
    },
    /// Server teleport / position correction.
    Teleport(Teleport),
    /// Chat message.
    Chat(ChatMessage),
    /// The server ends the session (chat JSON).
    Disconnect(ByteString),
    /// Health, food and saturation.
    Health(Health),
    /// The world's time (`update_time`).
    Time(TimeUpdate),
    /// Abilities.
    Abilities(Abilities),
    /// The server selects a hotbar slot.
    HeldSlot(i8),
    /// Game state change (`reason`, `value`), e.g. reason 3 = game mode.
    GameState {
        /// Reason id (same numbering in all supported versions).
        reason: u8,
        /// Value.
        value: f32,
    },
    /// Window confirm transaction.
    Transaction {
        /// Window id.
        window_id: i8,
        /// Action number.
        action: i16,
        /// Accepted.
        accepted: bool,
    },
    /// A window opened.
    OpenWindow(i32),
    /// The open window was closed by the server.
    CloseWindow(i32),
    /// Compression threshold change in the play state (1.8).
    SetCompression(i32),
    /// Entity velocity (blocks per tick; the wire's 1/8000 units converted).
    Velocity {
        /// The entity.
        entity_id: i32,
        /// Motion per tick.
        motion: Vec3,
    },
    /// The player motion an explosion adds.
    ExplosionPush(Vec3),
    /// Movement speed attribute of an entity (entity properties packet).
    MovementSpeed {
        /// The entity.
        entity_id: i32,
        /// Base value.
        base: f64,
        /// Modifiers `(uuid, amount, operation)` in packet order.
        modifiers: Vec<(Uuid, f64, i8)>,
    },
    /// The attributes of an entity the core reads (1.9 – 1.16 entity properties packet):
    /// base and modifiers `(uuid, amount, operation)` in packet order, when the packet has them.
    LegacyAttributes {
        /// The entity.
        entity_id: i32,
        /// `generic.movement_speed`.
        movement_speed: Option<LegacyAttribute>,
        /// `generic.attack_speed`.
        attack_speed: Option<LegacyAttribute>,
    },
    /// A status effect was applied to an entity.
    Effect {
        /// The entity.
        entity_id: i32,
        /// Effect id.
        id: i8,
        /// Amplifier (level − 1).
        amplifier: i8,
    },
    /// A status effect was applied, with its duration and flags (replaces [`Inbound::Effect`]
    /// in the decoders since 0.4.8; the engine still accepts both).
    EffectApplied(StatusEffect),
    /// The world's spawn point.
    SpawnPoint(SpawnPoint),
    /// A player death with its killer and message (replaces [`Inbound::Died`] in the decoders
    /// since 0.4.8; the engine still accepts both).
    Death(Death),
    /// 26.x `damage_event`: an entity was hurt (with the damage source).
    Damage(Hurt),
    /// A scoreboard team packet (decoded with [`crate::Interests::TEAMS`]; parsed by the engine
    /// into [`crate::teams::Teams`]).
    Teams(crate::teams::TeamsPacket),
    /// A status effect ended.
    EffectRemoved {
        /// The entity.
        entity_id: i32,
        /// Effect id.
        id: i8,
    },
    /// Entity status (e.g. 9 = our item use finished).
    EntityStatus {
        /// The entity.
        entity_id: i32,
        /// Status id.
        status: i8,
    },
    /// An entity (the player, if it is our id) died (1.16 `combat_event` "entity dead").
    Died {
        /// The dead player's entity id.
        entity_id: i32,
    },
    /// Movement attributes of an entity (1.20.5+ registry attributes; only the ones movement
    /// reads are kept).
    Attributes {
        /// The entity.
        entity_id: i32,
        /// The attributes in packet order.
        attributes: Vec<AttributeUpdate>,
    },
    /// The server's ping (1.17+): answered with a pong.
    Ping(i32),
    /// A chunk batch starts (1.20.2+).
    ChunkBatchStart,
    /// A chunk batch ended with this many chunks (1.20.2+): answered with the chunks per tick.
    ChunkBatchFinished(i32),
    /// The server moves the connection back to the configuration state (1.20.2+).
    StartConfiguration,
    /// A server resource pack (1.20.3+ ids).
    ResourcePackPush {
        /// Pack id.
        id: Uuid,
        /// The server requires it.
        required: bool,
    },
    /// The server asks for a cookie (1.20.5+).
    CookieRequest(ByteString),
    /// The server sends the client to another server (1.20.5+ `transfer`): the session ends
    /// with [`crate::SessionEnd::Transferred`] (followed with [`crate::Client::follow_transfers`]).
    Transfer {
        /// Target host.
        host: String,
        /// Target port.
        port: u16,
    },
    /// The server stores a cookie (1.20.5+).
    StoreCookie {
        /// Key.
        key: ByteString,
        /// Value.
        value: Bytes,
    },
    /// A rotation-only server turn (1.21.2+ `player_rotation`).
    Rotate {
        /// Yaw (added when `relative_yaw`).
        yaw: f32,
        /// Pitch (added when `relative_pitch`).
        pitch: f32,
        /// Yaw is relative.
        relative_yaw: bool,
        /// Pitch is relative.
        relative_pitch: bool,
    },
    /// The server shows a dialog (26.1+ `show_dialog`, only with
    /// [`crate::Interests::DIALOGS`]).
    ShowDialog(std::sync::Arc<crate::dialog::Dialog>),
    /// The server closes the open dialog (`clear_dialog`).
    ClearDialog,
}

/// One attribute of a 1.9 – 1.16 entity properties packet: base and modifiers
/// `(uuid, amount, operation)` in packet order.
pub type LegacyAttribute = (f64, Vec<(Uuid, f64, i8)>);

/// One entry of a 1.20.5+ attributes packet.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct AttributeUpdate {
    /// Registry name without namespace (`movement_speed`, `step_height`, …).
    pub name: &'static str,
    /// Base value.
    pub base: f64,
    /// Modifiers `(id, amount, operation)` in packet order.
    pub modifiers: Vec<(ByteString, f64, i8)>,
}

/// Sneak / sprint `entity_action` values.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EntityAction {
    /// Start sneaking.
    StartSneaking,
    /// Stop sneaking.
    StopSneaking,
    /// Start sprinting.
    StartSprinting,
    /// Stop sprinting.
    StopSprinting,
    /// Start gliding with an elytra (1.9+ `START_FALL_FLYING`; ghast sends it on 26.1).
    StartFallFlying,
}

/// The one movement packet of a tick.
///
/// `horizontal_collision` is sent from 1.21.2 on (always `false` for older versions).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum MovePacket {
    /// `flying` (C03): only on-ground.
    Flying {
        /// On ground.
        on_ground: bool,
        /// Horizontal collision (1.21.2+).
        horizontal_collision: bool,
    },
    /// `position` (C04).
    Position {
        /// Feet position.
        pos: Vec3,
        /// On ground.
        on_ground: bool,
        /// Horizontal collision (1.21.2+).
        horizontal_collision: bool,
    },
    /// `look` (C05).
    Look {
        /// Yaw.
        yaw: f32,
        /// Pitch.
        pitch: f32,
        /// On ground.
        on_ground: bool,
        /// Horizontal collision (1.21.2+).
        horizontal_collision: bool,
    },
    /// `position_look` (C06).
    PositionLook {
        /// Feet position.
        pos: Vec3,
        /// Yaw.
        yaw: f32,
        /// Pitch.
        pitch: f32,
        /// On ground.
        on_ground: bool,
        /// Horizontal collision (1.21.2+).
        horizontal_collision: bool,
    },
}

impl MovePacket {
    /// The 1.8 trace name (`C03` … `C06`).
    #[must_use]
    pub fn trace_id(&self) -> &'static str {
        match self {
            Self::Flying { .. } => "C03",
            Self::Position { .. } => "C04",
            Self::Look { .. } => "C05",
            Self::PositionLook { .. } => "C06",
        }
    }
}

/// Client settings (`settings` packet), sent right after join game like vanilla.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct ClientSettings {
    /// Locale, e.g. `en_US` (1.8) / `en_us` (1.16).
    pub locale: String,
    /// View distance in chunks.
    pub view_distance: i8,
    /// Chat visibility: 0 full, 1 commands only, 2 hidden.
    pub chat_mode: i8,
    /// Chat colours.
    pub chat_colors: bool,
    /// Displayed skin parts (bit mask; 0x7f = all).
    pub skin_parts: u8,
    /// Main hand (1.9+): 0 left, 1 right.
    pub main_hand: i32,
}

impl ClientSettings {
    /// The locale, e.g. `en_US` (1.8) / `en_us` (1.16).
    #[must_use]
    pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
        self.locale = locale.into();
        self
    }

    /// The view distance in chunks.
    #[must_use]
    pub const fn with_view_distance(mut self, chunks: i8) -> Self {
        self.view_distance = chunks;
        self
    }

    /// Chat visibility: 0 full, 1 commands only, 2 hidden.
    #[must_use]
    pub const fn with_chat_mode(mut self, mode: i8) -> Self {
        self.chat_mode = mode;
        self
    }

    /// Chat colours.
    #[must_use]
    pub const fn with_chat_colors(mut self, on: bool) -> Self {
        self.chat_colors = on;
        self
    }

    /// Displayed skin parts (bit mask; 0x7f = all).
    #[must_use]
    pub const fn with_skin_parts(mut self, mask: u8) -> Self {
        self.skin_parts = mask;
        self
    }

    /// Main hand (1.9+): 0 left, 1 right.
    #[must_use]
    pub const fn with_main_hand(mut self, hand: i32) -> Self {
        self.main_hand = hand;
        self
    }
}

impl Default for ClientSettings {
    fn default() -> Self {
        ClientSettings {
            locale: "en_US".to_owned(),
            view_distance: 8,
            chat_mode: 0,
            chat_colors: true,
            skin_parts: 0x7f,
            main_hand: 1,
        }
    }
}

/// A block face, as in the dig / place packets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Face {
    /// −Y (0).
    Down,
    /// +Y (1).
    Up,
    /// −Z (2).
    North,
    /// +Z (3).
    South,
    /// −X (4).
    West,
    /// +X (5).
    East,
}

impl Face {
    /// The wire value 0 … 5.
    #[must_use]
    pub const fn id(self) -> i8 {
        match self {
            Face::Down => 0,
            Face::Up => 1,
            Face::North => 2,
            Face::South => 3,
            Face::West => 4,
            Face::East => 5,
        }
    }

    /// From the wire value.
    #[must_use]
    pub const fn from_id(id: i8) -> Option<Face> {
        Some(match id {
            0 => Face::Down,
            1 => Face::Up,
            2 => Face::North,
            3 => Face::South,
            4 => Face::West,
            5 => Face::East,
            _ => return None,
        })
    }

    /// The neighbouring block in this direction.
    #[must_use]
    pub const fn offset(self, p: ghast_protocol::BlockPos) -> ghast_protocol::BlockPos {
        let (x, y, z) = match self {
            Face::Down => (0, -1, 0),
            Face::Up => (0, 1, 0),
            Face::North => (0, 0, -1),
            Face::South => (0, 0, 1),
            Face::West => (-1, 0, 0),
            Face::East => (1, 0, 0),
        };
        ghast_protocol::BlockPos::new(p.x + x, p.y + y, p.z + z)
    }
}

/// The `use_entity` action.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum EntityUse {
    /// Right click (0).
    Interact,
    /// Left click (1).
    Attack,
    /// Right click at a point relative to the entity position (2).
    InteractAt(Vec3),
}

/// `block_dig` status values used by the client.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum DigStatus {
    /// Start destroying a block (0).
    Start,
    /// Abort destroying (1).
    Abort,
    /// Finish destroying (2).
    Finish,
    /// Release the used item: stop eating / blocking / drawing (5).
    ReleaseUseItem,
    /// Drop the whole held stack (3; the drop key with control held).
    DropStack,
    /// Drop one item of the held stack (4; the drop key).
    DropItem,
    /// Swap the main- and off-hand stacks (6; 1.9+, the swap-hands key).
    SwapHands,
}

impl DigStatus {
    /// The wire value.
    #[must_use]
    pub const fn id(self) -> i32 {
        match self {
            DigStatus::Start => 0,
            DigStatus::Abort => 1,
            DigStatus::Finish => 2,
            DigStatus::ReleaseUseItem => 5,
            DigStatus::DropStack => 3,
            DigStatus::DropItem => 4,
            DigStatus::SwapHands => 6,
        }
    }
}

/// The vehicle the player rides ([`crate::TickContext::vehicle`]).
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Vehicle {
    /// Its entity id.
    pub entity_id: i32,
    /// Position after this tick (the client's, for a vehicle it controls).
    pub pos: Vec3,
    /// Yaw.
    pub yaw: f32,
    /// Pitch.
    pub pitch: f32,
    /// On the ground.
    pub on_ground: bool,
    /// The client moves it (a boat) rather than the server (a minecart).
    pub controlled: bool,
}

/// Serverbound play packets the core writes, common to every version.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum Outbound {
    /// Keep-alive answer.
    KeepAlive(i64),
    /// Teleport confirm (1.9+; never produced for 1.8).
    TeleportConfirm(i32),
    /// The movement packet.
    Move(MovePacket),
    /// Sneak / sprint change.
    EntityAction {
        /// Our entity id.
        entity_id: i32,
        /// The action.
        action: EntityAction,
    },
    /// Chat line or command (already truncated to the version's limit).
    Chat(String),
    /// Respawn request (client command "perform respawn").
    Respawn,
    /// Window confirm transaction answer.
    Transaction {
        /// Window id.
        window_id: i8,
        /// Action number.
        action: i16,
        /// Accepted.
        accepted: bool,
    },
    /// Abilities (sent when the client toggles flight).
    Abilities {
        /// Flags (1 invulnerable, 2 flying, 4 may fly, 8 creative).
        flags: i8,
        /// Flying speed.
        flying_speed: f32,
        /// Walking speed.
        walking_speed: f32,
    },
    /// Select a hotbar slot (0 … 8).
    HeldSlot(i16),
    /// Arm swing (main hand).
    Swing,
    /// `block_dig`.
    Dig {
        /// Status.
        status: DigStatus,
        /// Block.
        pos: ghast_protocol::BlockPos,
        /// Face.
        face: Face,
    },
    /// `block_place` on a block face (1.8 with the held stack; 1.16 main hand).
    Place {
        /// The block clicked.
        pos: ghast_protocol::BlockPos,
        /// The face clicked.
        face: Face,
        /// Hit point relative to the block (floats, 0 … 1).
        cursor: Vec3,
        /// The held stack (1.8 sends it; vanilla servers / Grim compare it with the hand).
        held: Option<ghast_inventory::Stack>,
        /// 1.9+: the off hand.
        off_hand: bool,
    },
    /// [`Outbound::Place`] of a ray that started inside the clicked block's outline (1.14+
    /// `insideBlock`; 1.8 – 1.12 write it as a plain placement).
    PlaceInside {
        /// The block clicked.
        pos: ghast_protocol::BlockPos,
        /// The face clicked.
        face: Face,
        /// Hit point relative to the block (floats, 0 … 1).
        cursor: Vec3,
        /// The held stack.
        held: Option<ghast_inventory::Stack>,
        /// The off hand.
        off_hand: bool,
    },
    /// Use the held item: 1.8 `block_place` in vanilla's own form (position −1/−1/−1, face 255,
    /// the held stack, cursor 0/0/0 — what servers and anticheats expect; other forms are
    /// flagged as bad packets); 1.9+ `use_item` with the hand.
    UseItem {
        /// The held stack.
        held: Option<ghast_inventory::Stack>,
        /// 1.9+: the off hand.
        off_hand: bool,
    },
    /// 1.9+: off-hand arm swing.
    SwingOffHand,
    /// `use_entity`: attack or interact with an entity.
    UseEntity {
        /// The entity.
        target: i32,
        /// What to do.
        action: EntityUse,
        /// 1.9+: the off hand (interactions).
        off_hand: bool,
        /// 1.16: the sneak key is held.
        sneaking: bool,
    },
    /// Client settings.
    Settings(ClientSettings),
    /// A packet of the inventory (window click, confirm answer, close, open inventory).
    Inventory(ghast_inventory::Outgoing),
    /// The client brand plugin message (`MC|Brand` on 1.8, `minecraft:brand` on 1.13+).
    Brand(String),
    /// Held movement keys (1.21.2+ `player_input`; sneaking is sent this way).
    PlayerInput(Controls),
    /// End of the client tick (1.21.2+ `tick_end`, every tick).
    TickEnd,
    /// The client finished loading the level (1.21.4+ `player_loaded`).
    PlayerLoaded,
    /// Announce the chat session the wire layer holds (1.19.3+ `chat_session_update`; the
    /// keys never pass through the core).
    ChatSessionUpdate,
    /// Chunk batch acknowledgement with the desired chunks per tick (1.20.2+).
    ChunkBatchReceived(f32),
    /// Pong for a server ping (1.17+).
    Pong(i32),
    /// Resource pack status (1.20.3+): 0 loaded, 1 declined, 3 accepted, 4 downloaded, …
    ResourcePackStatus {
        /// Pack id.
        id: Uuid,
        /// Status.
        result: i32,
    },
    /// Cookie answer (1.20.5+): the stored value, if any.
    CookieResponse {
        /// Key.
        key: ByteString,
        /// Value.
        value: Option<Bytes>,
    },
    /// Rotation-only movement packet, as the answer to a server turn (1.21.2+).
    LookAnswer {
        /// Yaw.
        yaw: f32,
        /// Pitch.
        pitch: f32,
    },
    /// `move_vehicle` (serverbound): where the vehicle the player controls is (26.1 boats).
    VehicleMove {
        /// Position.
        pos: Vec3,
        /// Yaw.
        yaw: f32,
        /// Pitch.
        pitch: f32,
        /// The vehicle's on-ground flag.
        on_ground: bool,
    },
    /// `steer_vehicle` (1.9 - 1.21.1): a passenger's movement input after its tick, every
    /// tick while riding (1.12.2, 1.16.5 boats).
    SteerVehicle {
        /// Sideways input.
        sideways: f32,
        /// Forward input.
        forward: f32,
        /// Jump key.
        jump: bool,
        /// Sneak key.
        sneak: bool,
    },
    /// `paddle_boat` / `steer_boat`: the boat's paddle states (26.1, every boat tick).
    SteerBoat {
        /// Left paddle.
        left: bool,
        /// Right paddle.
        right: bool,
    },
    /// `custom_click_action` (26.1+): a dialog button's custom action, with its payload tag
    /// (written as vanilla does: the tag length-prefixed, `TAG_End` for none).
    CustomClickAction {
        /// Action id.
        id: String,
        /// Payload tag.
        payload: Option<ghast_protocol::nbt::AnonNbt>,
    },
    /// A dialog's command as vanilla sends it (`sendUnattendedCommand` after its checks): an
    /// unsigned `chat_command` (without the `/`).
    DialogCommand(String),
    /// A packet the behaviour built itself ([`crate::TickContext::send_raw`]), written as given.
    Raw(ghast_protocol::RawPacket),
}

/// A status effect on the player as the server applied it (`entity_effect`; a re-application
/// with the same values is a new one).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct ActiveEffect {
    /// Effect id in the classic 1-based numbering (1 speed, 5 strength, 10 regeneration, 11
    /// resistance, 22 absorption …; 26.x: the registry id + 1, the same numbers).
    pub id: i8,
    /// Amplifier (level − 1).
    pub amplifier: i8,
    /// Duration in ticks when the packet arrived (−1: infinite, 1.19.4+).
    pub duration: i32,
    /// The flags as sent: 1.8 bit 0 = hide particles; 1.9+ bit 0 ambient, bit 1 show
    /// particles, bit 2 show icon (1.14+).
    pub flags: u8,
    /// The tick ([`crate::TickContext::tick`]) in which the behaviour first saw it.
    pub received_tick: u64,
}

impl ActiveEffect {
    /// Ticks left at tick `now` as the vanilla client counts them down (one per client tick
    /// from the packet on; at least 0), `None` for an infinite effect.
    #[must_use]
    pub fn remaining(&self, now: u64) -> Option<i32> {
        if self.is_infinite() {
            return None;
        }
        let gone = i64::try_from(now.saturating_sub(self.received_tick)).unwrap_or(i64::MAX);
        Some((i64::from(self.duration) - gone).max(0) as i32)
    }

    /// An effect without an end (duration −1).
    #[must_use]
    pub fn is_infinite(&self) -> bool {
        self.duration == -1
    }
}

/// A change of the player's status effects ([`crate::TickEvents::effects`]), one per packet.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum EffectEvent {
    /// An effect was applied (new, upgraded, refreshed or re-sent).
    Applied(ActiveEffect),
    /// The server removed the effect with this id.
    Removed(i8),
    /// Every effect ended with the player entity (respawn, dimension change, join).
    Cleared,
}

/// `entity_effect` with its duration and flags (see [`ActiveEffect`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct StatusEffect {
    /// The entity.
    pub entity_id: i32,
    /// Effect id (classic 1-based numbering).
    pub id: i8,
    /// Amplifier (level − 1).
    pub amplifier: i8,
    /// Duration in ticks (−1: infinite).
    pub duration: i32,
    /// Flags as sent.
    pub flags: u8,
}

/// The world's spawn point as the server sent it (`spawn_position`): where the compass points
/// and where a player without a bed respawns.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct SpawnPoint {
    /// Block position.
    pub pos: ghast_protocol::BlockPos,
    /// Spawn yaw (1.17+; 0 before).
    pub yaw: f32,
    /// Spawn pitch (26.x; 0 before).
    pub pitch: f32,
    /// The dimension (26.x; `None` before: the current one).
    pub dimension: Option<String>,
}

/// A player death the server announced (1.8 – 1.16.5 `combat_event` "entity dead", 1.17+
/// `player_combat_kill`). The server sends it only to the player who died.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Death {
    /// The dead player's entity id (ours).
    pub entity_id: i32,
    /// The killer's entity id (1.8 – 1.19.4; `None` when the server sent −1 and on 1.20+,
    /// whose packet has no killer).
    pub killer_id: Option<i32>,
    /// The death message.
    pub message: ChatMessage,
}

/// A hurt of the player ([`crate::TickEvents::hurt`]): 1.8 – 1.16.5 a hurt entity status, 26.x
/// a `damage_event` with its source.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Hurt {
    /// The hurt entity (ours in [`crate::TickEvents::hurt`]).
    pub entity_id: i32,
    /// 1.8 – 1.16.5: the entity status (2 hurt; 1.9+ 33 thorns, 36 drowning, 37 burning; 1.14+
    /// 44 sweet berry bush). `None` on 26.x.
    pub status: Option<i8>,
    /// 26.x: the damage type's registry id (`minecraft:damage_type`). `None` before.
    pub source_type: Option<i32>,
    /// 26.x: the entity that caused the damage (the shooter for a projectile), if any.
    pub attacker: Option<i32>,
    /// 26.x: the entity that dealt it directly (the projectile, or the attacker), if any.
    pub direct: Option<i32>,
}

impl Hurt {
    /// A legacy hurt status.
    #[must_use]
    pub fn from_status(entity_id: i32, status: i8) -> Self {
        Hurt {
            entity_id,
            status: Some(status),
            source_type: None,
            attacker: None,
            direct: None,
        }
    }

    /// A 26.x damage event (`cause` / `direct`: the wire's optional entity ids, already
    /// decoded: `None` for none).
    #[must_use]
    pub fn from_damage(
        entity_id: i32,
        source_type: i32,
        cause: Option<i32>,
        direct: Option<i32>,
    ) -> Self {
        Hurt {
            entity_id,
            status: None,
            source_type: Some(source_type),
            attacker: cause,
            direct,
        }
    }
}

/// A step of an item use (eating, drinking, blocking, drawing a bow) of the player
/// ([`crate::TickEvents::item_use`]). `item` is the used stack's item id (the version's
/// numbering, as [`ghast_inventory::Stack::id`]), `off_hand` the hand it is in (always `false`
/// on 1.8), `ticks` the player ticks the use lasted (vanilla's `getItemUseTime` /
/// `getTicksUsingItem`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum UseEvent {
    /// The right button started a use (the client's `setCurrentHand` / `startUsingItem`, in the
    /// key handling that sent the `use_item`).
    Started {
        /// The used item.
        item: i32,
        /// In the off hand.
        off_hand: bool,
    },
    /// The server finished the use (entity status 9 for our entity: the food was eaten, the
    /// potion drunk; the item's effects and the stack's new count follow in their own
    /// packets).
    Finished {
        /// The used item.
        item: i32,
        /// In the off hand.
        off_hand: bool,
        /// Player ticks it lasted.
        ticks: u32,
    },
    /// The right button was released before the server finished it (`release_use_item` sent:
    /// a bow shot, a lowered shield, eating cut short).
    Released {
        /// The used item.
        item: i32,
        /// In the off hand.
        off_hand: bool,
        /// Player ticks it lasted.
        ticks: u32,
    },
    /// The use ended without a release or a finish: the held slot changed (the behaviour's
    /// `select_slot` or the server's), the used hand no longer holds that item, the drop key
    /// dropped it, the game mode became spectator (26.x), or a new player entity (join,
    /// respawn). On 1.8 / 1.12 also a server `set_slot` of the used stack (a new stack object,
    /// as the real client compares): a use restarted by the held button in the tick of a
    /// finish ends this way when the eaten stack's update comes a tick later, while the server
    /// keeps using (see the README's Grim notes; release the button for one tick on
    /// [`UseEvent::Finished`] to avoid it).
    Interrupted {
        /// The used item.
        item: i32,
        /// In the off hand.
        off_hand: bool,
        /// Player ticks it lasted.
        ticks: u32,
    },
}