ghast-client 0.5.3

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! 1.16.5: the client-side physics of the tracked non-living entities
//! ([`crate::Interests::ENTITY_PHYSICS`]): projectiles, item entities, experience orbs, primed
//! TNT and falling blocks run their own tick on the client every client tick
//! (`ClientWorld.tickEntity`), with the client's side of the rules
//! (`ghast_physics::v1_16_5::{projectile, drop}`, oracle-proven per kind).
//!
//! The physics state is the client's copy of the entity. Each packet the tracker applied is
//! handed to the copy the way `ClientPlayNetworkHandler` does it, and the copy is written back
//! to the tracker ([`ghast_entity::v1_16_5::Tracker::client_simulated`]):
//!
//! * spawn (`onEntitySpawn`): the entity the client constructs at the packet's position, with
//!   the packet's rotation; the spawn packet's motion is *not* applied (a hurting projectile
//!   turns it into its acceleration, `ExplosiveProjectileEntity`); an item's, an orb's and a
//!   TNT's constructor motion comes from the client's unseeded random — here the packet's
//!   motion, which the velocity packet a server sends right after a spawn replaces anyway;
//! * moves and teleports (`onEntityUpdate`, `onEntityPosition`): the copy moves to the new
//!   tracked position and rotation (`updateTrackedPositionAndAngles`: `setPosition`,
//!   `setRotation` with `% 360`); a fishing bobber ignores both; the ground flag is the
//!   packet's;
//! * velocity (`setVelocityClient`): a projectile with a previous rotation of 0 / 0 also turns
//!   to the motion, an arrow's despawn timer restarts;
//! * entity data: no gravity, a TNT's fuse, a dangerous wither skull, a tipped arrow's colour,
//!   a fire-proof item stack; an arrow's no-clip flag and a bobber hooked to an entity stop the
//!   simulation (not modelled).
//!
//! The client discards a TNT whose fuse ran out, a falling block of air and a bobber without its
//! player owner; it creates no bobber whose owner is not a player (not simulated here).
//!
//! Not simulated: entity hits, pickup, merging, an orb following a player within 8 blocks,
//! passengers, the falling block's removal of its own block from the client world, and the
//! random draws of a client entity (unseeded in vanilla; seeded with the entity id here).

use std::collections::HashMap;

use super::*;
use ghast_physics::v1_16_5::Side;
use ghast_physics::v1_16_5::drop::{self, Drop, DropKind};
use ghast_physics::v1_16_5::projectile::{self, Projectile, ProjectileKind};

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Projectile(ProjectileKind),
    Drop(DropKind),
}

impl Kind {
    fn of(name: &str) -> Option<Kind> {
        // 1.16.5 has one `potion` entity type (splash or lingering by its item; the same
        // physics).
        if name == "potion" {
            return Some(Kind::Projectile(ProjectileKind::SplashPotion));
        }
        ProjectileKind::from_entity_name(name)
            .map(Kind::Projectile)
            .or_else(|| DropKind::from_entity_name(name).map(Kind::Drop))
    }
}

#[derive(Debug)]
enum State {
    Projectile(Projectile),
    Drop(Drop),
}

/// One simulated entity.
#[derive(Debug)]
struct Entry {
    state: State,
    /// An arrow's no-clip flag or a bobber hooked to an entity: not simulated.
    no_physics: bool,
    /// `updateNeeded`: filed in a loaded chunk (an entity that comes into the loaded area
    /// first gets filed, and ticks from the next tick on).
    filed: bool,
}

/// A position / motion / rotation / ground update for the tracker.
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);

/// The simulated entities (a side table: only while [`crate::Interests::ENTITY_PHYSICS`] is on).
#[derive(Debug, Default)]
pub(super) struct NonLiving16 {
    map: HashMap<i32, Entry>,
    updates: Vec<Update>,
    discards: Vec<i32>,
}

impl NonLiving16 {
    /// Forgets every entity (a new world, a new tracker).
    pub(super) fn clear(&mut self) {
        self.map.clear();
    }
}

/// Entity data indices (1.16.5: `Entity` defines 0 – 6, a subclass starts at 7).
mod data_index {
    pub(super) const NO_GRAVITY: u8 = 5;
    /// `ItemEntity.STACK`, `PersistentProjectileEntity.PROJECTILE_FLAGS`,
    /// `WitherSkullEntity.CHARGED`, `TntEntity.FUSE`, `FishingBobberEntity.HOOK_ENTITY_ID`.
    pub(super) const FIRST: u8 = 7;
    /// `ArrowEntity.COLOR`.
    pub(super) const ARROW_COLOR: u8 = 9;
}

impl Sim16 {
    /// Switches the client-side physics of the non-living entities on or off.
    pub(super) fn set_nonliving(&mut self, on: bool) {
        if on == self.nonliving.is_some() {
            return;
        }
        // Entities spawned before are known again once the server sends them again.
        self.nonliving = on.then(Box::default);
    }

