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
//! 1.12.2 item uses in the air (`ClientPlayerInteractionManager.method_12234` after its packet:
//! the stack's use on the client, Legacy Yarn `Item.method_13649`), oracle-proven
//! (`tests/golden/1.12.2/air_use.jsonl.gz`, `AirUseDump`): the items whose use reads more than
//! the stack. Their own ray (5 blocks, with or without still fluids: buckets, bottles, lily
//! pads, ender eyes; the boat's ray), the ammunition (bows), the blocks and stacks they change
//! on the client. In 1.12 only a SUCCESS ends the use key, without a swing
//! ([`AirResult::Consume`]); PASS and FAIL both give the off hand its turn ([`AirResult::Pass`]).
//! The classes the held-item flags already decide answer [`AirAnswer::Flags`].
//!
//! Not modelled (answered [`AirAnswer::Unknown`]): a boat item with other tracked entities
//! near, a glass bottle with an area effect cloud tracked, the item cooldowns (an item cooling
//! down passes after its packet), stacks with `CanPlaceOn` in adventure mode. Without an entity
//! tracker only the player's own box counts as an entity.

use std::sync::atomic::{AtomicI16, Ordering};

use ghast_data::v1_12::item_use::{UseClass, arrow, use_class};
use ghast_data::v1_12::{BlockState, MaterialKind};
use ghast_physics::math::Aabb;
use ghast_physics::pick::v1_12 as pick;
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_12::World,
    /// The player's box.
    pub bb: Aabb,
    /// The player climbs (`isClimbing`; a spectator never does).
    pub climbing: bool,
    /// Gliding (`method_13055`).
    pub fall_flying: bool,
    /// The dimension boils water (`doesWaterVaporize`: the nether).
    pub nether: 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,
    /// The client world's map id counter (`getIntState("map")`: the next empty map's id).
    pub maps: &'a AtomicI16,
}

const BUCKET: i32 = 325;
const WATER_BUCKET: i32 = 326;
const LAVA_BUCKET: i32 = 327;
const POTION: i32 = 373;
const FILLED_MAP: i32 = 358;

const PASS: AirResult = AirResult::Pass;
/// SUCCESS: the use key ends (1.12 swings for no item use).
const DONE: AirResult = AirResult::Consume;

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

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),
    }
}

/// `World.getBlockState`: air outside the world (an unloaded position reads as air, as an
/// empty client chunk does).
fn state(w: &ghast_world::v1_12::World, p: BlockPos) -> BlockState {
    let valid = (0..256).contains(&p.y)
        && (-30_000_000..30_000_000).contains(&p.x)
        && (-30_000_000..30_000_000).contains(&p.z);
    if !valid {
        return BlockState::AIR;
    }
    w.block_state(p.x, p.y, p.z).unwrap_or(BlockState::AIR)
}

/// `Block.isReplaceable(world, pos)` (`method_8638`): the material's, the snow layer's lowest
/// layer, a double plant whose lower half is tall grass or a fern.
fn replaceable(w: &ghast_world::v1_12::World, p: BlockPos) -> bool {
    let s = state(w, p);
    match s.block().id() {
        78 => s.meta() == 0,
        175 => {
            // the plant's kind is the lower half's (a lone upper half: the default sunflower)
            let lower = if s.meta() & 8 != 0 {
                let b = state(w, offset(p, 0));
                if b.block().id() == 175 { b.meta() } else { 0 }
            } else {
                s.meta()
            };
            matches!(lower & 7, 2 | 3)
        }
        _ => s.block().material().replaceable,
    }
}

/// A stack with a one-entry compound (the client's own NBT for the stacks it makes).
fn with_tag(id: i32, 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(id, 1, 0).with_nbt(nbt)
}

/// `canModify` outside survival and creative: only a stack naming the block in `CanPlaceOn`
/// (not modelled: such a stack is undecided).
fn may_not_modify(q: &AirQuery<'_>) -> Option<bool> {
    if matches!(q.game_mode, GameMode::Survival | GameMode::Creative) {
        Some(false)
    } else if q.stack.nbt().is_some() {
        None
    } else {
        Some(true)
    }
}

