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,
}
}
#[derive(Default, Debug)]
pub(super) struct Summary {
pub cases: usize,
pub placed: usize,
pub predicted: usize,
pub unpredicted: usize,
pub air_use: usize,
pub undecided: usize,
pub crosshair: usize,
pub packets: usize,
pub diffs: Vec<String>,
}
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) => {
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,
}));
for x in -1..=0 {
for z in -1..=0 {
e.sim
.world_packet(&crate::sim::test_chunks::$chunks(x, z))
.unwrap();
}
}
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 }),
);
}
}
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);
}
for x in -4..=4 {
for y in 63..=69 {
for z in -2..=6 {
let raw = before.get(&(x, y, z)).copied().unwrap_or(0);
e.sim
.test_set_block(x, y, z, ($state)(raw));
}
}
}
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"]));
}
e.inventory_mut().set_creative(mode == GameMode::Creative);
let sneak = c["sneaking"].as_bool().unwrap();
e.core.pose.sneaking = sneak;
($sneak)(&mut e, sneak, mode);
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(),
)
});
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,
})
};
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();
e.core.ready = true;
let mut target = None;
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 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()))
);
let air_use = $offhand
&& held
.as_ref()
.is_some_and(|h| u16::try_from(h.id()).is_ok_and($air));
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 || want_target.is_none();
if got != want && air_use {
sum.air_use += 1;
} 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:?}"));
}
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 -4..=4 {
for y in 63..=69 {
for z in -2..=6 {
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;
} else if changed && !wrong {
sum.predicted += 1;
}
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);
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
);
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,
}
},
|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
);
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,
}
},
|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
);
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());
}