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
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
//! The client-side physics of the non-living entities (`Interests::ENTITY_PHYSICS`) on the
//! legacy versions against the real client: `tests/golden/<version>/nonliving_tracking.jsonl.gz`
//! (oracle `NonLivingTrackDump` of that version). Projectiles, items, orbs, primed TNT and
//! falling blocks are spawned (each followed by the server's velocity packet), moved, looked,
//! teleported, given motion and entity data and destroyed by random packets over a floor with
//! walls, water and slippery patches; every tick the tracker's position, motion, rotation and
//! ground flag of every entity (after the tick's packets, before its entity tick) must equal
//! the real client's, bit for bit, and the set of entities too (the client discards TNT whose
//! fuse ran out, a falling block of air).

use super::tests::opts;
use super::*;
use ghast_protocol::RawPacket;
use serde_json::Value;
use std::io::BufRead;

fn hex64(v: &Value) -> f64 {
    f64::from_bits(u64::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}

fn hex32(v: &Value) -> f32 {
    f32::from_bits(u32::from_str_radix(v.as_str().unwrap(), 16).unwrap())
}

fn unhex(s: &str) -> bytes::Bytes {
    (0..s.len() / 2)
        .map(|i| u8::from_str_radix(&s[2 * i..2 * i + 2], 16).unwrap())
        .collect::<Vec<u8>>()
        .into()
}

/// A version's sim, world and packet ids.
trait Fixture {
    type S: Sim;
    const GAME: GameVersion;
    const GOLDEN: &'static str;
    fn sim() -> Self::S;
    fn chunk(x: i32, z: i32) -> RawPacket;
    /// Sets one block of a golden `fills` entry.
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value);
    fn packet_id(name: &str) -> i32;
    /// Kinds the golden must hold at least.
    const KINDS: usize;
    /// The spawn packet of a motionless snowball with entity id 50 at (4.5, 66, 4.5).
    fn snowball() -> RawPacket;
    /// The legacy join packet with our entity id `me` (the tracker learns it); `None`: the sim
    /// is told directly.
    fn login(me: i32) -> Option<RawPacket> {
        let _ = me;
        None
    }
}

/// A 1.8 / 1.12 object spawn of a motionless snowball (object type 61) with entity id 50 at
/// (4.5, 66, 4.5): `uuid` for 1.12 (absent on 1.8), positions as `f64` (1.12) or fixed-point
/// `i32` (1.8), object data 0 (no motion follows).
fn legacy_snowball(id: i32, uuid: bool, fixed: bool) -> RawPacket {
    let mut b = Body::default().varint(50);
    if uuid {
        b = b.bytes(&[9; 16]);
    }
    b = b.bytes(&[61]);
    for v in [4.5f64, 66.0, 4.5] {
        b = if fixed {
            b.bytes(&((v * 32.0) as i32).to_be_bytes())
        } else {
            b.bytes(&v.to_be_bytes())
        };
    }
    b = b.bytes(&[0, 0]).bytes(&0i32.to_be_bytes());
    if uuid {
        b = b.bytes(&[0; 6]);
    }
    b.raw(id)
}

struct V18;

impl Fixture for V18 {
    type S = crate::sim::Sim18;
    const GAME: GameVersion = GameVersion::V1_8_9;
    const GOLDEN: &'static str = "1.8.9";
    const KINDS: usize = 12;
    fn sim() -> Self::S {
        crate::sim::Sim18::new()
    }
    fn chunk(x: i32, z: i32) -> RawPacket {
        crate::sim::test_chunks::v1_8(x, z)
    }
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
        let id = fill[6].as_u64().unwrap() as u16;
        let meta = fill[7].as_u64().unwrap() as u16;
        s.test_set_block(
            x,
            y,
            z,
            ghast_data::v1_8::BlockState::from_raw_vanilla(id << 4 | (meta & 15)),
        );
    }
    fn packet_id(name: &str) -> i32 {
        use ghast_protocol::v1_8::play::clientbound::id;
        legacy_id(
            name,
            [
                id::SPAWN_ENTITY,
                id::SPAWN_ENTITY_EXPERIENCE_ORB,
                id::ENTITY_VELOCITY,
                id::REL_ENTITY_MOVE,
                id::ENTITY_LOOK,
                id::ENTITY_MOVE_LOOK,
                id::ENTITY,
                id::ENTITY_TELEPORT,
                id::ENTITY_METADATA,
                id::ENTITY_DESTROY,
            ],
        )
    }
    fn snowball() -> RawPacket {
        legacy_snowball(
            ghast_protocol::v1_8::play::clientbound::id::SPAWN_ENTITY,
            false,
            true,
        )
    }
    fn login(me: i32) -> Option<RawPacket> {
        // entity id, game mode, dimension, difficulty, max players, level type, reduced debug
        let mut b = me.to_be_bytes().to_vec();
        b.extend_from_slice(&[0, 0, 1, 20, 4]);
        b.extend_from_slice(b"flat");
        b.push(0);
        Some(RawPacket {
            id: ghast_protocol::v1_8::play::clientbound::id::LOGIN,
            body: bytes::Bytes::from(b),
        })
    }
}

