ghast-client 0.5.4

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
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
//! Engine replays of the legacy right-click-on-block vectors (`tests/golden/<v>/place.jsonl.gz`,
//! oracle `PlaceDump`): the real client's use key on a block (crosshair, `onRightClick`, the
//! item's placement on the client world, the swing, the fallback item use). Here the same world,
//! pose, held stack and game mode go into the engine, the right mouse button is pressed for one
//! tick, and the engine's packets (block placement, swing, encoded by the version's wire layer)
//! must equal the real client's, byte for byte. Every block ghast predicts must be the one the
//! client set; a block the client set that ghast does not predict is counted as unpredicted (the
//! server's block update decides it) — never a different state. The held stack's count after the
//! click must be the client's.

use super::super::tests::opts;
use super::super::*;
use crate::common::JoinGame;
use crate::version::ClientVersion;
use ghast_protocol::frame::{FrameDecoder, FrameEncoder};
use serde_json::Value;
use std::io::BufRead;

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

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

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

fn hex(b: &[u8]) -> String {
    b.iter().map(|x| format!("{x:02x}")).collect()
}

fn stack_1_8(h: &Value) -> Option<ghast_inventory::Stack> {
    use ghast_protocol::codec::decode_exact;
    let b = bytes::Bytes::from(unhex(h.as_str().unwrap()));
    ghast_inventory::from_legacy_slot(
        decode_exact::<ghast_protocol::types::slot::legacy::Slot>(&b).unwrap(),
    )
}

fn mode_of(s: &str) -> GameMode {
    match s {
        "survival" => GameMode::Survival,
        "creative" => GameMode::Creative,
        "adventure" => GameMode::Adventure,
        _ => GameMode::Spectator,
    }
}

/// What a replay counted.
#[derive(Default, Debug)]
pub(super) struct Summary {
    pub cases: usize,
    pub placed: usize,
    pub predicted: usize,
    pub unpredicted: usize,
    /// 1.12: clicks whose packets differ after a boat's or a bucket's use in the air.
    pub air_use: usize,
    /// Clicks the rules leave undecided whose packets differ.
    pub undecided: usize,
    /// Cases whose crosshair target differs from the client's.
    pub crosshair: usize,
    pub packets: usize,
    /// (air-use vectors) cases whose inventory the client changed and ghast did not predict
    /// exactly (a slot left to the server's update).
    pub inv_unpredicted: usize,
    /// Cases whose item use in the air (ghast wrote its `use_item` packet) changed a block or
    /// a slot on the client that ghast did not predict.
    pub air_unpredicted: usize,
    pub diffs: Vec<String>,
}

