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
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
//! The player's own state from real packet bodies on every version, decoded by the version's
//! wire layer: status effects with durations and their events, absorption from our entity
//! data, the spawn point, our hurts and our death with its killer.

use super::tests::{Script, engine, join};
use super::*;
use crate::common::{ActiveEffect, EffectEvent};
use crate::version::ClientVersion;
use bytes::BufMut;
use ghast_protocol::RawPacket;
use ghast_protocol::codec::McWrite;

/// Every version the client engine runs.
#[cfg(not(feature = "v26_3"))]
const VERSIONS: [GameVersion; 5] = [
    GameVersion::V1_8_9,
    GameVersion::V1_12_2,
    GameVersion::V1_16_5,
    GameVersion::V26_1,
    GameVersion::V26_2,
];
/// With 26.3.
#[cfg(feature = "v26_3")]
const VERSIONS: [GameVersion; 6] = [
    GameVersion::V1_8_9,
    GameVersion::V1_12_2,
    GameVersion::V1_16_5,
    GameVersion::V26_1,
    GameVersion::V26_2,
    GameVersion::V26_3,
];

/// Our entity id in the test join.
const ME: i32 = 7;

/// The version's packet ids by name.
fn pid(v: GameVersion, name: &str) -> i32 {
    macro_rules! ids {
        ($m:ident) => {{
            use ghast_protocol::$m::play::clientbound::id;
            match name {
                "effect" => id::ENTITY_EFFECT,
                "remove_effect" => id::REMOVE_ENTITY_EFFECT,
                "status" => id::ENTITY_STATUS,
                "metadata" => id::ENTITY_METADATA,
                "spawn" => id::SPAWN_POSITION,
                "velocity" => id::ENTITY_VELOCITY,
                "explosion" => id::EXPLOSION,
                _ => unreachable!("{name}"),
            }
        }};
    }
    match v {
        GameVersion::V1_8_9 => ids!(v1_8),
        GameVersion::V1_12_2 => ids!(v1_12_2),
        GameVersion::V1_16_5 => ids!(v1_16_5),
        GameVersion::V26_1 => ids!(v26_1),
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => ids!(v26_3),
        _ => ids!(v26_2),
    }
}

/// Decodes `raw` with the version's wire layer and hands it to the engine.
fn feed(e: &mut Engine<Box<dyn Sim>>, raw: &RawPacket) {
    let v = e.core.opts.caps.version;
    let p = match v {
        GameVersion::V1_8_9 => crate::version::V1_8::decode_play(raw, &mut ()),
        GameVersion::V1_12_2 => {
            crate::version::V1_12_2::decode_play(raw, &mut crate::version::Wire1_12::default())
        }
        GameVersion::V1_16_5 => crate::version::V1_16_5::decode_play(raw, &mut ()),
        GameVersion::V26_1 => {
            crate::version::V26_1::decode_play(raw, &mut crate::version::Wire26_1::default())
        }
        #[cfg(feature = "v26_3")]
        GameVersion::V26_3 => {
            crate::version::V26_3::decode_play(raw, &mut crate::version::Wire26_3::default())
        }
        _ => crate::version::V26_2::decode_play(raw, &mut crate::version::Wire26_2::default()),
    }
    .unwrap();
    match p {
        Some(p) => e.handle(p),
        // Entity data is the sim's alone.
        None => assert_eq!(raw.id, pid(v, "metadata"), "a packet the core decodes"),
    }
    // Our entity data reaches the sim as a world packet.
    if raw.id == pid(v, "metadata") {
        e.sim.world_packet(raw).unwrap();
    }
}

fn modern(v: GameVersion) -> bool {
    v.caps().configuration_state
}

/// `entity_effect` for us: speed (1) II for `duration` ticks.
fn effect(v: GameVersion, amplifier: i8, duration: i32) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    b.put_varint(ME);
    if modern(v) {
        b.put_varint(0); // registry id 0 = speed
        b.put_varint(i32::from(amplifier));
        b.put_varint(duration);
        b.put_u8(0x06);
    } else {
        b.put_i8(1);
        b.put_i8(amplifier);
        b.put_varint(duration);
        b.put_u8(if v == GameVersion::V1_8_9 { 1 } else { 0x06 });
    }
    RawPacket::new(pid(v, "effect"), b.freeze())
}