struct V112;

impl Fixture for V112 {
    type S = crate::sim::Sim12;
    const GAME: GameVersion = GameVersion::V1_12_2;
    const GOLDEN: &'static str = "1.12.2";
    const KINDS: usize = 13;
    fn sim() -> Self::S {
        crate::sim::Sim12::new()
    }
    fn chunk(x: i32, z: i32) -> RawPacket {
        crate::sim::test_chunks::v1_12_2(x, z)
    }
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
        let id = fill[6].as_u64().unwrap() as u16;
        let meta = fill[7].as_u64().unwrap() as u16;
        s.test_set_block(
            x,
            y,
            z,
            ghast_data::v1_12::BlockState::from_raw_vanilla(id << 4 | (meta & 15)),
        );
    }
    fn packet_id(name: &str) -> i32 {
        use ghast_protocol::v1_12_2::play::clientbound::id;
        legacy_id(
            name,
            [
                id::SPAWN_ENTITY,
                id::SPAWN_ENTITY_EXPERIENCE_ORB,
                id::ENTITY_VELOCITY,
                id::REL_ENTITY_MOVE,
                id::ENTITY_LOOK,
                id::ENTITY_MOVE_LOOK,
                id::ENTITY,
                id::ENTITY_TELEPORT,
                id::ENTITY_METADATA,
                id::ENTITY_DESTROY,
            ],
        )
    }
    fn snowball() -> RawPacket {
        legacy_snowball(
            ghast_protocol::v1_12_2::play::clientbound::id::SPAWN_ENTITY,
            true,
            false,
        )
    }
    fn login(me: i32) -> Option<RawPacket> {
        // entity id, game mode, dimension (int), difficulty, max players, level type, reduced
        // debug
        let mut b = me.to_be_bytes().to_vec();
        b.push(0);
        b.extend_from_slice(&0i32.to_be_bytes());
        b.extend_from_slice(&[1, 20, 4]);
        b.extend_from_slice(b"flat");
        b.push(0);
        Some(RawPacket {
            id: ghast_protocol::v1_12_2::play::clientbound::id::LOGIN,
            body: bytes::Bytes::from(b),
        })
    }
}

/// A packet body under construction (big-endian wire types).
#[derive(Default)]
struct Body(Vec<u8>);

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

/// Without `Interests::ENTITY_PHYSICS` nothing is simulated: a snowball keeps the position of
/// its spawn packet; with it, the same packets make it fall.
fn only_with_the_interest<F: Fixture>() {
    let run = |physics: bool| {
        let mut e = Engine::new(opts(F::GAME), F::sim());
        e.sim.set_entities(crate::client::entity_config(
            crate::Interests::ENTITY_TRACKING,
            F::GAME.caps(),
        ));
        e.sim.set_entity_physics(physics);
        e.sim.world_packet(&F::chunk(0, 0)).unwrap();
        e.sim.world_packet(&F::snowball()).unwrap();
        let mut pose = e.core.pose;
        for _ in 0..5 {
            e.sim.tick_entities(&mut pose);
        }
        e.sim.entities().unwrap().get(50).unwrap().position()
    };
    assert_eq!(run(false), [4.5, 66.0, 4.5]);
    let p = run(true);
    assert!(p[1] < 66.0 && p[0] == 4.5 && p[2] == 4.5, "{p:?}");
}

struct V116;