    /// A packet the simulated entities care about, after the tracker applied it.
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::defs::p754::types::EntityMetadataValue as V;
        use ghast_protocol::v1_16_5::play::clientbound as cb;
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return Ok(());
        };
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let id = match raw.id {
            cb::id::LOGIN => {
                n.clear();
                return Ok(());
            }
            cb::id::SPAWN_ENTITY | cb::id::SPAWN_ENTITY_EXPERIENCE_ORB => {
                let id = r.read_varint()?;
                n.map.remove(&id);
                let me = self.rt.own_id;
                if let Some(e) = t.get(id)
                    && let Some(state) = spawned(e, |o| {
                        o == me || t.get(o).is_some_and(ghast_entity::Entity::is_player)
                    })
                {
                    // addEntityPrivate files it in its chunk when that is loaded.
                    let filed = column_loaded(&self.world, e.position());
                    n.map.insert(
                        id,
                        Entry {
                            state,
                            no_physics: false,
                            filed,
                        },
                    );
                } else {
                    return Ok(());
                }
                id
            }
            cb::id::ENTITY_VELOCITY => {
                let id = r.read_varint()?;
                let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
                    return Ok(());
                };
                match &mut en.state {
                    State::Projectile(p) => p.set_velocity_client(e.velocity()),
                    State::Drop(d) => d.set_vel(e.velocity()),
                }
                id
            }
            cb::id::REL_ENTITY_MOVE
            | cb::id::ENTITY_MOVE_LOOK
            | cb::id::ENTITY_LOOK
            | cb::id::ENTITY
            | cb::id::ENTITY_TELEPORT => {
                let id = r.read_varint()?;
                let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
                    return Ok(());
                };
                match &mut en.state {
                    // The bare `entity` packet only sets the ground flag (no setPosition: the
                    // box keeps its own rounding).
                    _ if raw.id == cb::id::ENTITY => {}
                    // FishingBobberEntity.updateTrackedPositionAndAngles does nothing.
                    State::Projectile(p) if p.kind() == ProjectileKind::FishingBobber => {}
                    State::Projectile(p) => {
                        p.set_pos(e.position());
                        p.set_rotation(e.yaw() % 360.0, e.pitch() % 360.0);
                    }
                    State::Drop(d) => d.set_pos(e.position()),
                }
                match &mut en.state {
                    State::Projectile(p) => p.set_on_ground(e.on_ground()),
                    State::Drop(d) => d.set_on_ground(e.on_ground()),
                }
                id
            }
            cb::id::ENTITY_METADATA => {
                let id = r.read_varint()?;
                let Some(en) = n.map.get_mut(&id) else {
                    return Ok(());
                };
                let p: cb::EntityMetadata = raw.decode_as()?;
                for m in &p.metadata {
                    match (&mut en.state, m.key, &m.value) {
                        (State::Projectile(p), data_index::NO_GRAVITY, V::Boolean(b)) => {
                            p.set_no_gravity(*b);
                        }
                        (State::Drop(d), data_index::NO_GRAVITY, V::Boolean(b)) => {
                            d.set_no_gravity(*b);
                        }
                        (State::Projectile(p), data_index::FIRST, V::Byte(f))
                            if matches!(
                                p.kind(),
                                ProjectileKind::Arrow
                                    | ProjectileKind::SpectralArrow
                                    | ProjectileKind::Trident
                            ) =>
                        {
                            en.no_physics = *f as u8 & 0x02 != 0;
                        }
                        (State::Projectile(p), data_index::ARROW_COLOR, V::VarInt(c))
                            if p.kind() == ProjectileKind::Arrow =>
                        {
                            p.set_tipped(*c != -1);
                        }
                        (State::Projectile(p), data_index::FIRST, V::Boolean(b))
                            if p.kind() == ProjectileKind::WitherSkull =>
                        {
                            p.set_dangerous(*b);
                        }
                        (State::Projectile(p), data_index::FIRST, V::VarInt(h))
                            if p.kind() == ProjectileKind::FishingBobber =>
                        {
                            en.no_physics = *h > 0;
                        }
                        (State::Drop(d), data_index::FIRST, V::VarInt(f))
                            if d.kind() == DropKind::PrimedTnt =>
                        {
                            d.set_fuse(*f);
                        }
                        (State::Drop(d), data_index::FIRST, V::Slot(s))
                            if d.kind() == DropKind::Item =>
                        {
                            d.set_fire_immune(fire_proof(s));
                        }
                        _ => {}
                    }
                }
                return Ok(());
            }
            _ => return Ok(()),
        };
        // The copy as the handler left it.
        if let Some(en) = n.map.get(&id) {
            let (pos, vel, rot, g) = copy_of(&en.state, t.get(id));
            t.client_simulated(id, pos, vel, rot, g);
        }
        Ok(())
    }

    /// One client tick of the simulated entities (`ClientWorld.tickEntity` of each one that
    /// ticks: not riding, in a loaded column).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_nonliving(&mut self) {
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return;
        };
        if n.map.is_empty() {
            return;
        }
        let world = &self.world;
        let me = self.rt.own_id;
        let NonLiving16 {
            map,
            updates,
            discards,
        } = &mut **n;
        updates.clear();
        discards.clear();
        map.retain(|&id, en| {
            let Some(e) = t.get(id) else {
                return false;
            };
            if e.vehicle().is_some() {
                return true;
            }
            // shouldTickEntity: its column is loaded; else checkEntityChunkPos unfiles it.
            if !column_loaded(world, e.position()) {
                en.filed = false;
                return true;
            }
            if en.no_physics || !en.filed {
                if let State::Projectile(p) = &mut en.state {
                    p.skip_tick();
                }
                // checkEntityChunkPos: filed in its (loaded) chunk from now on.
                en.filed = true;
                return true;
            }
            match &mut en.state {
                State::Projectile(p) => {
                    if p.kind() == ProjectileKind::FishingBobber {
                        // FishingBobberEntity.getPlayerOwner: the spawn's owner, a player.
                        let owner = e.data();
                        let pos = if owner == me {
                            Some([0.0; 3])
                        } else {
                            t.get(owner)
                                .filter(|o| o.is_player())
                                .map(ghast_entity::Entity::position)
                        };
                        p.set_owner_pos(pos);
                    }
                    projectile::tick_projectile(p, Side::Client, world);
                    if p.removed() {
                        discards.push(id);
                        return false;
                    }
                }
                State::Drop(d) => {
                    drop::tick_drop(d, Side::Client, world);
                    if d.removed() {
                        discards.push(id);
                        return false;
                    }
                }
            }
            let (pos, vel, rot, g) = copy_of(&en.state, Some(e));
            // checkEntityChunkPos after the tick: a move out of the loaded area unfiles it.
            en.filed = column_loaded(world, pos);
            updates.push((id, pos, vel, rot, g));
            true
        });
        for &(id, pos, vel, rot, g) in updates.iter() {
            t.client_simulated(id, pos, vel, rot, g);
        }
        for &id in discards.iter() {
            t.client_discarded(id);
        }
    }
}