/// One replay per version: the sim, its data and protocol modules, the test chunks, the wire
/// layer and the packet names the oracle writes.
macro_rules! replay {
    ($name:ident, $sim:ty, $data:ident, $proto:ident, $version:expr, $chunks:ident, $wire:ty, $offhand:expr, $named:expr, $sneak:expr, $stone:expr, $state:expr, $raw:expr, $stack:expr, $air:expr, $miss_known:expr, $hex_slot:expr) => {
pub(super) fn $name(path: &std::path::Path) -> Summary {
    use ghast_protocol::$proto::play::serverbound::id;
    let f = std::fs::File::open(path).unwrap_or_else(|e| panic!("{}: {e}", path.display()));
    let mut sum = Summary::default();
    let only: Option<u64> = std::env::var("GHAST_PLACE_CASE")
        .ok()
        .map(|c| c.parse().unwrap());
    for line in std::io::BufReader::new(flate2::read::GzDecoder::new(f)).lines() {
        let c: Value = serde_json::from_str(&line.unwrap()).unwrap();
        if c.get("type").is_some() {
            continue;
        }
        let k = c["case"].as_u64().unwrap();
        if only.is_some_and(|o| o != k) {
            continue;
        }
        sum.cases += 1;
        let mode = mode_of(c["mode"].as_str().unwrap());
        let mut e = Engine::new(opts($version), <$sim>::new());
        e.handle(Inbound::JoinGame(JoinGame {
            entity_id: 1,
            game_mode: mode,
            dimension: "0".into(),
            hardcore: false,
            dimension_nbt: None,
            respawn_screen: true,
        }));
        // the abilities the server sends with the game mode (`GameMode.setAbilities`:
        // invulnerable, flying, may fly, creative)
        e.handle(Inbound::Abilities(crate::common::Abilities {
            flags: match mode {
                GameMode::Creative => 0b1101,
                GameMode::Spectator => 0b0111,
                _ => 0,
            },
            flying_speed: 0.05,
            walking_speed: 0.1,
        }));
        if let Some(food) = c.get("food") {
            e.handle(Inbound::Health(crate::common::Health {
                health: 20.0,
                food: food.as_i64().unwrap() as i32,
                saturation: 5.0,
                ..crate::common::Health::default()
            }));
        }
        for x in -1..=0 {
            for z in -1..=0 {
                e.sim
                    .world_packet(&crate::sim::test_chunks::$chunks(x, z))
                    .unwrap();
            }
        }
        // the oracle world: a stone floor at y 63 for x -4..=4, z -3..=7 only
        for x in -16..16 {
            for z in -16..16 {
                let floor = (-4..=4).contains(&x) && (-3..=7).contains(&z);
                e.sim.test_set_block(
                    x,
                    63,
                    z,
                    ($state)(if floor { $stone } else { 0 }),
                );
            }
        }
        // the area: the case's blocks, air elsewhere
        let mut before = std::collections::HashMap::new();
        for b in c["blocks"].as_array().unwrap() {
            let v: Vec<i32> = (0..4).map(|i| b[i].as_i64().unwrap() as i32).collect();
            before.insert((v[0], v[1], v[2]), v[3] as u16);
        }
        // the region the case's blocks cover (air-use vectors: what an item's ray reaches)
        let area: [i32; 6] = c.get("area").map_or([-4, 63, -2, 4, 69, 6], |a| {
            std::array::from_fn(|i| a[i].as_i64().unwrap() as i32)
        });
        for x in area[0]..=area[3] {
            for y in area[1]..=area[4] {
                for z in area[2]..=area[5] {
                    let raw = before.get(&(x, y, z)).copied().unwrap_or(0);
                    e.sim
                        .test_set_block(x, y, z, ($state)(raw));
                }
            }
        }
        // the client world's facts of an air-use case (a dimension whose water vaporizes)
        e.sim.test_air_case(&c);
        let pos = &c["pos"];
        let (yaw, pitch) = (f32v(&c["yaw"]), f32v(&c["pitch"]));
        e.handle(Inbound::Teleport(crate::common::Teleport {
            x: f64v(&pos[0]),
            y: f64v(&pos[1]),
            z: f64v(&pos[2]),
            yaw,
            pitch,
            teleport_id: None,
            ..Default::default()
        }));
        let sel = c["selected"].as_u64().unwrap() as u8;
        e.core.test_set_slot(sel);
        let held = ($stack)(&c["held"]);
        e.inventory_mut()
            .on_set_slot(0, 36 + i16::from(sel), held.clone());
        if $offhand {
            e.inventory_mut().on_set_slot(0, 45, ($stack)(&c["offhand"]));
        }
        // the other inventory slots (`PlayerInventory` indices)
        for st in c.get("inv").and_then(Value::as_array).into_iter().flatten() {
            let k = st[0].as_u64().unwrap() as i16;
            let slot = match k {
                0..=8 => 36 + k,
                9..=35 => k,
                36..=39 => 44 - k,
                _ => 45,
            };
            e.inventory_mut().on_set_slot(0, slot, ($stack)(&st[1]));
        }
        e.inventory_mut().set_creative(mode == GameMode::Creative);
        let sneak = c["sneaking"].as_bool().unwrap();
        // the sneaking pose before anything reads the player (the rules' box, the eyes)
        e.core.pose.sneaking = sneak;
        ($sneak)(&mut e, sneak, mode);
        // the client's target (the crosshair is oracle-proven separately, `picks.jsonl.gz`: a
        // different target is counted, not compared further)
        let t = &c["target"];
        let want_target = (t["type"] == "BLOCK").then(|| {
            let p = &t["pos"];
            (
                ghast_protocol::BlockPos::new(
                    p[0].as_i64().unwrap() as i32,
                    p[1].as_i64().unwrap() as i32,
                    p[2].as_i64().unwrap() as i32,
                ),
                crate::common::Face::from_id(t["face"].as_i64().unwrap() as i8).unwrap(),
            )
        });
        // what the rules decide before the packet (an undecided click's packets are the engine's
        // guess: counted, not compared)
        // (1.12: the off hand's turn too, after a main hand whose click did not succeed)
        let off = if $offhand {
            ($stack)(&c["offhand"])
        } else {
            None
        };
        let decided = want_target.is_none_or(|(p, f)| {
            let hit: [f64; 3] = std::array::from_fn(|i| f64v(&t["hit"][i]));
            let base = [p.x, p.y, p.z];
            let rules = |h: Option<&ghast_inventory::Stack>| {
                e.sim.place_rules(&crate::sim::predict::PlaceQuery {
                    pos: p,
                    face: f,
                    cursor: std::array::from_fn(|i| (hit[i] - f64::from(base[i])) as f32),
                    held: h,
                    sneaking: sneak,
                    any_item: held.is_some() || off.is_some(),
                    game_mode: mode,
                    yaw,
                    food: use_food_level(&e.core),
                })
            };
            let r = rules(held.as_ref());
            let known = |r: crate::sim::predict::PlaceRules| {
                r.block_packet.is_some() && r.used.is_some()
            };
            known(r) && (!$offhand || r.used == Some(true) || known(rules(off.as_ref())))
        });
        let t0 = Instant::now();
        // the oracle clicks without a tick: the pose as set (sneaking: the crouched eyes)
        e.core.ready = true;

        let mut target = None;
        // the right button for one tick
        e.core.forced_look = Some((yaw, pitch));
        e.note_inbound(t0);
        e.tick(
            &mut super::super::tests::Script(|ctx: &mut TickContext<'_>| {
                ctx.set_controls(Controls {
                    sneak,
                    ..Controls::default()
                });
                ctx.set_buttons(Buttons {
                    left: false,
                    right: true,
                });
                target = match ctx.press_preview(hands::Button::Right) {
                    hands::PressOutcome::Block(t) => Some((
                        t.pos,
                        t.face,
                        [
                            (t.hit.x - f64::from(t.pos.x)) as f32,
                            (t.hit.y - f64::from(t.pos.y)) as f32,
                            (t.hit.z - f64::from(t.pos.z)) as f32,
                        ],
                    )),
                    _ => None,
                };
            }),
            t0,
        );
        let out = std::mem::take(e.outbound());
        let used_item = out.iter().any(|o| matches!(o, Outbound::UseItem { .. }));
        let mut left = false;
        // the same block and face, and the same hit point
        let want_hit = want_target.map(|(p, f)| {
            let hit: [f64; 3] = std::array::from_fn(|i| f64v(&t["hit"][i]));
            let base = [p.x, p.y, p.z];
            (
                p,
                f,
                std::array::from_fn::<f32, 3, _>(|i| (hit[i] - f64::from(base[i])) as f32),
            )
        });
        if target != want_hit {
            sum.crosshair += 1;
            if std::env::var_os("GHAST_PLACE_CROSSHAIR").is_some() {
                let clicked = before
                    .get(&want_target.map_or((0, 0, 0), |(p, _)| (p.x, p.y, p.z)))
                    .copied()
                    .unwrap_or(0);
                eprintln!(
                    "crosshair case {k} sneak {sneak} mode {:?} clicked {} ghast {target:?} client {want_hit:?}",
                    mode,
                    clicked >> 4
                );
            }
            continue;
        }
        let mut enc = FrameEncoder::new();
        for o in &out {
            <$wire as ClientVersion>::write_play(&mut enc, o, &mut Default::default()).unwrap();
        }
        let bytes = enc.take();
        let mut dec = FrameDecoder::new();
        dec.push(&bytes);
        let mut got = Vec::new();
        while let Some(p) = dec.next_packet().unwrap() {
            if p.id == id::BLOCK_PLACE {
                got.push(format!("p{}", hex(&p.body)));
            } else if let Some(n) = ($named)(p.id) {
                got.push(n.replace("{}", &hex(&p.body)));
            }
        }
        let want: Vec<String> = c["packets"]
            .as_array()
            .unwrap()
            .iter()
            .map(|p| p.as_str().unwrap().to_owned())
            .collect();
        sum.packets += want.len();
        let at = format!(
            "case {k} ({} held {:?})",
            c["mode"],
            held.as_ref().map(|s| (s.id(), s.damage()))
        );
        // 1.12: the main hand's use in the air of a boat or a bucket (a ray with fluids, the
        // boat's room, the bucket's fill or pour) is not modelled
        let air_use = $offhand
            && held
                .as_ref()
                .is_some_and(|h| u16::try_from(h.id()).is_ok_and($air));
        // no block clicked (the crosshair missed): the item's use in the air alone, which the
        // click rules do not cover (counted with the air uses)
        // (also the off hand's use in the air, the click's last step)
        let off_air = off
            .as_ref()
            .is_some_and(|h| u16::try_from(h.id()).is_ok_and($air));
        let air_use = air_use || off_air || (!$miss_known && want_target.is_none());
        if got != want && air_use {
            sum.air_use += 1;
            if std::env::var_os("GHAST_PLACE_AIR").is_some() {
                eprintln!(
                    "air case {k} mode {:?} sneak {sneak} target {} held {:?} off {:?} ghast {got:?} client {want:?}",
                    mode,
                    t["type"],
                    held.as_ref().map(|s| (s.id(), s.count())),
                    off.as_ref().map(|s| (s.id(), s.count())),
                );
            }
        } else if got != want && !decided {
            sum.undecided += 1;
            if std::env::var_os("GHAST_PLACE_UNDECIDED").is_some() {
                let clicked = want_target
                    .and_then(|(p, _)| before.get(&(p.x, p.y, p.z)).copied())
                    .unwrap_or(0);
                eprintln!(
                    "undecided case {k} held {:?} clicked {} ghast {got:?} client {want:?}",
                    held.as_ref().map(|s| s.id()),
                    clicked >> 4
                );
            }
        } else if got != want {
            sum.diffs
                .push(format!("{at}: packets ghast {got:?}, client {want:?}"));
        }
        // the blocks
        let mut after = before.clone();
        for ch in c["changed"].as_array().unwrap() {
            let v: Vec<i32> = (0..5).map(|i| ch[i].as_i64().unwrap() as i32).collect();
            after.insert((v[0], v[1], v[2]), v[4] as u16);
        }
        let world = e.sim.test_world();
        let changed = !c["changed"].as_array().unwrap().is_empty();
        sum.placed += usize::from(changed);
        let mut ghast_changed = false;
        let mut wrong = false;
        for x in area[0]..=area[3] {
            for y in area[1]..=area[4] {
                for z in area[2]..=area[5] {
                    let g = world.block_state(x, y, z).map_or(0, $raw);
                    let b = before.get(&(x, y, z)).copied().unwrap_or(0);
                    let a = after.get(&(x, y, z)).copied().unwrap_or(0);
                    if g != b {
                        ghast_changed = true;
                        if g != a {
                            wrong = true;
                            sum.diffs.push(format!(
                                "{at}: block ({x}, {y}, {z}): ghast {g}, client {a} (before {b})"
                            ));
                        }
                    }
                }
            }
        }
        if changed && !ghast_changed {
            sum.unpredicted += 1;
            left = true;
            if std::env::var_os("GHAST_PLACE_UNPREDICTED").is_some() {
                eprintln!(
                    "blocks left to the server: {at} target {} changed {}",
                    t["type"], c["changed"]
                );
            }
        } else if changed && !wrong {
            sum.predicted += 1;
        }
        // (air-use vectors) the hand the client uses after the key, and every inventory slot
        if (decided || got == want) && !air_use {
            if let Some(u) = c.get("using") {
                let want_use = u.as_str().map(|h| h == "off");
                let got_use = e.core.hands.use_item().map(|(off, _)| off);
                if got_use != want_use {
                    sum.diffs.push(format!(
                        "{at}: using ghast {got_use:?}, client {want_use:?} (off hand?)"
                    ));
                }
            }
            if let Some(inv) = c.get("inv_after").and_then(Value::as_array) {
                let mut want_inv = std::collections::BTreeMap::new();
                for st in inv {
                    want_inv.insert(
                        st[0].as_u64().unwrap() as usize,
                        st[1].as_str().unwrap().to_owned(),
                    );
                }
                let mut got_inv = std::collections::BTreeMap::new();
                for k in 0..41 {
                    if let Some(s) = e.core.inv.player(k) {
                        got_inv.insert(k, ($hex_slot)(s));
                    }
                }
                // a slot ghast left as it was is the server's to update (a placement not
                // predicted); one it changed must be the client's
                let mut before_inv = std::collections::BTreeMap::new();
                for st in c["inv"].as_array().unwrap() {
                    before_inv.insert(
                        st[0].as_u64().unwrap() as usize,
                        st[1].as_str().unwrap().to_owned(),
                    );
                }
                for (k, h) in [(sel as usize, &c["held"]), (40, &c["offhand"])] {
                    let h = h.as_str().unwrap();
                    // (an empty stack: 1.9+ "00", 1.8 "ffff")
                    if h != "00" && h != "ffff" {
                        before_inv.insert(k, h.to_owned());
                    }
                }
                let wrong = (0..41).any(|k| {
                    let g = got_inv.get(&k);
                    g != want_inv.get(&k) && g != before_inv.get(&k)
                });
                if wrong {
                    sum.diffs.push(format!(
                        "{at}: inventory ghast {got_inv:?}, client {want_inv:?}"
                    ));
                } else if want_inv != before_inv && got_inv != want_inv {
                    sum.inv_unpredicted += 1;
                    left = true;
                    if std::env::var_os("GHAST_PLACE_INV").is_some() {
                        eprintln!("inventory left to the server: {at}: ghast {got_inv:?}, client {want_inv:?}");
                    }
                }
            }
        }
        // (an undecided block click's packets are a guess: its use in the air is not counted)
        if left && used_item && (decided || got == want) {
            sum.air_unpredicted += 1;
        }
        // the held stack's count
        let held_after = ($stack)(&c["slot_after"]);
        let now = e.core.inv.held().cloned();
        let count = |s: &Option<ghast_inventory::Stack>| s.as_ref().map(|s| (s.id(), s.count()));
        let count_before = count(&held);
        // (after packets the engine only guessed, its count is a guess too)
        if (decided || got == want)
            && count(&now) != count(&held_after)
            && count(&now) != count_before
        {
            sum.diffs.push(format!(
                "{at}: held ghast {:?}, client {:?}",
                count(&now),
                count(&held_after)
            ));
        }
    }
    sum
}
    };
}

