ghast-client 0.5.5

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
//! 1.8.9: the client's pistons (block events, moving blocks, the piston heads near the player
//! and the player among them).

use super::*;

impl Sim18 {
    /// `block_action`: a piston's extend / retract runs the client's piston.
    pub(super) fn block_action(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::v1_8::play::clientbound as cb;
        let p: cb::BlockAction = raw.decode_as()?;
        let block = p.block_id & 4095;
        if block != 29 && block != 33 {
            return Ok(());
        }
        self.piston_edits.clear();
        self.pistons.block_event(
            &self.world,
            [p.location.x, p.location.y, p.location.z],
            block as u8,
            p.byte1,
            p.byte2,
            &mut self.piston_edits,
        );
        self.apply_piston_edits();
        Ok(())
    }

    /// The player's tick while blocks move (kept out of the plain tick's code).
    #[cold]
    #[inline(never)]
    pub(super) fn step_pistons(&mut self, input: &ghast_physics::TickInput) {
        if let Some(r) = &mut self.rec {
            r.note_once("moving pistons not representable");
        }
        // The shared bounds of slabs, stairs, fences, ... (moving boxes are built from them)
        // are followed from here on, known once a query or ray sets them; ticks this model did
        // not follow, or entities that move or trace rays of their own on the client, may
        // have changed them.
        self.pistons.begin_bounds_tick(self.player.ticks_alive);
        // The crosshair ray before the world tick: a ray through a piston head leaves its plate
        // in the head block's shared bounds, which moving heads' boxes are built from. Only
        // traced here (while blocks move, the bounds are a plate or a head is within reach);
        // plain ticks skip it, and are only taken while the ray cannot meet a head. The
        // history starts known: a fresh client's head bounds are the full cube.
        {
            if std::mem::take(&mut self.ray_missed) {
                // Ticks without the ray while a head was within its reach (riding): vanilla's
                // ray may have left the plate of any head it passed in the shared bounds (a
                // head that has moved, gone or been left behind since: any facing).
                self.pistons.forget_head_bounds(0x3f);
            }
            let p = &self.player;
            let eye_h = if p.input.sneak {
                1.62f32 - 0.08
            } else {
                1.62f32
            };
            let eye = ghast_physics::pick::legacy::eye_position(p.pos, eye_h);
            let reach = f64::from(if p.abilities.creative { 5.0f32 } else { 4.5f32 });
            self.pistons.crosshair(
                &self.world,
                eye,
                ghast_physics::pick::legacy::look_vector(p.yaw, input.pitch),
                reach,
            );
        }
        // Vanilla may tick such entities between the ray and the player.
        self.forget_for_movers();
        // The player's half; vanilla ticks the other entities between the player and the moving
        // blocks, which push them too (with entity tracking the blocks' half runs from
        // `tick_entities`).
        let before = self.player.bb;
        ghast_physics::v1_8::tick_player_among_pistons(
            &mut self.player,
            input,
            &self.world,
            &ghast_physics::v1_8::Options::default(),
            &self.pistons,
            &mut self.packets,
        );
        // The player's own collision with a moving head whose bounds may be a plate this model
        // does not know.
        let head_unknown = self.pistons.head_unknown_touching(&before, &self.player.bb);
        self.pistons.end_bounds_tick(self.player.ticks_alive);
        if self.entities.is_some() && !self.pistons.is_empty() {
            self.piston_phase = true;
        } else {
            // ... and between the player and the moving blocks.
            self.forget_for_movers();
            self.piston_edits.clear();
            self.pistons.tick_after_entities(
                &mut self.player,
                &self.world,
                &ghast_physics::v1_8::Options::default(),
                &mut self.piston_edits,
            );
            self.apply_piston_edits();
            self.flag_untracked();
        }
        if head_unknown {
            self.piston_uncertain_at = Some(self.player.ticks_alive);
        }
        self.heads_near();
    }