impl Fixture for V116 {
    type S = crate::sim::Sim16;
    const GAME: GameVersion = GameVersion::V1_16_5;
    const GOLDEN: &'static str = "1.16.5";
    const KINDS: usize = 15;
    fn snowball() -> RawPacket {
        let ty = ghast_data::v1_16_5::entities()
            .iter()
            .find(|e| e.name == "snowball")
            .unwrap()
            .id;
        let mut b = Body::default()
            .varint(50)
            .bytes(&[9; 16])
            .varint(i32::from(ty));
        for v in [4.5f64, 66.0, 4.5] {
            b = b.bytes(&v.to_be_bytes());
        }
        b.bytes(&[0; 2 + 4 + 6])
            .raw(ghast_protocol::v1_16_5::play::clientbound::id::SPAWN_ENTITY)
    }
    fn sim() -> Self::S {
        crate::sim::Sim16::new()
    }
    fn chunk(x: i32, z: i32) -> RawPacket {
        crate::sim::test_chunks::v1_16_5(x, z)
    }
    fn set_block(s: &mut Self::S, x: i32, y: i32, z: i32, fill: &Value) {
        let st =
            ghast_data::v1_16_5::BlockState::from_id(fill[6].as_u64().unwrap() as u16).unwrap();
        s.test_set_block(x, y, z, st);
    }
    fn packet_id(name: &str) -> i32 {
        use ghast_protocol::v1_16_5::play::clientbound::id;
        legacy_id(
            name,
            [
                id::SPAWN_ENTITY,
                id::SPAWN_ENTITY_EXPERIENCE_ORB,
                id::ENTITY_VELOCITY,
                id::REL_ENTITY_MOVE,
                id::ENTITY_LOOK,
                id::ENTITY_MOVE_LOOK,
                id::ENTITY,
                id::ENTITY_TELEPORT,
                id::ENTITY_METADATA,
                id::ENTITY_DESTROY,
            ],
        )
    }
}

fn legacy_id(name: &str, ids: [i32; 10]) -> i32 {
    let i = match name {
        "spawn_entity" => 0,
        "spawn_entity_experience_orb" => 1,
        "entity_velocity" => 2,
        "rel_entity_move" => 3,
        "entity_look" => 4,
        "entity_move_look" => 5,
        "entity" => 6,
        "entity_teleport" => 7,
        "entity_metadata" => 8,
        "entity_destroy" => 9,
        n => panic!("unknown packet {n}"),
    };
    ids[i]
}

/// Compares the tracker with one tick line; returns the number of entities compared.
fn compare<S: Sim>(e: &Engine<S>, rec: &Value, at: &str) -> usize {
    let t = e.sim.entities().unwrap();
    let want = rec["entities"].as_array().unwrap();
    let mut got: Vec<i32> = t.iter().map(ghast_entity::Entity::id).collect();
    got.sort_unstable();
    let ids: Vec<i32> = want
        .iter()
        .map(|w| w["id"].as_i64().unwrap() as i32)
        .collect();
    assert_eq!(got, ids, "{at}: entity ids");
    for w in want {
        let id = w["id"].as_i64().unwrap() as i32;
        let x = t.get(id).unwrap();
        let ty = w["type"].as_str().unwrap();
        let pos: Vec<f64> = (0..3).map(|k| hex64(&w["pos"][k])).collect();
        let vel: Vec<f64> = (0..3).map(|k| hex64(&w["vel"][k])).collect();
        let bits = |a: &[f64]| a.iter().map(|v| v.to_bits()).collect::<Vec<_>>();
        assert_eq!(
            bits(&x.position()),
            bits(&pos),
            "{at}: {ty} {id} pos {:?} want {pos:?}",
            x.position()
        );
        assert_eq!(
            bits(&x.velocity()),
            bits(&vel),
            "{at}: {ty} {id} vel {:?} want {vel:?}",
            x.velocity()
        );
        let rot = [hex32(&w["rot"][0]), hex32(&w["rot"][1])];
        assert_eq!(
            [x.yaw().to_bits(), x.pitch().to_bits()],
            [rot[0].to_bits(), rot[1].to_bits()],
            "{at}: {ty} {id} rot {:?} want {rot:?}",
            [x.yaw(), x.pitch()]
        );
        assert_eq!(
            x.on_ground(),
            w["ground"].as_bool().unwrap(),
            "{at}: {ty} {id} ground"
        );
    }
    want.len()
}