replay!(
    replay_1_8,
    crate::sim::Sim18,
    v1_8,
    v1_8,
    GameVersion::V1_8_9,
    v1_8,
    crate::version::V1_8,
    false,
    |i| {
        use ghast_protocol::v1_8::play::serverbound::id;
        match i {
            id::ARM_ANIMATION => Some("o:HandSwingC2SPacket"),
            id::HELD_ITEM_SLOT => Some("o:UpdateSelectedSlotC2SPacket"),
            _ => None,
        }
    },
    |_: &mut Engine<crate::sim::Sim18>, _: bool, _: GameMode| {},
    1 << 4,
    ghast_data::v1_8::BlockState::from_raw_vanilla,
    ghast_data::v1_8::BlockState::raw,
    stack_1_8,
    |_: u16| false,
    true,
    hex_1_12
);

replay!(
    replay_1_12,
    crate::sim::Sim12,
    v1_12,
    v1_12_2,
    GameVersion::V1_12_2,
    v1_12_2,
    crate::version::V1_12_2,
    true,
    |i| {
        use ghast_protocol::v1_12_2::play::serverbound::id;
        match i {
            id::ARM_ANIMATION => Some("o:HandSwingC2SPacket:{}"),
            id::USE_ITEM => Some("o:SwingHandC2SPacket:{}"),
            id::HELD_ITEM_SLOT => Some("o:UpdateSelectedSlotC2SPacket:{}"),
            _ => None,
        }
    },
    // the eyes read the physics player's sneak key
    |e: &mut Engine<crate::sim::Sim12>, sneak: bool, _: GameMode| {
        let mut p = *e.sim.test_player();
        p.input.sneak = sneak;
        e.sim.test_set_player(p);
    },
    1 << 4,
    ghast_data::v1_12::BlockState::from_raw_vanilla,
    ghast_data::v1_12::BlockState::raw,
    stack_1_8,
    ghast_data::v1_12::place::air_use_unknown,
    true,
    hex_1_12
);

