ghast-client 0.5.1

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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
//! 1.16.5 item uses in the air (`ClientPlayerInteractionManager.interactItem` after its packet:
//! the stack's `use` on the client), oracle-proven (`tests/golden/1.16.5/air_use.jsonl.gz`,
//! `AirUseDump`): the items whose use reads more than the stack. Their own ray (5 blocks, with
//! or without fluids: buckets, boats, bottles, lily pads, spawn eggs, ender eyes), the
//! ammunition (bows, crossbows), the blocks and stacks they change on the client. The classes
//! the held-item flags already decide answer [`AirAnswer::Flags`].
//!
//! Not modelled (answered [`AirAnswer::Unknown`]): an item the ray of a boat could meet with
//! other entities near it, the item cooldowns (an item cooling down passes after its packet).
//! Without an entity tracker only the player's own box counts as an entity.

use ghast_data::v1_16_5::item_use::{UseClass, arrow, crossbow_held_ammo, use_class};
use ghast_data::v1_16_5::place::{Held, Mode, Use, inert, lily_pad};
use ghast_data::v1_16_5::{Block, BlockState, Item};
use ghast_physics::math::Aabb;
use ghast_physics::pick::v1_16_5::{self as pick, Fluids};
use ghast_protocol::BlockPos;
use ghast_protocol::nbt::{Compound, NamedTag, RawNbt, Tag};

use super::predict::{AirAnswer, AirQuery, AirResult, AirUse, HandChange};
use crate::common::GameMode;

/// What the rules read besides the query.
pub(crate) struct Ctx<'a> {
    pub world: &'a ghast_world::v1_16_5::World,
    /// The player's box.
    pub bb: Aabb,
    /// The player climbs (`isClimbing`).
    pub climbing: bool,
    /// The camera's height (the pose's eye height).
    pub eye_y: f64,
    /// The dimension boils water (`isUltrawarm`).
    pub ultrawarm: bool,
    /// Gliding.
    pub fall_flying: bool,
    /// The tracked entities (`None`: no tracker).
    pub entities: Option<&'a ghast_entity::Entities>,
    /// Our own entity id (left out of the entities).
    pub own_id: i32,
}

fn item_name(id: i32) -> Option<&'static str> {
    Item::from_id(u16::try_from(id).ok()?).map(|i| i.info().name)
}

fn item_id(name: &str) -> i32 {
    Item::from_name(name).map_or(0, |i| i32::from(i.id()))
}

/// A stack with a one-entry compound (the client's own NBT for the stacks it makes).
fn with_tag(name: &str, key: &str, value: Tag) -> ghast_inventory::Stack {
    let nbt = RawNbt::from_named(&NamedTag {
        name: String::new(),
        tag: Tag::Compound(Compound(vec![(key.to_owned(), value)])),
    })
    .ok();
    ghast_inventory::Stack::new(item_id(name), 1, 0).with_nbt(nbt)
}

/// The root compound of a stack's NBT.
fn tag_of(s: &ghast_inventory::Stack) -> Option<Compound> {
    match s.nbt()?.parse().ok()??.tag {
        Tag::Compound(c) => Some(c),
        _ => None,
    }
}

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

const PASS: AirResult = AirResult::Pass;

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

/// The state at `p` (`World.getBlockState`: void air outside the build height; an unloaded
/// position reads as air, as an empty client chunk does).
fn state(w: &ghast_world::v1_16_5::World, p: BlockPos) -> BlockState {
    if !(0..256).contains(&p.y) {
        return Block::VOID_AIR.default_state();
    }
    w.block_state(p.x, p.y, p.z).unwrap_or(BlockState::AIR)
}

/// `state` set at `p` on the client, when its neighbours do not change with it.
fn set(
    w: &ghast_world::v1_16_5::World,
    p: BlockPos,
    s: BlockState,
) -> Option<Vec<(BlockPos, u32)>> {
    (0..6)
        .all(|d| inert(state(w, offset(p, d))))
        .then(|| vec![(p, u32::from(s.id()))])
}