    /// Piston heads within the crosshair's reach keep the ray traced on every tick (the slow
    /// path), so the heads' shared bounds stay known while the player is near them. The heads
    /// around are listed by a scan when the player has moved away from the last one's centre
    /// and kept up to date by the block changes and chunk loads since. Returns whether one is
    /// near (its centre within 8 blocks of the eye; the ray reaches blocks whose centre is at
    /// most 5 + 0.87 away, and a head missing from the list is at least 7.5 away on one axis).
    #[cold]
    #[inline(never)]
    pub(super) fn heads_near(&mut self) -> bool {
        const SCAN: i32 = 10;
        let p = self.player.pos;
        let eye = [p[0], p[1] + 1.62, p[2]];
        let at = eye.map(|v| v.floor() as i32);
        let far = |c: [i32; 3]| (0..3).any(|k| (at[k] - c[k]).abs() > SCAN - 7);
        if self.heads_center.is_none_or(far) {
            self.heads.clear();
            scan_heads(&self.world, at, SCAN, &mut self.heads);
            self.heads_center = Some(at);
        }
        let near = self.heads.iter().any(|h| {
            let d = (0..3)
                .map(|k| (f64::from(h[k]) + 0.5 - eye[k]).powi(2))
                .sum::<f64>();
            d <= 8.0 * 8.0
        });
        self.pistons.set_ray_needed(near);
        near
    }

    /// Nothing moves and the head bounds are the full cube, kept watched only because heads are
    /// loaded ([`ghast_physics::v1_8::Pistons::watch_only`]), and none is within the crosshair's
    /// reach from this tick's eye: the plain tick applies (its ray cannot meet a head, and its
    /// collision queries leave the full cube the bounds already are).
    #[cold]
    #[inline(never)]
    pub(super) fn heads_out_of_reach(&mut self) -> bool {
        if !self.pistons.watch_only() || self.heads_near() {
            return false;
        }
        // Other entities' queries and rays still meet the loaded heads on this tick.
        if self.bounds_movers() {
            self.pistons.forget_head_bounds(0x3f);
        }
        true
    }

    /// Piston heads may now be loaded ([`Sim18::head_watch`]).
    #[cold]
    #[inline(never)]
    fn watch_heads(&mut self) {
        self.head_watch = true;
        self.pistons.set_heads_loaded(true);
    }

    /// Columns `(cx, cz)` were loaded or replaced: a head in their sections' palettes starts the
    /// watch ([`Sim18::head_watch`]); while it runs, the list of the heads around is rescanned
    /// when a column meets its cube.
    pub(super) fn columns_loaded(&mut self, cols: impl Iterator<Item = (i32, i32)>) {
        for (cx, cz) in cols {
            if let Some(c) = self.heads_center {
                const R: i32 = 10;
                let meets = |v: i32, at: i32| v * 16 <= at + R && v * 16 + 15 >= at - R;
                if meets(cx, c[0]) && meets(cz, c[2]) {
                    self.heads_center = None;
                }
            }
            if self.head_watch {
                continue;
            }
            let Some(col) = self.world.column(cx, cz) else {
                continue;
            };
            if (0..16).any(|i| {
                col.section(i)
                    .is_some_and(|s| s.any_state(|r| r >> 4 == 34))
            }) {
                self.watch_heads();
            }
        }
    }

    /// The world was cleared or replaced (login, respawn): with no column left no head is loaded.
    pub(super) fn world_replaced(&mut self) {
        self.heads.clear();
        self.heads_center = None;
        if self.world.columns().is_empty() {
            self.head_watch = false;
            self.pistons.set_heads_loaded(false);
            self.pistons.set_ray_needed(false);
        }
    }

    /// A block at `(x, y, z)` changes from `old` to `new` (packets, the pistons' writes): the
    /// list of the heads around ([`Sim18::update_ray_need`]) follows it.
    #[inline]
    pub(super) fn head_change(
        &mut self,
        x: i32,
        y: i32,
        z: i32,
        old: Option<ghast_data::v1_8::BlockState>,
        new_is_head: bool,
    ) {
        if new_is_head && !self.head_watch {
            self.watch_heads();
        }
        if head_facing(old) == 0 && !new_is_head {
            return;
        }
        if self.heads_center.is_some() {
            self.heads.retain(|h| *h != [x, y, z]);
            if new_is_head {
                self.heads.push([x, y, z]);
            }
        }
    }

