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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
//! Modern versions: 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
//! (`ClientLevel.tickNonPassenger`: `commonTick`, then the entity's `tick`), with the client's
//! side of the rules (`ghast_physics::modern::{projectile, drop}`, oracle-proven per kind).
//!
//! The tracker keeps doing what it did (packets, the `commonTick` interpolation step of orbs
//! and bobbers); after its tick each simulated entity runs one physics tick from the tracker's
//! state and writes position, motion, rotation and ground flag back
//! ([`super::entity::Tracker::client_simulated`]). The physics state keeps what packets do not
//! carry (water state, first tick, an arrow stuck in a block, an orb's skipped first tick, a
//! fuse); whatever a packet changed since the last tick (position, motion, rotation, ground) is
//! taken from the tracker before the tick, which is where a vanilla client's packet handler
//! puts it.
//!
//! Entity data that changes the tick: `NO_GRAVITY` (such an entity is not simulated: the
//! physics has no no-gravity rule yet, it stays where its packets put it), an arrow's
//! `IN_GROUND` and no-physics flag, a wither skull's `DANGEROUS`, a TNT's fuse, a bobber's hooked
//! entity (a hooked bobber is not simulated); `projectile_power` sets a hurting projectile's
//! acceleration. A motion packet with a non-zero motion frees a stuck arrow
//! (`AbstractArrow.lerpMotion`).
//!
//! Not simulated: entity hits, pickup, merging, an orb following a player within 8 blocks
//! (`followNearbyPlayer`, which a client runs too), a biting bobber's jerk, passengers (they
//! ride, `rideTick`), and the random draws of a client entity (unseeded in vanilla: a bobber's
//! bobbing differs between two vanilla clients too).

use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};

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

/// Entity data indices (26.1 – 26.3: the `Entity` class defines 0 – 7, a subclass starts at 8).
mod data_index {
    pub(super) const NO_GRAVITY: u8 = 5;
    /// `AbstractArrow.ID_FLAGS` (0x02: no physics), `WitherSkull.DATA_DANGEROUS`,
    /// `PrimedTnt.DATA_FUSE_ID`, `FishingHook.DATA_HOOKED_ENTITY`.
    pub(super) const FIRST: u8 = 8;
    /// `AbstractArrow.IN_GROUND`.
    pub(super) const ARROW_IN_GROUND: u8 = 10;
}

/// An identity hasher for entity ids.
#[derive(Default)]
pub(super) struct IdHasher(u64);

impl Hasher for IdHasher {
    fn finish(&self) -> u64 {
        self.0
    }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = self.0.rotate_left(8) ^ u64::from(b);
        }
    }
    fn write_i32(&mut self, i: i32) {
        self.0 = u64::from(i as u32).wrapping_mul(0x9E37_79B9_7F4A_7C15);
    }
}

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

impl Kind {
    fn of(name: &str) -> Option<Kind> {
        ProjectileKind::from_entity_name(name)
            .map(Kind::Projectile)
            .or_else(|| DropKind::from_entity_name(name).map(Kind::Drop))
    }
    fn arrow(self) -> bool {
        matches!(
            self,
            Kind::Projectile(
                ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident
            )
        )
    }
}

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

/// One simulated entity.
#[derive(Debug)]
struct Entry {
    kind: Kind,
    /// The physics state (`None` until its first tick: built from the tracker then).
    state: Option<State>,
    no_gravity: bool,
    /// An arrow's no-physics flag, a bobber hooked to an entity.
    no_physics: bool,
    /// Entity data and packets that arrived before the first tick.
    in_ground: Option<bool>,
    dangerous: Option<bool>,
    fuse: Option<i32>,
    power: Option<f64>,
    /// Position and rotation before this tick's interpolation step (orbs and bobbers).
    pre: Option<([f64; 3], [f32; 2])>,
}

impl Entry {
    fn new(kind: Kind) -> Entry {
        Entry {
            kind,
            state: None,
            no_gravity: false,
            no_physics: false,
            in_ground: None,
            dangerous: None,
            fuse: None,
            power: None,
            pre: None,
        }
    }

    fn projectile(&mut self) -> Option<&mut Projectile> {
        match &mut self.state {
            Some(State::Projectile(p)) => Some(p),
            _ => None,
        }
    }
}

/// 26.3+: the client's interpolation takes over the moves of a client-simulated entity
/// (`Entity.recordMovement` for `MoveSimulationType.SERVER_AND_CLIENT`, the same version step
/// as [`modern::Rules::SIMULATED_ON_CLIENT`]).
const PREDICTED: bool = <Rules as modern::Rules>::SIMULATED_ON_CLIENT;