/// `Waterloggable` (the blocks with the `waterlogged` property).
fn waterlogged(s: BlockState) -> Option<bool> {
    let p = ghast_data::v1_16_5::Property::from_name("waterlogged")?;
    s.get(p).map(|v| v == "true")
}

fn with_waterlogged(s: BlockState, on: bool) -> Option<BlockState> {
    let p = ghast_data::v1_16_5::Property::from_name("waterlogged")?;
    s.with(p, if on { "true" } else { "false" })
}

/// [`super::Sim::air_use`] of 1.16.5.
pub(crate) fn air_use(cx: &Ctx<'_>, q: &AirQuery<'_>) -> AirAnswer {
    let Some(class) = u16::try_from(q.stack.id()).ok().and_then(use_class) else {
        return AirAnswer::Unknown;
    };
    let eye = [q.eyes.x, cx.eye_y, q.eyes.z];
    let held_block = q
        .inv
        .held()
        .and_then(|s| item_name(s.id()))
        .and_then(Block::from_name);
    let ray = |f: Fluids| pick::item_ray(cx.world, eye, q.yaw, q.pitch, f, held_block);
    let creative = q.creative;
    match class {
        // the held-item flags (proven with the combat and click oracles)
        UseClass::Plain
        | UseClass::Armor
        | UseClass::Elytra
        | UseClass::Trident
        | UseClass::Thrown
        | UseClass::FishingRod => AirAnswer::Flags,
        // thrown by the server; the client uses one up (and sets the cooldown: not modelled)
        UseClass::EnderPearl => AirAnswer::Known(AirUse {
            result: AirResult::Success,
            starts: false,
            blocks: Some(Vec::new()),
            hand: if creative {
                HandChange::Keep
            } else {
                HandChange::UseOne
            },
        }),
        // `ItemUsage.consumeHeldItem` (whatever the hunger: honey bottles too) and the shield
        UseClass::MilkBucket | UseClass::Drink | UseClass::Shield => {
            known(AirResult::Consume, true)
        }
        UseClass::Firework => known(
            if cx.fall_flying {
                AirResult::Success
            } else {
                PASS
            },
            false,
        ),
        UseClass::OnAStick => known(PASS, false),
        // the book screen (writable) or the server's book (written)
        UseClass::WritableBook | UseClass::WrittenBook => known(AirResult::Success, false),
        // the hand empties outside creative before the recipes are read (none: fail)
        UseClass::KnowledgeBook => {
            let recipes =
                tag_of(q.stack).is_some_and(|t| matches!(t.get("Recipes"), Some(Tag::List(_))));
            AirAnswer::Known(AirUse {
                result: if recipes { AirResult::Success } else { PASS },
                starts: false,
                blocks: Some(Vec::new()),
                hand: if creative {
                    HandChange::Keep
                } else {
                    HandChange::Empty
                },
            })
        }
        // `FilledMapItem.createMap` on the client: map id 0
        UseClass::EmptyMap => AirAnswer::Known(AirUse {
            result: AirResult::Success,
            starts: false,
            blocks: Some(Vec::new()),
            hand: HandChange::Exchange {
                output: with_tag("filled_map", "map", Tag::Int(0)),
                creative_keeps: false,
            },
        }),
        UseClass::Bow => {
            let ammo = creative || has_arrow(q.inv);
            known(if ammo { AirResult::Consume } else { PASS }, ammo)
        }
        UseClass::Crossbow => {
            // `isCharged`: `getBoolean("Charged")`
            let charged = tag_of(q.stack).filter(|t| match t.get("Charged") {
                Some(Tag::Byte(b)) => *b != 0,
                Some(Tag::Short(v)) => *v as i8 != 0,
                Some(Tag::Int(v)) => *v as i8 != 0,
                _ => false,
            });
            if let Some(t) = charged {
                // shoots (the server's projectiles); the client empties the stack's
                // `ChargedProjectiles` and clears `Charged`
                return AirAnswer::Known(AirUse {
                    result: AirResult::Consume,
                    starts: false,
                    blocks: Some(Vec::new()),
                    hand: HandChange::Replace(fired(q.stack, t)),
                });
            }
            let held = [q.inv.offhand(), q.inv.held()]
                .into_iter()
                .flatten()
                .any(|s| u16::try_from(s.id()).is_ok_and(crossbow_held_ammo));
            let ammo = held || has_arrow(q.inv) || creative;
            known(if ammo { AirResult::Consume } else { PASS }, ammo)
        }
        UseClass::EnderEye => {
            let hit = ray(Fluids::None);
            let frame = hit.is_block()
                && state(cx.world, pos_of(hit.pos)).block() == Block::END_PORTAL_FRAME;
            if frame {
                known(PASS, false)
            } else {
                known(AirResult::Consume, true)
            }
        }
        UseClass::SpawnEgg => {
            let hit = ray(Fluids::SourceOnly);
            known(
                if hit.is_block() {
                    AirResult::Success
                } else {
                    PASS
                },
                false,
            )
        }
        UseClass::GlassBottle => {
            let hit = ray(Fluids::SourceOnly);
            let water = hit.is_block()
                && state(cx.world, pos_of(hit.pos))
                    .fluid()
                    .is_some_and(|f| f.kind == ghast_data::FluidKind::Water);
            if !water {
                return known(PASS, false);
            }
            AirAnswer::Known(AirUse {
                result: AirResult::Success,
                starts: false,
                blocks: Some(Vec::new()),
                hand: HandChange::Exchange {
                    output: with_tag("potion", "Potion", Tag::String("minecraft:water".into())),
                    creative_keeps: true,
                },
            })
        }
        UseClass::LilyPad => {
            let hit = ray(Fluids::SourceOnly);
            let above = [hit.pos[0], hit.pos[1] + 1, hit.pos[2]];
            let held = Held {
                id: u16::try_from(q.stack.id()).unwrap_or(0),
                count: q.stack.count(),
                nbt: q.stack.nbt().is_some(),
            };
            let mode = match q.game_mode {
                GameMode::Creative => Mode::Creative,
                GameMode::Adventure => Mode::Adventure,
                GameMode::Spectator => Mode::Spectator,
                _ => Mode::Survival,
            };
            let player = ghast_data::Aabb {
                min_x: cx.bb.min_x,
                min_y: cx.bb.min_y,
                min_z: cx.bb.min_z,
                max_x: cx.bb.max_x,
                max_y: cx.bb.max_y,
                max_z: cx.bb.max_z,
            };
            let o = lily_pad(above, hit.face as u8, held, mode, &player, &|[x, y, z]| {
                state(cx.world, BlockPos::new(x, y, z)).id()
            });
            match o.result {
                Some(Use::Success) => AirAnswer::Known(AirUse {
                    result: AirResult::Success,
                    starts: false,
                    blocks: o.placed.map(|v| {
                        v.into_iter()
                            .map(|([x, y, z], s)| (BlockPos::new(x, y, z), u32::from(s)))
                            .collect()
                    }),
                    hand: if o.count_after.is_some_and(|n| n < held.count) {
                        HandChange::UseOne
                    } else {
                        HandChange::Keep
                    },
                }),
                Some(_) => known(PASS, false),
                None => AirAnswer::Unknown,
            }
        }
        UseClass::Boat => boat(cx, q, eye, &ray(Fluids::Any)),
        UseClass::Bucket => bucket(cx, q, &ray),
        _ => AirAnswer::Unknown,
    }
}