    /// `true` when the client world may hold an entity that vanilla moves (`Entity.move`) or
    /// that traces block rays on the client: items, orbs, projectiles, falling blocks, TNT,
    /// boats we boarded, ... Their collision queries and rays change the shared bounds of
    /// slabs, stairs, fences, ... and of the piston head (anywhere in the loaded world: a query
    /// that meets a static head leaves the full cube, a ray through one its plate), which
    /// moving boxes are built from and this model does not follow. Players, mobs, armor stands,
    /// paintings, item frames, leash knots, end crystals and minecarts do neither on the
    /// client; nor does a boat whose empty flag is set (`BoatEntity.tick`: it only steps
    /// toward the server's position), which holds until we board it. Without entity tracking,
    /// or with a tracker that started after the join, the client view cannot rule such an
    /// entity out: always `true`.
    #[cold]
    #[inline(never)]
    pub(super) fn bounds_movers(&self) -> bool {
        use ghast_entity::EntityType;
        self.tracker_late
            || self.entities.as_ref().is_none_or(|t| {
                t.iter().any(|e| match e.entity_type() {
                    EntityType::Player
                    | EntityType::LegacyMob(_)
                    | EntityType::Painting
                    | EntityType::LegacyObject(10 | 51 | 71 | 77 | 78) => false,
                    EntityType::LegacyObject(1) => self.boarded.contains(&e.id()),
                    _ => true,
                })
            })
    }

    /// Other entities may tick here ([`Sim18::bounds_movers`]): the shared bounds of slabs,
    /// stairs, fences, ... and the piston head bounds are not known until a query or ray of
    /// this model sets them again.
    #[cold]
    #[inline(never)]
    fn forget_for_movers(&mut self) {
        if self.bounds_movers() {
            self.pistons.forget_shared_bounds();
            self.pistons.forget_head_bounds(0x3f);
        }
    }

    /// Not modelled: moving boxes from bounds the model does not track next to the player;
    /// a push that met an entity the view does not follow or whose outcome depends on head
    /// bounds a ray on a tick without moving blocks may have left (plain ticks do not trace the
    /// ray).
    fn flag_untracked(&mut self) {
        if self.pistons.take_unmodelled() | self.pistons.untracked_near(&self.player.bb) {
            self.piston_uncertain_at = Some(self.player.ticks_alive);
        }
    }