/// 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 NonLiving {
    map: HashMap<i32, Entry, BuildHasherDefault<IdHasher>>,
    updates: Vec<Update>,
    /// 26.3: the moves of this tick's entity ticks (`recordMovement`).
    moves: Vec<(i32, [f64; 3])>,
    discards: Vec<i32>,
}

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

impl ModernSim {
    /// 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);
        self.filter_dirty = true;
    }

    /// The packet ids the non-living physics reads beyond the tracker's.
    pub(super) fn nonliving_packet_ids(&self) -> &'static [i32] {
        use super::proto::play::clientbound as cb;
        if self.nonliving.is_some() && self.entities.is_some() {
            &[cb::id::SET_PROJECTILE_POWER]
        } else {
            &[]
        }
    }

    /// 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 super::proto::play::clientbound as cb;
        use super::proto::types::EntityMetadataEntryValue as V;
        let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
            return Ok(());
        };
        let mut r = ghast_protocol::Reader::new(&raw.body);
        match raw.id {
            cb::id::LOGIN | cb::id::RESPAWN => n.clear(),
            cb::id::SPAWN_ENTITY => {
                let id = r.read_varint()?;
                r.skip(16)?; // uuid
                let ty = r.read_varint()?;
                let kind = u16::try_from(ty)
                    .ok()
                    .and_then(super::data::entity_type)
                    .and_then(|t| Kind::of(t.name));
                // A spawn is a new entity: a fresh state (or none, for another type).
                match kind {
                    Some(k) if t.get(id).is_some() => {
                        n.map.insert(id, Entry::new(k));
                    }
                    _ => {
                        n.map.remove(&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 (&m.value, m.key, en.kind) {
                        (V::Boolean(b), data_index::NO_GRAVITY, _) => en.no_gravity = *b,
                        (V::Byte(f), data_index::FIRST, k) if k.arrow() => {
                            en.no_physics = *f as u8 & 0x02 != 0;
                        }
                        (V::Boolean(b), data_index::ARROW_IN_GROUND, k) if k.arrow() => {
                            match en.projectile() {
                                Some(p) => p.set_in_ground(*b),
                                None => en.in_ground = Some(*b),
                            }
                        }
                        (
                            V::Boolean(b),
                            data_index::FIRST,
                            Kind::Projectile(ProjectileKind::WitherSkull),
                        ) => match en.projectile() {
                            Some(p) => p.set_dangerous(*b),
                            None => en.dangerous = Some(*b),
                        },
                        (V::Int(f), data_index::FIRST, Kind::Drop(DropKind::PrimedTnt)) => {
                            match &mut en.state {
                                Some(State::Drop(d)) => d.set_fuse(*f),
                                _ => en.fuse = Some(*f),
                            }
                        }
                        (
                            V::Int(h),
                            data_index::FIRST,
                            Kind::Projectile(ProjectileKind::FishingBobber),
                        ) => en.no_physics = *h > 0,
                        _ => {}
                    }
                }
            }
            cb::id::ENTITY_VELOCITY => {
                // AbstractArrow.lerpMotion: a non-zero motion frees a stuck arrow.
                let id = r.read_varint()?;
                let Some(en) = n.map.get_mut(&id).filter(|en| en.kind.arrow()) else {
                    return Ok(());
                };
                let moving = t.get(id).is_some_and(|e| {
                    let v = e.velocity();
                    v[0] * v[0] + v[1] * v[1] + v[2] * v[2] > 0.0
                });
                if moving {
                    match en.projectile() {
                        Some(p) => {
                            if p.in_ground() {
                                p.set_in_ground(false);
                            }
                        }
                        None => {
                            if en.in_ground == Some(true) {
                                en.in_ground = Some(false);
                            }
                        }
                    }
                }
            }
            cb::id::SET_PROJECTILE_POWER => {
                let p: cb::SetProjectilePower = raw.decode_as()?;
                if let Some(en) = n.map.get_mut(&p.id) {
                    match en.projectile() {
                        Some(s) => s.set_acceleration_power(p.acceleration_power),
                        None => en.power = Some(p.acceleration_power),
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Before the tracker's tick: `setOldPosAndRot` of the interpolating ones (orbs and
    /// bobbers), which the interpolation step then moves.
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_before_tick(&mut self) {
        let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
            return;
        };
        for (&id, en) in &mut n.map {
            en.pre = t
                .get(id)
                .filter(|e| super::entity::interpolation_target(e).is_some())
                .map(|e| (e.position(), [e.yaw(), e.pitch()]));
        }
    }

    /// One client tick of the simulated entities, after the tracker's tick.
    #[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.own.id;
        let NonLiving {
            map,
            updates,
            moves,
            discards,
        } = &mut **n;
        updates.clear();
        moves.clear();
        discards.clear();
        map.retain(|&id, en| {
            let Some(e) = t.get(id) else {
                return false;
            };
            if !t.is_ticking(e) || en.no_gravity || en.no_physics || e.vehicle().is_some() {
                return true;
            }
            let st = en.state.get_or_insert_with(|| build(en.kind, e));
            match st {
                State::Projectile(p) => {
                    // Entity data and packets that came before the first tick.
                    if let Some(g) = en.in_ground.take() {
                        p.set_in_ground(g);
                    }
                    if let Some(d) = en.dangerous.take() {
                        p.set_dangerous(d);
                    }
                    if let Some(a) = en.power.take() {
                        p.set_acceleration_power(a);
                    }
                    // FishingHook.getPlayerOwner: the spawn's owner must be a player.
                    if p.kind() == ProjectileKind::FishingBobber {
                        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);
                    }
                    take_packets_p(p, e);
                    if let Some((pos, r)) = en.pre.take() {
                        p.set_interpolation_start(pos, r[0], r[1]);
                    }
                    projectile::tick_projectile::<Rules, _>(p, Side::Client, world);
                    if p.removed() {
                        discards.push(id);
                        return false;
                    }
                    updates.push((id, p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()));
                    if PREDICTED {
                        moves.extend(p.moved_last_tick().iter().map(|&m| (id, m)));
                    }
                }
                State::Drop(d) => {
                    // FallingBlockEntity.tick: a falling block of air (the spawn's state id 0)
                    // is discarded.
                    if d.kind() == DropKind::FallingBlock && e.data() == 0 {
                        discards.push(id);
                        return false;
                    }
                    if let Some(f) = en.fuse.take() {
                        d.set_fuse(f);
                    }
                    take_packets_d(d, e);
                    if let Some((pos, r)) = en.pre.take() {
                        d.set_interpolation_start(pos, r[0], r[1]);
                    }
                    drop::tick_drop::<Rules, _>(d, Side::Client, world);
                    if d.removed() {
                        discards.push(id);
                        return false;
                    }
                    updates.push((id, d.pos(), d.vel(), [e.yaw(), e.pitch()], d.on_ground()));
                    if PREDICTED {
                        moves.extend(d.moved_last_tick().iter().map(|&m| (id, m)));
                    }
                }
            }
            true
        });
        for &(id, pos, vel, rot, g) in updates.iter() {
            t.client_simulated(id, pos, vel, rot, g);
        }
        // 26.3 (`MoveSimulationType.SERVER_AND_CLIENT`): each move goes into the interpolation
        // in progress at once (`recordMovement`).
        let level = &self.player.level;
        for &(id, m) in moves.iter() {
            t.client_predicted_move(id, m, |e, bb| block_free(world, level, e, bb));
        }
        for &id in discards.iter() {
            t.client_discarded(id);
        }
    }
}

/// The physics state of a freshly spawned entity (`EntityType.create` + `recreateFromPacket`):
/// the tracker's position, motion, rotation and ground flag. Vanilla's client entity random is
/// unseeded (a bobber's bobbing, an orb's hop in lava differ between two clients); here it is
/// seeded with the entity id.
fn build(kind: Kind, e: &ghast_entity::Entity) -> State {
    let (pos, vel) = (e.position(), e.velocity());
    let seed = i64::from(e.id());
    match kind {
        Kind::Projectile(k) => State::Projectile(
            Projectile::new(k, pos, vel)
                .with_rotation(e.yaw(), e.pitch())
                .with_on_ground(e.on_ground())
                .with_random_seed(seed),
        ),
        Kind::Drop(k) => State::Drop(
            Drop::new(k, pos, vel)
                .with_id(e.id())
                .with_on_ground(e.on_ground())
                .with_random_seed(seed),
        ),
    }
}

fn same(a: [f64; 3], b: [f64; 3]) -> bool {
    (0..3).all(|i| a[i].to_bits() == b[i].to_bits())
}

/// What packets changed since the last tick (the tracker holds it): position, motion, rotation,
/// ground flag.
fn take_packets_p(p: &mut Projectile, e: &ghast_entity::Entity) {
    if !same(p.pos(), e.position()) {
        p.set_pos(e.position());
    }
    if !same(p.vel(), e.velocity()) {
        p.set_vel(e.velocity());
    }
    if p.yaw().to_bits() != e.yaw().to_bits() || p.pitch().to_bits() != e.pitch().to_bits() {
        p.set_rotation(e.yaw(), e.pitch());
    }
    if p.on_ground() != e.on_ground() {
        p.set_on_ground(e.on_ground());
    }
}

fn take_packets_d(d: &mut Drop, e: &ghast_entity::Entity) {
    if !same(d.pos(), e.position()) {
        d.set_pos(e.position());
    }
    if !same(d.vel(), e.velocity()) {
        d.set_vel(e.velocity());
    }
    if d.on_ground() != e.on_ground() {
        d.set_on_ground(e.on_ground());
    }
}