/// A charged crossbow after `shootAll` on the client: `clearProjectiles` (the list emptied in
/// place, put back as an empty list) and `setCharged(false)`, the other entries kept in order.
fn fired(s: &ghast_inventory::Stack, mut t: Compound) -> ghast_inventory::Stack {
    let mut put = |key: &str, v: Tag| match t.0.iter_mut().find(|(k, _)| k == key) {
        Some(e) => e.1 = v,
        None => t.0.push((key.to_owned(), v)),
    };
    put(
        "ChargedProjectiles",
        Tag::List(ghast_protocol::nbt::List::default()),
    );
    put("Charged", Tag::Byte(0));
    let nbt = RawNbt::from_named(&NamedTag {
        name: String::new(),
        tag: Tag::Compound(t),
    })
    .ok();
    s.clone().with_nbt(nbt)
}

/// `LivingEntity.isClimbing` at the feet (a spectator never climbs; the caller checks): a
/// climbable block, or an open trapdoor above a ladder facing the same way. (Here and not
/// through the physics' own test, whose one caller in the movement keeps it inlined there.)
pub(crate) fn climbing(w: &ghast_world::v1_16_5::World, pos: [f64; 3]) -> bool {
    use ghast_data::PhysicsFlags;
    use ghast_data::v1_16_5::Property;
    let p = BlockPos::new(
        pos[0].floor() as i32,
        pos[1].floor() as i32,
        pos[2].floor() as i32,
    );
    let s = state(w, p);
    let f = s.block().physics().flags;
    if f.contains(PhysicsFlags::CLIMBABLE) {
        return true;
    }
    if f.contains(PhysicsFlags::TRAPDOOR) && s.get(Property::Open) == Some("true") {
        let below = state(w, offset(p, 0));
        return below.block() == Block::LADDER
            && below.get(Property::Facing) == s.get(Property::Facing);
    }
    false
}