    /// The block-entity half of the client tick (`World.tickEntities` after every entity): the
    /// moving blocks advance and push the player and the other entities the client view
    /// follows (players, mobs, armor stands: it moves its copies itself; they interpolate on
    /// toward the server's positions from there). A push that meets a boat, a minecart, another
    /// solid object, a rider or a ridden entity is flagged ([`super::WorldView::piston_uncertain`]).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_piston_phase(&mut self, pose: &mut Pose) {
        use ghast_entity::EntityType;
        use ghast_physics::math::Aabb;
        use ghast_physics::v1_8 as phys;
        self.piston_phase = false;
        // Vanilla ticks the other entities before the moving blocks.
        self.forget_for_movers();
        let mut others: Vec<(i32, phys::PistonEntity)> = Vec::new();
        let mut solids: Vec<(Aabb, [i32; 3])> = Vec::new();
        if let Some(t) = self.entities.as_ref().filter(|t| t.tracks_client_motion()) {
            let me = t.self_id();
            for e in t.iter() {
                if Some(e.id()) == me {
                    continue;
                }
                let (Some(b), Some(o)) = (e.drawn_bounding_box(), e.search_order()) else {
                    continue;
                };
                let bb = Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5]);
                let section = [o.0, o.2, o.1];
                let ty = e.entity_type();
                if ty == EntityType::LegacyObject(1) {
                    // A boat is solid for the others' moves (`getBox`).
                    solids.push((bb, section));
                }
                let living = matches!(
                    ty,
                    EntityType::Player | EntityType::LegacyMob(_) | EntityType::LegacyObject(78)
                );
                // Objects a piston moves on the client that the view does not follow (boats,
                // minecarts, TNT, end crystals, fireballs, falling blocks); hanging entities do
                // not move on the client, items, orbs and projectiles are not followed (their
                // drawn position is the server's).
                let solid_object =
                    matches!(ty, EntityType::LegacyObject(1 | 10 | 50 | 51 | 63 | 70));
                if !living && !solid_object {
                    continue;
                }
                let spectator = ty == EntityType::Player && t.tab_game_mode(&e.uuid()) == Some(3);
                let step_height = match ty {
                    EntityType::Player => 0.0,
                    // EndermanEntity 1.0, HorseBaseEntity 0.5 while not ridden (riders are not
                    // followed).
                    EntityType::LegacyMob(58) => 1.0,
                    EntityType::LegacyMob(100) => 0.5,
                    _ => phys::STEP_HEIGHT,
                };
                let p = e.drawn_position();
                others.push((
                    e.id(),
                    phys::PistonEntity {
                        bb,
                        pos: p,
                        on_ground: e.drawn_on_ground(),
                        in_web: e.drawn_in_web(),
                        step_height,
                        sneaking: ty == EntityType::Player
                            && ghast_entity::v1_8::flags(e) & 0x02 != 0,
                        moved: !spectator,
                        followed: living && e.vehicle().is_none() && e.passengers().is_empty(),
                        section,
                    },
                ));
            }
        }
        let before: Vec<phys::PistonEntity> = others.iter().map(|o| o.1).collect();
        let mut list: Vec<phys::PistonEntity> = others.iter().map(|o| o.1).collect();
        self.piston_edits.clear();
        if self.ride.is_some() {
            self.pistons.tick_blocks_among(
                &self.world,
                &phys::Options::default(),
                &mut list,
                &solids,
                &mut self.piston_edits,
            );
        } else {
            self.pistons.tick_after_entities_among(
                &mut self.player,
                &self.world,
                &phys::Options::default(),
                &mut list,
                &solids,
                &mut self.piston_edits,
            );
        }
        self.apply_piston_edits();
        if let Some(t) = &mut self.entities {
            for ((id, _), (a, b)) in others.iter().zip(list.iter().zip(&before)) {
                if a != b {
                    let x = a.bb;
                    t.client_pushed(
                        *id,
                        a.pos,
                        [x.min_x, x.min_y, x.min_z, x.max_x, x.max_y, x.max_z],
                        a.on_ground,
                        a.in_web,
                    );
                }
            }
        }
        if self.ride.is_none() {
            self.flag_untracked();
            sync_pose(pose, &self.player);
        } else if self.pistons.take_unmodelled() {
            self.piston_uncertain_at = Some(self.player.ticks_alive);
        }
    }

    /// The moving blocks' tick while the player rides (they do not push it here).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_piston_blocks(&mut self) {
        self.piston_edits.clear();
        self.pistons
            .tick_blocks(&self.world, &mut self.piston_edits);
        self.apply_piston_edits();
    }

    /// Writes the pistons' world changes into the chunk store.
    fn apply_piston_edits(&mut self) {
        for k in 0..self.piston_edits.len() {
            let ([x, y, z], s) = self.piston_edits[k];
            let old = self.world.block_state(x, y, z);
            self.head_change(x, y, z, old, s.block().id() == 34);
            if self.world.set_block_state(x, y, z, s) {
                self.updates
                    .push(BlockPos::new(x, y, z), u32::from(s.raw()));
            }
        }
    }

    piston_bookkeeping!(moving: |s| s.block().id() == ghast_physics::v1_8::MOVING_PISTON);
}

/// Lists the piston heads within `r` blocks (a cube) of `at`.
#[cold]
#[inline(never)]
fn scan_heads(w: &ghast_world::v1_8::World, at: [i32; 3], r: i32, out: &mut Vec<[i32; 3]>) {
    for x in at[0] - r..=at[0] + r {
        for z in at[2] - r..=at[2] + r {
            if !w.is_column_loaded(x >> 4, z >> 4) {
                continue;
            }
            for y in (at[1] - r).max(0)..=(at[1] + r).min(255) {
                if w.block_state(x, y, z).is_some_and(|s| s.block().id() == 34) {
                    out.push([x, y, z]);
                }
            }
        }
    }
}

/// `1 << facing` of a piston head state, else 0.
#[inline]
fn head_facing(s: Option<ghast_data::v1_8::BlockState>) -> u8 {
    match s {
        Some(s) if s.block().id() == 34 && s.meta() & 7 <= 5 => 1 << (s.meta() & 7),
        _ => 0,
    }
}