/// The column at `pos` is loaded (`ClientChunkManager.isChunkLoaded`).
fn column_loaded(w: &ghast_world::v1_16_5::World, pos: [f64; 3]) -> bool {
    w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
}

/// Position, motion, rotation and ground flag of the client copy (a drop keeps the tracker's
/// rotation: its tick never turns it).
fn copy_of(s: &State, e: Option<&ghast_entity::Entity>) -> ([f64; 3], [f64; 3], [f32; 2], bool) {
    match s {
        State::Projectile(p) => (p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()),
        State::Drop(d) => (
            d.pos(),
            d.vel(),
            e.map_or([0.0; 2], |e| [e.yaw(), e.pitch()]),
            d.on_ground(),
        ),
    }
}

/// The client's copy of a freshly spawned entity (`onEntitySpawn` / `onExperienceOrbSpawn`: the
/// constructor at the packet's position, then the packet's rotation); `None` for other types and
/// for a bobber whose owner is not a player (`owner_is_player`): vanilla creates none. Its random
/// is seeded with the entity id.
fn spawned(e: &ghast_entity::Entity, owner_is_player: impl Fn(i32) -> bool) -> Option<State> {
    let kind = Kind::of(ghast_entity::v1_16_5::info(e.entity_type())?.name)?;
    let (pos, vel) = (e.position(), e.velocity());
    let seed = i64::from(e.id());
    Some(match kind {
        Kind::Projectile(k) => {
            if k == ProjectileKind::FishingBobber && !owner_is_player(e.data()) {
                return None;
            }
            // Only a hurting projectile reads the spawn motion (its acceleration).
            let mut p = Projectile::new(k, pos, vel).with_random_seed(seed);
            p.set_vel([0.0; 3]);
            p.set_rotation(e.yaw(), e.pitch());
            State::Projectile(p)
        }
        Kind::Drop(k) => {
            let d = Drop::new(
                k,
                pos,
                if k == DropKind::FallingBlock {
                    [0.0; 3]
                } else {
                    vel
                },
            )
            .with_id(e.id())
            .with_random_seed(seed);
            State::Drop(if k == DropKind::FallingBlock {
                d.with_block(
                    u16::try_from(e.data())
                        .ok()
                        .and_then(ghast_data::v1_16_5::BlockState::from_id)
                        .unwrap_or(ghast_data::v1_16_5::BlockState::AIR),
                )
            } else {
                d
            })
        }
    })
}

/// `Item.isFireproof` of an item entity's stack (netherite items and ancient debris).
fn fire_proof(s: &ghast_protocol::types::slot::modern::Slot) -> bool {
    s.item()
        .and_then(|i| u16::try_from(i.id).ok())
        .and_then(ghast_data::v1_16_5::Item::from_id)
        .is_some_and(|i| {
            let n = i.info().name;
            n.starts_with("netherite_") || n == "ancient_debris"
        })
}