Skip to main content

ghast_client/version/
mod.rs

1//! Per-version glue between the generated packets of `ghast-protocol` and the common layer.
2//!
3//! [`ClientVersion`] is implemented for the protocol marker types of the enabled versions
4//! (`ghast_protocol::{V1_8, V1_12_2, V1_16_5, V26_1}`).
5//! The connection and its tick loop are generic over it, so every hot path is monomorphised
6//! per version (no trait objects); the bot API above it only sees [`crate::common`] types.
7
8use std::fmt;
9use std::str::FromStr;
10
11use ghast_protocol::{DecodeError, EncodeError, FrameEncoder, PacketFilter, RawPacket, Version};
12
13use crate::common::{
14    ConfigInbound, ConfigOutbound, Inbound, LoginInbound, Outbound, Pose, Teleport,
15};
16use crate::interest::Interests;
17
18mod caps;
19#[cfg(ghast_modern)]
20mod commands;
21#[cfg(feature = "v1_12_2")]
22mod v1_12_2;
23#[cfg(feature = "v1_16_5")]
24mod v1_16_5;
25#[cfg(feature = "v1_8")]
26mod v1_8;
27#[cfg(feature = "v26_1")]
28pub(crate) mod v26_1;
29#[cfg(feature = "v26_2")]
30pub(crate) mod v26_2;
31
32pub use caps::{Capabilities, DataSet, ItemModel, PhysicsRules};
33#[cfg(feature = "v1_8")]
34pub use ghast_protocol::v1_8::V1_8;
35#[cfg(feature = "v1_12_2")]
36pub use ghast_protocol::v1_12_2::V1_12_2;
37#[cfg(feature = "v1_16_5")]
38pub use ghast_protocol::v1_16_5::V1_16_5;
39#[cfg(feature = "v26_1")]
40pub use ghast_protocol::v26_1::V26_1;
41#[cfg(feature = "v26_2")]
42pub use ghast_protocol::v26_2::V26_2;
43#[cfg(feature = "v26_1")]
44pub use v26_1::Wire as Wire26_1;
45#[cfg(feature = "v26_2")]
46pub use v26_2::Wire as Wire26_2;
47
48/// A protocol version the client supports, chosen at run time.
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
50#[non_exhaustive]
51pub enum GameVersion {
52    /// 1.8 – 1.8.9 (protocol 47).
53    V1_8_9,
54    /// 1.12.2 (protocol 340).
55    V1_12_2,
56    /// 1.16.4 – 1.16.5 (protocol 754).
57    V1_16_5,
58    /// 26.1 – 26.1.2 (protocol 775).
59    V26_1,
60    /// 26.2 (protocol 776).
61    V26_2,
62}
63
64impl GameVersion {
65    /// Every supported version, oldest first. A slice, so that adding a version is not a
66    /// breaking change.
67    pub const ALL: &'static [GameVersion] = &[
68        GameVersion::V1_8_9,
69        GameVersion::V1_12_2,
70        GameVersion::V1_16_5,
71        GameVersion::V26_1,
72        GameVersion::V26_2,
73    ];
74
75    /// What this version can do (the row the client core reads instead of comparing
76    /// versions).
77    #[must_use]
78    pub const fn caps(self) -> &'static Capabilities {
79        match self {
80            Self::V1_8_9 => &caps::V1_8_9,
81            Self::V1_12_2 => &caps::V1_12_2,
82            Self::V1_16_5 => &caps::V1_16_5,
83            Self::V26_1 => &caps::V26_1,
84            Self::V26_2 => &caps::V26_2,
85        }
86    }
87
88    /// Whether this build of the library includes the version (its cargo feature is on).
89    #[must_use]
90    pub const fn enabled(self) -> bool {
91        match self {
92            Self::V1_8_9 => cfg!(feature = "v1_8"),
93            Self::V1_12_2 => cfg!(feature = "v1_12_2"),
94            Self::V1_16_5 => cfg!(feature = "v1_16_5"),
95            Self::V26_1 => cfg!(feature = "v26_1"),
96            Self::V26_2 => cfg!(feature = "v26_2"),
97        }
98    }
99
100    /// Protocol number.
101    #[must_use]
102    pub const fn protocol(self) -> i32 {
103        self.caps().protocol
104    }
105
106    /// This version's row in the protocol table ([`ghast_protocol::versions`]): module,
107    /// feature, every game version sharing the protocol number, wire facts (the row exists
108    /// whether or not the version is compiled in; see its `enabled`).
109    #[must_use]
110    pub fn protocol_info(self) -> &'static ghast_protocol::ProtocolVersion {
111        ghast_protocol::versions::by_protocol(self.protocol())
112            .expect("every GameVersion has a row in the protocol table")
113    }
114
115    /// Display name (`"1.8.9"`, `"1.12.2"`, `"1.16.5"`).
116    #[must_use]
117    pub const fn name(self) -> &'static str {
118        match self {
119            Self::V1_8_9 => "1.8.9",
120            Self::V1_12_2 => "1.12.2",
121            Self::V1_16_5 => "1.16.5",
122            Self::V26_1 => "26.1",
123            Self::V26_2 => "26.2",
124        }
125    }
126
127    /// `true` for 1.9 and later: the attack cooldown, the off hand, swinging after the click,
128    /// no 0.1 targeting border on entity boxes ([`Capabilities::combat_1_9`]).
129    #[must_use]
130    pub const fn combat_1_9(self) -> bool {
131        self.caps().combat_1_9
132    }
133
134    /// Eye height above the feet while standing ([`Capabilities::eye_height`]).
135    #[must_use]
136    pub const fn eye_height(self) -> f64 {
137        self.caps().eye_height
138    }
139
140    /// Eye height while sneaking: 1.54 in 1.8 – 1.12 (`getEyeHeight` − 0.08), 1.27 in 1.16
141    /// (the crouching pose) ([`Capabilities::sneak_eye_height`]).
142    #[must_use]
143    pub const fn sneak_eye_height(self) -> f64 {
144        self.caps().sneak_eye_height
145    }
146}
147
148impl fmt::Display for GameVersion {
149    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
150        f.write_str(self.name())
151    }
152}
153
154/// Error parsing a [`GameVersion`].
155#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
156#[error("unsupported Minecraft version `{0}` (supported: 1.8.9, 1.12.2, 1.16.5, 26.1, 26.2)")]
157pub struct UnknownVersion(pub String);
158
159impl FromStr for GameVersion {
160    type Err = UnknownVersion;
161
162    /// Accepts `1.8`, `1.8.x`, `47`, `1.12.2`, `340`, `1.16.4`, `1.16.5`, `754`, `26.1`,
163    /// `26.1.1`, `26.1.2`, `775`, `26.2` and `776`.
164    fn from_str(s: &str) -> Result<Self, Self::Err> {
165        match s.trim() {
166            "1.8" | "1.8.0" | "1.8.1" | "1.8.2" | "1.8.3" | "1.8.4" | "1.8.5" | "1.8.6"
167            | "1.8.7" | "1.8.8" | "1.8.9" | "47" => Ok(Self::V1_8_9),
168            "1.12.2" | "340" => Ok(Self::V1_12_2),
169            "1.16.4" | "1.16.5" | "754" => Ok(Self::V1_16_5),
170            "26.1" | "26.1.0" | "26.1.1" | "26.1.2" | "775" => Ok(Self::V26_1),
171            "26.2" | "26.2.0" | "776" => Ok(Self::V26_2),
172            other => Err(UnknownVersion(other.to_owned())),
173        }
174    }
175}
176
177/// What a protocol version needs to provide to the client.
178///
179/// Sealed: implemented for the enabled versions' markers (`ghast_protocol::{V1_8, V1_12_2,
180/// V1_16_5, V26_1}`) only.
181pub trait ClientVersion: Version + sealed::Sealed {
182    /// The run-time tag of this version.
183    const GAME: GameVersion;
184    /// Longest chat line the server accepts, in UTF-16 units (vanilla truncates to it).
185    const CHAT_LIMIT: usize;
186
187    /// Queues the handshake packet (next state = login).
188    fn write_handshake(enc: &mut FrameEncoder, host: &str, port: u16) -> Result<(), EncodeError>;
189    /// Per-connection state of the wire layer (block action sequence numbers, chat
190    /// acknowledgements, cookies); `()` for versions without any.
191    type Wire: Default + fmt::Debug + Send;
192
193    /// Queues the login start packet (1.19+ also send the profile id).
194    fn write_login_start(
195        enc: &mut FrameEncoder,
196        username: &str,
197        uuid: uuid::Uuid,
198    ) -> Result<(), EncodeError>;
199    /// Queues the encryption response.
200    fn write_encryption_response(
201        enc: &mut FrameEncoder,
202        shared_secret: &[u8],
203        verify_token: &[u8],
204    ) -> Result<(), EncodeError>;
205    /// Queues a "not understood" answer to a login plugin request.
206    fn write_plugin_response(enc: &mut FrameEncoder, message_id: i32) -> Result<(), EncodeError>;
207    /// Decodes a login-state packet; `Ok(None)` for packets the client ignores.
208    fn decode_login(raw: &RawPacket) -> Result<Option<LoginInbound>, DecodeError>;
209    /// Queues the handshake of a connection that follows a server transfer (1.20.5+ intent 3,
210    /// `transfer`); older versions have no transfers.
211    fn write_transfer_handshake(
212        enc: &mut FrameEncoder,
213        host: &str,
214        port: u16,
215    ) -> Result<(), EncodeError> {
216        Self::write_handshake(enc, host, port)
217    }
218    /// The cookies the server stored (carried to a transfer target, vanilla `TransferState`).
219    fn take_cookies(
220        wire: &mut Self::Wire,
221    ) -> Vec<(ghast_protocol::types::ByteString, bytes::Bytes)> {
222        let _ = wire;
223        Vec::new()
224    }
225    /// Restores carried cookies into a new connection's wire state.
226    fn put_cookies(
227        wire: &mut Self::Wire,
228        cookies: Vec<(ghast_protocol::types::ByteString, bytes::Bytes)>,
229    ) {
230        let _ = (wire, cookies);
231    }
232    /// A login-state cookie answer from the wire's cookies (a transferred connection has the
233    /// previous server's); default: [`ClientVersion::write_login_cookie_response`].
234    fn write_login_cookie_response_from(
235        enc: &mut FrameEncoder,
236        key: &str,
237        wire: &mut Self::Wire,
238    ) -> Result<(), EncodeError> {
239        let _ = wire;
240        Self::write_login_cookie_response(enc, key)
241    }
242    /// Queues a login-state cookie answer (1.20.5+; never called for older versions).
243    fn write_login_cookie_response(enc: &mut FrameEncoder, key: &str) -> Result<(), EncodeError> {
244        let _ = (enc, key);
245        Ok(())
246    }
247    /// Queues `login_acknowledged` (1.20.2+; never called for older versions).
248    fn write_login_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
249        let _ = enc;
250        Ok(())
251    }
252    /// Decodes a configuration-state packet (1.20.2+); `Ok(None)` for packets the client
253    /// ignores. Registry data is returned raw ([`ConfigInbound::RegistryData`]).
254    fn decode_configuration(
255        raw: &RawPacket,
256        wire: &mut Self::Wire,
257    ) -> Result<Option<ConfigInbound>, DecodeError> {
258        let _ = (raw, wire);
259        Ok(None)
260    }
261    /// Queues a configuration-state packet (1.20.2+).
262    fn write_configuration(
263        enc: &mut FrameEncoder,
264        out: &ConfigOutbound,
265        wire: &mut Self::Wire,
266    ) -> Result<(), EncodeError> {
267        let _ = (enc, out, wire);
268        Ok(())
269    }
270    /// A `registry_data` packet of the configuration state, for the wire layer (chat types).
271    fn note_registry(raw: &RawPacket, wire: &mut Self::Wire) {
272        let _ = (raw, wire);
273    }
274    /// Queues `configuration_acknowledged` (play → configuration, 1.20.2+).
275    fn write_configuration_acknowledged(enc: &mut FrameEncoder) -> Result<(), EncodeError> {
276        let _ = enc;
277        Ok(())
278    }
279    /// Gives the inventory what the configuration state carried for it (26.1: registry and tag
280    /// bodies, kept raw by the inventory until a screen needs them), once per configuration.
281    fn feed_inventory_config(inv: &mut ghast_inventory::Inventory, wire: &mut Self::Wire) {
282        let _ = (inv, wire);
283    }
284    /// The entity a mount screen (`horse_screen_open`) belongs to; `None` for other packets
285    /// and versions without one.
286    #[inline(always)]
287    fn mount_screen_entity(raw: &RawPacket) -> Option<i32> {
288        let _ = raw;
289        None
290    }
291    /// Opens the mount screen of [`ClientVersion::mount_screen_entity`] with what it reads off
292    /// the entity (type id, `canUseSlot(SADDLE)`, `canUseSlot(BODY)`; `None`: unknown).
293    fn open_mount_screen(
294        inv: &mut ghast_inventory::Inventory,
295        raw: &RawPacket,
296        mount: Option<(i32, bool, bool)>,
297    ) -> Result<(), DecodeError> {
298        let _ = (inv, raw, mount);
299        Ok(())
300    }
301    /// Sees a batch of outbound packets before they are written (26.1: the rotation of this
302    /// tick's movement packet, which `use_item` carries).
303    #[inline(always)]
304    fn prepare_play(out: &[crate::common::Outbound], wire: &mut Self::Wire) {
305        let _ = (out, wire);
306    }
307    /// Starts a chat session with these profile keys (1.19.3+ `setKeyPair`: a new random
308    /// session id, a new signature chain); `false` when the version has no signed chat. The
309    /// core then announces it ([`crate::common::Outbound::ChatSessionUpdate`]).
310    fn begin_chat_session(
311        wire: &mut Self::Wire,
312        keys: &std::sync::Arc<ghast_auth::chat::ProfileKeys>,
313        profile_id: uuid::Uuid,
314    ) -> bool {
315        let _ = (wire, keys, profile_id);
316        false
317    }
318    /// The session is in online mode, so the client starts a chat session (`prepareKeyPair`):
319    /// up to 26.1 when the connection is encrypted, since 26.2 when the play login says so
320    /// (`onlineMode`).
321    #[inline]
322    fn online_mode(wire: &Self::Wire, encrypted: bool) -> bool {
323        let _ = wire;
324        encrypted
325    }
326    /// What the client sends on `start_configuration` before `configuration_acknowledged`
327    /// (26.1 `handleConfigurationStart`: the pending chat acknowledgement).
328    fn write_configuration_start_replies(
329        enc: &mut FrameEncoder,
330        wire: &mut Self::Wire,
331    ) -> Result<(), EncodeError> {
332        let _ = (enc, wire);
333        Ok(())
334    }
335    /// Packets the wire layer itself owes the server after decoding (chat acknowledgements).
336    fn write_wire_replies(
337        enc: &mut FrameEncoder,
338        wire: &mut Self::Wire,
339    ) -> Result<(), EncodeError> {
340        let _ = (enc, wire);
341        Ok(())
342    }
343
344    /// The block-prediction sequence number of the last predicting packet written (1.19+
345    /// `BlockStatePredictionHandler`; `None` on versions without one).
346    fn prediction_sequence(wire: &Self::Wire) -> Option<i32> {
347        let _ = wire;
348        None
349    }
350
351    /// `ClientPacketListener.verifyCommand` for a dialog command (versions without dialogs:
352    /// never asked).
353    fn check_command(wire: &mut Self::Wire, command: &str) -> crate::dialog::CommandCheck {
354        let _ = (wire, command);
355        crate::dialog::CommandCheck::ParseErrors
356    }
357
358    /// The play-state packet filter for the given interests: everything the core needs plus
359    /// what the interests ask for. Everything else is dropped before it is decoded.
360    fn play_filter(interests: Interests) -> PacketFilter;
361    /// Decodes a play-state packet; `Ok(None)` for packets the core does not use.
362    fn decode_play(raw: &RawPacket, wire: &mut Self::Wire) -> Result<Option<Inbound>, DecodeError>;
363    /// Applies an inventory packet (windows, slots, confirms, held slot, login / respawn
364    /// reset) to the inventory; returns the confirm answer to send now, if any. Other packets
365    /// are ignored.
366    fn inventory_packet(
367        inv: &mut ghast_inventory::Inventory,
368        raw: &RawPacket,
369    ) -> Result<Option<ghast_inventory::Outgoing>, DecodeError>;
370    /// The inventory version.
371    const INVENTORY: ghast_inventory::Version;
372    /// Hands the wire layer's registry facts to the inventory (1.20.5+ hashed stacks).
373    fn configure_inventory(inv: &mut ghast_inventory::Inventory, wire: &Self::Wire) {
374        let _ = (inv, wire);
375    }
376    /// Queues a play-state packet.
377    fn write_play(
378        enc: &mut FrameEncoder,
379        out: &Outbound,
380        wire: &mut Self::Wire,
381    ) -> Result<(), EncodeError>;
382    /// Applies a server teleport to the pose the way this version's client does
383    /// (`onPlayerPositionLook` + `Entity.updatePositionAndAngles`).
384    fn apply_teleport(pose: &mut Pose, t: &Teleport);
385}
386
387/// The world and movement implementation of a version (crate-internal).
388pub(crate) trait HasSim {
389    /// World + mover.
390    type Sim: crate::sim::Sim;
391    /// A fresh world and player.
392    fn new_sim(opts: &crate::sim::SimOptions) -> Self::Sim;
393}
394
395mod sealed {
396    // Deliberately unnameable: downstream crates cannot implement `ClientVersion`.
397    #[allow(unnameable_types, reason = "sealed trait pattern")]
398    pub trait Sealed {}
399    #[cfg(feature = "v1_8")]
400    impl Sealed for super::V1_8 {}
401    #[cfg(feature = "v1_12_2")]
402    impl Sealed for super::V1_12_2 {}
403    #[cfg(feature = "v1_16_5")]
404    impl Sealed for super::V1_16_5 {}
405    #[cfg(feature = "v26_1")]
406    impl Sealed for super::V26_1 {}
407    #[cfg(feature = "v26_2")]
408    impl Sealed for super::V26_2 {}
409}
410
411/// Truncates `s` to at most `max` UTF-16 units (Java's `String.length()`), at a character
412/// boundary.
413pub(crate) fn truncate_utf16(s: &str, max: usize) -> &str {
414    let mut units = 0;
415    for (i, c) in s.char_indices() {
416        units += c.len_utf16();
417        if units > max {
418            return &s[..i];
419        }
420    }
421    s
422}
423
424/// The common part of vanilla's teleport handling: relative axes are added, absolute axes
425/// zero that axis' motion; rotations are added when relative. Returns the new yaw / pitch
426/// before the version's `updatePositionAndAngles` normalisation.
427pub(crate) fn teleport_target(pose: &mut Pose, t: &Teleport) -> (f32, f32) {
428    use crate::common::teleport_flags as fl;
429    let mut x = t.x;
430    let mut y = t.y;
431    let mut z = t.z;
432    if t.flags & fl::X != 0 {
433        x += pose.pos.x;
434    } else {
435        pose.motion.x = 0.0;
436    }
437    if t.flags & fl::Y != 0 {
438        y += pose.pos.y;
439    } else {
440        pose.motion.y = 0.0;
441    }
442    if t.flags & fl::Z != 0 {
443        z += pose.pos.z;
444    } else {
445        pose.motion.z = 0.0;
446    }
447    pose.pos = crate::common::Vec3::new(x, y, z);
448    let mut yaw = t.yaw;
449    let mut pitch = t.pitch;
450    if t.flags & fl::PITCH != 0 {
451        pitch += pose.pitch;
452    }
453    if t.flags & fl::YAW != 0 {
454        yaw += pose.yaw;
455    }
456    (yaw, pitch)
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    #[test]
464    fn protocol_rows() {
465        for &v in GameVersion::ALL {
466            assert_eq!(v.caps().version, v);
467            let row = v.protocol_info();
468            assert_eq!(row.protocol, v.protocol());
469            assert!(row.enabled || !v.enabled());
470            assert!(row.game_versions.contains(&v.name()));
471        }
472    }
473
474    #[test]
475    fn parse_versions() {
476        assert_eq!("1.8.8".parse::<GameVersion>().unwrap(), GameVersion::V1_8_9);
477        assert_eq!("754".parse::<GameVersion>().unwrap(), GameVersion::V1_16_5);
478        assert_eq!(
479            "1.12.2".parse::<GameVersion>().unwrap(),
480            GameVersion::V1_12_2
481        );
482        assert_eq!("340".parse::<GameVersion>().unwrap(), GameVersion::V1_12_2);
483        assert!("1.12.1".parse::<GameVersion>().is_err());
484        assert_eq!(GameVersion::V1_8_9.protocol(), 47);
485        assert_eq!(GameVersion::V1_12_2.protocol(), 340);
486        assert_eq!(GameVersion::V1_16_5.protocol(), 754);
487    }
488
489    #[test]
490    fn utf16_truncation() {
491        assert_eq!(truncate_utf16("hello", 3), "hel");
492        assert_eq!(truncate_utf16("hello", 10), "hello");
493        // U+1F600 is two UTF-16 units: never split.
494        assert_eq!(truncate_utf16("a\u{1F600}b", 2), "a");
495        assert_eq!(truncate_utf16("a\u{1F600}b", 3), "a\u{1F600}");
496    }
497}