fn remove_effect(v: GameVersion) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    b.put_varint(ME);
    if modern(v) {
        b.put_varint(0);
    } else {
        b.put_i8(1);
    }
    RawPacket::new(pid(v, "remove_effect"), b.freeze())
}

/// Our absorption amount in our entity data (index 17 / 11 / 14 / 17).
fn absorption(v: GameVersion, a: f32) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    b.put_varint(ME);
    match v {
        GameVersion::V1_8_9 => {
            // type 3 (float) << 5 | index 17
            b.put_u8(3 << 5 | 17);
            b.put_f32(a);
            b.put_u8(0x7f);
        }
        _ => {
            let (index, float) = match v {
                GameVersion::V1_12_2 => (11, 2),
                GameVersion::V1_16_5 => (14, 2),
                _ => (17, 3),
            };
            b.put_u8(index);
            b.put_varint(float);
            b.put_f32(a);
            b.put_u8(0xff);
        }
    }
    RawPacket::new(pid(v, "metadata"), b.freeze())
}

fn tick_with(e: &mut Engine<Box<dyn Sim>>, f: impl FnMut(&mut TickContext<'_>)) {
    let mut b = Script(f);
    e.tick(&mut b, Instant::now());
}

/// Effects keep their duration and the tick the behaviour first saw them; every packet is an
/// event (a re-application with the same values too), a respawn clears them.
#[test]
fn own_effects_with_durations_and_events() {
    for v in VERSIONS {
        let mut e = engine(v);
        join(&mut e);
        e.note_inbound(Instant::now());
        for _ in 0..2 {
            tick_with(&mut e, |_| {});
        }
        feed(&mut e, &effect(v, 1, 600));
        let mut seen: (u64, Vec<ActiveEffect>, Vec<EffectEvent>) = (0, Vec::new(), Vec::new());
        tick_with(&mut e, |ctx| {
            seen = (
                ctx.tick(),
                ctx.effects().to_vec(),
                ctx.events().effects().to_vec(),
            )
        });
        let (t, effects, events) = seen.clone();
        assert_eq!(effects.len(), 1, "{v:?}");
        let a = effects[0];
        assert_eq!((a.id, a.amplifier, a.duration), (1, 1, 600), "{v:?}");
        assert_eq!(a.received_tick, t, "{v:?}");
        assert_eq!(a.remaining(t + 100), Some(500));
        assert_eq!(a.remaining(t + 1000), Some(0));
        assert_eq!(events, [EffectEvent::Applied(a)], "{v:?}");
        // The same effect again: a new event and a new receive tick.
        tick_with(&mut e, |_| {});
        feed(&mut e, &effect(v, 1, 600));
        tick_with(&mut e, |ctx| {
            seen = (
                ctx.tick(),
                ctx.effects().to_vec(),
                ctx.events().effects().to_vec(),
            )
        });
        assert_eq!(seen.1.len(), 1, "{v:?}");
        assert_eq!(seen.1[0].received_tick, seen.0, "{v:?}");
        assert!(matches!(seen.2[..], [EffectEvent::Applied(_)]), "{v:?}");
        feed(&mut e, &remove_effect(v));
        tick_with(&mut e, |ctx| {
            seen = (0, ctx.effects().to_vec(), ctx.events().effects().to_vec())
        });
        assert!(seen.1.is_empty(), "{v:?}");
        assert_eq!(seen.2, [EffectEvent::Removed(1)], "{v:?}");
        // Infinite (1.19.4+ duration −1), then a respawn drops it (the behaviour waits for
        // the server position then: the events stay pending).
        feed(&mut e, &effect(v, 0, -1));
        e.handle(Inbound::Respawn {
            dimension: e.core.dimension.clone(),
            game_mode: GameMode::Survival,
            keep: 0,
        });
        assert!(e.core.active_effects.is_empty(), "{v:?}");
        assert!(
            matches!(e.core.pending.effects()[..], [EffectEvent::Applied(a), EffectEvent::Cleared] if a.remaining(1 << 40).is_none()),
            "{v:?} {:?}",
            e.core.pending.effects()
        );
    }
}

/// `Health::absorption` from our entity data, version-independent.
#[test]
fn absorption_from_own_entity_data() {
    for v in VERSIONS {
        let mut e = engine(v);
        join(&mut e);
        e.sim.test_set_own_id(ME);
        e.note_inbound(Instant::now());
        tick_with(&mut e, |_| {});
        feed(&mut e, &absorption(v, 4.0));
        let mut seen = (0.0, false);
        tick_with(&mut e, |ctx| {
            seen = (ctx.health().absorption, ctx.events().health_changed)
        });
        assert_eq!(seen, (4.0, true), "{v:?}");
        // update_health does not touch it.
        e.handle(Inbound::Health(Health {
            health: 10.0,
            ..Health::default()
        }));
        tick_with(&mut e, |ctx| seen = (ctx.health().absorption, false));
        assert_eq!(seen.0, 4.0, "{v:?}");
    }
}

/// The spawn point, our hurt statuses (26.x: the damage event) and our death with its killer.
#[test]
fn spawn_point_hurt_and_death() {
    for v in VERSIONS {
        let mut e = engine(v);
        join(&mut e);
        e.note_inbound(Instant::now());
        tick_with(&mut e, |_| {});
        // spawn_position: (-3, 70, 12).
        let mut b = bytes::BytesMut::new();
        let (x, y, z) = (-3i64, 70i64, 12i64);
        if v == GameVersion::V1_8_9 || v == GameVersion::V1_12_2 {
            b.put_i64(((x & 0x3ff_ffff) << 38) | ((y & 0xfff) << 26) | (z & 0x3ff_ffff));
        } else {
            if modern(v) {
                b.put_varint(19);
                b.put_slice(b"minecraft:overworld");
            }
            b.put_i64(((x & 0x3ff_ffff) << 38) | ((z & 0x3ff_ffff) << 12) | (y & 0xfff));
            if modern(v) {
                b.put_f32(90.0);
                b.put_f32(-10.0);
            }
        }
        feed(&mut e, &RawPacket::new(pid(v, "spawn"), b.freeze()));
        // Hurt: status 2 (legacy) / damage_event with attacker 42 (26.x).
        let hurt = if modern(v) {
            let mut b = bytes::BytesMut::new();
            b.put_varint(ME);
            b.put_varint(3);
            b.put_varint(43);
            b.put_varint(43);
            b.put_u8(0);
            let id = modern_cb_id!(v, DAMAGE_EVENT);
            RawPacket::new(id, b.freeze())
        } else {
            let mut b = bytes::BytesMut::new();
            b.put_i32(ME);
            b.put_i8(2);
            RawPacket::new(pid(v, "status"), b.freeze())
        };
        feed(&mut e, &hurt);
        // Death: 1.8 – 1.16.5 combat_event "entity dead" (player, killer 42, JSON message);
        // 26.x player_combat_kill (player, NBT text component).
        let mut b = bytes::BytesMut::new();
        let death_id = match v {
            GameVersion::V1_8_9 | GameVersion::V1_12_2 | GameVersion::V1_16_5 => {
                b.put_varint(2);
                b.put_varint(ME);
                b.put_i32(42);
                let msg = br#"{"text":"slain"}"#;
                b.put_varint(msg.len() as i32);
                b.put_slice(msg);
                match v {
                    GameVersion::V1_8_9 => {
                        ghast_protocol::v1_8::play::clientbound::id::COMBAT_EVENT
                    }
                    GameVersion::V1_12_2 => {
                        ghast_protocol::v1_12_2::play::clientbound::id::COMBAT_EVENT
                    }
                    _ => ghast_protocol::v1_16_5::play::clientbound::id::COMBAT_EVENT,
                }
            }
            _ => {
                b.put_varint(ME);
                // TAG_String "slain" (network NBT: no root name).
                b.put_u8(8);
                b.put_u16(5);
                b.put_slice(b"slain");
                modern_cb_id!(v, DEATH_COMBAT_EVENT)
            }
        };
        feed(&mut e, &RawPacket::new(death_id, b.freeze()));
        let mut seen = None;
        tick_with(&mut e, |ctx| {
            seen = Some((
                ctx.tick(),
                ctx.spawn_position().cloned(),
                ctx.events().hurt().to_vec(),
                ctx.last_hurt_tick(),
                ctx.events().deaths().to_vec(),
            ))
        });
        let (t, spawn, hurt, last_hurt, deaths) = seen.unwrap();
        let spawn = spawn.unwrap();
        assert_eq!(
            spawn.pos,
            ghast_protocol::BlockPos::new(-3, 70, 12),
            "{v:?}"
        );
        if modern(v) {
            assert_eq!((spawn.yaw, spawn.pitch), (90.0, -10.0));
            assert_eq!(spawn.dimension.as_deref(), Some("minecraft:overworld"));
            assert_eq!(hurt.len(), 1);
            assert_eq!(
                (hurt[0].source_type, hurt[0].attacker, hurt[0].direct),
                (Some(3), Some(42), Some(42))
            );
        } else {
            assert_eq!(hurt.len(), 1, "{v:?}");
            assert_eq!(hurt[0].status, Some(2), "{v:?}");
        }
        assert_eq!(last_hurt, Some(t), "{v:?}");
        assert_eq!(deaths.len(), 1, "{v:?}");
        assert_eq!(deaths[0].entity_id, ME);
        let killer = if modern(v) { None } else { Some(42) };
        assert_eq!(deaths[0].killer_id, killer, "{v:?}");
        assert_eq!(deaths[0].message.plain(), "slain", "{v:?}");
    }
}

/// A team with Alice on it in the version's team packet layout (red, no friendly fire).
/// The version's velocity packet for `id` (legacy: i16 / 8000; 26.x: the packed vector) and the
/// motion the client reads from it.
fn velocity(v: GameVersion, id: i32, m: [f64; 3]) -> (RawPacket, Vec3) {
    let mut b = bytes::BytesMut::new();
    b.put_varint(id);
    let read = if modern(v) {
        let p = ghast_protocol::types::LpVec3::from_vec3(m);
        p.write(&mut b);
        p.to_vec3()
    } else {
        for c in m {
            b.put_i16((c * 8000.0) as i16);
        }
        m
    };
    (
        RawPacket::new(pid(v, "velocity"), b.freeze()),
        Vec3::new(read[0], read[1], read[2]),
    )
}

/// An explosion at (0, 64, 0) pushing the player by `m` (26.x: no blocks, a plain particle, a
/// registry sound).
fn explosion(v: GameVersion, m: [f32; 3]) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    if modern(v) {
        for c in [0.0, 64.0, 0.0] {
            b.put_f64(c);
        }
        b.put_f32(3.0);
        b.put_i32(0);
        b.put_u8(1);
        for c in m {
            b.put_f64(f64::from(c));
        }
        b.put_varint(0); // particle type 0 (no data)
        b.put_varint(1); // sound: registry id 0
        b.put_varint(0); // no block particles
        #[cfg(feature = "v26_3")]
        if v == GameVersion::V26_3 {
            b.put_u8(1); // 26.3: play the sound
        }
    } else {
        for c in [0.0, 64.0, 0.0, 3.0] {
            b.put_f32(c);
        }
        b.put_i32(0);
        for c in m {
            b.put_f32(c);
        }
    }
    RawPacket::new(pid(v, "explosion"), b.freeze())
}