/// A stack as the legacy wire writes it (hex).
fn hex_1_12(s: &ghast_inventory::Stack) -> String {
    let mut b = bytes::BytesMut::new();
    ghast_protocol::codec::Encode::encode(&ghast_inventory::to_legacy_slot(Some(s)), &mut b)
        .unwrap();
    hex(&b)
}

/// A stack as the 1.16.5 wire writes it (hex).
fn hex_1_16(s: &ghast_inventory::Stack) -> String {
    let mut b = bytes::BytesMut::new();
    ghast_protocol::codec::Encode::encode(&ghast_inventory::to_modern_slot(Some(s)), &mut b)
        .unwrap();
    hex(&b)
}

/// The 1.16.5 wire slot (present, item id, count, NBT).
fn stack_1_16(h: &Value) -> Option<ghast_inventory::Stack> {
    use ghast_protocol::codec::decode_exact;
    let b = bytes::Bytes::from(unhex(h.as_str().unwrap()));
    ghast_inventory::from_modern_slot(
        decode_exact::<ghast_protocol::types::slot::modern::Slot>(&b).unwrap(),
    )
}

replay!(
    replay_1_16,
    crate::sim::Sim16,
    v1_16_5,
    v1_16_5,
    GameVersion::V1_16_5,
    v1_16_5,
    crate::version::V1_16_5,
    true,
    |i| {
        use ghast_protocol::v1_16_5::play::serverbound::id;
        match i {
            id::ARM_ANIMATION => Some("o:HandSwingC2SPacket:{}"),
            id::USE_ITEM => Some("o:PlayerInteractItemC2SPacket:{}"),
            id::HELD_ITEM_SLOT => Some("o:UpdateSelectedSlotC2SPacket:{}"),
            _ => None,
        }
    },
    // the eyes and the box read the physics player's sneak key and pose
    |e: &mut Engine<crate::sim::Sim16>, sneak: bool, mode: GameMode| {
        let mut p = *e.sim.test_player();
        p.input.sneaking = sneak;
        if sneak && mode != GameMode::Spectator {
            p.pose = ghast_physics::v1_16_5::Pose::Crouching;
            p.bb.max_y = p.bb.min_y + 1.5;
        }
        e.sim.test_set_player(p);
    },
    1,
    |id: u16| ghast_data::v1_16_5::BlockState::from_id(id).unwrap(),
    ghast_data::v1_16_5::BlockState::id,
    stack_1_16,
    ghast_data::v1_16_5::place::air_use_unknown,
    true,
    hex_1_16
);