fn pos_of(p: [i32; 3]) -> BlockPos {
    BlockPos::new(p[0], p[1], p[2])
}

/// `PlayerEntity.getArrowType` beyond the hands: an arrow anywhere in the inventory.
fn has_arrow(inv: &ghast_inventory::Inventory) -> bool {
    (0..41).any(|k| {
        inv.player(k)
            .is_some_and(|s| u16::try_from(s.id()).is_ok_and(arrow))
    })
}

/// `BoatItem.use`.
fn boat(
    cx: &Ctx<'_>,
    q: &AirQuery<'_>,
    eye: [f64; 3],
    hit: &ghast_physics::pick::BlockHit,
) -> AirAnswer {
    if !hit.is_block() {
        return known(PASS, false);
    }
    let _ = q;
    // the entities a boat collides with: here the player itself; another entity near the
    // ray or the boat is not modelled
    if let Some(ents) = cx.entities {
        let reach = Aabb::new(
            eye[0] - 7.0,
            eye[1] - 7.0,
            eye[2] - 7.0,
            eye[0] + 7.0,
            eye[1] + 7.0,
            eye[2] + 7.0,
        );
        let near = ents.iter().any(|e| {
            e.id() != cx.own_id
                && e.bounding_box().is_none_or(|b| {
                    b[3] > reach.min_x
                        && b[0] < reach.max_x
                        && b[4] > reach.min_y
                        && b[1] < reach.max_y
                        && b[5] > reach.min_z
                        && b[2] < reach.max_z
                })
        });
        if near {
            return AirAnswer::Unknown;
        }
    }
    // the player itself is pushable unless it climbs
    let me: &[Aabb] = if cx.climbing {
        &[]
    } else {
        std::slice::from_ref(&cx.bb)
    };
    let fits = ghast_physics::v1_16_5::boat_item_fits(cx.world, hit.location, me);
    known(if fits { AirResult::Success } else { PASS }, false)
}

/// One `placeFluid` try.
enum Pour {
    /// The spot takes no fluid (the try beside the hit follows).
    NoRoom,
    /// The placement fails.
    Fail,
    /// Placed: the blocks set on the client (`None`: left to the server).
    Done(Option<Vec<(BlockPos, u32)>>),
}