/// Our velocity packets and explosion pushes reach the behaviour as knockback events in arrival
/// order (another entity's velocity does not), once.
#[test]
fn knockback_events() {
    for v in VERSIONS {
        let mut e = engine(v);
        join(&mut e);
        e.note_inbound(Instant::now());
        tick_with(&mut e, |_| {});
        let (own, motion) = velocity(v, ME, [0.25, 0.375, -0.125]);
        let (other, _) = velocity(v, ME + 1, [0.5, 0.5, 0.5]);
        feed(&mut e, &own);
        feed(&mut e, &other);
        feed(&mut e, &explosion(v, [0.5, 0.25, -1.0]));
        let mut seen = Vec::new();
        tick_with(&mut e, |ctx| seen = ctx.events().knockback().to_vec());
        let kinds: Vec<(Vec3, bool)> = seen.iter().map(|k| (k.motion, k.explosion)).collect();
        assert_eq!(
            kinds,
            [(motion, false), (Vec3::new(0.5, 0.25, -1.0), true)],
            "{v:?}"
        );
        tick_with(&mut e, |ctx| seen = ctx.events().knockback().to_vec());
        assert!(seen.is_empty(), "{v:?}");
    }
}

fn team_packet(v: GameVersion) -> RawPacket {
    let mut b = bytes::BytesMut::new();
    b.put_string("red").unwrap();
    b.put_i8(0);
    let nbt = |b: &mut bytes::BytesMut, s: &str| {
        b.put_u8(8);
        b.put_u16(s.len() as u16);
        b.put_slice(s.as_bytes());
    };
    let id = match v {
        GameVersion::V1_8_9 | GameVersion::V1_12_2 => {
            for s in ["Red", "[R] ", ""] {
                b.put_string(s).unwrap();
            }
            b.put_u8(0);
            b.put_string("always").unwrap();
            if v == GameVersion::V1_12_2 {
                b.put_string("never").unwrap();
            }
            b.put_i8(12);
            if v == GameVersion::V1_8_9 {
                ghast_protocol::v1_8::play::clientbound::id::SCOREBOARD_TEAM
            } else {
                ghast_protocol::v1_12_2::play::clientbound::id::TEAMS
            }
        }
        GameVersion::V1_16_5 => {
            b.put_string(r#"{"text":"Red"}"#).unwrap();
            b.put_u8(0);
            b.put_string("always").unwrap();
            b.put_string("never").unwrap();
            b.put_varint(12);
            b.put_string(r#"{"text":"[R] "}"#).unwrap();
            b.put_string(r#"{"text":""}"#).unwrap();
            ghast_protocol::v1_16_5::play::clientbound::id::TEAMS
        }
        GameVersion::V26_1 => {
            nbt(&mut b, "Red");
            b.put_u8(0);
            b.put_varint(0);
            b.put_varint(1);
            b.put_varint(12);
            nbt(&mut b, "[R] ");
            nbt(&mut b, "");
            ghast_protocol::v26_1::play::clientbound::id::TEAMS
        }
        _ => {
            nbt(&mut b, "Red");
            nbt(&mut b, "[R] ");
            nbt(&mut b, "");
            b.put_varint(0);
            b.put_varint(1);
            b.put_u8(1);
            b.put_varint(12);
            b.put_u8(0);
            modern_cb_id!(v, TEAMS)
        }
    };
    b.put_varint(1);
    b.put_string("Alice").unwrap();
    RawPacket::new(id, b.freeze())
}

/// The scoreboard teams on every version, only with the interest; a join clears them.
#[test]
fn teams_on_every_version() {
    for v in VERSIONS {
        let mut e = engine(v);
        join(&mut e);
        e.note_inbound(Instant::now());
        // Without the interest the packet is ignored.
        feed(&mut e, &team_packet(v));
        assert!(e.core.teams.is_none());
        e.track_teams(true);
        feed(&mut e, &team_packet(v));
        let mut seen = None;
        tick_with(&mut e, |ctx| {
            seen = ctx.teams().and_then(|t| t.team_of("Alice")).cloned();
        });
        let t = seen.unwrap_or_else(|| panic!("{v:?}"));
        assert_eq!((&*t.name, t.prefix.as_str()), ("red", "[R] "), "{v:?}");
        assert_eq!((t.color, t.friendly_fire), (Some(12), false), "{v:?}");
        let rule = if v == GameVersion::V1_8_9 {
            "always"
        } else {
            "never"
        };
        assert_eq!(t.collision_rule, rule, "{v:?}");
        join(&mut e);
        assert!(e.core.teams.as_ref().unwrap().is_empty(), "{v:?}");
    }
}