/// Replays the version's golden (or `GHAST_NONLIVING_<version>` = a larger run of the same
/// dump, `oracle/run.sh nonliving-tracking --seed N --cases N --out FILE`).
fn replay<F: Fixture>() {
    let var = format!("GHAST_NONLIVING_{}", F::GOLDEN.replace('.', "_"));
    let path = std::env::var(&var).unwrap_or_else(|_| {
        format!(
            "{}/../../tests/golden/{}/nonliving_tracking.jsonl.gz",
            env!("CARGO_MANIFEST_DIR"),
            F::GOLDEN
        )
    });
    let f = std::fs::File::open(&path).unwrap_or_else(|e| panic!("{path}: {e}"));
    let mut lines = std::io::BufReader::new(flate2::read::GzDecoder::new(f))
        .lines()
        .map(|l| serde_json::from_str::<Value>(&l.unwrap()).unwrap())
        .peekable();
    let (mut cases, mut ticks, mut compared) = (0, 0, 0);
    let mut kinds = std::collections::BTreeSet::new();
    while let Some(sc) = lines.next() {
        assert_eq!(sc["type"], "scenario");
        cases += 1;
        let name = sc["name"].as_str().unwrap().to_owned();
        let me = sc["tracking"]["player_id"].as_i64().unwrap() as i32;
        let mut e = Engine::new(opts(F::GAME), F::sim());
        e.sim.set_entities(crate::client::entity_config(
            crate::Interests::ENTITY_TRACKING,
            F::GAME.caps(),
        ));
        e.sim.set_entity_physics(true);
        e.sim.test_set_own_id(me);
        if let Some(login) = F::login(me) {
            e.sim.world_packet(&login).unwrap();
        }
        for r in sc["loaded_chunks"].as_array().unwrap() {
            let r: Vec<i32> = (0..4).map(|k| r[k].as_i64().unwrap() as i32).collect();
            for x in r[0]..=r[2] {
                for z in r[1]..=r[3] {
                    e.sim.world_packet(&F::chunk(x, z)).unwrap();
                }
            }
        }
        for fill in sc["fills"].as_array().unwrap() {
            let v: Vec<i32> = (0..6).map(|k| fill[k].as_i64().unwrap() as i32).collect();
            for x in v[0]..=v[3] {
                for y in v[1]..=v[4] {
                    for z in v[2]..=v[5] {
                        F::set_block(&mut e.sim, x, y, z, fill);
                    }
                }
            }
        }
        let mut pose = e.core.pose;
        while let Some(rec) = lines.next_if(|l| l["type"] == "tick") {
            let k = rec["tick"].as_i64().unwrap();
            for p in rec["packets"].as_array().unwrap() {
                let raw = RawPacket {
                    id: F::packet_id(p[0].as_str().unwrap()),
                    body: unhex(p[1].as_str().unwrap()),
                };
                e.sim.world_packet(&raw).unwrap();
            }
            for w in rec["entities"].as_array().unwrap() {
                kinds.insert(w["type"].as_str().unwrap().to_owned());
            }
            compared += compare(&e, &rec, &format!("{name} tick {k}"));
            e.sim.tick_entities(&mut pose);
            ticks += 1;
        }
    }
    eprintln!(
        "{} non-living physics: {cases} cases, {ticks} ticks, {compared} entity states identical, kinds {kinds:?}",
        F::GOLDEN
    );
    assert!(
        cases >= 10 && ticks >= 400 && compared >= 2000,
        "{cases} {ticks} {compared}"
    );
    assert!(kinds.len() >= F::KINDS, "{kinds:?}");
}

#[test]
fn nonliving_physics_matches_the_oracle_1_16_5() {
    replay::<V116>();
}

#[test]
fn nonliving_physics_only_with_the_interest_1_16_5() {
    only_with_the_interest::<V116>();
}

#[test]
fn nonliving_physics_matches_the_oracle_1_12_2() {
    replay::<V112>();
}

#[test]
fn nonliving_physics_only_with_the_interest_1_12_2() {
    only_with_the_interest::<V112>();
}

#[test]
fn nonliving_physics_matches_the_oracle_1_8_9() {
    replay::<V18>();
}

#[test]
fn nonliving_physics_only_with_the_interest_1_8_9() {
    only_with_the_interest::<V18>();
}