/// [`super::Sim::air_use`] of 1.12.2.
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 n = |v: f64| if v == 0.0 { 0.0 } else { v };
    let eye = [n(q.eyes.x), n(q.eyes.y), n(q.eyes.z)];
    let look = pick::look_vector(q.yaw, q.pitch);
    let ray = |liquids: bool| pick::item_ray(cx.world, eye, look, liquids);
    let creative = q.creative;
    match class {
        // the held-item flags (proven with the combat and click oracles)
        UseClass::Plain
        | UseClass::Food
        | UseClass::Armor
        | UseClass::Elytra
        | UseClass::Thrown
        | UseClass::OnAStick
        | UseClass::MilkBucket
        | UseClass::Drink
        | UseClass::Shield => AirAnswer::Flags,
        // casts or reels in: the client swings the hand (`swingHand`, its packet after the
        // use's)
        UseClass::FishingRod => known(AirResult::Success, false),
        // passes on the client (the server spawns)
        UseClass::SpawnEgg => known(PASS, false),
        // thrown by the server; the client uses one up (and sets the cooldown: not modelled)
        UseClass::EnderPearl => AirAnswer::Known(AirUse {
            result: DONE,
            starts: false,
            blocks: Some(Vec::new()),
            hand: if creative {
                HandChange::Keep
            } else {
                HandChange::UseOne
            },
        }),
        UseClass::Firework => known(if cx.fall_flying { DONE } else { PASS }, false),
        // the book screen (writable) or the server's book (written)
        UseClass::WritableBook | UseClass::WrittenBook => known(DONE, false),
        // the hand empties outside creative before the recipes are read (none: fail)
        UseClass::KnowledgeBook => {
            // `contains("Recipes", 9)`: a list
            let tag = q.stack.nbt().and_then(|r| r.parse().ok()).flatten();
            let recipes = tag.is_some_and(|t| match t.tag {
                Tag::Compound(c) => matches!(c.get("Recipes"), Some(Tag::List(_))),
                _ => false,
            });
            AirAnswer::Known(AirUse {
                result: if recipes { DONE } else { PASS },
                starts: false,
                blocks: Some(Vec::new()),
                hand: if creative {
                    HandChange::Keep
                } else {
                    HandChange::Empty
                },
            })
        }
        // `FilledMapItem.method_13663` on the client: the world's next map id
        UseClass::EmptyMap => {
            let id = cx.maps.fetch_add(1, Ordering::Relaxed);
            AirAnswer::Known(AirUse {
                result: DONE,
                starts: false,
                blocks: Some(Vec::new()),
                hand: HandChange::ExchangeLegacy {
                    output: ghast_inventory::Stack::new(FILLED_MAP, 1, id),
                },
            })
        }
        UseClass::Bow => {
            let ammo = creative || has_arrow(q.inv);
            known(if ammo { DONE } else { PASS }, ammo)
        }
        UseClass::EnderEye => {
            let frame = ray(false).is_some_and(|h| {
                h.is_block() && state(cx.world, pos_of(h.pos)).block().id() == 120
            });
            if frame {
                known(PASS, false)
            } else {
                known(DONE, true)
            }
        }
        UseClass::GlassBottle => glass_bottle(cx, q, ray(true)),
        UseClass::LilyPad => lily_pad(cx, q, ray(true)),
        UseClass::Boat => boat(cx, q, eye, look),
        UseClass::Bucket => bucket(cx, q, &ray),
        _ => AirAnswer::Unknown,
    }
}

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

/// `BowItem.method_11362` (the ammunition search): an arrow in either hand or 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))
    })
}

/// `GlassBottleItem` (no dragon's breath cloud near: with a tracker, any area effect cloud is
/// undecided).
fn glass_bottle(
    cx: &Ctx<'_>,
    q: &AirQuery<'_>,
    hit: Option<ghast_physics::pick::BlockHit>,
) -> AirAnswer {
    if let Some(ents) = cx.entities
        && ents
            .iter()
            .any(|e| matches!(e.entity_type(), ghast_entity::EntityType::LegacyObject(3)))
    {
        return AirAnswer::Unknown;
    }
    let Some(hit) = hit.filter(ghast_physics::pick::BlockHit::is_block) else {
        return known(PASS, false);
    };
    match may_not_modify(q) {
        None => return AirAnswer::Unknown,
        Some(true) => return known(PASS, false),
        Some(false) => {}
    }
    let at = state(cx.world, pos_of(hit.pos));
    if at.block().material().kind != MaterialKind::Water {
        return known(PASS, false);
    }
    AirAnswer::Known(AirUse {
        result: DONE,
        starts: false,
        blocks: Some(Vec::new()),
        hand: HandChange::ExchangeLegacy {
            output: with_tag(POTION, "Potion", Tag::String("minecraft:water".into())),
        },
    })
}

/// `LilyPadItem`: a pad above still water (level 0) whose block above is air.
fn lily_pad(
    cx: &Ctx<'_>,
    q: &AirQuery<'_>,
    hit: Option<ghast_physics::pick::BlockHit>,
) -> AirAnswer {
    let Some(hit) = hit else {
        return known(PASS, false);
    };
    if !hit.is_block() {
        return known(PASS, false);
    }
    match may_not_modify(q) {
        None => return AirAnswer::Unknown,
        Some(true) => return known(PASS, false),
        Some(false) => {}
    }
    let pos = pos_of(hit.pos);
    let at = state(cx.world, pos);
    let above = offset(pos, 1);
    let still_water = at.block().material().kind == MaterialKind::Water && at.meta() == 0;
    if !(still_water && state(cx.world, above).block().material().kind == MaterialKind::Air) {
        return known(PASS, false);
    }
    // `setBlockState` refuses above the build height
    let blocks = if (0..256).contains(&above.y) {
        vec![(
            above,
            u32::from(ghast_data::v1_12::Block::WATERLILY.default_state().raw()),
        )]
    } else {
        Vec::new()
    };
    AirAnswer::Known(AirUse {
        result: DONE,
        starts: false,
        blocks: Some(blocks),
        hand: if q.creative {
            HandChange::Keep
        } else {
            HandChange::UseOne
        },
    })
}

