ghast-client 0.5.6

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
//! 26.x item uses in the air (`MultiPlayerGameMode.useItem` after its packet: `ItemStack.use` on
//! the client) for the items whose `use` reads more than the held-item flags: their own block ray
//! (`Item.getPlayerPOVHitResult`: from the eyes along the look to the block interaction range,
//! outline shapes, a fluid mode), the ammunition, the stack's components. A `Success` ends the
//! use key's turn with the swing (26.3: no swing packet), `CONSUME` without it; `FAIL` and `PASS`
//! hand the turn to the next hand.
//!
//! Decided here (26.1 – 26.3 read from the client jars; the entity click replays prove them):
//!
//! - spawn eggs (`SpawnEggItem.use`): a block on the ray (fluids: sources only) succeeds, else
//!   pass. 26.3 also fails for a type that cannot spawn (a hostile mob in peaceful): the client's
//!   difficulty is not tracked, so a non-peaceful world is assumed;
//! - filled buckets (water, lava, the mob buckets: `BucketItem.use`, ray without fluids): no
//!   block passes; adventure fails; a fluid poured into air succeeds and the hand's stack becomes
//!   an empty bucket outside creative (`ItemUtils.createFilledResult`). The fluid the client sets
//!   is left to the server's block update;
//! - boats and rafts (`BoatItem.use`, ray with every fluid): no block passes, so does an eye
//!   inside a pickable entity's box; a boat box (at the hit point) free of blocks, the border and
//!   the boats / shulkers around succeeds, else fails;
//! - bundles (start using, success), books (the screen; success), empty maps (success), the
//!   fishing rod (success), knowledge books (one used up outside creative; no recipes: fail);
//! - bows and crossbows (`BowItem.use` / `CrossbowItem.use`): with ammunition (an arrow in a hand
//!   or the inventory, a crossbow also a firework in a hand) or in creative: start using
//!   (`CONSUME`), else fail.
//!
//! Not decided (`AirAnswer::Unknown`: nothing after the use is predicted): a fluid on the ray of
//! a spawn egg or a boat, a bucket poured anywhere but into air or into a block that holds water,
//! a stack with `can_place_on` in adventure, a charged crossbow (its shot changes the stack), a
//! boat box that meets a happy ghast.

use super::*;
use crate::sim::predict::{AirAnswer, AirQuery, AirResult, AirUse, HandChange};
use ghast_physics::pick::BlockHit;

fn known(result: AirResult, starts: bool, hand: HandChange) -> AirAnswer {
    AirAnswer::Known(AirUse {
        result,
        starts,
        blocks: Some(Vec::new()),
        hand,
    })
}

const PASS: AirAnswer = AirAnswer::Known(AirUse {
    result: AirResult::Pass,
    starts: false,
    blocks: None,
    hand: HandChange::Keep,
});

/// The buckets with a fluid (`BucketItem` with content): water for all but lava.
const WATER_BUCKETS: &[&str] = &[
    "water_bucket",
    "cod_bucket",
    "salmon_bucket",
    "pufferfish_bucket",
    "tropical_fish_bucket",
    "axolotl_bucket",
    "tadpole_bucket",
    "sulfur_cube_bucket",
];

/// The fluid mode of an item's ray.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Fluids {
    /// `ClipContext.Fluid.NONE`.
    None,
    /// `SOURCE_ONLY` / `ANY`: a fluid on the ray is not modelled.
    Stop,
}