fn golden(v: &str) -> std::path::PathBuf {
    std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
        .join("../../tests/golden")
        .join(v)
        .join("place.jsonl.gz")
}

fn report(v: &str, s: &Summary) {
    eprintln!(
        "{v} place: {} cases ({} with another crosshair target), {} placements by the client: {} predicted, {} left to the server; {} packets ({} undecided clicks differ, {} after a use in the air: a miss, a boat, a bucket...), {} differences",
        s.cases,
        s.crosshair,
        s.placed,
        s.predicted,
        s.unpredicted,
        s.packets,
        s.undecided,
        s.air_use,
        s.diffs.len()
    );
    let n = std::env::var("GHAST_PLACE_SHOW")
        .ok()
        .and_then(|v| v.parse().ok())
        .unwrap_or(25);
    for d in s.diffs.iter().take(n) {
        eprintln!("  {d}");
    }
}

#[test]
fn place_golden_1_8_9() {
    let path = std::env::var_os("GHAST_PLACE_VECTORS_1_8")
        .map_or_else(|| golden("1.8.9"), std::path::PathBuf::from);
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_8(&path);
    report("1.8.9", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

#[test]
fn place_golden_1_12_2() {
    let path = std::env::var_os("GHAST_PLACE_VECTORS_1_12")
        .map_or_else(|| golden("1.12.2"), std::path::PathBuf::from);
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_12(&path);
    report("1.12.2", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

#[test]
fn place_golden_1_16_5() {
    let path = std::env::var_os("GHAST_PLACE_VECTORS_1_16")
        .map_or_else(|| golden("1.16.5"), std::path::PathBuf::from);
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_16(&path);
    report("1.16.5", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

/// 1.16.5 item uses in the air (`tests/golden/1.16.5/air_use.jsonl.gz`, oracle `AirUseDump`):
/// the use key with buckets, boats, bottles, lily pads, spawn eggs, ender eyes, bows,
/// crossbows, food and the other items through the same replay, plus the hand the client
/// uses after the key and every inventory slot.
#[test]
fn air_use_golden_1_16_5() {
    let path = std::env::var_os("GHAST_AIR_VECTORS_1_16").map_or_else(
        || {
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../tests/golden/1.16.5/air_use.jsonl.gz")
        },
        std::path::PathBuf::from,
    );
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_16(&path);
    report("1.16.5 air use", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

/// 1.12.2 item uses in the air (`tests/golden/1.12.2/air_use.jsonl.gz`, oracle `AirUseDump`):
/// the use key with buckets, boats, bottles, lily pads, spawn eggs, ender eyes, bows, food and
/// the other items through the same replay, plus the hand the client uses after the key and
/// every inventory slot.
#[test]
fn air_use_golden_1_12_2() {
    let path = std::env::var_os("GHAST_AIR_VECTORS_1_12").map_or_else(
        || {
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../tests/golden/1.12.2/air_use.jsonl.gz")
        },
        std::path::PathBuf::from,
    );
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_12(&path);
    report("1.12.2 air use", &s);
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
}

/// 1.8.9 item uses in the air (`tests/golden/1.8.9/air_use.jsonl.gz`, oracle `AirUseDump`): the
/// use key with buckets, boats, glass bottles, lily pads, bows, potions, thrown items, food, maps
/// and the other items through the same replay, plus the hand the client uses after the key and
/// every inventory slot. Every block and slot the client changed after a use in the air must be
/// predicted (block clicks the place rules leave to the server are counted, not failed).
#[test]
fn air_use_golden_1_8_9() {
    let path = std::env::var_os("GHAST_AIR_VECTORS_1_8").map_or_else(
        || {
            std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
                .join("../../tests/golden/1.8.9/air_use.jsonl.gz")
        },
        std::path::PathBuf::from,
    );
    if !path.exists() {
        eprintln!("{} missing", path.display());
        return;
    }
    let s = replay_1_8(&path);
    report("1.8.9 air use", &s);
    eprintln!(
        "1.8.9 air use: {} inventories left to the server, {} uses in the air with a change left to the server",
        s.inv_unpredicted, s.air_unpredicted
    );
    assert!(s.diffs.is_empty(), "{} differences", s.diffs.len());
    assert_eq!(s.air_unpredicted, 0, "uses in the air left to the server");
}