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
//! The bot's own fishing bobber on every version (`crate::fishing`), from packet bodies in each
//! version's wire layout through the sim's packet path: another player's bobber is not ours,
//! ours is cast, bites (1.16.5 / 26.x the synced flag, 1.8.9 / 1.12.2 the splash sound at the
//! bobber), is hooked (1.12.2+) and goes away with its destroy packet; the bite's packets are
//! in the filter only while our bobber is out.

use super::tests::{engine, load};
use super::*;
use crate::fishing::{BobberState, FishingEvent};
use ghast_protocol::RawPacket;

const ME: i32 = 5;
const OTHER: i32 = 6;
const POS: [f64; 3] = [8.5, 70.0, 8.5];

/// A packet body writer.
#[derive(Default)]
struct W(Vec<u8>);

impl W {
    fn varint(mut self, v: i32) -> W {
        let mut v = v as u32;
        loop {
            let b = (v & 0x7f) as u8;
            v >>= 7;
            if v == 0 {
                self.0.push(b);
                return self;
            }
            self.0.push(b | 0x80);
        }
    }
    fn bytes(mut self, b: &[u8]) -> W {
        self.0.extend_from_slice(b);
        self
    }
    fn raw(self, id: i32) -> RawPacket {
        RawPacket {
            id,
            body: self.0.into(),
        }
    }
}

/// The version's packets for the test.
struct V {
    game: GameVersion,
    /// Our bobber's spawn (entity `id`, owner `owner`) at [`POS`].
    spawn: fn(i32, i32) -> RawPacket,
    /// The bite: the splash sound at a point, or the biting flag of entity `id`.
    bite: fn(i32, [f64; 3]) -> RawPacket,
    /// Entity `id`'s synced hooked-entity value (`None`: the version has none).
    hooked: Option<fn(i32, i32) -> RawPacket>,
    /// Destroys entity `id`.
    destroy: fn(i32) -> RawPacket,
    /// The packet id the filter takes in while our bobber is out.
    bite_packet: i32,
    /// 1.8 / 1.12: the join packet with our entity id (the tracker learns its own id: vanilla
    /// builds a bobber only for an owner it knows).
    login: Option<fn() -> RawPacket>,
}

/// A UUID per entity id (a duplicate UUID is not added).
fn uuid(e: i32) -> [u8; 16] {
    (u128::from(e as u32) | 7 << 64).to_be_bytes()
}

fn fixed(v: f64) -> [u8; 4] {
    ((v * 32.0).floor() as i32).to_be_bytes()
}

fn eighth(v: f64) -> [u8; 4] {
    ((v * 8.0) as i32).to_be_bytes()
}

fn f64s(w: W, p: [f64; 3]) -> W {
    w.bytes(&p[0].to_be_bytes())
        .bytes(&p[1].to_be_bytes())
        .bytes(&p[2].to_be_bytes())
}

fn v1_8() -> V {
    use ghast_protocol::v1_8::play::clientbound::id;
    V {
        game: GameVersion::V1_8_9,
        spawn: |e, owner| {
            // object 90 with the owner as data (above 0: the motion follows)
            W::default()
                .varint(e)
                .bytes(&[90])
                .bytes(&fixed(POS[0]))
                .bytes(&fixed(POS[1]))
                .bytes(&fixed(POS[2]))
                .bytes(&[0, 0])
                .bytes(&owner.to_be_bytes())
                .bytes(&[0; 6])
                .raw(id::SPAWN_ENTITY)
        },
        bite: |_, p| {
            W::default()
                .varint(13)
                .bytes(b"random.splash")
                .bytes(&eighth(p[0]))
                .bytes(&eighth(p[1]))
                .bytes(&eighth(p[2]))
                .bytes(&0.25f32.to_be_bytes())
                .bytes(&[63])
                .raw(id::NAMED_SOUND_EFFECT)
        },
        hooked: None,
        destroy: |e| W::default().varint(1).varint(e).raw(id::ENTITY_DESTROY),
        bite_packet: id::NAMED_SOUND_EFFECT,
        // entity id, game mode, dimension, difficulty, max players, level type, reduced debug
        login: Some(|| {
            W::default()
                .bytes(&ME.to_be_bytes())
                .bytes(&[0, 0, 1, 20, 4])
                .bytes(b"flat")
                .bytes(&[0])
                .raw(id::LOGIN)
        }),
    }
}