/// `BoatItem` (its ray from the eyes with the look: vanilla interpolates both with tick delta
/// 1.0, the current values but for float rounding).
fn boat(cx: &Ctx<'_>, q: &AirQuery<'_>, eye: [f64; 3], look: [f64; 3]) -> AirAnswer {
    let Some(hit) = pick::item_ray(cx.world, eye, look, true) else {
        return known(PASS, false);
    };
    // the entities whose box holds the eyes (a pass), and those the boat collides with: here
    // the player itself; another entity near is not modelled
    if let Some(ents) = cx.entities {
        let near = ents.iter().any(|e| {
            e.id() != cx.own_id
                && e.bounding_box().is_none_or(|b| {
                    b[3] > eye[0] - 7.0
                        && b[0] < eye[0] + 7.0
                        && b[4] > eye[1] - 7.0
                        && b[1] < eye[1] + 7.0
                        && b[5] > eye[2] - 7.0
                        && b[2] < eye[2] + 7.0
                })
        });
        if near {
            return AirAnswer::Unknown;
        }
    }
    if !hit.is_block() {
        return known(PASS, false);
    }
    let water = matches!(state(cx.world, pos_of(hit.pos)).block().id(), 8 | 9);
    let at = [
        hit.location[0],
        if water {
            hit.location[1] - 0.12
        } else {
            hit.location[1]
        },
        hit.location[2],
    ];
    // the player is pushable unless it climbs
    let me: &[Aabb] = if cx.climbing {
        &[]
    } else {
        std::slice::from_ref(&cx.bb)
    };
    if !ghast_physics::v1_12::boat_item_fits(cx.world, at, me) {
        return known(PASS, false);
    }
    AirAnswer::Known(AirUse {
        result: DONE,
        starts: false,
        blocks: Some(Vec::new()),
        hand: if q.creative {
            HandChange::Keep
        } else {
            HandChange::UseOne
        },
    })
}

/// `BucketItem`.
fn bucket(
    cx: &Ctx<'_>,
    q: &AirQuery<'_>,
    ray: &dyn Fn(bool) -> Option<ghast_physics::pick::BlockHit>,
) -> AirAnswer {
    let empty = q.stack.id() == BUCKET;
    let Some(hit) = ray(empty).filter(ghast_physics::pick::BlockHit::is_block) else {
        return known(PASS, false);
    };
    match may_not_modify(q) {
        None => return AirAnswer::Unknown,
        Some(true) => return known(PASS, false),
        Some(false) => {}
    }
    let w = cx.world;
    let pos = pos_of(hit.pos);
    let face = hit.face as u8;
    if empty {
        let at = state(w, pos);
        let filled = match at.block().material().kind {
            MaterialKind::Water if at.meta() == 0 => WATER_BUCKET,
            MaterialKind::Lava if at.meta() == 0 => LAVA_BUCKET,
            _ => return known(PASS, false),
        };
        return AirAnswer::Known(AirUse {
            result: DONE,
            starts: false,
            blocks: Some(vec![(pos, u32::from(BlockState::AIR.raw()))]),
            hand: if q.creative {
                HandChange::Keep
            } else {
                HandChange::ExchangeLegacy {
                    output: ghast_inventory::Stack::new(filled, 1, 0),
                }
            },
        });
    }
    let target = if replaceable(w, pos) && face == 1 {
        pos
    } else {
        offset(pos, face)
    };
    // `method_11365`: air, a material that is not solid, or a replaceable block
    let s = state(w, target);
    let m = s.block().material();
    if !(m.kind == MaterialKind::Air || !m.solid || replaceable(w, target)) {
        return known(PASS, false);
    }
    let water = q.stack.id() == WATER_BUCKET;
    let blocks = if (cx.nether && water) || !(0..256).contains(&target.y) {
        // boiled away; `setBlockState` refuses outside the build height
        Vec::new()
    } else {
        let placed = if water {
            ghast_data::v1_12::Block::FLOWING_WATER
        } else {
            ghast_data::v1_12::Block::FLOWING_LAVA
        }
        .default_state();
        if placed == s {
            Vec::new()
        } else {
            vec![(target, u32::from(placed.raw()))]
        }
    };
    AirAnswer::Known(AirUse {
        result: DONE,
        starts: false,
        blocks: Some(blocks),
        hand: if q.creative {
            HandChange::Keep
        } else {
            HandChange::Replace(ghast_inventory::Stack::new(BUCKET, 1, 0))
        },
    })
}