impl ModernSim {
    /// [`Sim::air_use`] of 26.x.
    pub(super) fn air_use_26(&self, q: &AirQuery<'_>) -> AirAnswer {
        let Some(name) = super::inv::item_name(q.stack.id()) else {
            return AirAnswer::Flags;
        };
        let creative = q.creative;
        match name {
            _ if name.ends_with("_spawn_egg") => match self.item_ray(q, Fluids::Stop) {
                None => AirAnswer::Unknown,
                Some(h) if h.is_block() => known(AirResult::Success, false, HandChange::Keep),
                Some(_) => PASS,
            },
            "lava_bucket" => self.bucket(q, false),
            _ if WATER_BUCKETS.contains(&name) => self.bucket(q, true),
            _ if name.ends_with("_boat") || name.ends_with("_raft") => self.boat(q, name),
            _ if name == "bundle" || name.ends_with("_bundle") => {
                known(AirResult::Success, true, HandChange::Keep)
            }
            "written_book" | "writable_book" | "map" | "fishing_rod" => {
                known(AirResult::Success, false, HandChange::Keep)
            }
            "knowledge_book" => {
                // The recipes component (a list: its count first; the item's default is empty).
                let ty = super::proto::types::SlotComponentType::RECIPES.0;
                let recipes = q
                    .stack
                    .components()
                    .and_then(|c| c.get(ty))
                    .is_some_and(|v| {
                        ghast_protocol::Reader::new(&v)
                            .read_varint()
                            .is_ok_and(|n| n > 0)
                    });
                let hand = if creative {
                    HandChange::Keep
                } else {
                    HandChange::UseOne
                };
                let result = if recipes {
                    AirResult::Success
                } else {
                    AirResult::Pass
                };
                known(result, false, hand)
            }
            "bow" => {
                let ammo = creative || ammunition(q.inv, false);
                ammo_use(ammo)
            }
            "crossbow" => {
                let ty = super::proto::types::SlotComponentType::CHARGED_PROJECTILES.0;
                let charged = q
                    .stack
                    .components()
                    .and_then(|c| c.get(ty))
                    .is_some_and(|v| {
                        ghast_protocol::Reader::new(&v)
                            .read_varint()
                            .is_ok_and(|n| n > 0)
                    });
                if charged {
                    return AirAnswer::Unknown;
                }
                // Player.getProjectile: creative finds an arrow when nothing else is there.
                ammo_use(creative || ammunition(q.inv, true))
            }
            _ => AirAnswer::Flags,
        }
    }

    /// `Item.getPlayerPOVHitResult`: the eyes (`getEyePosition()`: the position, not lerped),
    /// along the look to the block interaction range, outline shapes (the main hand's block
    /// form for its own outline). `None`: `fluids` is [`Fluids::Stop`] and a fluid lies on the
    /// ray before the first block hit.
    fn item_ray(&self, q: &AirQuery<'_>, fluids: Fluids) -> Option<BlockHit> {
        use super::pick;
        let p = &self.player;
        let eye = [p.pos[0], p.pos[1] + f64::from(p.dims.eye_height), p.pos[2]];
        let view = pick::view_vector(q.yaw, q.pitch);
        let range = self.ranges[0].value();
        let to = [
            eye[0] + view[0] * range,
            eye[1] + view[1] * range,
            eye[2] + view[2] * range,
        ];
        let held_block = q
            .inv
            .held()
            .and_then(|s| u16::try_from(s.id()).ok())
            .and_then(super::data::Item::from_id)
            .and_then(super::data::Item::block);
        let hit = ghast_physics::pick::traverse(eye, to, |pos| {
            let state = ghast_physics::BlockView::block(&self.world, pos[0], pos[1], pos[2]);
            if fluids == Fluids::Stop && state.phys().fluid() != 0 {
                return Some(None);
            }
            let (o, i) = pick::shapes(state, pos, held_block);
            if o.shape.empty {
                return None;
            }
            ghast_physics::pick::clip_block(&o, &i, eye, to, pos).map(Some)
        });
        match hit {
            Some(Some(h)) => Some(h),
            Some(None) => None,
            None => Some(BlockHit::miss(
                to,
                ghast_physics::pick::Direction::approximate_nearest(
                    eye[0] - to[0],
                    eye[1] - to[1],
                    eye[2] - to[2],
                ),
            )),
        }
    }