fn v1_12() -> V {
    use ghast_protocol::v1_12_2::play::clientbound::id;
    V {
        game: GameVersion::V1_12_2,
        spawn: |e, owner| {
            f64s(W::default().varint(e).bytes(&uuid(e)).bytes(&[90]), POS)
                .bytes(&[0, 0])
                .bytes(&owner.to_be_bytes())
                .bytes(&[0; 6])
                .raw(id::SPAWN_ENTITY)
        },
        bite: |_, p| {
            // entity.bobber.splash, category neutral (6)
            W::default()
                .varint(153)
                .varint(6)
                .bytes(&eighth(p[0]))
                .bytes(&eighth(p[1]))
                .bytes(&eighth(p[2]))
                .bytes(&0.25f32.to_be_bytes())
                .bytes(&1.0f32.to_be_bytes())
                .raw(id::SOUND_EFFECT)
        },
        hooked: Some(|e, h| {
            // index 6, VarInt (type 1)
            W::default()
                .varint(e)
                .bytes(&[6])
                .varint(1)
                .varint(h)
                .bytes(&[0xff])
                .raw(id::ENTITY_METADATA)
        }),
        destroy: |e| W::default().varint(1).varint(e).raw(id::ENTITY_DESTROY),
        bite_packet: id::SOUND_EFFECT,
        // entity id, game mode, dimension (int), difficulty, max players, level type, reduced
        // debug
        login: Some(|| {
            W::default()
                .bytes(&ME.to_be_bytes())
                .bytes(&[0])
                .bytes(&0i32.to_be_bytes())
                .bytes(&[1, 20, 4])
                .bytes(b"flat")
                .bytes(&[0])
                .raw(id::LOGIN)
        }),
    }
}

fn v1_16_5() -> V {
    use ghast_protocol::v1_16_5::play::clientbound::id;
    V {
        game: GameVersion::V1_16_5,
        spawn: |e, owner| {
            let ty = i32::from(
                ghast_data::v1_16_5::entity_by_name("fishing_bobber")
                    .unwrap()
                    .id,
            );
            f64s(W::default().varint(e).bytes(&uuid(e)).varint(ty), POS)
                .bytes(&[0, 0])
                .bytes(&owner.to_be_bytes())
                .bytes(&[0; 6])
                .raw(id::SPAWN_ENTITY)
        },
        bite: |e, _| {
            // CAUGHT_FISH: index 8, Boolean (type 7)
            W::default()
                .varint(e)
                .bytes(&[8])
                .varint(7)
                .bytes(&[1, 0xff])
                .raw(id::ENTITY_METADATA)
        },
        hooked: Some(|e, h| {
            W::default()
                .varint(e)
                .bytes(&[7])
                .varint(1)
                .varint(h)
                .bytes(&[0xff])
                .raw(id::ENTITY_METADATA)
        }),
        destroy: |e| W::default().varint(1).varint(e).raw(id::ENTITY_DESTROY),
        bite_packet: id::ENTITY_METADATA,
        login: None,
    }
}

fn v26_1() -> V {
    use ghast_protocol::v26_1::play::clientbound as cb;
    V {
        game: GameVersion::V26_1,
        spawn: |e, owner| {
            let ty = ghast_data::v26_1::entity_by_name("fishing_bobber")
                .unwrap()
                .id;
            let p = cb::SpawnEntity {
                entity_id: e,
                object_uuid: uuid::Uuid::from_u64_pair(1, e as u64),
                r#type: i32::from(ty),
                x: POS[0],
                y: POS[1],
                z: POS[2],
                velocity: ghast_protocol::types::LpVec3::ZERO,
                pitch: 0,
                yaw: 0,
                head_pitch: 0,
                object_data: owner,
            };
            let mut enc = ghast_protocol::FrameEncoder::new();
            enc.write_packet(&p).unwrap();
            let out = enc.out_mut().split().freeze();
            // the frame's length and the packet id
            let mut r = &out[..];
            for _ in 0..2 {
                while r[0] & 0x80 != 0 {
                    r = &r[1..];
                }
                r = &r[1..];
            }
            RawPacket {
                id: cb::id::SPAWN_ENTITY,
                body: bytes::Bytes::copy_from_slice(r),
            }
        },
        bite: |e, _| {
            // DATA_BITING: index 9, boolean (8)
            W::default()
                .varint(e)
                .bytes(&[9])
                .varint(8)
                .bytes(&[1, 0xff])
                .raw(cb::id::ENTITY_METADATA)
        },
        hooked: Some(|e, h| {
            // DATA_HOOKED_ENTITY: index 8, int (1)
            W::default()
                .varint(e)
                .bytes(&[8])
                .varint(1)
                .varint(h)
                .bytes(&[0xff])
                .raw(cb::id::ENTITY_METADATA)
        }),
        destroy: |e| W::default().varint(1).varint(e).raw(cb::id::ENTITY_DESTROY),
        bite_packet: cb::id::ENTITY_METADATA,
        login: None,
    }
}

fn events(e: &mut Engine<Box<dyn Sim>>) -> Vec<FishingEvent> {
    let mut v = Vec::new();
    if e.sim.fishing_news() {
        e.sim.drain_fishing(&mut v);
    }
    v
}

