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)]
98pub enum ChatPosition {
99    /// A player chat message.
100    Chat,
101    /// A system message (command feedback, server announcements).
102    System,
103    /// The action bar above the hotbar.
104    ActionBar,
105    /// A value this client does not know.
106    Other(i8),
107}
108
109impl ChatPosition {
110    /// From the wire byte (same values in every supported version).
111    #[must_use]
112    pub fn from_wire(v: i8) -> Self {
113        match v {
114            0 => Self::Chat,
115            1 => Self::System,
116            2 => Self::ActionBar,
117            v => Self::Other(v),
118        }
119    }
120}
121
122/// A chat message from the server. The text stays raw JSON until asked for.
123#[derive(Debug, Clone, PartialEq, Eq)]
124pub struct ChatMessage {
125    /// The chat component as the server sent it (JSON).
126    pub json: ByteString,
127    /// Where it is shown.
128    pub position: ChatPosition,
129    /// Sender UUID (1.16+; `None` on 1.8 and for system messages with the nil UUID).
130    pub sender: Option<Uuid>,
131}
132
133impl ChatMessage {
134    /// The message as plain text, with legacy `§` formatting codes kept.
135    #[must_use]
136    pub fn text(&self) -> String {
137        ghast_protocol::chat::to_plain_text(&self.json)
138    }
139
140    /// The message as plain text without `§` formatting codes.
141    #[must_use]
142    pub fn plain(&self) -> String {
143        ghast_protocol::chat::strip_formatting(&self.text())
144    }
145}
146
147/// Converts a chat component (JSON) to plain text without formatting codes.
148#[must_use]
149pub fn chat_to_plain(json: &str) -> String {
150    ghast_protocol::chat::strip_formatting(&ghast_protocol::chat::to_plain_text(json))
151}
152
153/// Game mode.
154#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
155pub enum GameMode {
156    /// Survival.
157    #[default]
158    Survival,
159    /// Creative.
160    Creative,
161    /// Adventure.
162    Adventure,
163    /// Spectator.
164    Spectator,
165    /// A value this client does not know.
166    Other(u8),
167}
168
169impl GameMode {
170    /// From the wire value (the hardcore bit 0x08 of 1.8 is ignored).
171    #[must_use]
172    pub fn from_wire(v: u8) -> Self {
173        match v & 0x07 {
174            0 => Self::Survival,
175            1 => Self::Creative,
176            2 => Self::Adventure,
177            3 => Self::Spectator,
178            _ => Self::Other(v),
179        }
180    }
181}
182
183/// Player abilities (`abilities` packet).
184#[derive(Debug, Clone, Copy, PartialEq)]
185pub struct Abilities {
186    /// Raw flags: 1 invulnerable, 2 flying, 4 may fly, 8 creative (instant break).
187    pub flags: i8,
188    /// Flying speed (0.05 by default).
189    pub flying_speed: f32,
190    /// Walking speed (0.1 by default).
191    pub walking_speed: f32,
192}
193
194impl Default for Abilities {
195    fn default() -> Self {
196        Abilities {
197            flags: 0,
198            flying_speed: 0.05,
199            walking_speed: 0.1,
200        }
201    }
202}
203
204impl Abilities {
205    /// The server allows flight.
206    #[must_use]
207    pub fn may_fly(&self) -> bool {
208        self.flags & 4 != 0
209    }
210
211    /// The server says the player is flying.
212    #[must_use]
213    pub fn flying(&self) -> bool {
214        self.flags & 2 != 0
215    }
216}
217
218/// Health, food and saturation (`update_health`).
219#[derive(Debug, Clone, Copy, PartialEq)]
220pub struct Health {
221    /// Health points (20 = full; ≤ 0 = dead).
222    pub health: f32,
223    /// Food level 0 … 20.
224    pub food: i32,
225    /// Food saturation.
226    pub saturation: f32,
227}
228
229impl Default for Health {
230    fn default() -> Self {
231        Health {
232            health: 20.0,
233            food: 20,
234            saturation: 5.0,
235        }
236    }
237}
238
239/// Relative-teleport flag bits of the server's position packet.
240pub mod teleport_flags {
241    /// X is relative.
242    pub const X: i8 = 0x01;
243    /// Y is relative.
244    pub const Y: i8 = 0x02;
245    /// Z is relative.
246    pub const Z: i8 = 0x04;
247    /// Yaw is relative.
248    pub const YAW: i8 = 0x08;
249    /// Pitch is relative.
250    pub const PITCH: i8 = 0x10;
251}
252
253/// A server teleport (position packet), before it is applied to the pose.
254#[derive(Debug, Clone, Copy, PartialEq)]
255pub struct Teleport {
256    /// X (absolute or relative, see `flags`).
257    pub x: f64,
258    /// Y.
259    pub y: f64,
260    /// Z.
261    pub z: f64,
262    /// Yaw.
263    pub yaw: f32,
264    /// Pitch.
265    pub pitch: f32,
266    /// [`teleport_flags`] bits.
267    pub flags: i8,
268    /// Teleport id to confirm (1.9+).
269    pub teleport_id: Option<i32>,
270}
271
272/// Login-state packets from the server, common to every version.
273#[derive(Debug, Clone, PartialEq)]
274pub enum LoginInbound {
275    /// The server refused the login (chat JSON).
276    Disconnect(ByteString),
277    /// Online mode: the server asks for encryption.
278    EncryptionRequest {
279        /// Server id (usually empty) for the session hash.
280        server_id: ByteString,
281        /// The server's RSA public key (DER).
282        public_key: Bytes,
283        /// Token to encrypt and send back.
284        verify_token: Bytes,
285    },
286    /// Compression starts with the next packet.
287    Compress(i32),
288    /// Login finished; the connection is in the play state.
289    Success {
290        /// The player's UUID as the server assigned it.
291        uuid: Option<Uuid>,
292        /// The player's name.
293        username: ByteString,
294    },
295    /// A login plugin request (1.13+): answered with "not understood".
296    PluginRequest {
297        /// Message id to answer.
298        message_id: i32,
299        /// Channel name.
300        channel: ByteString,
301    },
302}
303
304/// Static information from the join game packet.
305#[derive(Debug, Clone, PartialEq)]
306pub struct JoinGame {
307    /// The player's entity id.
308    pub entity_id: i32,
309    /// Game mode.
310    pub game_mode: GameMode,
311    /// Dimension: the 1.8 id (−1 nether, 0 overworld, 1 end) as a string, or the 1.16 world
312    /// name (e.g. `minecraft:overworld`).
313    pub dimension: String,
314    /// Hardcore world.
315    pub hardcore: bool,
316    /// 1.16: the dimension codec and dimension type NBT, kept raw (not parsed).
317    pub dimension_nbt: Option<(ghast_protocol::nbt::RawNbt, ghast_protocol::nbt::RawNbt)>,
318    /// 1.16: the respawn screen is shown (false = immediate respawn gamerule).
319    pub respawn_screen: bool,
320}
321
322/// Clientbound play packets the core understands, common to every version.
323#[derive(Debug, Clone, PartialEq)]
324pub enum Inbound {
325    /// Keep-alive to echo.
326    KeepAlive(i64),
327    /// Join game (also sent again on a proxy server switch).
328    JoinGame(JoinGame),
329    /// Respawn / dimension change.
330    Respawn {
331        /// Dimension key (see [`JoinGame::dimension`]).
332        dimension: String,
333        /// Game mode after the respawn.
334        game_mode: GameMode,
335    },
336    /// Server teleport / position correction.
337    Teleport(Teleport),
338    /// Chat message.
339    Chat(ChatMessage),
340    /// The server ends the session (chat JSON).
341    Disconnect(ByteString),
342    /// Health, food and saturation.
343    Health(Health),
344    /// Abilities.
345    Abilities(Abilities),
346    /// The server selects a hotbar slot.
347    HeldSlot(i8),
348    /// Game state change (`reason`, `value`), e.g. reason 3 = game mode.
349    GameState {
350        /// Reason id (same numbering in all supported versions).
351        reason: u8,
352        /// Value.
353        value: f32,
354    },
355    /// Window confirm transaction.
356    Transaction {
357        /// Window id.
358        window_id: i8,
359        /// Action number.
360        action: i16,
361        /// Accepted.
362        accepted: bool,
363    },
364    /// A window opened.
365    OpenWindow(i32),
366    /// The open window was closed by the server.
367    CloseWindow(i32),
368    /// Compression threshold change in the play state (1.8).
369    SetCompression(i32),
370    /// Entity velocity (blocks per tick; the wire's 1/8000 units converted).
371    Velocity {
372        /// The entity.
373        entity_id: i32,
374        /// Motion per tick.
375        motion: Vec3,
376    },
377    /// The player motion an explosion adds.
378    ExplosionPush(Vec3),
379    /// Movement speed attribute of an entity (entity properties packet).
380    MovementSpeed {
381        /// The entity.
382        entity_id: i32,
383        /// Base value.
384        base: f64,
385        /// Modifiers `(uuid, amount, operation)` in packet order.
386        modifiers: Vec<(Uuid, f64, i8)>,
387    },
388    /// A status effect was applied to an entity.
389    Effect {
390        /// The entity.
391        entity_id: i32,
392        /// Effect id.
393        id: i8,
394        /// Amplifier (level − 1).
395        amplifier: i8,
396    },
397    /// A status effect ended.
398    EffectRemoved {
399        /// The entity.
400        entity_id: i32,
401        /// Effect id.
402        id: i8,
403    },
404    /// Entity status (e.g. 9 = our item use finished).
405    EntityStatus {
406        /// The entity.
407        entity_id: i32,
408        /// Status id.
409        status: i8,
410    },
411    /// An entity (the player, if it is our id) died (1.16 `combat_event` "entity dead").
412    Died {
413        /// The dead player's entity id.
414        entity_id: i32,
415    },
416}
417
418/// Sneak / sprint `entity_action` values.
419#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
420pub enum EntityAction {
421    /// Start sneaking.
422    StartSneaking,
423    /// Stop sneaking.
424    StopSneaking,
425    /// Start sprinting.
426    StartSprinting,
427    /// Stop sprinting.
428    StopSprinting,
429}
430
431/// The one movement packet of a tick.
432#[derive(Debug, Clone, Copy, PartialEq)]
433pub enum MovePacket {
434    /// `flying` (C03): only on-ground.
435    Flying {
436        /// On ground.
437        on_ground: bool,
438    },
439    /// `position` (C04).
440    Position {
441        /// Feet position.
442        pos: Vec3,
443        /// On ground.
444        on_ground: bool,
445    },
446    /// `look` (C05).
447    Look {
448        /// Yaw.
449        yaw: f32,
450        /// Pitch.
451        pitch: f32,
452        /// On ground.
453        on_ground: bool,
454    },
455    /// `position_look` (C06).
456    PositionLook {
457        /// Feet position.
458        pos: Vec3,
459        /// Yaw.
460        yaw: f32,
461        /// Pitch.
462        pitch: f32,
463        /// On ground.
464        on_ground: bool,
465    },
466}
467
468impl MovePacket {
469    /// The 1.8 trace name (`C03` … `C06`).
470    #[must_use]
471    pub fn trace_id(&self) -> &'static str {
472        match self {
473            Self::Flying { .. } => "C03",
474            Self::Position { .. } => "C04",
475            Self::Look { .. } => "C05",
476            Self::PositionLook { .. } => "C06",
477        }
478    }
479}
480
481/// Client settings (`settings` packet), sent right after join game like vanilla.
482#[derive(Debug, Clone, PartialEq)]
483pub struct ClientSettings {
484    /// Locale, e.g. `en_US` (1.8) / `en_us` (1.16).
485    pub locale: String,
486    /// View distance in chunks.
487    pub view_distance: i8,
488    /// Chat visibility: 0 full, 1 commands only, 2 hidden.
489    pub chat_mode: i8,
490    /// Chat colours.
491    pub chat_colors: bool,
492    /// Displayed skin parts (bit mask; 0x7f = all).
493    pub skin_parts: u8,
494    /// Main hand (1.9+): 0 left, 1 right.
495    pub main_hand: i32,
496}
497
498impl Default for ClientSettings {
499    fn default() -> Self {
500        ClientSettings {
501            locale: "en_US".to_owned(),
502            view_distance: 8,
503            chat_mode: 0,
504            chat_colors: true,
505            skin_parts: 0x7f,
506            main_hand: 1,
507        }
508    }
509}
510
511/// A block face, as in the dig / place packets.
512#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
513pub enum Face {
514    /// −Y (0).
515    Down,
516    /// +Y (1).
517    Up,
518    /// −Z (2).
519    North,
520    /// +Z (3).
521    South,
522    /// −X (4).
523    West,
524    /// +X (5).
525    East,
526}
527
528impl Face {
529    /// The wire value 0 … 5.
530    #[must_use]
531    pub const fn id(self) -> i8 {
532        match self {
533            Face::Down => 0,
534            Face::Up => 1,
535            Face::North => 2,
536            Face::South => 3,
537            Face::West => 4,
538            Face::East => 5,
539        }
540    }
541
542    /// From the wire value.
543    #[must_use]
544    pub const fn from_id(id: i8) -> Option<Face> {
545        Some(match id {
546            0 => Face::Down,
547            1 => Face::Up,
548            2 => Face::North,
549            3 => Face::South,
550            4 => Face::West,
551            5 => Face::East,
552            _ => return None,
553        })
554    }
555
556    /// The neighbouring block in this direction.
557    #[must_use]
558    pub const fn offset(self, p: ghast_protocol::BlockPos) -> ghast_protocol::BlockPos {
559        let (x, y, z) = match self {
560            Face::Down => (0, -1, 0),
561            Face::Up => (0, 1, 0),
562            Face::North => (0, 0, -1),
563            Face::South => (0, 0, 1),
564            Face::West => (-1, 0, 0),
565            Face::East => (1, 0, 0),
566        };
567        ghast_protocol::BlockPos::new(p.x + x, p.y + y, p.z + z)
568    }
569}
570
571/// The `use_entity` action.
572#[derive(Debug, Clone, Copy, PartialEq)]
573pub enum EntityUse {
574    /// Right click (0).
575    Interact,
576    /// Left click (1).
577    Attack,
578    /// Right click at a point relative to the entity position (2).
579    InteractAt(Vec3),
580}
581
582/// `block_dig` status values used by the client.
583#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
584pub enum DigStatus {
585    /// Start destroying a block (0).
586    Start,
587    /// Abort destroying (1).
588    Abort,
589    /// Finish destroying (2).
590    Finish,
591    /// Release the used item: stop eating / blocking / drawing (5).
592    ReleaseUseItem,
593}
594
595impl DigStatus {
596    /// The wire value.
597    #[must_use]
598    pub const fn id(self) -> i32 {
599        match self {
600            DigStatus::Start => 0,
601            DigStatus::Abort => 1,
602            DigStatus::Finish => 2,
603            DigStatus::ReleaseUseItem => 5,
604        }
605    }
606}
607
608/// Serverbound play packets the core writes, common to every version.
609#[derive(Debug, Clone, PartialEq)]
610pub enum Outbound {
611    /// Keep-alive answer.
612    KeepAlive(i64),
613    /// Teleport confirm (1.9+; never produced for 1.8).
614    TeleportConfirm(i32),
615    /// The movement packet.
616    Move(MovePacket),
617    /// Sneak / sprint change.
618    EntityAction {
619        /// Our entity id.
620        entity_id: i32,
621        /// The action.
622        action: EntityAction,
623    },
624    /// Chat line or command (already truncated to the version's limit).
625    Chat(String),
626    /// Respawn request (client command "perform respawn").
627    Respawn,
628    /// Window confirm transaction answer.
629    Transaction {
630        /// Window id.
631        window_id: i8,
632        /// Action number.
633        action: i16,
634        /// Accepted.
635        accepted: bool,
636    },
637    /// Abilities (sent when the client toggles flight).
638    Abilities {
639        /// Flags (1 invulnerable, 2 flying, 4 may fly, 8 creative).
640        flags: i8,
641        /// Flying speed.
642        flying_speed: f32,
643        /// Walking speed.
644        walking_speed: f32,
645    },
646    /// Select a hotbar slot (0 … 8).
647    HeldSlot(i16),
648    /// Arm swing (main hand).
649    Swing,
650    /// `block_dig`.
651    Dig {
652        /// Status.
653        status: DigStatus,
654        /// Block.
655        pos: ghast_protocol::BlockPos,
656        /// Face.
657        face: Face,
658    },
659    /// `block_place` on a block face (1.8 with the held stack; 1.16 main hand).
660    Place {
661        /// The block clicked.
662        pos: ghast_protocol::BlockPos,
663        /// The face clicked.
664        face: Face,
665        /// Hit point relative to the block (floats, 0 … 1).
666        cursor: Vec3,
667        /// The held stack (1.8 sends it; vanilla servers / Grim compare it with the hand).
668        held: Option<ghast_inventory::Stack>,
669        /// 1.9+: the off hand.
670        off_hand: bool,
671    },
672    /// Use the held item (1.8 `block_place` at −1/−1/−1 face 255 with the held stack; 1.16
673    /// `use_item`).
674    UseItem {
675        /// The held stack.
676        held: Option<ghast_inventory::Stack>,
677        /// 1.9+: the off hand.
678        off_hand: bool,
679    },
680    /// 1.9+: off-hand arm swing.
681    SwingOffHand,
682    /// `use_entity`: attack or interact with an entity.
683    UseEntity {
684        /// The entity.
685        target: i32,
686        /// What to do.
687        action: EntityUse,
688        /// 1.9+: the off hand (interactions).
689        off_hand: bool,
690        /// 1.16: the sneak key is held.
691        sneaking: bool,
692    },
693    /// Client settings.
694    Settings(ClientSettings),
695    /// A packet of the inventory (window click, confirm answer, close, open inventory).
696    Inventory(ghast_inventory::Outgoing),
697    /// The client brand plugin message (`MC|Brand` on 1.8, `minecraft:brand` on 1.13+).
698    Brand(String),
699}