use super::*;
use crate::common::Teleport;
use crate::common::{ChatPosition, EntityAction, JoinGame};
use ghast_protocol::RawPacket;
pub(super) fn opts(version: GameVersion) -> CoreOptions {
CoreOptions {
name: "test".into(),
caps: version.caps(),
settings: ClientSettings::default(),
brand: Some("vanilla".into()),
sensitivity: 0.5,
silent_hold: Duration::from_millis(1500),
hold_turn_on_action: true,
accept_required_packs: true,
entity_push: true,
turn_rate: (
crate::rotation::Rotation::MAX_YAW_PER_TICK,
crate::rotation::Rotation::MAX_PITCH_PER_TICK,
),
gui_releases_keys: true,
inventory: match version.instance() {
GameVersion::V1_8_9 => ghast_inventory::Version::V1_8,
GameVersion::V1_12_2 => ghast_inventory::Version::V1_12,
GameVersion::V26_1 => ghast_inventory::Version::V26_1,
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => ghast_inventory::Version::V26_2,
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => ghast_inventory::Version::V26_3,
_ => ghast_inventory::Version::V1_16_5,
},
}
}
pub(super) fn engine(version: GameVersion) -> Engine<Box<dyn Sim>> {
let sim: Box<dyn Sim> = match version.instance() {
GameVersion::V1_8_9 => Box::new(crate::sim::Sim18::new()),
GameVersion::V1_12_2 => Box::new(crate::sim::Sim12::new()),
GameVersion::V26_1 => Box::new(crate::sim::Sim26::test_overworld()),
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => Box::new(crate::sim::Sim262::test_overworld()),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => Box::new(crate::sim::Sim263::test_overworld()),
_ => Box::new(crate::sim::Sim16::new()),
};
Engine::new(opts(version), sim)
}
pub(super) fn load(e: &mut Engine<Box<dyn Sim>>, x: i32, z: i32) {
let raw = match e.core.opts.caps.version.instance() {
GameVersion::V1_8_9 => crate::sim::test_chunks::v1_8(x, z),
GameVersion::V1_12_2 => crate::sim::test_chunks::v1_12_2(x, z),
GameVersion::V26_1 => crate::sim::test_chunks::v26_1(x, z),
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => crate::sim::test_chunks::v26_2(x, z),
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => crate::sim::test_chunks::v26_3(x, z),
_ => crate::sim::test_chunks::v1_16_5(x, z),
};
e.sim.world_packet(&raw).unwrap();
}
pub(super) fn join(e: &mut Engine<Box<dyn Sim>>) {
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 7,
game_mode: GameMode::Survival,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
for x in -1..=1 {
for z in -1..=1 {
load(e, x, z);
}
}
e.handle(Inbound::Teleport(Teleport {
x: 8.5,
y: 64.0,
z: 8.5,
yaw: 90.0,
pitch: 0.0,
flags: 0,
teleport_id: None,
..Default::default()
}));
e.handle(Inbound::GameState {
reason: 13,
value: 0.0,
});
e.core.near_loaded = 1;
e.outbound().clear();
}
pub(super) fn names(out: &mut Vec<Outbound>) -> Vec<&'static str> {
let v = out
.iter()
.map(|o| match o {
Outbound::Move(m) => m.trace_id(),
Outbound::Chat(_) => "chat",
Outbound::HeldSlot(_) => "held_slot",
Outbound::Swing => "swing",
Outbound::EntityAction { .. } | Outbound::RidingJump { .. } => "entity_action",
Outbound::KeepAlive(_) => "keep_alive",
Outbound::Transaction { .. } => "transaction",
Outbound::TeleportConfirm(_) | Outbound::TeleportConfirmPose { .. } => {
"teleport_confirm"
}
Outbound::Punch => "punch",
Outbound::Respawn => "respawn",
Outbound::Settings(_) => "settings",
Outbound::Brand(_) => "brand",
Outbound::Abilities { .. } => "abilities",
Outbound::Dig { .. } => "block_dig",
Outbound::Place { .. } | Outbound::PlaceInside { .. } | Outbound::UseItem { .. } => {
"block_place"
}
Outbound::SwingOffHand => "swing_off",
Outbound::UseEntity { .. } => "use_entity",
Outbound::Inventory(_) => "inventory",
Outbound::PlayerInput(_) => "player_input",
Outbound::TickEnd => "tick_end",
Outbound::PlayerLoaded => "player_loaded",
Outbound::ChatSessionUpdate => "chat_session_update",
Outbound::ChunkBatchReceived(_) => "chunk_batch_received",
Outbound::Pong(_) => "pong",
Outbound::ResourcePackStatus { .. } => "resource_pack",
Outbound::CookieResponse { .. } => "cookie_response",
Outbound::LookAnswer { .. } => "C05",
Outbound::VehicleMove { .. } => "vehicle_move",
Outbound::SteerBoat { .. } => "steer_boat",
Outbound::SteerVehicle { .. } => "steer_vehicle",
Outbound::CustomClickAction { .. } => "custom_click_action",
Outbound::DialogCommand(_) => "chat_command",
Outbound::TabComplete { .. } => "tab_complete",
Outbound::UpdateSign { .. } => "update_sign",
Outbound::EditBook(_) => "edit_book",
Outbound::Raw(_) => "raw",
})
.collect();
out.clear();
v
}
pub(super) struct Script<F: FnMut(&mut TickContext<'_>)>(pub(super) F);
impl<F: FnMut(&mut TickContext<'_>)> Behavior for Script<F> {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
(self.0)(ctx);
}
}
#[test]
fn join_sends_settings_then_brand() {
let mut e = engine(GameVersion::V1_8_9);
e.handle(Inbound::JoinGame(JoinGame {
entity_id: 1,
game_mode: GameMode::Creative,
dimension: "0".into(),
hardcore: false,
dimension_nbt: None,
respawn_screen: true,
}));
assert_eq!(names(e.outbound()), ["settings", "brand"]);
}
#[test]
fn nothing_before_the_first_teleport() {
let mut e = engine(GameVersion::V1_8_9);
let mut b = Idle;
let t0 = Instant::now();
load(&mut e, 0, 0);
e.outbound().clear();
for i in 0..5 {
e.tick(&mut b, t0 + Duration::from_millis(50 * i));
}
assert!(e.outbound().is_empty());
}
#[test]
fn teleport_reply_per_version() {
let mut e = engine(GameVersion::V1_16_5);
e.handle(Inbound::Teleport(Teleport {
x: 1.0,
y: 2.0,
z: 3.0,
yaw: 450.0,
pitch: 100.0,
flags: 0,
teleport_id: Some(5),
..Default::default()
}));
let out = std::mem::take(e.outbound());
assert_eq!(out[0], Outbound::TeleportConfirm(5));
match out[1] {
Outbound::Move(MovePacket::PositionLook {
yaw,
pitch,
on_ground,
..
}) => {
assert_eq!((yaw, pitch, on_ground), (90.0, 90.0, false));
}
ref o => panic!("unexpected {o:?}"),
}
let mut e = engine(GameVersion::V1_8_9);
e.handle(Inbound::Teleport(Teleport {
x: 1.0,
y: 2.0,
z: 3.0,
yaw: 450.0,
pitch: 100.0,
flags: 0,
teleport_id: None,
..Default::default()
}));
let out = std::mem::take(e.outbound());
assert_eq!(out.len(), 1);
assert!(matches!(
out[0],
Outbound::Move(MovePacket::PositionLook {
yaw: 90.0,
pitch: 100.0,
..
})
));
}
#[test]
fn entity_pick_uses_the_tracker_and_the_proven_pick() {
use ghast_protocol::v1_8::play::clientbound::id;
use std::cell::Cell;
let raw = |id: i32, b: Vec<u8>| RawPacket {
id,
body: bytes::Bytes::from(b),
};
let zombie = |eid: u8, x: f64| {
let mut b = vec![eid, 54];
for v in [x, 64.0, 8.5] {
b.extend(((v * 32.0) as i32).to_be_bytes());
}
b.extend([0, 0, 0, 0, 0, 0, 0, 0, 0, 0x7f]);
raw(id::SPAWN_ENTITY_LIVING, b)
};
let mut e = engine(GameVersion::V1_8_9);
let mut login = 7i32.to_be_bytes().to_vec();
login.extend([0, 0, 2, 20, 7]);
login.extend(b"default");
login.push(0);
e.sim.world_packet(&raw(id::LOGIN, login)).unwrap();
e.sim.set_entities(Some(ghast_entity::Config::default()));
join(&mut e);
let pos: i64 = (4 << 38) | (65 << 26) | 8;
let mut b = pos.to_be_bytes().to_vec();
b.push(1 << 4);
e.sim.world_packet(&raw(id::BLOCK_CHANGE, b)).unwrap();
let t0 = Instant::now();
e.note_inbound(t0);
let seen = Cell::new((None, None));
let look = |e: &mut Engine<Box<dyn Sim>>| {
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.set((
ctx.target_entity().map(|h| (h.id, h.distance)),
ctx.target().map(|t| (t.pos, t.face)),
));
});
e.tick(&mut b, t0);
seen.get()
};
assert_eq!(
look(&mut e),
(
None,
Some((ghast_protocol::BlockPos::new(4, 65, 8), crate::Face::East))
)
);
e.sim.world_packet(&zombie(50, 6.5)).unwrap();
let (ent, block) = look(&mut e);
let (eid, d) = ent.unwrap();
assert_eq!(eid, 50);
assert!((d - 1.6).abs() < 1e-6, "{d}");
assert_eq!(block, None);
e.sim
.world_packet(&raw(id::ENTITY_DESTROY, vec![1, 50]))
.unwrap();
e.sim.world_packet(&zombie(51, 5.0)).unwrap();
assert_eq!(look(&mut e), (None, None));
}
#[test]
fn actions_precede_the_single_movement_packet() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 2 {
ctx.select_slot(3);
ctx.chat("hello");
ctx.swing();
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
}
});
e.tick(&mut b, t0);
assert_eq!(names(e.outbound()), ["C06"]);
e.tick(&mut b, t0);
assert_eq!(
names(e.outbound()),
["held_slot", "chat", "swing", "entity_action", "C03"]
);
for _ in 0..100 {
e.tick(&mut b, t0);
let n = names(e.outbound());
assert_eq!(n.len(), 1, "one movement packet per tick: {n:?}");
}
}
#[test]
fn raw_packets_keep_the_call_order() {
use crate::version::ClientVersion;
for v in [GameVersion::V1_8_9, GameVersion::V26_1] {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut refused = None;
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 3 {
ctx.swing();
ctx.send_raw(0x7f, vec![1, 2, 3]);
ctx.send_packet(&ghast_protocol::v26_1::play::serverbound::ArmAnimation {
hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
})
.unwrap();
refused = Some(ctx.send_packet(
&ghast_protocol::v26_1::play::clientbound::KeepAlive { keep_alive_id: 1 },
));
ctx.chat("after");
}
});
for _ in 0..2 {
e.tick(&mut b, t0);
}
e.outbound().clear();
e.tick(&mut b, t0);
let out = e.outbound().clone();
let n = names(e.outbound());
assert_eq!(n[..4], ["swing", "raw", "raw", "chat"], "{v:?} {n:?}");
let movement = n.iter().position(|x| {
x.starts_with('C') || x.contains("position") || *x == "flying" || *x == "look"
});
assert!(movement.is_none_or(|m| m > 3), "{v:?} {n:?}");
assert!(refused.unwrap().is_err());
let typed = ghast_protocol::v26_1::play::serverbound::ArmAnimation {
hand: ghast_protocol::v26_1::play::serverbound::ArmAnimationHand::OFF_HAND,
};
let mut want = ghast_protocol::FrameEncoder::new();
want.write_packet(&typed).unwrap();
let mut got = ghast_protocol::FrameEncoder::new();
let mut wire = crate::version::Wire26_1::default();
crate::version::V26_1::write_play(&mut got, &out[2], &mut wire).unwrap();
assert_eq!(got.take(), want.take());
}
}
#[test]
fn standing_bot_packets() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let mut b = Idle;
let t0 = Instant::now();
e.note_inbound(t0);
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert!(matches!(
out[..],
[Outbound::Move(MovePacket::PositionLook {
on_ground: false,
..
})]
));
let mut kinds = Vec::new();
for _ in 0..42 {
e.tick(&mut b, t0);
kinds.extend(names(e.outbound()));
}
assert_eq!(kinds.iter().filter(|k| **k == "C04").count(), 2);
assert_eq!(kinds.iter().filter(|k| **k == "C03").count(), 40);
assert_eq!((kinds[20], kinds[41]), ("C04", "C04"));
assert!(e.core.sent.on_ground);
}
#[test]
fn silent_server_freezes_behaviour() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut ticks = 0;
let mut b = Script(|ctx: &mut TickContext<'_>| {
ticks += 1;
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
});
e.tick(&mut b, t0 + Duration::from_millis(100));
e.tick(&mut b, t0 + Duration::from_millis(1600));
let n = names(e.outbound());
assert_eq!(n, ["entity_action", "C06", "entity_action", "C03"]);
e.note_inbound(t0 + Duration::from_millis(1700));
e.tick(&mut b, t0 + Duration::from_millis(1700));
let _ = b;
assert_eq!(ticks, 2);
}
#[test]
fn keepalive_answered_transactions_left_to_the_inventory() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
e.handle(Inbound::KeepAlive(42));
e.handle(Inbound::Transaction {
window_id: 0,
action: -5,
accepted: false,
});
assert_eq!(std::mem::take(e.outbound()), [Outbound::KeepAlive(42)]);
}
#[test]
fn panicking_behaviour_does_not_stop_the_tick() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
let mut b = Script(|ctx: &mut TickContext<'_>| {
if ctx.tick() == 2 {
panic!("boom");
}
});
let hook = std::panic::take_hook();
std::panic::set_hook(Box::new(|_| {}));
for _ in 0..5 {
e.tick(&mut b, t0);
}
std::panic::set_hook(hook);
assert!(e.state.failed);
assert_eq!(names(e.outbound()).len(), 5);
}
#[test]
fn chat_events_reach_the_behaviour_once() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
e.handle(Inbound::Chat(ChatMessage {
rendered: None,
json: r#"{"text":"hi"}"#.into(),
position: ChatPosition::System,
sender: None,
}));
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.extend(ctx.events().chat.iter().map(ChatMessage::plain));
});
let t0 = Instant::now();
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
assert_eq!(seen, ["hi"]);
}
#[test]
fn joining_dead_respawns_like_vanilla() {
let mut versions = vec![
(GameVersion::V1_8_9, false),
(GameVersion::V1_12_2, false),
(GameVersion::V1_16_5, true),
(GameVersion::V26_1, true),
];
#[cfg(feature = "v26_2")]
versions.push((GameVersion::V26_2, true));
#[cfg(feature = "v26_3")]
versions.push((GameVersion::V26_3, true));
for (v, rule) in versions {
for immediate in [false, true] {
let mut e = engine(v);
join(&mut e);
if rule {
e.handle(Inbound::GameState {
reason: 11,
value: if immediate { 1.0 } else { 0.0 },
});
}
e.handle(Inbound::Health(crate::common::Health {
health: 0.0,
food: 20,
saturation: 5.0,
..crate::common::Health::default()
}));
let t0 = Instant::now();
e.note_inbound(t0);
let mut died = false;
let mut b = Script(|ctx: &mut TickContext<'_>| died |= ctx.events().died);
let mut respawns = 0;
for _ in 0..3 {
e.tick(&mut b, t0);
respawns += e
.outbound()
.iter()
.filter(|o| matches!(o, Outbound::Respawn))
.count();
e.outbound().clear();
}
let _ = b;
assert!(died, "{v:?}");
let want = if rule && immediate { 3 } else { 0 };
assert_eq!(respawns, want, "{v:?} immediate {immediate}");
}
}
}
#[test]
fn immediate_respawn_1_16() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
e.handle(Inbound::GameState {
reason: 11,
value: 1.0,
});
e.handle(Inbound::Died { entity_id: 7 });
assert_eq!(e.outbound().as_slice(), [Outbound::Respawn]);
}
#[test]
fn dig_with_the_left_button() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
let down = ctx.target().is_some_and(|t| {
t.pos == ghast_protocol::BlockPos::new(8, 63, 8) && t.face == crate::Face::Up
});
ctx.set_buttons(Buttons {
left: down,
right: false,
});
});
let mut ticks = Vec::new();
for _ in 0..200 {
e.tick(&mut b, t0);
let n = names(e.outbound());
assert_eq!(n.iter().filter(|x| x.starts_with('C')).count(), 1, "{n:?}");
assert!(n.last().unwrap().starts_with('C'), "movement last: {n:?}");
ticks.push(n);
}
let flat: Vec<&str> = ticks.iter().flatten().copied().collect();
assert_eq!(
flat.iter().filter(|x| **x == "block_dig").count(),
2,
"start + finish"
);
assert!(e.core.hands.broken == 1);
let start = ticks.iter().position(|t| t.contains(&"block_dig")).unwrap();
let finish = ticks
.iter()
.rposition(|t| t.contains(&"block_dig"))
.unwrap();
assert_eq!(finish - start, 150);
assert!(e.sim.block_query(8, 63, 8).unwrap().air);
assert!(
e.core.pose.pos.y < 64.0,
"falls into the hole: {:?}",
e.core.pose.pos
);
}
#[test]
fn outbound_visible_to_the_behaviour() {
use crate::version::ClientVersion;
struct Watch {
seen: Vec<Vec<Outbound>>,
seq: Vec<Option<i32>>,
}
impl Behavior for Watch {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
self.seq.push(ctx.prediction_sequence());
ctx.set_aim(90.0, 89.5);
let down = ctx.target().is_some_and(|t| t.face == crate::Face::Up);
ctx.set_buttons(Buttons {
left: down,
right: false,
});
}
fn after_tick(&mut self, view: &TickView<'_>) {
self.seen.push(view.outbound().to_vec());
assert_eq!(view.prediction_sequence(), *self.seq.last().unwrap());
}
}
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Watch {
seen: Vec::new(),
seq: Vec::new(),
};
for t in 0..20 {
e.note_sequence(Some(t));
e.tick(&mut b, t0);
assert_eq!(*e.outbound(), *b.seen.last().unwrap());
e.outbound().clear();
}
assert_eq!(b.seq.last(), Some(&Some(19)));
let dig = b
.seen
.iter()
.find(|o| o.iter().any(|p| matches!(p, Outbound::Dig { .. })))
.expect("a dig start");
assert!(matches!(
dig.iter()
.find(|p| matches!(p, Outbound::Dig { .. }))
.unwrap(),
Outbound::Dig {
status: crate::common::DigStatus::Start,
face: crate::Face::Up,
..
}
));
assert!(matches!(dig.last(), Some(Outbound::Move(_))));
let mut wire = crate::version::Wire26_1::default();
let mut enc = ghast_protocol::FrameEncoder::new();
let dig = |status| Outbound::Dig {
status,
pos: ghast_protocol::BlockPos::new(1, 2, 3),
face: crate::Face::Up,
};
use crate::common::DigStatus;
assert_eq!(crate::version::V26_1::prediction_sequence(&wire), Some(0));
for (s, want) in [
(DigStatus::Start, 1),
(DigStatus::Abort, 1),
(DigStatus::Start, 2),
(DigStatus::Finish, 3),
] {
crate::version::V26_1::write_play(&mut enc, &dig(s), &mut wire).unwrap();
assert_eq!(
crate::version::V26_1::prediction_sequence(&wire),
Some(want)
);
}
assert_eq!(crate::version::V1_8::prediction_sequence(&()), None);
}
#[test]
fn dig_speed_and_item_facts() {
let mut e = engine(GameVersion::V1_16_5);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Script(|ctx: &mut TickContext<'_>| {
let id = |n: &str| i32::from(ghast_data::v1_16_5::Item::from_name(n).unwrap().id());
let bread = ctx.item_facts(&ghast_inventory::Stack::new(id("bread"), 3, 0));
assert!(bread.is_some_and(|f| f.food && f.usable && !f.places_block && f.count == 3));
let dirt = ctx.item_facts(&ghast_inventory::Stack::new(id("dirt"), 1, 0));
assert!(dirt.is_some_and(|f| f.places_block && !f.food));
});
e.tick(&mut b, t0);
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
e.note_inbound(t0);
let got = std::cell::Cell::new(None);
let mut b = Script(|ctx: &mut TickContext<'_>| {
let stone = ghast_protocol::BlockPos::new(8, 63, 8);
let pick = ghast_inventory::Stack::new(278, 1, 0);
let facts = ctx.item_facts(&pick).unwrap();
assert!(!facts.places_block && !facts.food);
got.set(Some((
ctx.dig_speed(stone, None),
ctx.dig_speed(stone, Some(&pick)),
ctx.dig_speed(ghast_protocol::BlockPos::new(8, 64, 8), None),
ctx.dig_speed(ghast_protocol::BlockPos::new(500, 63, 8), None),
)));
});
for _ in 0..40 {
e.tick(&mut b, t0);
}
assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
let (hand, pick, air, unloaded) = got.get().expect("ticked");
assert_eq!(hand, Some(1.0 / 1.5 / 100.0));
assert_eq!(pick, Some(8.0 / 1.5 / 30.0));
assert_eq!(air, Some(0.0));
assert_eq!(unloaded, None);
}
#[test]
fn place_needs_the_sent_look() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut results = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
results.push(ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)));
});
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let mut placed_tick = None;
for i in 0..20 {
e.tick(&mut b, t0);
let n = names(e.outbound());
if n.contains(&"block_place") {
assert_eq!(n[..2], ["block_place", "swing"], "{n:?}");
placed_tick.get_or_insert(i);
}
}
let _ = b;
let first = results.iter().position(|r| *r).unwrap();
assert!(first > 3, "refused while still turning");
assert_eq!(placed_tick, Some(first));
assert_eq!(e.core.inv.held().map(|s| s.id()), Some(50));
}
#[test]
fn sneak_action_order() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(Controls {
sneak: true,
..Controls::default()
});
});
e.tick(&mut b, Instant::now());
let out = std::mem::take(e.outbound());
assert_eq!(
out[0],
Outbound::EntityAction {
entity_id: 7,
action: EntityAction::StartSneaking
}
);
assert!(matches!(out[1], Outbound::Move(_)));
}
#[test]
fn block_updates_per_version() {
use ghast_protocol::BlockPos;
for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
let mut e = engine(v);
join(&mut e);
e.sim.collect_block_updates(true);
let t0 = Instant::now();
e.note_inbound(t0);
let raws = match v.instance() {
GameVersion::V1_8_9 => {
use ghast_protocol::v1_8::play::clientbound as cb;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 59 << 4 | 7,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_x: 0,
chunk_z: 0,
records: vec![cb::MultiBlockChangeRecords {
horizontal_pos: 5 << 4 | 6,
y: 62,
block_id: 60 << 4 | 7,
}],
})
.unwrap(),
]
}
GameVersion::V1_12_2 => {
use ghast_protocol::v1_12_2::play::clientbound as cb;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 59 << 4 | 7,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_x: 0,
chunk_z: 0,
records: vec![cb::MultiBlockChangeRecords {
horizontal_pos: 5 << 4 | 6,
y: 62,
block_id: 60 << 4 | 7,
}],
})
.unwrap(),
]
}
GameVersion::V26_1 => {
use ghast_protocol::v26_1::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
#[cfg(feature = "v26_2")]
GameVersion::V26_2 => {
use ghast_protocol::v26_2::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
#[cfg(feature = "v26_3")]
GameVersion::V26_3 => {
use ghast_protocol::v26_3::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: -1,
},
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
_ => {
use ghast_protocol::v1_16_5::play::clientbound as cb;
let local = (5 << 8 | 6 << 4 | 14) as i64;
vec![
RawPacket::from_packet(&cb::BlockChange {
location: BlockPos::new(3, 63, 4),
r#type: 1,
})
.unwrap(),
RawPacket::from_packet(&cb::MultiBlockChange {
chunk_coordinates: cb::MultiBlockChangeChunkCoordinates {
x: 0,
z: 0,
y: 0xF_FFFF,
},
not_trust_edges: false,
records: vec![9 << 12 | local],
})
.unwrap(),
]
}
};
for raw in &raws {
e.sim.world_packet(raw).unwrap();
}
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.push(ctx.events().block_updates.clone());
});
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
let want = match v.instance() {
GameVersion::V1_8_9 | GameVersion::V1_12_2 => vec![
(BlockPos::new(3, 63, 4), 59 << 4 | 7),
(BlockPos::new(5, 62, 6), 60 << 4 | 7),
],
_ => vec![(BlockPos::new(3, 63, 4), 1), (BlockPos::new(5, -2, 6), 9)],
};
assert_eq!(seen, [want, Vec::new()], "{v:?}");
e.sim.collect_block_updates(false);
e.sim.world_packet(&raws[0]).unwrap();
let mut n = usize::MAX;
let mut b = Script(|ctx: &mut TickContext<'_>| n = ctx.events().block_updates.len());
e.tick(&mut b, t0);
let _ = b;
assert_eq!(n, 0);
}
}
#[test]
fn set_flying_needs_may_fly() {
for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.handle(Inbound::Teleport(Teleport {
x: 8.5,
y: 70.0,
z: 8.5,
yaw: 90.0,
pitch: 0.0,
flags: 0,
teleport_id: Some(2),
..Default::default()
}));
e.outbound().clear();
let mut b = Script(|ctx: &mut TickContext<'_>| ctx.set_flying(true));
e.tick(&mut b, t0);
assert!(!names(e.outbound()).contains(&"abilities"), "{v:?}");
assert!(!e.core.pose.flying);
e.handle(Inbound::Abilities(Abilities {
flags: 4,
..Abilities::default()
}));
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert_eq!(
out[0],
Outbound::Abilities {
flags: 6,
flying_speed: 0.05,
walking_speed: 0.1
},
"{v:?}"
);
assert!(matches!(out[1], Outbound::Move(_)), "{out:?}");
assert!(e.core.pose.flying && e.core.sent.flying);
e.tick(&mut b, t0);
assert!(!names(e.outbound()).contains(&"abilities"));
let _ = b;
}
}
#[test]
fn v1_12_2_walks_with_physics() {
let mut e = engine(GameVersion::V1_12_2);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut idle = Script(|_: &mut TickContext<'_>| {});
e.tick(&mut idle, t0);
assert!(
!names(e.outbound())
.iter()
.any(|n| matches!(*n, "C04" | "C06"))
);
for _ in 0..5 {
e.tick(&mut idle, t0);
}
e.outbound().clear();
let start = e.core.pose.pos;
assert!(e.core.pose.on_ground, "{:?}", e.core.pose);
let mut walk = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(crate::common::Controls {
forward: true,
..Default::default()
});
});
for _ in 0..10 {
e.tick(&mut walk, t0);
}
let _ = walk;
let moved = names(e.outbound());
assert!(
moved.iter().any(|n| matches!(*n, "C04" | "C06")),
"{moved:?}"
);
assert!(e.core.pose.pos.x < start.x - 0.5, "{:?}", e.core.pose.pos);
assert_eq!(e.core.pose.pos.y, 64.0);
let mut stop = Script(|ctx: &mut TickContext<'_>| {
ctx.set_controls(crate::common::Controls::default());
});
for _ in 0..30 {
e.tick(&mut stop, t0);
}
e.outbound().clear();
for _ in 0..5 {
e.tick(&mut stop, t0);
}
let _ = (idle, stop);
let still = names(e.outbound());
assert!(still.len() <= 1 && !still.contains(&"C03"), "{still:?}");
}
#[test]
fn finished_behaviour_is_not_ticked() {
struct Three(std::rc::Rc<std::cell::Cell<u32>>);
impl Behavior for Three {
fn tick(&mut self, _ctx: &mut TickContext<'_>) {
self.0.set(self.0.get() + 1);
}
fn running(&self) -> bool {
self.0.get() < 3
}
}
let ticks = std::rc::Rc::new(std::cell::Cell::new(0));
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b: Box<dyn Behavior> = Box::new(Three(ticks.clone()));
for _ in 0..10 {
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
assert!(
out.iter().any(|o| matches!(o, Outbound::Move(_))),
"{out:?}"
);
}
assert_eq!(
ticks.get(),
3,
"not ticked after running() == false (through the Box)"
);
}
#[test]
fn turn_held_on_a_place_tick() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut tick = 0;
let mut placed_at = None;
let mut pitches = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
tick += 1;
if placed_at.is_none() {
ctx.set_aim(90.0, 89.5);
if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
placed_at = Some(tick);
ctx.set_aim(90.0, -60.0);
}
} else {
ctx.set_aim(90.0, -60.0);
}
pitches.push(ctx.pose().pitch);
});
for _ in 0..30 {
e.tick(&mut b, t0);
e.outbound().clear();
}
let _ = b;
let p = placed_at.expect("placed");
assert_eq!(e.core.held_turns, 1);
assert_eq!(pitches[p], pitches[p - 1], "{pitches:?}");
assert!(pitches[p + 1] < pitches[p], "{pitches:?}");
}
#[test]
fn click_ticket_matches_the_confirm() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let mut ticket = None;
let mut n = 0;
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
if n == 1 {
ctx.open_inventory().unwrap();
} else if ticket.is_none() {
ticket = ctx
.click(ghast_inventory::Click::Pickup {
slot: 36,
right: false,
})
.ok();
}
});
for _ in 0..3 {
e.tick(&mut b, t0);
}
let _ = b;
let t = ticket.expect("click sent");
assert_eq!(t.window_id, 0);
assert!(t.matches(&ghast_inventory::ClickResult::new(
0,
t.action,
ghast_inventory::ClickOutcome::Accepted,
)));
}
#[test]
fn planting_uses_the_seed_at_once() {
use ghast_protocol::v1_8::play::clientbound as cb;
for (soil, item, used) in [
(60 << 4 | 7, 295, true),
(1 << 4, 295, false),
(1 << 4, 50, true),
] {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let raw = RawPacket::from_packet(&cb::BlockChange {
location: floor,
r#type: soil,
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(item, 64, 0)));
let mut done = false;
let mut b = Script(|ctx: &mut TickContext<'_>| {
ctx.set_aim(90.0, 89.5);
if !done {
done = ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5));
}
});
let mut sent = None;
for _ in 0..20 {
e.tick(&mut b, t0);
for o in e.outbound().drain(..) {
if let Outbound::Place { held, .. } = o {
sent = held.map(|h| h.count());
}
}
}
let _ = b;
assert_eq!(sent, Some(64), "the packet carries the stack before use");
let left = e.core.inv.held().map(|s| s.count());
assert_eq!(
left,
Some(if used { 63 } else { 64 }),
"soil {soil} item {item}"
);
}
}
#[test]
fn planned_look_is_the_next_look() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
e.core
.inv
.on_set_slot(0, 36, Some(ghast_inventory::Stack::new(50, 64, 0)));
let floor = ghast_protocol::BlockPos::new(8, 63, 8);
let mut n = 0;
let mut placed = false;
let mut plans: Vec<(f32, f32)> = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
if n % 5 == 0 {
} else if !placed {
ctx.set_aim(90.0, 89.5);
if ctx.place(floor, crate::Face::Up, Vec3::new(8.5, 64.0, 8.5)) {
placed = true;
ctx.set_aim(90.0, -60.0);
}
} else {
ctx.set_aim(150.0, -60.0);
}
let p = ctx.planned_look();
assert_eq!(p, ctx.planned_look());
plans.push(p);
});
let mut looks = Vec::new();
for _ in 0..40 {
e.tick(&mut b, t0);
e.outbound().clear();
looks.push((e.core.pose.yaw, e.core.pose.pitch));
}
let _ = b;
assert!(placed);
assert_eq!(e.core.test_held_turns(), 1);
assert_eq!(plans, looks);
}
#[test]
fn teleport_event_has_the_sent_pose_before() {
for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
seen.extend(ctx.events().teleports.iter().copied());
});
e.tick(&mut b, t0);
let sent = e.core.sent;
let tp = Teleport {
x: 10.5,
y: 64.0,
z: 8.5,
yaw: 30.0,
pitch: 0.0,
flags: crate::common::teleport_flags::YAW,
teleport_id: Some(9),
relative: crate::common::teleport_flags::YAW as u32,
..Default::default()
};
e.handle(Inbound::Teleport(tp));
e.tick(&mut b, t0);
e.tick(&mut b, t0);
let _ = b;
assert_eq!(seen.len(), 2, "{v:?}");
let ev = seen[1];
assert_eq!(ev.teleport, tp);
assert_eq!(ev.sent_before, sent);
assert_eq!(ev.after.pos, Vec3::new(10.5, 64.0, 8.5));
assert_eq!(ev.after.yaw, sent.yaw + 30.0, "{v:?}");
}
}
#[test]
fn closed_window_frees_the_buttons() {
for &v in GameVersion::ALL.iter().filter(|v| v.enabled()) {
let mut e = engine(v);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
if v.instance() == GameVersion::V1_16_5 {
use ghast_protocol::v1_16_5::play::clientbound as cb;
let raw = RawPacket::from_packet(&cb::BlockChange {
location: ghast_protocol::BlockPos::new(8, 63, 8),
r#type: 1,
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
}
e.core.inv.on_open_window(
5,
Some(ghast_inventory::WindowKind::Chest { rows: 3 }),
"Vault".into(),
);
e.handle(Inbound::OpenWindow(5));
e.core
.inv
.on_set_slot(-1, -1, Some(ghast_inventory::Stack::new(1, 3, 0)));
let mut n = 0;
let mut closed_at = None;
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
ctx.set_aim(90.0, 89.5);
ctx.set_buttons(Buttons {
left: true,
right: false,
});
if n == 15 {
assert!(ctx.inventory().cursor().is_some());
ctx.close_window().unwrap();
assert_eq!(ctx.open_window(), None);
let inv = ctx.inventory();
assert!(!inv.gui_open() && inv.window().is_none() && inv.cursor().is_none());
closed_at = Some(n);
}
});
let mut first_dig = None;
for i in 1..=30 {
e.tick(&mut b, t0);
let out = std::mem::take(e.outbound());
if first_dig.is_none()
&& out.iter().any(|o| {
matches!(
o,
Outbound::Dig {
status: crate::common::DigStatus::Start,
..
}
)
})
{
first_dig = Some(i);
}
}
let _ = b;
assert_eq!(closed_at, Some(15));
let d = first_dig.unwrap_or_else(|| panic!("{v:?}: no dig after the close"));
assert!(d >= 15, "{v:?}: dug at tick {d} with the window open");
}
}
#[test]
fn swings_count_every_arm_swing() {
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut n = 0;
let mut seen = Vec::new();
let mut b = Script(|ctx: &mut TickContext<'_>| {
n += 1;
ctx.set_aim(90.0, 89.5);
if n == 1 {
ctx.swing();
ctx.swing();
}
if n == 20 {
ctx.set_buttons(Buttons {
left: true,
right: false,
});
}
seen.push(ctx.swings());
});
let mut sent = 0u64;
for _ in 0..30 {
e.tick(&mut b, t0);
sent += count_swings(&std::mem::take(e.outbound()));
}
let _ = b;
assert_eq!(seen[0], 2, "this tick's own swings count at once");
assert!(sent > 10, "the held button swings: {sent}");
assert_eq!(*seen.last().unwrap() + 1, sent);
assert_eq!(e.core.swings, sent);
}
#[test]
fn column_view_and_world_config() {
for config in [
None,
Some(
ghast_world::WorldConfig::default()
.with_biomes(true)
.with_light(true),
),
] {
let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
world: config,
..crate::sim::SimOptions::default()
});
let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
join(&mut e);
let w: &dyn WorldView = &e.sim;
let col = w.column(0, 0).expect("loaded");
assert_eq!(u32::from(col.raw(8, 63, 8)), w.raw_block(8, 63, 8).unwrap());
assert_eq!(col.raw(8, 63, 8), 1 << 4);
assert!(w.column(5, 5).is_none());
let light = col.sky_light(8, 63, 8);
assert_eq!(light.is_some(), config.is_some(), "{config:?}");
let biomes = !matches!(col.biomes(), ghast_world::Biomes::None);
assert_eq!(biomes, config.is_some(), "{config:?}");
}
}
#[test]
fn after_tick_sees_the_sent_pose() {
struct Obs {
n: u32,
views: Vec<(u64, Pose, u64)>,
}
impl Behavior for Obs {
fn tick(&mut self, ctx: &mut TickContext<'_>) {
self.n += 1;
ctx.set_aim(150.0, 10.0);
ctx.set_controls(Controls {
forward: true,
..Controls::default()
});
}
fn running(&self) -> bool {
self.n < 5
}
fn after_tick(&mut self, view: &TickView<'_>) {
self.views.push((view.tick(), *view.sent(), view.swings()));
assert!(view.world().is_column_loaded(0, 0));
assert_eq!(view.version(), GameVersion::V1_8_9);
}
}
let mut e = engine(GameVersion::V1_8_9);
join(&mut e);
let t0 = Instant::now();
e.note_inbound(t0);
let mut b = Obs {
n: 0,
views: Vec::new(),
};
let mut sent = Vec::new();
for _ in 0..10 {
e.tick(&mut b, t0);
e.outbound().clear();
sent.push(e.core.sent);
}
assert_eq!(b.n, 5);
assert_eq!(b.views.len(), 10, "also after the behaviour finished");
for (i, (_, p, _)) in b.views.iter().enumerate() {
assert_eq!(*p, sent[i]);
}
assert_ne!(
b.views[0].1.yaw, b.views[4].1.yaw,
"the view follows the turn"
);
}
#[test]
fn block_entities_follow_the_world_config() {
use ghast_protocol::v1_8::play::clientbound as cb;
for on in [false, true] {
let sim = crate::sim::Sim18::with(&crate::sim::SimOptions {
world: on.then(|| ghast_world::WorldConfig::default().with_block_entities(true)),
..crate::sim::SimOptions::default()
});
assert_eq!(sim.world_packet_ids().contains(&cb::id::UPDATE_SIGN), on);
let mut e = Engine::new(opts(GameVersion::V1_8_9), Box::new(sim) as Box<dyn Sim>);
join(&mut e);
let raw = RawPacket::from_packet(&cb::UpdateSign {
location: ghast_protocol::BlockPos::new(3, 64, 4),
text1: "\"Hello\"".into(),
text2: "\"\"".into(),
text3: "\"\"".into(),
text4: "\"\"".into(),
})
.unwrap();
e.sim.world_packet(&raw).unwrap();
let w: &dyn WorldView = &e.sim;
let be = w.column(0, 0).unwrap().block_entity(3, 64, 4);
assert_eq!(be.is_some(), on, "{be:?}");
}
}