fn check(v: &V) {
    let mut e = engine(v.game);
    e.sim.set_entities(crate::client::entity_config(
        crate::Interests::ENTITY_TRACKING,
        v.game.caps(),
    ));
    e.sim.test_set_own_id(ME);
    if let Some(login) = v.login {
        e.sim.world_packet(&login()).unwrap();
    }
    load(&mut e, 0, 0);
    let mut pose = e.core.pose;
    let g = v.game;
    // the splash sound is read only while our bobber is out (entity data is read anyway on
    // the versions whose bite is a flag)
    let sound = matches!(g, GameVersion::V1_8_9 | GameVersion::V1_12_2);
    let packet = |e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket| {
        e.sim.world_packet(raw).unwrap();
    };

    // another player's bobber is not ours
    packet(&mut e, &(v.spawn)(40, OTHER));
    assert!(e.sim.fishing().is_none(), "{g:?}: another player's bobber");
    assert!(events(&mut e).is_empty());
    if sound {
        assert!(!e.sim.entity_packet_ids().contains(&v.bite_packet));
    }

    // ours
    packet(&mut e, &(v.spawn)(41, ME));
    let t = (
        e.sim
            .entities()
            .unwrap()
            .get(41)
            .map(|x| (x.entity_type(), x.data())),
        e.sim
            .entities()
            .unwrap()
            .iter()
            .map(|x| x.id())
            .collect::<Vec<_>>(),
    );
    let b = *e
        .sim
        .fishing()
        .unwrap_or_else(|| panic!("{g:?}: our bobber (tracked: {t:?})"));
    assert_eq!((b.id, b.state, b.biting), (41, BobberState::Flying, false));
    assert!(e.sim.take_filter_dirty(), "{g:?}: the filter grows");
    assert!(e.sim.entity_packet_ids().contains(&v.bite_packet));
    e.sim.tick_entities(&mut pose);
    assert_eq!(e.sim.fishing().unwrap().age, 1);

    // a splash far away (legacy) is not our bite; the bite is
    if sound {
        packet(&mut e, &(v.bite)(41, [POS[0] + 5.0, POS[1], POS[2]]));
        assert!(!e.sim.fishing().unwrap().biting, "{g:?}: a far splash");
    }
    packet(&mut e, &(v.bite)(41, POS));
    assert!(e.sim.fishing().unwrap().biting, "{g:?}: the bite");

    // hooked to the other bobber's entity (1.12.2+)
    if let Some(h) = v.hooked {
        packet(&mut e, &h(41, 41));
        let b = *e.sim.fishing().unwrap();
        assert_eq!((b.state, b.hooked), (BobberState::Hooked, Some(40)));
    }

    // gone with its destroy packet, at the next tick
    packet(&mut e, &(v.destroy)(41));
    e.sim.tick_entities(&mut pose);
    assert!(e.sim.fishing().is_none(), "{g:?}: gone");
    assert!(e.sim.take_filter_dirty(), "{g:?}: the filter shrinks");
    if sound {
        assert!(!e.sim.entity_packet_ids().contains(&v.bite_packet));
    }
    let mut want = vec![FishingEvent::Cast { id: 41 }, FishingEvent::Bite { id: 41 }];
    if v.hooked.is_some() {
        want.push(FishingEvent::Hooked { id: 41, entity: 40 });
    }
    want.push(FishingEvent::Gone { id: 41 });
    assert_eq!(events(&mut e), want, "{g:?}");
}

#[test]
fn own_bobber_1_8_9() {
    check(&v1_8());
}

#[test]
fn own_bobber_1_12_2() {
    check(&v1_12());
}

#[test]
fn own_bobber_1_16_5() {
    check(&v1_16_5());
}

#[test]
fn own_bobber_26_1() {
    check(&v26_1());
}

/// The events reach the behaviour as `TickEvents::fishing` and the bobber as
/// `TickContext::fishing` (1.16.5).
#[test]
fn behaviour_sees_the_bobber() {
    struct Watch(Vec<FishingEvent>, Option<i32>);
    impl Behavior for Watch {
        fn name(&self) -> &str {
            "fishing-watch"
        }
        fn tick(&mut self, ctx: &mut TickContext<'_>) {
            self.0.extend_from_slice(ctx.events().fishing());
            self.1 = ctx.fishing().map(|b| b.id);
        }
    }
    let v = v1_16_5();
    let mut e = engine(v.game);
    super::tests::join(&mut e);
    e.sim.set_entities(crate::client::entity_config(
        crate::Interests::ENTITY_TRACKING,
        v.game.caps(),
    ));
    e.sim.test_set_own_id(ME);
    let mut b = Watch(Vec::new(), None);
    e.tick(&mut b, Instant::now());
    e.sim.world_packet(&(v.spawn)(41, ME)).unwrap();
    e.sim.world_packet(&(v.bite)(41, POS)).unwrap();
    e.tick(&mut b, Instant::now());
    assert_eq!(
        b.0,
        [FishingEvent::Cast { id: 41 }, FishingEvent::Bite { id: 41 }]
    );
    assert_eq!(b.1, Some(41));
}