/// `BucketItem.use`.
fn bucket(
    cx: &Ctx<'_>,
    q: &AirQuery<'_>,
    ray: &dyn Fn(Fluids) -> ghast_physics::pick::BlockHit,
) -> AirAnswer {
    let name = item_name(q.stack.id()).unwrap_or("");
    let fluid = match name {
        "bucket" => None,
        "lava_bucket" => Some(Block::LAVA),
        _ => Some(Block::WATER),
    };
    let hit = ray(if fluid.is_none() {
        Fluids::SourceOnly
    } else {
        Fluids::None
    });
    if !hit.is_block() {
        return known(PASS, false);
    }
    let pos = pos_of(hit.pos);
    let face = hit.face as u8;
    // `canPlaceOn`: a player who may not modify the world (adventure) needs CanPlaceOn
    if !matches!(q.game_mode, GameMode::Survival | GameMode::Creative) {
        return known(PASS, false);
    }
    let w = cx.world;
    let at = state(w, pos);
    let Some(fluid) = fluid else {
        // `FluidDrainable.tryDrainFluid` on the client
        let (left, filled) = match at.block().name() {
            "water" | "lava" if at.fluid().is_some_and(|f| f.still()) => (
                Some(BlockState::AIR),
                if at.block() == Block::LAVA {
                    "lava_bucket"
                } else {
                    "water_bucket"
                },
            ),
            "bubble_column" => (Some(BlockState::AIR), "water_bucket"),
            _ if waterlogged(at) == Some(true) => (with_waterlogged(at, false), "water_bucket"),
            _ => (None, ""),
        };
        let Some(left) = left else {
            return known(PASS, false);
        };
        return AirAnswer::Known(AirUse {
            result: AirResult::Success,
            starts: false,
            blocks: set(w, pos, left),
            hand: HandChange::Exchange {
                output: ghast_inventory::Stack::new(item_id(filled), 1, 0),
                creative_keeps: true,
            },
        });
    };
    let water = fluid == Block::WATER;
    let fillable = |s: BlockState| {
        waterlogged(s).is_some()
            || matches!(
                s.block().name(),
                "kelp" | "kelp_plant" | "seagrass" | "tall_seagrass"
            )
    };
    let target = if fillable(at) && water {
        pos
    } else {
        offset(pos, face)
    };
    // `placeFluid`, once more beside the hit when the first spot takes no fluid
    let place = |p: BlockPos| -> Pour {
        let s = state(w, p);
        let n = s.block().name();
        let bucket_place = !matches!(n, "end_gateway" | "end_portal")
            && (s.material_replaceable() || !s.material_solid());
        let fill = waterlogged(s) == Some(false) && water;
        if !(s.is_air() || bucket_place || fill) {
            return Pour::NoRoom;
        }
        // water boils away in an ultrawarm dimension; `tryFillWithFluid` changes nothing on the
        // client
        if (cx.ultrawarm && water) || (fillable(s) && water) {
            return Pour::Done(Some(Vec::new()));
        }
        let new = fluid.default_state();
        if !(0..256).contains(&p.y) {
            return Pour::Fail;
        }
        if s == new {
            // the same state: `setBlockState` refuses, a still fluid counts as placed
            return if s.fluid().is_some_and(|f| f.still()) {
                Pour::Done(Some(Vec::new()))
            } else {
                Pour::Fail
            };
        }
        Pour::Done(set(w, p, new))
    };
    let blocks = match place(target) {
        Pour::NoRoom => match place(offset(pos, face)) {
            Pour::Done(b) => b,
            Pour::NoRoom | Pour::Fail => return known(PASS, false),
        },
        Pour::Fail => return known(PASS, false),
        Pour::Done(b) => b,
    };
    AirAnswer::Known(AirUse {
        result: AirResult::Success,
        starts: false,
        blocks,
        hand: if q.creative {
            HandChange::Keep
        } else {
            HandChange::Replace(ghast_inventory::Stack::new(item_id("bucket"), 1, 0))
        },
    })
}