    /// `BucketItem.use` of a filled bucket (`water`: its content is water).
    fn bucket(&self, q: &AirQuery<'_>, water: bool) -> AirAnswer {
        let Some(hit) = self.item_ray(q, Fluids::None) else {
            return AirAnswer::Unknown;
        };
        if !hit.is_block() {
            return PASS;
        }
        // Player.mayUseItemAt: abilities.mayBuild (not in adventure) or the stack's can_place_on.
        if q.game_mode == crate::common::GameMode::Adventure {
            let ty = super::proto::types::SlotComponentType::CAN_PLACE_ON.0;
            if q.stack.components().is_some_and(|c| c.get(ty).is_some()) {
                return AirAnswer::Unknown;
            }
            return PASS;
        }
        let state_at = |p: [i32; 3]| ghast_physics::BlockView::block(&self.world, p[0], p[1], p[2]);
        let clicked = state_at(hit.pos);
        // A block that holds water (`LiquidBlockContainer`) takes it in place: not modelled.
        if water && holds_water(clicked) {
            return AirAnswer::Unknown;
        }
        let place = offset(hit.pos, hit.face as usize);
        // emptyContents into air: the fluid is set (or boils away), always a success.
        if !state_at(place).is_air() {
            return AirAnswer::Unknown;
        }
        let hand = if q.creative {
            HandChange::Keep
        } else {
            let bucket = super::data::Item::from_name("bucket").map_or(0, |i| i32::from(i.id()));
            HandChange::Exchange {
                output: ghast_inventory::Stack::new(bucket, 1, 0),
                creative_keeps: false,
            }
        };
        AirAnswer::Known(AirUse {
            result: AirResult::Success,
            starts: false,
            blocks: None,
            hand,
        })
    }

