use super::*;
impl<S: Sim> Engine<S> {
pub(crate) fn interests<B: Behavior>(&self, b: &B) -> Interests {
if self.state.failed {
Interests::NONE
} else {
b.interests()
}
}
pub(crate) fn stop<B: Behavior>(&mut self, b: &mut B, reason: &str) {
if self.state.started && !self.state.failed {
self.state.failed = true;
let name = self.core.opts.name.clone();
if catch_unwind(AssertUnwindSafe(|| b.stop(reason))).is_err() {
log::error!("[{name}] behaviour {} panicked in stop", b.name());
}
}
}
#[cfg(test)]
#[allow(dead_code, reason = "the engine tests need every version feature")]
pub(crate) fn tick<B: Behavior>(&mut self, b: &mut B, now: Instant) {
self.tick_with(b, now, &|_| crate::dialog::CommandCheck::ParseErrors);
}
pub(crate) fn tick_with<B: Behavior>(
&mut self,
b: &mut B,
now: Instant,
commands: &dyn Fn(&str) -> crate::dialog::CommandCheck,
) {
let c = &mut self.core;
c.tick += 1;
c.clocks.tick();
if let Some(h) = &mut c.hud
&& h.counting()
{
hud_countdown(h, &mut c.pending);
}
c.inv.tick();
let was_ready = c.ready;
c.ready = c.teleported_once
&& ((c.opts.caps.player_loaded_gate && c.client_loaded) || c.column_loaded(&self.sim));
if c.ready != was_ready {
if c.ready {
log::info!(
"[{}] t{} in the world at {:.3} {:.3} {:.3}",
c.opts.name,
c.tick,
c.pose.pos.x,
c.pose.pos.y,
c.pose.pos.z
);
} else {
log::debug!(
"[{}] t{} player column not loaded: not ticking",
c.opts.name,
c.tick
);
}
}
if c.chat_session_due && c.joined {
c.chat_session_due = false;
c.out.push(Outbound::ChatSessionUpdate);
}
if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
c.load_wait += 1;
let near = c.neighbourhood_loaded(&self.sim);
c.near_loaded = if near {
c.near_loaded.saturating_add(1)
} else {
0
};
let (compiled, timed_out) = (c.ready && c.near_loaded >= 2, c.load_wait >= 600);
#[cfg(test)]
let (compiled, timed_out) = c.test_gate.unwrap_or((compiled, timed_out));
if self.sim.load_gate_tick(compiled, timed_out) {
c.client_loaded = true;
c.gate_tick = true;
c.out.push(Outbound::PlayerLoaded);
log::debug!("[{}] t{} player loaded", c.opts.name, c.tick);
}
}
if !c.ready || (c.opts.caps.player_loaded_gate && !c.client_loaded) {
if c.opts.caps.sends_tick_end && c.joined {
c.out.push(Outbound::TickEnd);
}
if c.opts.caps.player_loaded_gate && c.joined && !c.client_loaded {
self.sim.tick_unloaded();
}
self.sim.tick_entities(&mut c.pose);
c.stamp_entities(&mut self.sim);
return;
}
let silent_for = c.last_inbound.map(|t| now.saturating_duration_since(t));
let silent = silent_for.is_some_and(|d| d > c.opts.silent_hold);
if silent != c.silent {
c.silent = silent;
if silent {
log::warn!(
"[{}] t{} server silent for {} ms: behaviour on hold",
c.opts.name,
c.tick,
silent_for.unwrap_or_default().as_millis()
);
} else {
log::info!(
"[{}] t{} server answering again: behaviour resumes",
c.opts.name,
c.tick
);
}
}
let slept = self.sim.take_sleep(&mut c.pose);
debug_assert_eq!(c.rare, c.sign.is_some() || c.sleeping.is_some() || c.dead);
if c.rare || slept.is_some() {
rare_screens_tick(c, &self.sim, slept);
}
if silent {
c.controls = Controls::default();
c.aimed = false;
} else if !self.state.failed && !self.state.done {
std::mem::swap(&mut c.pending, &mut c.current);
c.pending.clear();
if let Some(a) = self.sim.take_absorption() {
c.current.health_changed |= a.to_bits() != c.health.absorption.to_bits();
c.health.absorption = a;
}
if let Some(f) = self.sim.take_living_flags()
&& c.opts.caps.living_flags_drive_use
{
living_flags_use(c, f);
}
if !c.dialogs.is_empty() || !c.dialogs_pending.is_empty() {
c.dialogs.clear();
std::mem::swap(&mut c.dialogs, &mut c.dialogs_pending);
}
c.current.inventory = c.inv.drain_events();
if !c.hands.use_events.is_empty() {
take_use_events(c);
}
if let Some(s) = self.sim.entities_mut() {
let ev = s.drain_events();
let n = ev.len();
if n > 0 {
let skip = n.saturating_sub(MAX_PENDING_ENTITY_EVENTS);
let m = c.current.more();
m.entities.extend(ev.skip(skip));
m.entities_dropped = skip;
}
}
if self.sim.fishing_news() {
self.sim.drain_fishing(&mut c.current.more().fishing);
}
c.current.block_updates_dropped =
self.sim.drain_block_updates(&mut c.current.block_updates);
if c.current.inventory.player_changed {
let ench = |a: usize, id: i32, name: &str| {
c.inv.armor(a).map_or(0, |s| enchant_level(s, id, name))
};
let depth = ench(3, 8, "minecraft:depth_strider");
let soul = ench(3, -1, "minecraft:soul_speed");
c.aqua_affinity = ench(0, 6, "minecraft:aqua_affinity") > 0;
self.sim.boots(depth, soul);
self.sim.feet_item(c.inv.armor(3).map(|s| s.id()));
}
for o in c.inv.take_screen_packets() {
c.out.push(Outbound::Inventory(o));
}
let started = self.state.started;
self.state.started = true;
if !started {
c.rotation.reset(c.pose.yaw, c.pose.pitch);
}
let name = c.opts.name.clone();
let result = catch_unwind(AssertUnwindSafe(|| {
let held = held_item(&c.inv, &self.sim);
let mut ctx = TickContext {
core: c,
world: &self.sim,
held,
crosshair: std::cell::OnceCell::new(),
commands,
};
if !started {
b.start(&mut ctx);
}
b.tick(&mut ctx);
b.running()
}));
match result {
Ok(true) => {}
Ok(false) => {
self.state.done = true;
log::info!("[{name}] behaviour {} finished", b.name());
}
Err(_) => {
log::error!("[{name}] behaviour {} panicked: stopped", b.name());
self.stop(b, "panic");
}
}
}
let c = &mut self.core;
c.turned = false;
#[cfg(test)]
if let Some((yaw, pitch)) = c.forced_look.take() {
if !c.forced_aim || (c.aimed && !c.gate_tick) {
c.forced_aim = false;
c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
c.pose.yaw = yaw;
c.pose.pitch = pitch;
c.aimed = false;
} else {
c.forced_look = Some((yaw, pitch));
}
}
if c.gate_tick {
c.gate_tick = false;
held_look(c);
} else if c.aimed {
turn(c, &self.sim);
}
if c.entity_push != c.entity_push_sim {
c.entity_push_sim = c.entity_push;
self.sim.set_entity_push(c.entity_push);
}
if c.held_slot != c.sent_slot {
c.sent_slot = c.held_slot;
c.out.push(Outbound::HeldSlot(i16::from(c.sent_slot)));
}
c.slot_from_server = false;
{
let (gui, taken, eye) = if c.rare {
rare_keys(c, &self.sim)
} else {
let gui = c.inv.gui_open();
(
gui,
gui,
awake_eye_height(&self.sim, c.opts.caps, c.pose.sneaking),
)
};
let clicks = if c.clicks != 0 {
queued_presses(c, taken)
} else {
0
};
if self.sim.modern_inputs() && ((c.buttons.right && !gui) || c.hands.using_item()) {
self.sim.held_use_inputs(&mut c.inv);
}
let eyes = Vec3::new(c.pose.pos.x, c.pose.pos.y + eye, c.pose.pos.z);
let sim = &self.sim;
let blocks = |x: i32, y: i32, z: i32| sim.block_query(x, y, z);
let blocked = |p: ghast_protocol::BlockPos, f: crate::common::Face, id: u16| {
sim.place_suppressed(p, f, id)
};
let pick_rot = pick_rotation(c);
let look = hands::look_vector(pick_rot.0, pick_rot.1);
let held_id = c.inv.held().and_then(|s| u16::try_from(s.id()).ok());
let (left, right) = (c.buttons.left && !taken, c.buttons.right && !taken);
let (target, entity) = if left || right || clicks != 0 {
c.pick.fill(sim, c.opts.caps, eyes);
let crosshair = sim.crosshair_target(&PickQuery {
eyes,
rotation: pick_rot,
look,
held: held_id,
now: true,
creative: c.game_mode == GameMode::Creative,
player_bb: pick_box(c.pose.pos),
entities: &c.pick.entities,
});
let (b, mut e) = c.pick.split(crosshair, eyes);
if right
&& let Some(h) = &mut e
&& let Some(ents) = sim.entities()
{
h.interact = entity_click(c, ents, h.id);
}
(b, e)
} else {
(None, None)
};
let in_water = blocks(
eyes.x.floor() as i32,
eyes.y.floor() as i32,
eyes.z.floor() as i32,
)
.is_some_and(|b| b.water);
let mut held = held_item(&c.inv, sim);
let mut off_held = off_held_item(&c.inv, sim);
let creative = c.game_mode == GameMode::Creative;
if right {
use_equips(c, creative, &mut held, &mut off_held);
}
let mut placed = false;
let first = c.out.len();
let mut rules_now;
let rules: &dyn hands::RightRules = if right {
rules_now = click_rules(
sim,
&c.inv,
&c.pose,
c.game_mode,
&c.abilities,
eyes,
use_food_level_of(&c.abilities, c.opts.caps.invulnerable_eating, c.health.food),
);
if !c.cooldowns.is_empty() {
rules_now.cooling = cooling_hands(c);
}
&rules_now
} else {
&hands::NoRightRules
};
let mut io = HandsIo {
blocks: &blocks,
target,
held,
held_stack: c.inv.held().cloned(),
inv_version: c.inv.version(),
food: use_food_level(c),
off_held,
off_stack: c.inv.offhand().cloned(),
entity,
factors: DigFactors {
on_ground: c.pose.on_ground,
in_water,
aqua_affinity: c.aqua_affinity,
haste: c.effects.get(&3).map_or(0, |a| (*a as u8).wrapping_add(1)),
fatigue: c.effects.get(&4).map_or(0, |a| (*a as u8).wrapping_add(1)),
},
sneaking: c.pose.sneaking,
out: &mut c.out,
broken: &mut c.broken_now,
placed: &mut placed,
spectator: c.game_mode == GameMode::Spectator,
caps: c.opts.caps,
creative,
creative_dig: creative && c.opts.caps.creative_instant_dig,
place_blocked: &blocked,
rules,
};
c.hands.tick(left, right, clicks, &mut io);
if c.hands.used_ok != 0 {
let used = std::mem::take(&mut c.hands.used_ok);
if c.opts.caps.item_cooldowns != crate::version::ItemCooldownRules::None {
use_cooldowns(c, used);
}
}
let _ = placed;
if right && let Some(off_hand) = c.hands.equipped.take() {
equip_from_hand(&mut c.inv, off_hand, creative);
}
if c.out.len() != first {
predict_planting(c, sim, first);
click_stack_effects(c, first, entity);
if !c.hands.air_used.is_empty() {
air_used(c, &mut self.sim);
}
}
}
if !c.hands.attacks.is_empty() {
attack_effects(c, &mut self.sim);
}
if c.hands.using_item() && c.opts.caps.use_stop != crate::version::UseStop::AtSelect {
held_use_check(c);
} else {
c.use_mark = None;
}
if c.opts.caps.cooldown_reset != crate::version::CooldownReset::AtSelect {
cooldown_held_check(c);
}
if c.hands.dug || !c.hands.placing.is_empty() {
if !c.broken_now.is_empty() || !c.hands.placing.is_empty() || self.sim.records_digs() {
sent_predictions(c, &mut self.sim);
}
c.hands.dug = false;
c.hands.placing.clear();
}
if let Some(f) = c.want_flying.take() {
let first = c.out.len();
self.sim.set_flying(f, &mut c.out);
if c.out.len() > first {
c.pose.flying = f;
} else if f && !c.pose.flying {
log::debug!(
"[{}] t{} set_flying(true) refused: flight not allowed",
c.opts.name,
c.tick
);
}
}
let first = c.out.len();
let controls = movement_controls(c);
if self.sim.modern_inputs()
&& (c.hands.using_item()
|| c.hands.released_use().is_some()
|| controls.jump
|| self.sim.pre_tick_wanted())
{
let pre = crate::sim::PreTick {
using: c.hands.use_item(),
released: c.hands.released_use(),
controls,
look: (c.pose.yaw, c.pose.pitch),
};
if !self.sim.pre_tick(&c.inv, &pre) {
c.hands.stop_using();
}
}
let using = c.hands.using_item();
self.sim.hand_items(&mut c.inv);
self.sim
.step(&mut c.pose, controls, using, c.entity_id, &mut c.out);
if c.opts.caps.pick_head_yaw {
c.head_yaw = Some(c.pose.yaw);
}
self.sim.tick_entities(&mut c.pose);
self.sim.send_changes(c.entity_id, &mut c.out);
c.stamp_entities(&mut self.sim);
c.hands.count_use_tick();
for o in &c.out[first..] {
let Outbound::Move(m) = o else { continue };
match *m {
MovePacket::Position { pos, .. } => c.sent.pos = pos,
MovePacket::Look { yaw, pitch, .. } => {
c.sent.yaw = yaw;
c.sent.pitch = pitch;
}
MovePacket::PositionLook {
pos, yaw, pitch, ..
} => {
c.sent.pos = pos;
c.sent.yaw = yaw;
c.sent.pitch = pitch;
}
MovePacket::Flying { .. } => {}
}
if matches!(
m,
MovePacket::Position { .. } | MovePacket::PositionLook { .. }
) {
c.sent.motion = c.pose.motion;
}
}
c.sent.on_ground = c.pose.on_ground;
c.sent.sneaking = c.pose.sneaking;
c.sent.sprinting = c.pose.sprinting;
c.sent.flying = c.pose.flying;
c.swings += count_swings(&c.out);
if c.dead && c.joined && !c.respawn_screen && !c.inv.gui_open() {
c.out.push(Outbound::Respawn);
}
if c.opts.caps.sends_tick_end {
c.out.push(Outbound::TickEnd);
}
if !c.cooldowns.is_empty() {
tick_cooldowns(c);
}
if self.state.started && !self.state.failed {
let name = c.opts.name.clone();
let view = TickView {
core: &self.core,
world: &self.sim,
};
if catch_unwind(AssertUnwindSafe(|| b.after_tick(&view))).is_err() {
log::error!(
"[{name}] behaviour {} panicked in after_tick: stopped",
b.name()
);
self.stop(b, "panic");
}
}
}
}
pub(super) fn count_swings(out: &[Outbound]) -> u64 {
out.iter()
.filter(|o| matches!(o, Outbound::Swing | Outbound::SwingOffHand))
.count() as u64
}
#[inline]
pub(super) fn movement_controls(c: &mut Core) -> Controls {
if c.rare {
rare_controls(c)
} else if c.opts.gui_releases_keys && (c.inv.gui_open() || c.dialog.is_some()) {
screen_controls(c)
} else {
c.controls
}
}
#[cold]
#[inline(never)]
fn rare_controls(c: &mut Core) -> Controls {
if c.dead || c.sleeping.is_some() {
Controls::NONE
} else if c.opts.gui_releases_keys
&& (c.inv.gui_open() || c.dialog.is_some() || c.sign.is_some())
{
screen_controls(c)
} else {
c.controls
}
}
#[cold]
#[inline(never)]
fn rare_keys(c: &Core, sim: &(impl Sim + ?Sized)) -> (bool, bool, f64) {
let gui = c.inv.gui_open() || c.sign.is_some() || c.sleeping.is_some();
(
gui,
gui || c.dead,
pick_eye_height(sim, c.opts.caps, c.pose.sneaking),
)
}
#[cold]
#[inline(never)]
fn queued_presses(c: &mut Core, taken: bool) -> u8 {
let clicks = std::mem::take(&mut c.clicks);
if taken { 0 } else { clicks }
}
#[inline(always)]
fn turn(c: &mut Core, sim: &(impl Sim + ?Sized)) {
let (yaw, pitch) = c.rotation.step(c.pose.yaw, c.pose.pitch);
if c.opts.hold_turn_on_action && !post_look_ok(c, sim, yaw, pitch) {
c.held_turns += 1;
} else {
c.turned = yaw != c.pose.yaw || pitch != c.pose.pitch;
c.pose.yaw = yaw;
c.pose.pitch = pitch;
}
c.aimed = false;
}
#[cold]
#[inline(never)]
fn held_look(c: &mut Core) {
if c.sleeping.is_none() {
return;
}
c.aimed = false;
if c.opts.caps.sleep_levels_pitch {
c.pose.pitch = 0.0;
}
}
#[cold]
#[inline(never)]
fn screen_controls(c: &mut Core) -> Controls {
if !c.opts.caps.own_inventory_passes_keys
|| !c.inv.inventory_open()
|| c.dialog.is_some()
|| c.sign.is_some()
{
return Controls::NONE;
}
let keys = c.controls;
let held = c.screen_keys.get_or_insert(keys);
let still = |h: bool, k: bool| h && k;
*held = Controls {
forward: still(held.forward, keys.forward),
back: still(held.back, keys.back),
left: still(held.left, keys.left),
right: still(held.right, keys.right),
jump: still(held.jump, keys.jump),
sneak: still(held.sneak, keys.sneak),
sprint: still(held.sprint, keys.sprint),
};
Controls {
forward: keys.forward && !held.forward,
back: keys.back && !held.back,
left: keys.left && !held.left,
right: keys.right && !held.right,
jump: keys.jump && !held.jump,
sneak: keys.sneak && !held.sneak,
sprint: keys.sprint && !held.sprint,
}
}
#[cold]
#[inline(never)]
fn sent_predictions<S: Sim>(c: &mut Core, sim: &mut S) {
use crate::common::DigStatus;
let player = c.pose.pos;
let mut sequence = c.sequence.unwrap_or(0);
let mut broken = 0;
let mut placing = c.hands.placing.iter().copied().peekable();
let any_item = c.inv.held().is_some() || c.inv.offhand().is_some();
let mut used = [0u8; 2];
for (i, o) in c.out.iter().enumerate() {
match *o {
Outbound::Dig { status, pos, .. } => {
let predicting = matches!(status, DigStatus::Start | DigStatus::Finish);
if predicting {
sequence = sequence.wrapping_add(1);
} else if status != DigStatus::Abort {
continue;
}
let b = predicting && c.broken_now.get(broken) == Some(&pos);
if b {
broken += 1;
}
sim.dig_sent(pos, status, b, sequence, player);
}
Outbound::Place {
pos,
face,
cursor,
ref held,
off_hand,
}
| Outbound::PlaceInside {
pos,
face,
cursor,
ref held,
off_hand,
} => {
sequence = sequence.wrapping_add(1);
while placing.next_if(|&p| (p as usize) < i).is_some() {}
if placing.next_if_eq(&(i as u32)).is_some()
&& sim.place_sent(&crate::sim::predict::PlaceSent {
pos,
face,
held: held.as_ref(),
sneaking: c.pose.sneaking,
any_item,
game_mode: c.game_mode,
sequence,
player,
cursor: [cursor.x as f32, cursor.y as f32, cursor.z as f32],
yaw: c.pose.yaw,
})
&& crate::sim::predict::placing_uses_item(c.game_mode)
{
used[usize::from(off_hand)] = used[usize::from(off_hand)].saturating_add(1);
}
}
Outbound::UseItem { .. } => {
sequence = sequence.wrapping_add(1);
}
_ => {}
}
}
debug_assert_eq!(
broken,
c.broken_now.len(),
"a broken block without its dig packet"
);
for p in &c.broken_now[broken..] {
sim.predict_air(p.x, p.y, p.z);
}
c.broken_now.clear();
if used[0] > 0 {
c.inv.consume_held(used[0]);
}
if used[1] > 0 {
c.inv.consume_offhand(used[1]);
}
}
pub(super) struct ClickRules<'a, W: Sim + ?Sized> {
pub(super) sim: &'a W,
pub(super) inv: &'a ghast_inventory::Inventory,
pub(super) sneaking: bool,
pub(super) game_mode: GameMode,
pub(super) yaw: f32,
pub(super) pitch: f32,
pub(super) eyes: Vec3,
pub(super) food: i32,
pub(super) creative: bool,
pub(super) cooling: [bool; 2],
}
#[cold]
#[inline(never)]
pub(super) fn click_rules<'a, W: Sim + ?Sized>(
sim: &'a W,
inv: &'a ghast_inventory::Inventory,
pose: &Pose,
game_mode: GameMode,
abilities: &crate::common::Abilities,
eyes: Vec3,
food: i32,
) -> ClickRules<'a, W> {
ClickRules {
sim,
inv,
sneaking: pose.sneaking,
game_mode,
yaw: pose.yaw,
pitch: pose.pitch,
eyes,
food,
creative: abilities.creative_mode(),
cooling: [false; 2],
}
}
impl<W: Sim + ?Sized> hands::RightRules for ClickRules<'_, W> {
fn place(
&self,
pos: ghast_protocol::BlockPos,
face: crate::common::Face,
cursor: [f32; 3],
off_hand: bool,
) -> crate::sim::predict::PlaceRules {
let inv = self.inv;
let q = crate::sim::predict::PlaceQuery {
pos,
face,
cursor,
held: if off_hand { inv.offhand() } else { inv.held() },
sneaking: self.sneaking,
any_item: inv.held().is_some() || inv.offhand().is_some(),
game_mode: self.game_mode,
yaw: self.yaw,
food: self.food,
};
let rules = self.sim.place_rules(&q);
if !self.cooling[usize::from(off_hand)] || rules.block_packet == Some(false) {
return rules;
}
self.sim
.place_rules(&crate::sim::predict::PlaceQuery { held: None, ..q })
}
fn cooling(&self, off_hand: bool) -> bool {
self.cooling[usize::from(off_hand)]
}
fn air(&self, off_hand: bool) -> crate::sim::predict::AirAnswer {
let inv = self.inv;
let Some(stack) = (if off_hand { inv.offhand() } else { inv.held() }) else {
return crate::sim::predict::AirAnswer::Flags;
};
self.sim.air_use(&crate::sim::predict::AirQuery {
off_hand,
stack,
inv,
eyes: self.eyes,
yaw: self.yaw,
pitch: self.pitch,
game_mode: self.game_mode,
creative: self.creative,
})
}
}
pub(super) fn predict_planting(c: &mut Core, world: &dyn WorldView, first: usize) {
if !c.opts.caps.seed_planting_prediction || c.game_mode == GameMode::Creative {
return;
}
let mut uses = 0u8;
for o in &c.out[first..] {
let Outbound::Place {
pos,
face: crate::common::Face::Up,
held: Some(held),
off_hand: false,
..
} = o
else {
continue;
};
let soil = match held.id() {
295 | 361 | 362 | 391 | 392 => 60,
372 => 88,
_ => continue,
};
let id = |y: i32| world.raw_block(pos.x, y, pos.z).map(|s| s >> 4);
if held.count() > i32::from(uses) && id(pos.y) == Some(soil) && id(pos.y + 1) == Some(0) {
uses += 1;
}
}
if uses > 0 {
c.inv.consume_held(uses);
}
}