Skip to main content

ghast_client/
common.rs

1//! The version-agnostic layer: what the client core receives from and sends to the server,
2//! independent of the protocol version.
3//!
4//! Each supported version (see [`crate::version`]) maps its generated packets to [`Inbound`]
5//! and [`Outbound`] values. Only the packets the core or the behaviour needs are mapped; the
6//! rest is dropped by the frame decoder's filter before it is decoded.
7
8use bytes::Bytes;
9use ghast_protocol::types::ByteString;
10use uuid::Uuid;
11
12/// A position or direction in world space.
13#[derive(Debug, Clone, Copy, Default, PartialEq)]
14pub struct Vec3 {
15    /// East (+) / west (−).
16    pub x: f64,
17    /// Up (+) / down (−).
18    pub y: f64,
19    /// South (+) / north (−).
20    pub z: f64,
21}
22
23impl Vec3 {
24    /// A vector from its components.
25    #[must_use]
26    pub const fn new(x: f64, y: f64, z: f64) -> Self {
27        Vec3 { x, y, z }
28    }
29}
30
31/// The player's pose: feet position, look, motion and movement flags.
32///
33/// `yaw` / `pitch` are degrees in vanilla's convention (yaw is an unbounded `f32` like the
34/// client's `Entity.yaw`; 0 = south, 90 = west; pitch 90 = straight down).
35#[derive(Debug, Clone, Copy, Default, PartialEq)]
36pub struct Pose {
37    /// Feet position (bounding box minimum Y).
38    pub pos: Vec3,
39    /// Yaw in degrees.
40    pub yaw: f32,
41    /// Pitch in degrees.
42    pub pitch: f32,
43    /// Motion per tick.
44    pub motion: Vec3,
45    /// On ground as the client computes it (and sends it).
46    pub on_ground: bool,
47    /// Creative / ability flight.
48    pub flying: bool,
49    /// Sneaking (as sent with `entity_action`).
50    pub sneaking: bool,
51    /// Sprinting (as sent with `entity_action`).
52    pub sprinting: bool,
53}
54
55impl Pose {
56    /// Eye position: feet + 1.62 (1.54 while sneaking in 1.8; 1.16.5 uses a crouching pose
57    /// with eyes at 1.27, see [`crate::GameVersion::sneak_eye_height`]).
58    #[must_use]
59    pub fn eyes(&self, eye_height: f64) -> Vec3 {
60        Vec3::new(self.pos.x, self.pos.y + eye_height, self.pos.z)
61    }
62}
63
64/// Movement keys held for the next movement step (the keyboard state in vanilla).
65#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
66pub struct Controls {
67    /// Walk forward (W).
68    pub forward: bool,
69    /// Walk backward (S).
70    pub back: bool,
71    /// Strafe left (A).
72    pub left: bool,
73    /// Strafe right (D).
74    pub right: bool,
75    /// Jump (space).
76    pub jump: bool,
77    /// Sneak (shift).
78    pub sneak: bool,
79    /// Sprint key (ctrl).
80    pub sprint: bool,
81}
82
83impl Controls {
84    /// No key held.
85    pub const NONE: Controls = Controls {
86        forward: false,
87        back: false,
88        left: false,
89        right: false,
90        jump: false,
91        sneak: false,
92        sprint: false,
93    };
94}
95
96/// Where a chat message is shown.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
98#[non_exhaustive]
99pub enum ChatPosition {
100    /// A player chat message.
101    Chat,
102    /// A system message (command feedback, server announcements).
103    System,
104    /// The action bar above the hotbar.
105    ActionBar,
106    /// A value this client does not know.
107    Other(i8),
108}
109
110impl ChatPosition {
111    /// From the wire byte (same values in every supported version).
112    #[must_use]
113    pub fn from_wire(v: i8) -> Self {
114        match v {
115            0 => Self::Chat,
116            1 => Self::System,
117            2 => Self::ActionBar,
118            v => Self::Other(v),
119        }
120    }
121}
122
123/// A chat message from the server. The text stays raw JSON until asked for.
124#[derive(Debug, Clone, PartialEq, Eq)]
125#[non_exhaustive]
126pub struct ChatMessage {
127    /// The chat component as the server sent it (JSON).
128    pub json: ByteString,
129    /// Where it is shown.
130    pub position: ChatPosition,
131    /// Sender UUID (1.16+; `None` on 1.8 and for system messages with the nil UUID).
132    pub sender: Option<Uuid>,
133    /// 1.20.3+: the text already rendered from the NBT component (`json` is empty then).
134    pub(crate) rendered: Option<String>,
135}
136
137impl ChatMessage {
138    /// A message from its JSON chat component.
139    #[must_use]
140    pub fn from_json(json: ByteString, position: ChatPosition, sender: Option<Uuid>) -> Self {
141        ChatMessage {
142            json,
143            position,
144            sender,
145            rendered: None,
146        }
147    }
148
149    /// A message already rendered to plain text (1.20.3+ NBT components).
150    #[must_use]
151    pub fn from_text(text: String, position: ChatPosition, sender: Option<Uuid>) -> Self {
152        ChatMessage {
153            json: ByteString::from_static(""),
154            position,
155            sender,
156            rendered: Some(text),
157        }
158    }
159
160    /// The message as plain text, with legacy `§` formatting codes kept.
161    #[must_use]
162    pub fn text(&self) -> String {
163        match &self.rendered {
164            Some(t) => t.clone(),
165            None => ghast_protocol::chat::to_plain_text(&self.json),
166        }
167    }
168
169    /// The message as plain text without `§` formatting codes.
170    #[must_use]
171    pub fn plain(&self) -> String {
172        ghast_protocol::chat::strip_formatting(&self.text())
173    }
174}
175
176/// Converts a chat component (JSON) to plain text without formatting codes.
177#[must_use]
178pub fn chat_to_plain(json: &str) -> String {
179    ghast_protocol::chat::strip_formatting(&ghast_protocol::chat::to_plain_text(json))
180}
181
182/// Game mode.
183#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
184pub enum GameMode {
185    /// Survival.
186    #[default]
187    Survival,
188    /// Creative.
189    Creative,
190    /// Adventure.
191    Adventure,
192    /// Spectator.
193    Spectator,
194    /// A value this client does not know.
195    Other(u8),
196}
197
198impl GameMode {
199    /// From the wire value (the hardcore bit 0x08 of 1.8 is ignored).
200    #[must_use]
201    pub fn from_wire(v: u8) -> Self {
202        match v & 0x07 {
203            0 => Self::Survival,
204            1 => Self::Creative,
205            2 => Self::Adventure,
206            3 => Self::Spectator,
207            _ => Self::Other(v),
208        }
209    }
210}
211
212/// Player abilities (`abilities` packet).
213#[derive(Debug, Clone, Copy, PartialEq)]
214#[non_exhaustive]
215pub struct Abilities {
216    /// Raw flags: 1 invulnerable, 2 flying, 4 may fly, 8 creative (instant break).
217    pub flags: i8,
218    /// Flying speed (0.05 by default).
219    pub flying_speed: f32,
220    /// Walking speed (0.1 by default).
221    pub walking_speed: f32,
222}
223
224impl Default for Abilities {
225    fn default() -> Self {
226        Abilities {
227            flags: 0,
228            flying_speed: 0.05,
229            walking_speed: 0.1,
230        }
231    }
232}
233
234impl Abilities {
235    /// The server allows flight.
236    #[must_use]
237    pub fn may_fly(&self) -> bool {
238        self.flags & 4 != 0
239    }
240
241    /// The server says the player is flying.
242    #[must_use]
243    pub fn flying(&self) -> bool {
244        self.flags & 2 != 0
245    }
246
247    /// The server says the player takes no damage (creative, spectator).
248    #[must_use]
249    pub fn invulnerable(&self) -> bool {
250        self.flags & 1 != 0
251    }
252
253    /// The server says the player builds as in creative (`abilities.creativeMode`).
254    #[must_use]
255    pub(crate) fn creative_mode(&self) -> bool {
256        self.flags & 8 != 0
257    }
258}
259
260/// Health, food and saturation (`update_health`).
261#[derive(Debug, Clone, Copy, PartialEq)]
262#[non_exhaustive]
263pub struct Health {
264    /// Health points (20 = full; ≤ 0 = dead).
265    pub health: f32,
266    /// Food level 0 … 20.
267    pub food: i32,
268    /// Food saturation.
269    pub saturation: f32,
270    /// Absorption hearts (the player entity data's absorption amount; not part of
271    /// `update_health`, kept from our own `entity_metadata` on every version without entity
272    /// tracking, refreshed once per behaviour tick).
273    pub absorption: f32,
274}
275
276impl Default for Health {
277    fn default() -> Self {
278        Health {
279            health: 20.0,
280            food: 20,
281            saturation: 5.0,
282            absorption: 0.0,
283        }
284    }
285}
286
287/// The world's time (`update_time`), counted on between the server's updates like the
288/// vanilla client does (the server sends one a second).
289#[derive(Debug, Clone, Copy, PartialEq)]
290#[non_exhaustive]
291pub struct WorldTime {
292    /// Game time: the ticks the world has run (the packet's `age`).
293    pub age: i64,
294    /// The dimension's day clock in ticks, days included (`time_of_day + 24000 * day`);
295    /// `None` when the dimension has no day (26.x: the nether) or the server sent none.
296    pub day_time: Option<i64>,
297    /// Day clock ticks per game tick: 1 normally, 0 while the day stands still (the
298    /// `doDaylightCycle` / `advance_time` game rule off, or a paused 26.x clock).
299    pub day_rate: f32,
300}
301
302impl WorldTime {
303    /// The time of day, `0..24000` (0 = sunrise, 6000 = noon, 18000 = midnight).
304    #[must_use]
305    pub fn time_of_day(&self) -> Option<i64> {
306        self.day_time.map(|t| t.rem_euclid(24000))
307    }
308
309    /// The day number (`day_time / 24000`).
310    #[must_use]
311    pub fn day(&self) -> Option<i64> {
312        self.day_time.map(|t| t.div_euclid(24000))
313    }
314
315    /// The day stands still (`day_rate` is 0).
316    #[must_use]
317    pub fn day_frozen(&self) -> bool {
318        self.day_rate == 0.0
319    }
320}
321
322/// One clock of a [`TimeUpdate`]: a 26.x world clock (its `minecraft:world_clock` network id)
323/// or, on 1.8 – 1.16.5, the world's single day ([`ClockUpdate::LEGACY_DAY`]).
324#[derive(Debug, Clone, Copy, PartialEq, Default)]
325#[non_exhaustive]
326pub struct ClockUpdate {
327    /// Clock id.
328    pub id: i32,
329    /// Ticks of the clock.
330    pub total_ticks: i64,
331    /// Fraction of a tick (rates other than whole numbers).
332    pub partial_tick: f32,
333    /// Clock ticks per game tick (0 = stands still).
334    pub rate: f32,
335}
336
337impl ClockUpdate {
338    /// The id of the legacy day.
339    pub const LEGACY_DAY: i32 = -1;
340}
341
342/// `update_time` as the core reads it: the game time and the clocks it sets (at most
343/// [`TimeUpdate::MAX_CLOCKS`]; vanilla has two, further ones are dropped).
344#[derive(Debug, Clone, Copy, PartialEq, Default)]
345#[non_exhaustive]
346pub struct TimeUpdate {
347    /// Game time.
348    pub age: i64,
349    /// The clocks, `clocks[..len]`.
350    pub clocks: [ClockUpdate; TimeUpdate::MAX_CLOCKS],
351    /// Number of clocks.
352    pub len: u8,
353}
354
355impl TimeUpdate {
356    /// Clocks one update carries.
357    pub const MAX_CLOCKS: usize = 3;
358
359    /// 1.8 – 1.16.5: `age` and the day's `time`, negative while the daylight cycle is off
360    /// (vanilla's `WorldClient.setWorldTime`).
361    #[must_use]
362    pub fn legacy(age: i64, time: i64) -> TimeUpdate {
363        let mut u = TimeUpdate {
364            age,
365            ..TimeUpdate::default()
366        };
367        u.push(ClockUpdate {
368            id: ClockUpdate::LEGACY_DAY,
369            total_ticks: time.wrapping_abs(),
370            partial_tick: 0.0,
371            rate: if time < 0 { 0.0 } else { 1.0 },
372        });
373        u
374    }
375
376    /// Adds a clock (dropped when full).
377    pub fn push(&mut self, c: ClockUpdate) {
378        if let Some(slot) = self.clocks.get_mut(usize::from(self.len)) {
379            *slot = c;
380            self.len += 1;
381        }
382    }
383
384    /// 26.x `update_time` body: `age` (long), then a map of world clock (var-int id) to state
385    /// (var-long ticks, float partial tick, float rate). Decoded in place, nothing allocated.
386    ///
387    /// # Errors
388    /// A malformed body.
389    pub fn decode_modern(body: &bytes::Bytes) -> Result<TimeUpdate, ghast_protocol::DecodeError> {
390        let mut r = ghast_protocol::Reader::new(body);
391        let mut u = TimeUpdate {
392            age: r.read_i64()?,
393            ..TimeUpdate::default()
394        };
395        let n = r.read_varint()?;
396        for _ in 0..n.max(0) {
397            let c = ClockUpdate {
398                id: r.read_varint()?,
399                total_ticks: r.read_varlong()?,
400                partial_tick: r.read_f32()?,
401                rate: r.read_f32()?,
402            };
403            u.push(c);
404        }
405        Ok(u)
406    }
407
408    /// The clocks.
409    #[must_use]
410    pub fn clocks(&self) -> &[ClockUpdate] {
411        &self.clocks[..usize::from(self.len)]
412    }
413}
414
415/// The client's clocks (vanilla `ClientClockManager`; the legacy day is one of them).
416#[derive(Debug, Clone, Copy, Default)]
417pub(crate) struct Clocks {
418    known: bool,
419    age: i64,
420    last: i64,
421    len: u8,
422    c: [ClockUpdate; Clocks::CAP],
423}
424
425impl Clocks {
426    const CAP: usize = 4;
427
428    /// One client tick (`ClientLevel.tickTime`): game time + 1, the clocks follow.
429    #[inline]
430    pub(crate) fn tick(&mut self) {
431        if self.known {
432            self.age = self.age.wrapping_add(1);
433            self.advance();
434        }
435    }
436
437    /// `ClientClockManager.tick`: each clock moves by the game time passed times its rate.
438    fn advance(&mut self) {
439        let d = self.age.wrapping_sub(self.last);
440        self.last = self.age;
441        for c in &mut self.c[..usize::from(self.len)] {
442            let t = f64::from(c.partial_tick) + d as f64 * f64::from(c.rate);
443            // Mth.floor(double) -> int
444            let i = t as i32;
445            let whole = if t < f64::from(i) { i - 1 } else { i };
446            c.partial_tick = (t - f64::from(whole)) as f32;
447            c.total_ticks = c.total_ticks.wrapping_add(i64::from(whole));
448        }
449    }
450
451    /// `handleSetTime`: the game time, the clocks moved up to it, then the sent states.
452    pub(crate) fn apply(&mut self, u: &TimeUpdate) {
453        if !self.known {
454            self.known = true;
455            self.last = u.age;
456        }
457        self.age = u.age;
458        self.advance();
459        for s in u.clocks() {
460            let n = usize::from(self.len);
461            match self.c[..n].iter_mut().find(|c| c.id == s.id) {
462                Some(c) => *c = *s,
463                None if n < Clocks::CAP => {
464                    self.c[n] = *s;
465                    self.len += 1;
466                }
467                None => {}
468            }
469        }
470    }
471
472    /// The time with `day` as the day clock (`None` before the first update).
473    pub(crate) fn world_time(&self, day: Option<i32>) -> Option<WorldTime> {
474        if !self.known {
475            return None;
476        }
477        let c = day.and_then(|id| self.c[..usize::from(self.len)].iter().find(|c| c.id == id));
478        Some(WorldTime {
479            age: self.age,
480            day_time: c.map(|c| c.total_ticks),
481            day_rate: c.map_or(0.0, |c| c.rate),
482        })
483    }
484}
485
486/// Relative-teleport flag bits of the server's position packet.
487pub mod teleport_flags {
488    /// X is relative.
489    pub const X: i8 = 0x01;
490    /// Y is relative.
491    pub const Y: i8 = 0x02;
492    /// Z is relative.
493    pub const Z: i8 = 0x04;
494    /// Yaw is relative.
495    pub const YAW: i8 = 0x08;
496    /// Pitch is relative.
497    pub const PITCH: i8 = 0x10;
498}
499
500/// A server teleport (position packet), before it is applied to the pose.
501#[derive(Debug, Clone, Copy, PartialEq, Default)]
502#[non_exhaustive]
503pub struct Teleport {
504    /// X (absolute or relative, see `flags`).
505    pub x: f64,
506    /// Y.
507    pub y: f64,
508    /// Z.
509    pub z: f64,
510    /// Yaw.
511    pub yaw: f32,
512    /// Pitch.
513    pub pitch: f32,
514    /// [`teleport_flags`] bits.
515    pub flags: i8,
516    /// Teleport id to confirm (1.9+).
517    pub teleport_id: Option<i32>,
518    /// Every relative bit as on the wire: `flags` (bits 0 – 4) plus, from 1.21.2 on, 5 – 7
519    /// delta X / Y / Z relative and 8 "rotate the delta".
520    pub relative: u32,
521    /// The motion the teleport sets (1.21.2+; zero before).
522    pub delta: Vec3,
523}
524
525/// Login-state packets from the server, common to every version.
526#[derive(Debug, Clone, PartialEq)]
527#[non_exhaustive]
528pub enum LoginInbound {
529    /// The server refused the login (chat JSON).
530    Disconnect(ByteString),
531    /// Online mode: the server asks for encryption.
532    EncryptionRequest {
533        /// Server id (usually empty) for the session hash.
534        server_id: ByteString,
535        /// The server's RSA public key (DER).
536        public_key: Bytes,
537        /// Token to encrypt and send back.
538        verify_token: Bytes,
539    },
540    /// The server asks for encryption without a session-server check (1.20.5+
541    /// `shouldAuthenticate = false`): the client encrypts and skips the `join` call, so an
542    /// offline account can answer it too.
543    EncryptionRequestUnauthenticated {
544        /// Server id (usually empty).
545        server_id: ByteString,
546        /// The server's RSA public key (DER).
547        public_key: Bytes,
548        /// Token to encrypt and send back.
549        verify_token: Bytes,
550    },
551    /// Compression starts with the next packet.
552    Compress(i32),
553    /// Login finished; the connection is in the play state.
554    Success {
555        /// The player's UUID as the server assigned it.
556        uuid: Option<Uuid>,
557        /// The player's name.
558        username: ByteString,
559    },
560    /// A login plugin request (1.13+): answered with "not understood".
561    PluginRequest {
562        /// Message id to answer.
563        message_id: i32,
564        /// Channel name.
565        channel: ByteString,
566    },
567    /// The server asks for a cookie (1.20.5+): answered with none.
568    CookieRequest(ByteString),
569}
570
571/// A data pack the server offers as known (configuration `select_known_packs`).
572#[derive(Debug, Clone, PartialEq, Eq)]
573#[non_exhaustive]
574pub struct KnownPack {
575    /// Namespace (`minecraft`).
576    pub namespace: ByteString,
577    /// Pack id (`core`).
578    pub id: ByteString,
579    /// Pack version (the game version, e.g. `26.1.2`).
580    pub version: ByteString,
581}
582
583/// Configuration-state packets from the server the client reacts to (1.20.2+).
584#[derive(Debug, Clone, PartialEq)]
585#[non_exhaustive]
586pub enum ConfigInbound {
587    /// Keep-alive to echo.
588    KeepAlive(i64),
589    /// Ping to answer with a pong.
590    Ping(i32),
591    /// Configuration is done: answer and enter play.
592    Finish,
593    /// The server ends the connection (plain text).
594    Disconnect(String),
595    /// The packs the server can skip sending data for.
596    SelectKnownPacks(Vec<KnownPack>),
597    /// A registry (`registry_data`), kept raw for the world and the wire layer.
598    RegistryData(ghast_protocol::RawPacket),
599    /// A server resource pack.
600    ResourcePackPush {
601        /// Pack id.
602        id: Uuid,
603        /// The server requires it.
604        required: bool,
605    },
606    /// The server asks for a cookie.
607    CookieRequest(ByteString),
608    /// The server's code of conduct (26.x): the player accepts it to continue.
609    CodeOfConduct(String),
610    /// The server sends the client to another server (`host:port`): the session ends with
611    /// [`crate::SessionEnd::Transferred`] (followed with [`crate::Client::follow_transfers`]).
612    Transfer(String),
613    /// The server shows a dialog (26.1+, see [`crate::dialog`]).
614    ShowDialog(Box<crate::dialog::Dialog>),
615    /// The server closes the open dialog.
616    ClearDialog,
617}
618
619/// Configuration-state packets the client writes (1.20.2+).
620#[derive(Debug, Clone, PartialEq)]
621#[non_exhaustive]
622pub enum ConfigOutbound {
623    /// Keep-alive answer.
624    KeepAlive(i64),
625    /// Pong.
626    Pong(i32),
627    /// Acknowledge the end of configuration.
628    Finish,
629    /// The packs the client knows too.
630    SelectKnownPacks(Vec<KnownPack>),
631    /// Resource pack status (see [`Outbound::ResourcePackStatus`]).
632    ResourcePackStatus {
633        /// Pack id.
634        id: Uuid,
635        /// Status.
636        result: i32,
637    },
638    /// Cookie answer.
639    CookieResponse {
640        /// Key.
641        key: ByteString,
642    },
643    /// Accept the code of conduct.
644    AcceptCodeOfConduct,
645    /// The client brand.
646    Brand(String),
647    /// Client settings.
648    Settings(ClientSettings),
649    /// A dialog button's custom action (26.1+, see [`Outbound::CustomClickAction`]).
650    CustomClickAction {
651        /// Action id.
652        id: String,
653        /// Payload tag.
654        payload: Option<ghast_protocol::nbt::AnonNbt>,
655    },
656}
657
658/// Static information from the join game packet.
659#[derive(Debug, Clone, PartialEq)]
660#[non_exhaustive]
661pub struct JoinGame {
662    /// The player's entity id.
663    pub entity_id: i32,
664    /// Game mode.
665    pub game_mode: GameMode,
666    /// Dimension: the 1.8 id (−1 nether, 0 overworld, 1 end) as a string, or the 1.16 world
667    /// name (e.g. `minecraft:overworld`).
668    pub dimension: String,
669    /// Hardcore world.
670    pub hardcore: bool,
671    /// 1.16: the dimension codec and dimension type NBT, kept raw (not parsed).
672    pub dimension_nbt: Option<(ghast_protocol::nbt::RawNbt, ghast_protocol::nbt::RawNbt)>,
673    /// 1.16: the respawn screen is shown (false = immediate respawn gamerule).
674    pub respawn_screen: bool,
675}
676
677/// Clientbound play packets the core understands, common to every version.
678#[derive(Debug, Clone, PartialEq)]
679#[non_exhaustive]
680pub enum Inbound {
681    /// Keep-alive to echo.
682    KeepAlive(i64),
683    /// Join game (also sent again on a proxy server switch).
684    JoinGame(JoinGame),
685    /// Respawn / dimension change.
686    Respawn {
687        /// Dimension key (see [`JoinGame::dimension`]).
688        dimension: String,
689        /// Game mode after the respawn.
690        game_mode: GameMode,
691        /// 1.20.2+ data kept from the old player: bit 1 attributes, bit 2 entity data (the
692        /// last sent input and sprinting); 0 before.
693        keep: u8,
694    },
695    /// Server teleport / position correction.
696    Teleport(Teleport),
697    /// Chat message.
698    Chat(ChatMessage),
699    /// The server ends the session (chat JSON).
700    Disconnect(ByteString),
701    /// Health, food and saturation.
702    Health(Health),
703    /// The world's time (`update_time`).
704    Time(TimeUpdate),
705    /// Abilities.
706    Abilities(Abilities),
707    /// The server selects a hotbar slot.
708    HeldSlot(i8),
709    /// Game state change (`reason`, `value`), e.g. reason 3 = game mode.
710    GameState {
711        /// Reason id (same numbering in all supported versions).
712        reason: u8,
713        /// Value.
714        value: f32,
715    },
716    /// Window confirm transaction.
717    Transaction {
718        /// Window id.
719        window_id: i8,
720        /// Action number.
721        action: i16,
722        /// Accepted.
723        accepted: bool,
724    },
725    /// A window opened.
726    OpenWindow(i32),
727    /// The open window was closed by the server.
728    CloseWindow(i32),
729    /// Compression threshold change in the play state (1.8).
730    SetCompression(i32),
731    /// Entity velocity (blocks per tick; the wire's 1/8000 units converted).
732    Velocity {
733        /// The entity.
734        entity_id: i32,
735        /// Motion per tick.
736        motion: Vec3,
737    },
738    /// The player motion an explosion adds.
739    ExplosionPush(Vec3),
740    /// Movement speed attribute of an entity (entity properties packet).
741    MovementSpeed {
742        /// The entity.
743        entity_id: i32,
744        /// Base value.
745        base: f64,
746        /// Modifiers `(uuid, amount, operation)` in packet order.
747        modifiers: Vec<(Uuid, f64, i8)>,
748    },
749    /// The attributes of an entity the core reads (1.9 – 1.16 entity properties packet):
750    /// base and modifiers `(uuid, amount, operation)` in packet order, when the packet has them.
751    LegacyAttributes {
752        /// The entity.
753        entity_id: i32,
754        /// `generic.movement_speed`.
755        movement_speed: Option<LegacyAttribute>,
756        /// `generic.attack_speed`.
757        attack_speed: Option<LegacyAttribute>,
758    },
759    /// A status effect was applied to an entity.
760    Effect {
761        /// The entity.
762        entity_id: i32,
763        /// Effect id.
764        id: i8,
765        /// Amplifier (level − 1).
766        amplifier: i8,
767    },
768    /// A status effect was applied, with its duration and flags (replaces [`Inbound::Effect`]
769    /// in the decoders since 0.4.8; the engine still accepts both).
770    EffectApplied(StatusEffect),
771    /// The world's spawn point.
772    SpawnPoint(SpawnPoint),
773    /// A player death with its killer and message (replaces [`Inbound::Died`] in the decoders
774    /// since 0.4.8; the engine still accepts both).
775    Death(Death),
776    /// 26.x `damage_event`: an entity was hurt (with the damage source).
777    Damage(Hurt),
778    /// A scoreboard team packet (decoded with [`crate::Interests::TEAMS`]; parsed by the engine
779    /// into [`crate::teams::Teams`]).
780    Teams(crate::teams::TeamsPacket),
781    /// A status effect ended.
782    EffectRemoved {
783        /// The entity.
784        entity_id: i32,
785        /// Effect id.
786        id: i8,
787    },
788    /// Entity status (e.g. 9 = our item use finished).
789    EntityStatus {
790        /// The entity.
791        entity_id: i32,
792        /// Status id.
793        status: i8,
794    },
795    /// `set_cooldown` (1.9+): an item (1.12.2, 1.16.5) or cooldown group (26.x) cools down for
796    /// `ticks`; 0 removes its cooldown (see [`crate::cooldown`]).
797    ItemCooldown {
798        /// The item or group.
799        key: crate::cooldown::CooldownKey,
800        /// Its length in ticks (0: removed).
801        ticks: i32,
802    },
803    /// An entity (the player, if it is our id) died (1.16 `combat_event` "entity dead").
804    Died {
805        /// The dead player's entity id.
806        entity_id: i32,
807    },
808    /// Movement attributes of an entity (1.20.5+ registry attributes; only the ones movement
809    /// reads are kept).
810    Attributes {
811        /// The entity.
812        entity_id: i32,
813        /// The attributes in packet order.
814        attributes: Vec<AttributeUpdate>,
815    },
816    /// The server's ping (1.17+): answered with a pong.
817    Ping(i32),
818    /// A chunk batch starts (1.20.2+).
819    ChunkBatchStart,
820    /// A chunk batch ended with this many chunks (1.20.2+): answered with the chunks per tick.
821    ChunkBatchFinished(i32),
822    /// The server moves the connection back to the configuration state (1.20.2+).
823    StartConfiguration,
824    /// A server resource pack (1.20.3+ ids).
825    ResourcePackPush {
826        /// Pack id.
827        id: Uuid,
828        /// The server requires it.
829        required: bool,
830    },
831    /// The server asks for a cookie (1.20.5+).
832    CookieRequest(ByteString),
833    /// The server sends the client to another server (1.20.5+ `transfer`): the session ends
834    /// with [`crate::SessionEnd::Transferred`] (followed with [`crate::Client::follow_transfers`]).
835    Transfer {
836        /// Target host.
837        host: String,
838        /// Target port.
839        port: u16,
840    },
841    /// The server stores a cookie (1.20.5+).
842    StoreCookie {
843        /// Key.
844        key: ByteString,
845        /// Value.
846        value: Bytes,
847    },
848    /// A rotation-only server turn (1.21.2+ `player_rotation`).
849    Rotate {
850        /// Yaw (added when `relative_yaw`).
851        yaw: f32,
852        /// Pitch (added when `relative_pitch`).
853        pitch: f32,
854        /// Yaw is relative.
855        relative_yaw: bool,
856        /// Pitch is relative.
857        relative_pitch: bool,
858    },
859    /// The server shows a dialog (26.1+ `show_dialog`, only with
860    /// [`crate::Interests::DIALOGS`]).
861    ShowDialog(std::sync::Arc<crate::dialog::Dialog>),
862    /// The server closes the open dialog (`clear_dialog`).
863    ClearDialog,
864    /// A boss bar operation (1.9+ `boss_bar`, only with [`crate::Interests::HUD`]).
865    BossBar(crate::hud::BossBarOp),
866    /// A title operation (`title`, 26.x `set_title_text` / `set_subtitle_text` /
867    /// `set_titles_animation` / `clear_titles`; only with [`crate::Interests::HUD`]).
868    Title(crate::hud::TitleOp),
869    /// An action bar message (1.12 / 1.16.5 `title` action, 26.x `set_action_bar_text`; only
870    /// with [`crate::Interests::HUD`]). Chat messages at [`ChatPosition::ActionBar`] show there
871    /// too.
872    ActionBar(crate::hud::Text),
873    /// The tab list's header and footer (`playerlist_header`, only with
874    /// [`crate::Interests::HUD`]); `None` where the version's client drops an empty one.
875    TabList {
876        /// Header.
877        header: Option<crate::hud::Text>,
878        /// Footer.
879        footer: Option<crate::hud::Text>,
880    },
881    /// The answer to a tab-completion request (`tab_complete` / `command_suggestions`).
882    TabComplete(crate::hud::TabCompleteResponse),
883    /// The server opens the sign editor (`open_sign_entity`; see [`crate::sign`]).
884    OpenSign(crate::sign::SignEditor),
885    /// 1.8 / 1.12: an entity went to sleep in the bed at `bed` (`bed` packet; 1.13+ use the
886    /// entity data instead).
887    UseBed {
888        /// The sleeping entity.
889        entity_id: i32,
890        /// The bed (its head block).
891        bed: ghast_protocol::BlockPos,
892    },
893    /// 1.8 / 1.12: an entity woke up (`animation` 2; other animations are not decoded).
894    WakeUp(i32),
895}
896
897/// One attribute of a 1.9 – 1.16 entity properties packet: base and modifiers
898/// `(uuid, amount, operation)` in packet order.
899pub type LegacyAttribute = (f64, Vec<(Uuid, f64, i8)>);
900
901/// One entry of a 1.20.5+ attributes packet.
902#[derive(Debug, Clone, PartialEq)]
903#[non_exhaustive]
904pub struct AttributeUpdate {
905    /// Registry name without namespace (`movement_speed`, `step_height`, …).
906    pub name: &'static str,
907    /// Base value.
908    pub base: f64,
909    /// Modifiers `(id, amount, operation)` in packet order.
910    pub modifiers: Vec<(ByteString, f64, i8)>,
911}
912
913/// The player went to sleep or woke up ([`crate::TickEvents::sleep`]).
914#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
915#[non_exhaustive]
916pub enum SleepEvent {
917    /// The server put the player in the bed at this position (its head block): 1.8 / 1.12
918    /// `bed` packet, 1.16.5+ our sleeping position in the entity data. The client put the
919    /// player on the bed (see [`crate::TickContext::sleeping`]).
920    FellAsleep(ghast_protocol::BlockPos),
921    /// The player woke up (1.8 / 1.12 `animation` 2, 1.16.5+ the sleeping position cleared;
922    /// the server's teleport to the stand-up position follows).
923    WokeUp,
924}
925
926/// Sneak / sprint `entity_action` values.
927#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
928#[non_exhaustive]
929pub enum EntityAction {
930    /// Start sneaking.
931    StartSneaking,
932    /// Stop sneaking.
933    StopSneaking,
934    /// Start sprinting.
935    StartSprinting,
936    /// Stop sprinting.
937    StopSprinting,
938    /// Start gliding with an elytra (1.9+ `START_FALL_FLYING`; ghast sends it on 26.1).
939    StartFallFlying,
940    /// The mount jump ended (`STOP_RIDING_JUMP`, 1.9+; not on the wire on 1.8). Its start
941    /// carries a strength and is [`Outbound::RidingJump`].
942    StopRidingJump,
943    /// Leave the bed (`STOP_SLEEPING`: the sleep screen's "Leave Bed" button,
944    /// [`crate::TickContext::leave_bed`]).
945    LeaveBed,
946}
947
948/// The one movement packet of a tick.
949///
950/// `horizontal_collision` is sent from 1.21.2 on (always `false` for older versions).
951#[derive(Debug, Clone, Copy, PartialEq)]
952#[non_exhaustive]
953pub enum MovePacket {
954    /// `flying` (C03): only on-ground.
955    Flying {
956        /// On ground.
957        on_ground: bool,
958        /// Horizontal collision (1.21.2+).
959        horizontal_collision: bool,
960    },
961    /// `position` (C04).
962    Position {
963        /// Feet position.
964        pos: Vec3,
965        /// On ground.
966        on_ground: bool,
967        /// Horizontal collision (1.21.2+).
968        horizontal_collision: bool,
969    },
970    /// `look` (C05).
971    Look {
972        /// Yaw.
973        yaw: f32,
974        /// Pitch.
975        pitch: f32,
976        /// On ground.
977        on_ground: bool,
978        /// Horizontal collision (1.21.2+).
979        horizontal_collision: bool,
980    },
981    /// `position_look` (C06).
982    PositionLook {
983        /// Feet position.
984        pos: Vec3,
985        /// Yaw.
986        yaw: f32,
987        /// Pitch.
988        pitch: f32,
989        /// On ground.
990        on_ground: bool,
991        /// Horizontal collision (1.21.2+).
992        horizontal_collision: bool,
993    },
994}
995
996impl MovePacket {
997    /// The 1.8 trace name (`C03` … `C06`).
998    #[must_use]
999    pub fn trace_id(&self) -> &'static str {
1000        match self {
1001            Self::Flying { .. } => "C03",
1002            Self::Position { .. } => "C04",
1003            Self::Look { .. } => "C05",
1004            Self::PositionLook { .. } => "C06",
1005        }
1006    }
1007}
1008
1009/// Client settings (`settings` packet), sent right after join game like vanilla.
1010#[derive(Debug, Clone, PartialEq)]
1011#[non_exhaustive]
1012pub struct ClientSettings {
1013    /// Locale, e.g. `en_US` (1.8) / `en_us` (1.16).
1014    pub locale: String,
1015    /// View distance in chunks.
1016    pub view_distance: i8,
1017    /// Chat visibility: 0 full, 1 commands only, 2 hidden.
1018    pub chat_mode: i8,
1019    /// Chat colours.
1020    pub chat_colors: bool,
1021    /// Displayed skin parts (bit mask; 0x7f = all).
1022    pub skin_parts: u8,
1023    /// Main hand (1.9+): 0 left, 1 right.
1024    pub main_hand: i32,
1025}
1026
1027impl ClientSettings {
1028    /// The locale, e.g. `en_US` (1.8) / `en_us` (1.16).
1029    #[must_use]
1030    pub fn with_locale(mut self, locale: impl Into<String>) -> Self {
1031        self.locale = locale.into();
1032        self
1033    }
1034
1035    /// The view distance in chunks.
1036    #[must_use]
1037    pub const fn with_view_distance(mut self, chunks: i8) -> Self {
1038        self.view_distance = chunks;
1039        self
1040    }
1041
1042    /// Chat visibility: 0 full, 1 commands only, 2 hidden.
1043    #[must_use]
1044    pub const fn with_chat_mode(mut self, mode: i8) -> Self {
1045        self.chat_mode = mode;
1046        self
1047    }
1048
1049    /// Chat colours.
1050    #[must_use]
1051    pub const fn with_chat_colors(mut self, on: bool) -> Self {
1052        self.chat_colors = on;
1053        self
1054    }
1055
1056    /// Displayed skin parts (bit mask; 0x7f = all).
1057    #[must_use]
1058    pub const fn with_skin_parts(mut self, mask: u8) -> Self {
1059        self.skin_parts = mask;
1060        self
1061    }
1062
1063    /// Main hand (1.9+): 0 left, 1 right.
1064    #[must_use]
1065    pub const fn with_main_hand(mut self, hand: i32) -> Self {
1066        self.main_hand = hand;
1067        self
1068    }
1069}
1070
1071impl Default for ClientSettings {
1072    fn default() -> Self {
1073        ClientSettings {
1074            locale: "en_US".to_owned(),
1075            view_distance: 8,
1076            chat_mode: 0,
1077            chat_colors: true,
1078            skin_parts: 0x7f,
1079            main_hand: 1,
1080        }
1081    }
1082}
1083
1084/// A block face, as in the dig / place packets.
1085#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1086pub enum Face {
1087    /// −Y (0).
1088    Down,
1089    /// +Y (1).
1090    Up,
1091    /// −Z (2).
1092    North,
1093    /// +Z (3).
1094    South,
1095    /// −X (4).
1096    West,
1097    /// +X (5).
1098    East,
1099}
1100
1101impl Face {
1102    /// The wire value 0 … 5.
1103    #[must_use]
1104    pub const fn id(self) -> i8 {
1105        match self {
1106            Face::Down => 0,
1107            Face::Up => 1,
1108            Face::North => 2,
1109            Face::South => 3,
1110            Face::West => 4,
1111            Face::East => 5,
1112        }
1113    }
1114
1115    /// From the wire value.
1116    #[must_use]
1117    pub const fn from_id(id: i8) -> Option<Face> {
1118        Some(match id {
1119            0 => Face::Down,
1120            1 => Face::Up,
1121            2 => Face::North,
1122            3 => Face::South,
1123            4 => Face::West,
1124            5 => Face::East,
1125            _ => return None,
1126        })
1127    }
1128
1129    /// The neighbouring block in this direction.
1130    #[must_use]
1131    pub const fn offset(self, p: ghast_protocol::BlockPos) -> ghast_protocol::BlockPos {
1132        let (x, y, z) = match self {
1133            Face::Down => (0, -1, 0),
1134            Face::Up => (0, 1, 0),
1135            Face::North => (0, 0, -1),
1136            Face::South => (0, 0, 1),
1137            Face::West => (-1, 0, 0),
1138            Face::East => (1, 0, 0),
1139        };
1140        ghast_protocol::BlockPos::new(p.x + x, p.y + y, p.z + z)
1141    }
1142}
1143
1144/// The `use_entity` action.
1145#[derive(Debug, Clone, Copy, PartialEq)]
1146#[non_exhaustive]
1147pub enum EntityUse {
1148    /// Right click (0).
1149    Interact,
1150    /// Left click (1).
1151    Attack,
1152    /// Right click at a point relative to the entity position (2).
1153    InteractAt(Vec3),
1154}
1155
1156/// `block_dig` status values used by the client.
1157#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1158#[non_exhaustive]
1159pub enum DigStatus {
1160    /// Start destroying a block (0).
1161    Start,
1162    /// Abort destroying (1).
1163    Abort,
1164    /// Finish destroying (2).
1165    Finish,
1166    /// Release the used item: stop eating / blocking / drawing (5).
1167    ReleaseUseItem,
1168    /// Drop the whole held stack (3; the drop key with control held).
1169    DropStack,
1170    /// Drop one item of the held stack (4; the drop key).
1171    DropItem,
1172    /// Swap the main- and off-hand stacks (6; 1.9+, the swap-hands key).
1173    SwapHands,
1174    /// 26.3 `CHANGE_DESTROY_DIRECTION` (1 on the 26.3 wire, which shifts the later ids by
1175    /// one): the crosshair moved to another face of the block being dug.
1176    ChangeDirection,
1177}
1178
1179impl DigStatus {
1180    /// The wire value.
1181    #[must_use]
1182    pub const fn id(self) -> i32 {
1183        match self {
1184            DigStatus::Start => 0,
1185            DigStatus::Abort => 1,
1186            DigStatus::Finish => 2,
1187            DigStatus::ReleaseUseItem => 5,
1188            DigStatus::DropStack => 3,
1189            DigStatus::DropItem => 4,
1190            DigStatus::SwapHands => 6,
1191            // 26.3 only (its own numbering: `id_777`)
1192            DigStatus::ChangeDirection => 1,
1193        }
1194    }
1195
1196    /// The 26.3 wire value: `CHANGE_DESTROY_DIRECTION` took 1 and every later action moved
1197    /// up by one (abort 2, stop 3, drop all 4, drop 5, release 6, swap 7).
1198    #[cfg_attr(not(feature = "v26_3"), allow(dead_code))]
1199    pub(crate) const fn id_777(self) -> i32 {
1200        match self {
1201            DigStatus::Start => 0,
1202            DigStatus::ChangeDirection => 1,
1203            DigStatus::Abort => 2,
1204            DigStatus::Finish => 3,
1205            DigStatus::DropStack => 4,
1206            DigStatus::DropItem => 5,
1207            DigStatus::ReleaseUseItem => 6,
1208            DigStatus::SwapHands => 7,
1209        }
1210    }
1211}
1212
1213/// The vehicle the player rides ([`crate::TickContext::vehicle`]).
1214#[derive(Debug, Clone, Copy, PartialEq)]
1215#[non_exhaustive]
1216pub struct Vehicle {
1217    /// Its entity id.
1218    pub entity_id: i32,
1219    /// Position after this tick (the client's, for a vehicle it controls).
1220    pub pos: Vec3,
1221    /// Yaw.
1222    pub yaw: f32,
1223    /// Pitch.
1224    pub pitch: f32,
1225    /// On the ground.
1226    pub on_ground: bool,
1227    /// The client moves it (a boat) rather than the server (a minecart).
1228    pub controlled: bool,
1229}
1230
1231/// Serverbound play packets the core writes, common to every version.
1232#[derive(Debug, Clone, PartialEq)]
1233#[non_exhaustive]
1234pub enum Outbound {
1235    /// Keep-alive answer.
1236    KeepAlive(i64),
1237    /// Teleport confirm (1.9+; never produced for 1.8).
1238    TeleportConfirm(i32),
1239    /// 26.3 teleport confirm: the teleport id with the position and rotation the player took
1240    /// (`ServerboundAcceptTeleportationPacket`; no movement packet follows it).
1241    TeleportConfirmPose {
1242        /// Teleport id.
1243        id: i32,
1244        /// The player's position after the teleport.
1245        pos: Vec3,
1246        /// Yaw after the teleport.
1247        yaw: f32,
1248        /// Pitch after the teleport.
1249        pitch: f32,
1250    },
1251    /// The movement packet.
1252    Move(MovePacket),
1253    /// Sneak / sprint change.
1254    EntityAction {
1255        /// Our entity id.
1256        entity_id: i32,
1257        /// The action.
1258        action: EntityAction,
1259    },
1260    /// The mount jump bar was released: the `entity_action` packet's `START_RIDING_JUMP` with
1261    /// the jump strength ×100 as its jump-boost value.
1262    RidingJump {
1263        /// Our entity id.
1264        entity_id: i32,
1265        /// The jump bar ×100.
1266        strength: i32,
1267    },
1268    /// Chat line or command (already truncated to the version's limit).
1269    Chat(String),
1270    /// Respawn request (client command "perform respawn").
1271    Respawn,
1272    /// Window confirm transaction answer.
1273    Transaction {
1274        /// Window id.
1275        window_id: i8,
1276        /// Action number.
1277        action: i16,
1278        /// Accepted.
1279        accepted: bool,
1280    },
1281    /// Abilities (sent when the client toggles flight).
1282    Abilities {
1283        /// Flags (1 invulnerable, 2 flying, 4 may fly, 8 creative).
1284        flags: i8,
1285        /// Flying speed.
1286        flying_speed: f32,
1287        /// Walking speed.
1288        walking_speed: f32,
1289    },
1290    /// Select a hotbar slot (0 … 8).
1291    HeldSlot(i16),
1292    /// Arm swing (main hand).
1293    Swing,
1294    /// 26.3 `punch`: the payload-less packet an attack or a dig click sends where earlier
1295    /// versions sent the main-hand swing.
1296    Punch,
1297    /// `block_dig`.
1298    Dig {
1299        /// Status.
1300        status: DigStatus,
1301        /// Block.
1302        pos: ghast_protocol::BlockPos,
1303        /// Face.
1304        face: Face,
1305    },
1306    /// `block_place` on a block face (1.8 with the held stack; 1.16 main hand).
1307    Place {
1308        /// The block clicked.
1309        pos: ghast_protocol::BlockPos,
1310        /// The face clicked.
1311        face: Face,
1312        /// Hit point relative to the block (floats, 0 … 1).
1313        cursor: Vec3,
1314        /// The held stack (1.8 sends it; vanilla servers / Grim compare it with the hand).
1315        held: Option<ghast_inventory::Stack>,
1316        /// 1.9+: the off hand.
1317        off_hand: bool,
1318    },
1319    /// [`Outbound::Place`] of a ray that started inside the clicked block's outline (1.14+
1320    /// `insideBlock`; 1.8 – 1.12 write it as a plain placement).
1321    PlaceInside {
1322        /// The block clicked.
1323        pos: ghast_protocol::BlockPos,
1324        /// The face clicked.
1325        face: Face,
1326        /// Hit point relative to the block (floats, 0 … 1).
1327        cursor: Vec3,
1328        /// The held stack.
1329        held: Option<ghast_inventory::Stack>,
1330        /// The off hand.
1331        off_hand: bool,
1332    },
1333    /// Use the held item: 1.8 `block_place` in vanilla's own form (position −1/−1/−1, face 255,
1334    /// the held stack, cursor 0/0/0 — what servers and anticheats expect; other forms are
1335    /// flagged as bad packets); 1.9+ `use_item` with the hand.
1336    UseItem {
1337        /// The held stack.
1338        held: Option<ghast_inventory::Stack>,
1339        /// 1.9+: the off hand.
1340        off_hand: bool,
1341    },
1342    /// 1.9+: off-hand arm swing.
1343    SwingOffHand,
1344    /// `use_entity`: attack or interact with an entity.
1345    UseEntity {
1346        /// The entity.
1347        target: i32,
1348        /// What to do.
1349        action: EntityUse,
1350        /// 1.9+: the off hand (interactions).
1351        off_hand: bool,
1352        /// 1.16: the sneak key is held.
1353        sneaking: bool,
1354    },
1355    /// Client settings.
1356    Settings(ClientSettings),
1357    /// A packet of the inventory (window click, confirm answer, close, open inventory).
1358    Inventory(ghast_inventory::Outgoing),
1359    /// The client brand plugin message (`MC|Brand` on 1.8, `minecraft:brand` on 1.13+).
1360    Brand(String),
1361    /// Held movement keys (1.21.2+ `player_input`; sneaking is sent this way).
1362    PlayerInput(Controls),
1363    /// End of the client tick (1.21.2+ `tick_end`, every tick).
1364    TickEnd,
1365    /// The client finished loading the level (1.21.4+ `player_loaded`).
1366    PlayerLoaded,
1367    /// Announce the chat session the wire layer holds (1.19.3+ `chat_session_update`; the
1368    /// keys never pass through the core).
1369    ChatSessionUpdate,
1370    /// Chunk batch acknowledgement with the desired chunks per tick (1.20.2+).
1371    ChunkBatchReceived(f32),
1372    /// Pong for a server ping (1.17+).
1373    Pong(i32),
1374    /// Resource pack status (1.20.3+): 0 loaded, 1 declined, 3 accepted, 4 downloaded, …
1375    ResourcePackStatus {
1376        /// Pack id.
1377        id: Uuid,
1378        /// Status.
1379        result: i32,
1380    },
1381    /// Cookie answer (1.20.5+): the stored value, if any.
1382    CookieResponse {
1383        /// Key.
1384        key: ByteString,
1385        /// Value.
1386        value: Option<Bytes>,
1387    },
1388    /// Rotation-only movement packet, as the answer to a server turn (1.21.2+).
1389    LookAnswer {
1390        /// Yaw.
1391        yaw: f32,
1392        /// Pitch.
1393        pitch: f32,
1394    },
1395    /// `move_vehicle` (serverbound): where the vehicle the player controls is (26.1 boats).
1396    VehicleMove {
1397        /// Position.
1398        pos: Vec3,
1399        /// Yaw.
1400        yaw: f32,
1401        /// Pitch.
1402        pitch: f32,
1403        /// The vehicle's on-ground flag.
1404        on_ground: bool,
1405    },
1406    /// `steer_vehicle` (1.9 - 1.21.1): a passenger's movement input after its tick, every
1407    /// tick while riding (1.12.2, 1.16.5 boats).
1408    SteerVehicle {
1409        /// Sideways input.
1410        sideways: f32,
1411        /// Forward input.
1412        forward: f32,
1413        /// Jump key.
1414        jump: bool,
1415        /// Sneak key.
1416        sneak: bool,
1417    },
1418    /// `paddle_boat` / `steer_boat`: the boat's paddle states (26.1, every boat tick).
1419    SteerBoat {
1420        /// Left paddle.
1421        left: bool,
1422        /// Right paddle.
1423        right: bool,
1424    },
1425    /// `custom_click_action` (26.1+): a dialog button's custom action, with its payload tag
1426    /// (written as vanilla does: the tag length-prefixed, `TAG_End` for none).
1427    CustomClickAction {
1428        /// Action id.
1429        id: String,
1430        /// Payload tag.
1431        payload: Option<ghast_protocol::nbt::AnonNbt>,
1432    },
1433    /// A dialog's command as vanilla sends it (`sendUnattendedCommand` after its checks): an
1434    /// unsigned `chat_command` (without the `/`).
1435    DialogCommand(String),
1436    /// A tab-completion request (`tab_complete` / `command_suggestion`,
1437    /// [`crate::TickContext::tab_complete`]).
1438    TabComplete {
1439        /// 1.13+ transaction id (not sent on 1.8 – 1.12.2).
1440        id: i32,
1441        /// The text to complete (commands with their leading `/`).
1442        text: String,
1443        /// 1.12.2: complete as a command without the leading `/` (command blocks).
1444        assume_command: bool,
1445        /// 1.8 – 1.12.2: the block the crosshair is on (the vanilla chat screen sends it).
1446        block: Option<ghast_protocol::BlockPos>,
1447    },
1448    /// The sign editor's lines (`update_sign`, [`crate::TickContext::write_sign`]): already
1449    /// filtered like the vanilla screen ([`crate::sign::vanilla_line`]).
1450    UpdateSign {
1451        /// The sign.
1452        pos: ghast_protocol::BlockPos,
1453        /// 1.20+: the front side (not sent before 1.20).
1454        front: bool,
1455        /// The four lines.
1456        lines: Box<[String; 4]>,
1457    },
1458    /// The book screen's Done or Sign (1.8 / 1.12 `MC|BEdit` / `MC|BSign`, 1.13+ `edit_book`;
1459    /// [`crate::TickContext::edit_book`]).
1460    EditBook(Box<crate::book::BookEdit>),
1461    /// A packet the behaviour built itself ([`crate::TickContext::send_raw`]), written as given.
1462    Raw(ghast_protocol::RawPacket),
1463}
1464
1465/// A status effect on the player as the server applied it (`entity_effect`; a re-application
1466/// with the same values is a new one).
1467#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1468#[non_exhaustive]
1469pub struct ActiveEffect {
1470    /// Effect id in the classic 1-based numbering (1 speed, 5 strength, 10 regeneration, 11
1471    /// resistance, 22 absorption …; 26.x: the registry id + 1, the same numbers).
1472    pub id: i8,
1473    /// Amplifier (level − 1).
1474    pub amplifier: i8,
1475    /// Duration in ticks when the packet arrived (−1: infinite, 1.19.4+).
1476    pub duration: i32,
1477    /// The flags as sent: 1.8 bit 0 = hide particles; 1.9+ bit 0 ambient, bit 1 show
1478    /// particles, bit 2 show icon (1.14+).
1479    pub flags: u8,
1480    /// The tick ([`crate::TickContext::tick`]) in which the behaviour first saw it.
1481    pub received_tick: u64,
1482}
1483
1484impl ActiveEffect {
1485    /// Ticks left at tick `now` as the vanilla client counts them down (one per client tick
1486    /// from the packet on; at least 0), `None` for an infinite effect.
1487    #[must_use]
1488    pub fn remaining(&self, now: u64) -> Option<i32> {
1489        if self.is_infinite() {
1490            return None;
1491        }
1492        let gone = i64::try_from(now.saturating_sub(self.received_tick)).unwrap_or(i64::MAX);
1493        Some((i64::from(self.duration) - gone).max(0) as i32)
1494    }
1495
1496    /// An effect without an end (duration −1).
1497    #[must_use]
1498    pub fn is_infinite(&self) -> bool {
1499        self.duration == -1
1500    }
1501}
1502
1503/// A change of the player's status effects ([`crate::TickEvents::effects`]), one per packet.
1504#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1505#[non_exhaustive]
1506pub enum EffectEvent {
1507    /// An effect was applied (new, upgraded, refreshed or re-sent).
1508    Applied(ActiveEffect),
1509    /// The server removed the effect with this id.
1510    Removed(i8),
1511    /// Every effect ended with the player entity (respawn, dimension change, join).
1512    Cleared,
1513}
1514
1515/// `entity_effect` with its duration and flags (see [`ActiveEffect`]).
1516#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1517#[non_exhaustive]
1518pub struct StatusEffect {
1519    /// The entity.
1520    pub entity_id: i32,
1521    /// Effect id (classic 1-based numbering).
1522    pub id: i8,
1523    /// Amplifier (level − 1).
1524    pub amplifier: i8,
1525    /// Duration in ticks (−1: infinite).
1526    pub duration: i32,
1527    /// Flags as sent.
1528    pub flags: u8,
1529}
1530
1531/// The world's spawn point as the server sent it (`spawn_position`): where the compass points
1532/// and where a player without a bed respawns.
1533#[derive(Debug, Clone, PartialEq)]
1534#[non_exhaustive]
1535pub struct SpawnPoint {
1536    /// Block position.
1537    pub pos: ghast_protocol::BlockPos,
1538    /// Spawn yaw (1.17+; 0 before).
1539    pub yaw: f32,
1540    /// Spawn pitch (26.x; 0 before).
1541    pub pitch: f32,
1542    /// The dimension (26.x; `None` before: the current one).
1543    pub dimension: Option<String>,
1544}
1545
1546/// A player death the server announced (1.8 – 1.16.5 `combat_event` "entity dead", 1.17+
1547/// `player_combat_kill`). The server sends it only to the player who died.
1548#[derive(Debug, Clone, PartialEq, Eq)]
1549#[non_exhaustive]
1550pub struct Death {
1551    /// The dead player's entity id (ours).
1552    pub entity_id: i32,
1553    /// The killer's entity id (1.8 – 1.19.4; `None` when the server sent −1 and on 1.20+,
1554    /// whose packet has no killer).
1555    pub killer_id: Option<i32>,
1556    /// The death message.
1557    pub message: ChatMessage,
1558}
1559
1560/// A push of the server on the player ([`crate::TickEvents::knockback`]): our own entity's
1561/// velocity packet (an attack's knockback, a launch, any velocity the server sets) or an
1562/// explosion's push.
1563#[derive(Debug, Clone, Copy, PartialEq)]
1564#[non_exhaustive]
1565pub struct Knockback {
1566    /// The motion per tick: the velocity the client takes over (a velocity packet) or the one
1567    /// it adds to its own (an explosion).
1568    pub motion: Vec3,
1569    /// An explosion's push (added), not a velocity packet (set).
1570    pub explosion: bool,
1571}
1572
1573/// A hurt of the player ([`crate::TickEvents::hurt`]): 1.8 – 1.16.5 a hurt entity status, 26.x
1574/// a `damage_event` with its source.
1575#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1576#[non_exhaustive]
1577pub struct Hurt {
1578    /// The hurt entity (ours in [`crate::TickEvents::hurt`]).
1579    pub entity_id: i32,
1580    /// 1.8 – 1.16.5: the entity status (2 hurt; 1.9+ 33 thorns, 36 drowning, 37 burning; 1.14+
1581    /// 44 sweet berry bush). `None` on 26.x.
1582    pub status: Option<i8>,
1583    /// 26.x: the damage type's registry id (`minecraft:damage_type`). `None` before.
1584    pub source_type: Option<i32>,
1585    /// 26.x: the entity that caused the damage (the shooter for a projectile), if any.
1586    pub attacker: Option<i32>,
1587    /// 26.x: the entity that dealt it directly (the projectile, or the attacker), if any.
1588    pub direct: Option<i32>,
1589}
1590
1591impl Hurt {
1592    /// A legacy hurt status.
1593    #[must_use]
1594    pub fn from_status(entity_id: i32, status: i8) -> Self {
1595        Hurt {
1596            entity_id,
1597            status: Some(status),
1598            source_type: None,
1599            attacker: None,
1600            direct: None,
1601        }
1602    }
1603
1604    /// A 26.x damage event (`cause` / `direct`: the wire's optional entity ids, already
1605    /// decoded: `None` for none).
1606    #[must_use]
1607    pub fn from_damage(
1608        entity_id: i32,
1609        source_type: i32,
1610        cause: Option<i32>,
1611        direct: Option<i32>,
1612    ) -> Self {
1613        Hurt {
1614            entity_id,
1615            status: None,
1616            source_type: Some(source_type),
1617            attacker: cause,
1618            direct,
1619        }
1620    }
1621}
1622
1623/// A step of an item use (eating, drinking, blocking, drawing a bow) of the player
1624/// ([`crate::TickEvents::item_use`]). `item` is the used stack's item id (the version's
1625/// numbering, as [`ghast_inventory::Stack::id`]), `off_hand` the hand it is in (always `false`
1626/// on 1.8), `ticks` the player ticks the use lasted (vanilla's `getItemUseTime` /
1627/// `getTicksUsingItem`).
1628#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1629#[non_exhaustive]
1630pub enum UseEvent {
1631    /// The right button started a use (the client's `setCurrentHand` / `startUsingItem`, in the
1632    /// key handling that sent the `use_item`).
1633    Started {
1634        /// The used item.
1635        item: i32,
1636        /// In the off hand.
1637        off_hand: bool,
1638    },
1639    /// The server finished the use (entity status 9 for our entity: the food was eaten, the
1640    /// potion drunk; the item's effects and the stack's new count follow in their own
1641    /// packets).
1642    Finished {
1643        /// The used item.
1644        item: i32,
1645        /// In the off hand.
1646        off_hand: bool,
1647        /// Player ticks it lasted.
1648        ticks: u32,
1649    },
1650    /// The right button was released before the server finished it (`release_use_item` sent:
1651    /// a bow shot, a lowered shield, eating cut short).
1652    Released {
1653        /// The used item.
1654        item: i32,
1655        /// In the off hand.
1656        off_hand: bool,
1657        /// Player ticks it lasted.
1658        ticks: u32,
1659    },
1660    /// The use ended without a release or a finish: the held slot changed (the behaviour's
1661    /// `select_slot` or the server's), the used hand no longer holds that item, the drop key
1662    /// dropped it, the game mode became spectator (26.x), or a new player entity (join,
1663    /// respawn). On 1.8 / 1.12 also a server `set_slot` of the used stack (a new stack object,
1664    /// as the real client compares): a use restarted by the held button in the tick of a
1665    /// finish ends this way when the eaten stack's update comes a tick later, while the server
1666    /// keeps using (see the README's Grim notes; release the button for one tick on
1667    /// [`UseEvent::Finished`] to avoid it).
1668    Interrupted {
1669        /// The used item.
1670        item: i32,
1671        /// In the off hand.
1672        off_hand: bool,
1673        /// Player ticks it lasted.
1674        ticks: u32,
1675    },
1676}