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
469
470
471
472
473
474
475
476
477
//! 1.16.5: the other entities of the client world around the player (tracked ticks, pushes,
//! the player's own entity data) and the test hooks into them.

use super::*;

impl Sim16 {
    /// Test hook: the extension state (the dimension type).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_ext(&self) -> ghast_physics::v1_16_5::PlayerExt {
        self.ext
    }

    /// Test hook: our flags and rockets are read from now on (as after a jump press in the air
    /// with an elytra on).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_watch_glide(&mut self) {
        self.glide.watch = true;
    }

    /// A tracker for this sim: with the vanilla client's own entity view (tick order,
    /// interpolated positions and boxes) that pushes and entity collisions read.
    pub(super) fn tracker(c: ghast_entity::Config) -> ghast_entity::v1_16_5::Tracker {
        let mut t = ghast_entity::v1_16_5::Tracker::new(c);
        t.track_client_motion(true);
        t
    }

    /// Test hook: the player state (from an oracle record).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_set_player(&mut self, p: ghast_physics::v1_16_5::PlayerState) {
        self.player = p;
        self.piston_uncertain_at = None;
        self.filed_pos = p.pos;
        // The oracle files its player in its section during the setup (`checkEntityChunkPos`).
        if let Some(t) = &mut self.entities {
            t.self_filed(p.pos);
        }
    }

    /// Test hook: the player's scoreboard name (team rules).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_set_profile_name(&mut self, name: &str) {
        self.profile_name = name.into();
    }

    /// Test hook: record the session into `path` (written when the sim is dropped). Gated like
    /// the engine replay modules that use it.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_record(&mut self, path: &std::path::Path) {
        self.rec = Some(crate::record::Recorder::create(path).expect("recording file"));
    }

    /// Test hook: a `login` (own entity id, the overworld) into the entity tracker only.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_tracker_login(&mut self, own_id: i32) {
        use ghast_protocol::v1_16_5::play::clientbound::id;
        let Some(t) = &mut self.entities else { return };
        let mut b = Vec::new();
        b.extend_from_slice(&own_id.to_be_bytes());
        b.extend_from_slice(&[0, 0, 0xFF, 1]);
        let name = b"minecraft:overworld";
        b.push(name.len() as u8);
        b.extend_from_slice(name);
        b.extend_from_slice(&[10, 0, 0, 0, 10, 0, 0, 0]);
        b.push(name.len() as u8);
        b.extend_from_slice(name);
        b.extend_from_slice(&0i64.to_be_bytes());
        b.extend_from_slice(&[20, 10, 0, 1, 0, 0]);
        let raw = RawPacket {
            id: id::LOGIN,
            body: bytes::Bytes::from(b),
        };
        t.apply(&raw).unwrap();
    }

    /// Test hook: the client position and box the tracker keeps for entity `id`.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_tracker_type_name(&self, id: i32) -> Option<&'static str> {
        let e = self.entities.as_ref()?.get(id)?;
        Some(ghast_entity::v1_16_5::info(e.entity_type())?.name)
    }

    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_client_box(&self, id: i32) -> Option<([f64; 3], [f64; 6])> {
        let t = self.entities.as_ref()?;
        let (p, b) = view(t, self.parked, id);
        Some((p?, b?))
    }

    /// Test hook: the player state.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_player(&self) -> &ghast_physics::v1_16_5::PlayerState {
        &self.player
    }

    /// Test hook: the client world's tick order the tracker keeps.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_tick_order(&self) -> Vec<i32> {
        self.entities
            .as_ref()
            .map(|t| t.client_tick_order().collect())
            .unwrap_or_default()
    }

    /// [`Sim::tick_entities`] with a tracker (`ClientWorld.tickEntities`): the entities after
    /// the player push it after its tick.
    #[inline(never)]
    pub(super) fn tick_tracked(&mut self, pose: &mut Pose) {
        if !std::mem::take(&mut self.around.ticked) {
            // The player did not tick: the other entities still do.
            let w = &self.world;
            if let Some(t) = &mut self.entities {
                t.tick_client(|x, z| w.is_column_loaded(x, z));
                if !self.mounts.seen.is_empty() {
                    let vehicle = self.ride.as_ref().map(|r| r.id());
                    tick_watched_mounts(&mut self.mounts, t, w, self.ext.ultrawarm, vehicle);
                }
            }
            return;
        }
        if self.around.after.is_empty() {
            return;
        }
        let p = &mut self.player;
        for (rank, pusher) in &self.around.after {
            let push = ghast_physics::v1_16_5::push_by_with(p, self.filed_pos, &self.world, pusher);
            if let Some(v) = push
                && !self.mounts.seen.is_empty()
                && let Some(t) = self.entities.as_ref()
            {
                watched_mount_pushed(&mut self.mounts, t, *rank, v);
            }
        }
        self.around.after.clear();
        if !self.around.empty_boats_after.is_empty() {
            let a = &mut self.around;
            for pusher in std::mem::take(&mut a.empty_boats_after) {
                empty_boat(a, &pusher, true, p, self.filed_pos, &self.world);
            }
        }
        pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
        if let Some(r) = &mut self.rec {
            r.amend_state(&crate::record::state_1_16(&self.player));
        }
    }

    /// The entities around the player for this tick, as the 1.16.5 client's entity tick
    /// (`ClientWorld.tickEntities`) has them around the player's own tick: every tracked entity
    /// takes its interpolation step; the ones that tick before the player push it now, the
    /// boxes it collides with are those of the moment it ticks (after their tick for the
    /// entities before it, before it for the others), and the pushes of the entities after it
    /// are kept for [`Sim::tick_entities`].
    pub(super) fn entities_around(&mut self) {
        let parked = self.parked;
        let left = self.mounts.left;
        let vehicle = self.ride.as_ref().map(|r| r.id());
        let a = &mut self.around;
        a.boxes.clear();
        a.after.clear();
        a.before.clear();
        a.riders.clear();
        if !a.boat_pushes.is_empty() || !a.empty_boats_after.is_empty() {
            a.boat_pushes.clear();
            a.empty_boats_after.clear();
        }
        let Some(t) = self.entities.as_mut() else {
            return;
        };
        let w = &self.world;
        let loaded = |x: i32, z: i32| w.is_column_loaded(x, z);
        let p = &self.player;
        // Farther than any move of one tick can reach (the physics filters exactly).
        let reach = |v: f64| v.abs() + 3.0;
        let mut m = [reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2])];
        // In a boat: around the boat (the server may have moved it away from the seat), as far
        // as it can move.
        let mut at = p.bb;
        let vehicle_box = match self.ride.as_deref() {
            Some(Ride16::Boat(r)) => Some((r.boat.bb, r.boat.vel)),
            Some(Ride16::Cart(c)) => Some((c.cart.bb, [0.0; 3])),
            Some(Ride16::Mount(m)) => Some((m.mount.bb, m.mount.vel)),
            None => None,
        };
        if let Some((b, v)) = vehicle_box {
            let b = &b;
            at = ghast_physics::math::Aabb {
                min_x: at.min_x.min(b.min_x),
                min_y: at.min_y.min(b.min_y),
                min_z: at.min_z.min(b.min_z),
                max_x: at.max_x.max(b.max_x),
                max_y: at.max_y.max(b.max_y),
                max_z: at.max_z.max(b.max_z),
            };
            for i in 0..3 {
                m[i] = m[i].max(reach(v[i]));
            }
        }
        // The colliders that tick after the player: their boxes before their tick.
        let mut any = false;
        for e in t.iter() {
            let bits = entity_bits(e);
            if bits == 0 {
                continue;
            }
            any = true;
            if bits & (PUSH_LIVING | PUSH_BOAT) != 0
                && e.vehicle().is_some()
                && let (Some(q), Some(b)) = view(t, parked, e.id())
            {
                a.riders.push((e.id(), e.vehicle().unwrap_or(0), q, b));
            }
            if bits & COLLIDES == 0 || t.ticks_before_self(e.id()) || vehicle == Some(e.id()) {
                continue;
            }
            let (vp, vb) = view(t, parked, e.id());
            if let Some(b) = vb
                && near(&b, &at, m)
                && t.client_alive(e.id())
                && vp
                    .is_some_and(|q| loaded((q[0].floor() as i32) >> 4, (q[2].floor() as i32) >> 4))
            {
                a.boxes.push(aabb(b));
            }
        }
        t.self_filed(self.filed_pos);
        // A shulker a piston moved pushes from there (its tick pushes before it sits back).
        let mut shulkers: Vec<(i32, [f64; 3], [f64; 6])> = Vec::new();
        if std::mem::take(&mut self.piston_moved_shulker) {
            for e in t.iter() {
                if type_name(e) == Some("shulker")
                    && let (Some(p), Some(b)) = view(t, parked, e.id())
                {
                    shulkers.push((e.id(), p, b));
                }
            }
        }
        t.tick_client(loaded);
        a.ticked = true;
        if !self.mounts.seen.is_empty() {
            tick_watched_mounts(&mut self.mounts, t, w, self.ext.ultrawarm, vehicle);
        }
        if !any {
            return;
        }
        // The local player rides: in a boat we control, the other entities still collide and
        // push (the passenger's velocity is kept, its own boat excluded); on other vehicles
        // (not simulated) neither.
        // (The boat we got off by sneaking still lists us until the server says otherwise.)
        if let Some(me) = t.self_id()
            && t.iter().any(|e| {
                e.passengers().contains(&me)
                    && parked.is_none_or(|k| k.id != e.id())
                    && left != Some(e.id())
            })
        {
            let Some(id) = vehicle else {
                a.boxes.clear();
                return;
            };
            // Our boat's box is not in the list (its client view is the tracker's).
            let skip = t.client_box(id).map(aabb);
            a.boxes.retain(|b| Some(*b) != skip);
        }
        let own: &str = &self.profile_name;
        let teams = self.teams.as_deref().filter(|t| t.any_rule());
        for e in t.iter() {
            let bits = entity_bits(e);
            if bits == 0 {
                continue;
            }
            let id = e.id();
            let before = t.ticks_before_self(id);
            let (Some(pos), Some(b)) = view(t, parked, id) else {
                continue;
            };
            if vehicle == Some(id) {
                continue;
            }
            if bits & COLLIDES != 0
                && before
                && near(&b, &at, m)
                && t.client_alive(id)
                && loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
            {
                a.boxes.push(aabb(b));
            }
            if !self.entity_push || bits & (PUSH_LIVING | PUSH_BOAT) == 0 {
                continue;
            }
            let (pos, b) = match shulkers.iter().find(|s| s.0 == id) {
                Some(s) if before => (s.1, s.2),
                _ => (pos, b),
            };
            // Boats reach 0.2 farther; nothing else can touch the player (the ones after it
            // push the moved player: anything its move can reach).
            let (margin, from) = if before { ([0.25; 3], &p.bb) } else { (m, &at) };
            if !near(&b, from, margin) || !t.client_ticks(e, loaded) {
                continue;
            }
            // A spectator player has noClip and pushes nothing.
            if t.is_spectator(e) {
                continue;
            }
            // canBePushedBy: the pusher's and the player's team collision rules.
            if let Some(teams) = teams {
                let mut buf = [0u8; 36];
                let name = match t.scoreboard_name(e) {
                    Some(n) => n,
                    None => e.uuid().hyphenated().encode_lower(&mut buf),
                };
                if !teams.may_push(name, own) {
                    continue;
                }
            }
            let kind = if bits & PUSH_BOAT != 0 {
                ghast_physics::v1_16_5::PushKind::Boat
            } else {
                ghast_physics::v1_16_5::PushKind::Living
            };
            // Room after each rank for its passengers (they tick right after it).
            let rank = t.client_tick_rank(id).unwrap_or(u32::MAX).saturating_mul(4);
            let pusher = ghast_physics::v1_16_5::Pusher::new(pos, aabb(b), kind);
            if bits & PUSH_BOAT != 0 && e.passengers().is_empty() {
                empty_boat(a, &pusher, before, p, self.filed_pos, &self.world);
            }
            if before {
                a.before.push((rank, pusher));
            } else {
                a.after.push((rank, pusher));
            }
        }
        if !a.riders.is_empty() {
            rider_pushes(t, a, &p.bb, &at, m, self.entity_push, teams, own, &loaded);
        }
        a.before.sort_by_key(|x| x.0);
        a.after.sort_by_key(|x| x.0);
        let p = &mut self.player;
        for (rank, pusher) in &a.before {
            let push = ghast_physics::v1_16_5::push_by_with(p, self.filed_pos, &self.world, pusher);
            if let Some(v) = push
                && !self.mounts.seen.is_empty()
            {
                watched_mount_pushed(&mut self.mounts, t, *rank, v);
            }
        }
    }

    /// `entity_metadata` for our own entity (read once a riptide trident was held): the living
    /// entity flags (index 7), whose bit 4 is the riptide spin.
    pub(super) fn own_metadata(&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 mut r = ghast_protocol::Reader::new(&raw.body);
        let id = r.read_varint()?;
        if id != self.rt.own_id {
            if self.glide.pending.iter().any(|r| r.0 == id) {
                self.rocket_metadata(raw, id)?;
            }
            return Ok(());
        }
        let p: cb::EntityMetadata = raw.decode_as()?;
        for e in &p.metadata {
            match (e.key, &e.value) {
                (7, V::Byte(b)) => {
                    self.ext.apply_living_flags(*b as u8);
                    self.living_flags = Some(*b as u8);
                }
                // Entity.POSE as the server sends it with a sleep or wake-up: setPose's
                // calculateDimensions at once (the 0.2 × 0.2 box, or the standing box grown
                // from its minimum corner). Other poses: the client's own updatePose decides.
                (6, V::Pose(pose))
                    if *pose == 2 || self.player.pose == ghast_physics::v1_16_5::Pose::Sleeping =>
                {
                    use ghast_physics::v1_16_5::Pose;
                    self.player.set_pose(match pose {
                        1 | 4 => Pose::FallFlying,
                        2 => Pose::Sleeping,
                        3 => Pose::Swimming,
                        5 => Pose::Crouching,
                        _ => Pose::Standing,
                    });
                }
                // LivingEntity.SLEEPING_POSITION: onTrackedDataSet → setPositionInBed
                (13, V::OptPosition(p)) => {
                    if let Some(b) = p {
                        self.player.set_position(
                            f64::from(b.x) + 0.5,
                            f64::from(b.y) + 0.6875,
                            f64::from(b.z) + 0.5,
                        );
                    }
                    // isSleeping: the pose follows in the tick (updatePose)
                    self.ext.sleeping = p.is_some();
                    self.update_slow();
                    self.sleep = Some(*p);
                }
                // PlayerEntity.ABSORPTION_AMOUNT (its first entry: 14).
                (14, V::Float(a)) => {
                    self.absorption = *a;
                    self.absorption_dirty = true;
                }
                // The shared flags (sprinting, swimming, fall flying; sneaking is the input's:
                // `ClientPlayerEntity.isSneaking`).
                (0, V::Byte(b)) => {
                    self.server_flags = Some(*b as u8);
                    self.ext.apply_shared_flags(&mut self.player, *b as u8);
                    if let Some(r) = &mut self.rec {
                        r.note("own entity flags not representable");
                    }
                }
                _ => {}
            }
        }
        self.update_slow();
        Ok(())
    }
}