    /// `BoatItem.use`.
    fn boat(&self, q: &AirQuery<'_>, name: &str) -> AirAnswer {
        let Some(hit) = self.item_ray(q, Fluids::Stop) else {
            return AirAnswer::Unknown;
        };
        if !hit.is_block() {
            return PASS;
        }
        let p = &self.player;
        let eye = [p.pos[0], p.pos[1] + f64::from(p.dims.eye_height), p.pos[2]];
        let own = self.own.id;
        let tracked = self.entities.as_ref();
        // An eye inside a pickable entity's box (grown by its pick radius) passes. (The search
        // box around the look only drops entities whose box cannot hold the eye.)
        if let Some(t) = tracked {
            let inside = t.iter().any(|e| {
                e.id() != own
                    && t.pickable(e)
                    && e.bounding_box().is_some_and(|b| {
                        let r = f64::from(super::entity::pick_radius(e));
                        eye[0] >= b[0] - r
                            && eye[0] < b[3] + r
                            && eye[1] >= b[1] - r
                            && eye[1] < b[4] + r
                            && eye[2] >= b[2] - r
                            && eye[2] < b[5] + r
                    })
            });
            if inside {
                return PASS;
            }
        }
        // The boat at the hit point (setInitialPos): its type's box.
        let Some(dims) = super::data::entities::entity_by_name(name)
            .and_then(|i| super::data::entities::entity_type(i.id))
            .and_then(|t| t.size)
            .and_then(|s| s.default_dimensions())
        else {
            return AirAnswer::Unknown;
        };
        let [x, y, z] = hit.location;
        let b = dims.bounding_box(x, y, z);
        let bb = [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z];
        let free = modern::no_block_collision::<Rules, _>(
            &self.world,
            &self.player.level,
            hit.location,
            bb,
            &modern::CollisionContext {
                feet_y: y,
                ..Default::default()
            },
        );
        if !free {
            return known(AirResult::Pass, false, HandChange::Keep);
        }
        // Level.noCollision's entity part: a boat collides with what it may collide with
        // (`AbstractBoat.canCollideWith`: `canBeCollidedWith` or `isPushable`) when the boxes
        // overlap. Our own player is pushable unless it climbs.
        let meets = |o: [f64; 6]| {
            o[0] < bb[3]
                && o[3] > bb[0]
                && o[1] < bb[4]
                && o[4] > bb[1]
                && o[2] < bb[5]
                && o[5] > bb[2]
        };
        let b = &p.bb;
        if meets([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
            && !modern::on_climbable_ext::<Rules, _>(p, &self.ext, &self.world)
        {
            return known(AirResult::Pass, false, HandChange::Keep);
        }
        if let Some(t) = tracked {
            let mut unknown = false;
            for e in t.iter() {
                if e.id() == own || !e.bounding_box().is_some_and(meets) {
                    continue;
                }
                let feet_air = || {
                    let q = e.position();
                    self.world
                        .block_state(
                            q[0].floor() as i32,
                            q[1].floor() as i32,
                            q[2].floor() as i32,
                        )
                        .is_none_or(|s| s.is_air())
                };
                match boat_collides(t, e, feet_air) {
                    Some(true) => return known(AirResult::Pass, false, HandChange::Keep),
                    Some(false) => {}
                    None => unknown = true,
                }
            }
            if unknown {
                return AirAnswer::Unknown;
            }
        }
        known(AirResult::Success, false, HandChange::Keep)
    }
}

/// Whether a new boat collides with tracked entity `e` (`canBeCollidedWith(boat) ||
/// isPushable()`): boats, rafts and minecarts always; living entities while alive, not
/// spectators, not climbing (a block at the feet other than air is not decided), horses not
/// ridden, wardens not digging or emerging; bats and armor stands never. `None`: not decided
/// (a happy ghast, a creaking).
fn boat_collides(
    t: &super::entity::Tracker,
    e: &ghast_entity::Entity,
    feet_air: impl FnOnce() -> bool,
) -> Option<bool> {
    let ty = super::entity::entity_type(e)?;
    let name = ty.name;
    if name.ends_with("_boat") || name.ends_with("_raft") || name.ends_with("minecart") {
        return Some(true);
    }
    if matches!(name, "happy_ghast" | "creaking") {
        return None;
    }
    if !ty.is_living() || matches!(name, "bat" | "armor_stand") {
        return Some(false);
    }
    if !super::entity::alive(e) || t.is_spectator(e) {
        return Some(false);
    }
    let horse = matches!(
        name,
        "horse"
            | "donkey"
            | "mule"
            | "skeleton_horse"
            | "zombie_horse"
            | "camel"
            | "camel_husk"
            | "llama"
            | "trader_llama"
    );
    if horse && !e.passengers().is_empty() {
        return Some(false);
    }
    // Warden.isDiggingOrEmerging: the emerging (13) and digging (14) poses.
    if name == "warden" && matches!(super::entity::pose(e), 13 | 14) {
        return Some(false);
    }
    // onClimbable reads the block at the feet: only air is decided here.
    if !feet_air() {
        return None;
    }
    Some(true)
}

/// `BowItem.use` / `CrossbowItem.use` without a charge: ammunition starts the use (`CONSUME`),
/// none fails.
fn ammo_use(ammo: bool) -> AirAnswer {
    if ammo {
        known(AirResult::Consume, true, HandChange::Keep)
    } else {
        known(AirResult::Pass, false, HandChange::Keep)
    }
}

/// `Player.getProjectile` finds something (besides creative's arrow): an arrow (`#arrows`) in
/// a hand or anywhere in the inventory; a crossbow (`crossbow`) also takes a firework rocket in a
/// hand.
fn ammunition(inv: &ghast_inventory::Inventory, crossbow: bool) -> bool {
    let name = |s: &ghast_inventory::Stack| super::inv::item_name(s.id()).unwrap_or("");
    let arrow = |n: &str| matches!(n, "arrow" | "spectral_arrow" | "tipped_arrow");
    let held = [inv.offhand(), inv.held()]
        .into_iter()
        .flatten()
        .any(|s| arrow(name(s)) || (crossbow && name(s) == "firework_rocket"));
    held || (0..64).any(|k| inv.player(k).is_some_and(|s| arrow(name(s))))
}

/// `LiquidBlockContainer` (a water bucket pours into the block itself): the waterloggable
/// blocks, kelp and seagrass.
fn holds_water(s: BlockState) -> bool {
    s.get(super::data::Property::Waterlogged).is_some()
        || matches!(
            s.block().name(),
            "kelp" | "kelp_plant" | "seagrass" | "tall_seagrass"
        )
}

fn offset(p: [i32; 3], face: usize) -> [i32; 3] {
    let [x, y, z] = p;
    match face {
        0 => [x, y - 1, z],
        1 => [x, y + 1, z],
        2 => [x, y, z - 1],
        3 => [x, y, z + 1],
        4 => [x - 1, y, z],
        _ => [x + 1, y, z],
    }
}