use super::*;
pub(super) fn push_hud(ev: &mut TickEvents, e: crate::hud::HudEvent) {
let m = ev.more();
if m.hud.len() < MAX_PENDING_HUD {
m.hud.push(e);
} else {
m.hud_dropped += 1;
}
}
#[cold]
#[inline(never)]
fn hud_chat(c: &mut Core, m: ChatMessage) -> Option<ChatMessage> {
if let Some(h) = &mut c.hud {
if m.position == crate::common::ChatPosition::ActionBar {
let t = match &m.rendered {
Some(r) => crate::hud::Text::from_text(r.clone()),
None => crate::hud::Text::from_json(m.json.clone()),
};
let ev = &mut c.pending;
h.action_bar_op(t, |e| push_hud(ev, e));
}
if !c.chat_events {
return None;
}
}
Some(m)
}
#[cold]
#[inline(never)]
fn hud_packet(c: &mut Core, p: Inbound) {
match p {
Inbound::BossBar(op) => {
if let Some(h) = &mut c.hud {
let ev = &mut c.pending;
if !h.boss_bar_op(op, |e| push_hud(ev, e)) {
log::debug!(
"[{}] t{} update of an unknown boss bar",
c.opts.name,
c.tick
);
}
}
}
Inbound::Title(op) => {
if let Some(h) = &mut c.hud {
let ev = &mut c.pending;
h.title_op(op, |e| push_hud(ev, e));
}
}
Inbound::ActionBar(t) => {
if let Some(h) = &mut c.hud {
let ev = &mut c.pending;
h.action_bar_op(t, |e| push_hud(ev, e));
}
}
Inbound::TabList { header, footer } => {
if let Some(h) = &mut c.hud {
let ev = &mut c.pending;
h.tab_list(header, footer, |e| push_hud(ev, e));
}
}
Inbound::TabComplete(r) => {
let t = c.tabs.answer(r);
let m = c.pending.more();
if m.tabs.len() < MAX_PENDING_TABS {
m.tabs.push(t);
}
}
_ => {}
}
}
#[cold]
#[inline(never)]
pub(super) fn open_sign(c: &mut Core, sim: &(impl Sim + ?Sized), e: crate::sign::SignEditor) {
use crate::sign::{OpenSign, SignCloseReason, SignEvent, SignRules};
let rules = c.opts.caps.sign_editor;
let here = sim.sign_at(e.pos);
if rules == SignRules::Sided && here != Some(true) {
log::debug!(
"[{}] t{} sign editor at {:?} ignored: no sign there",
c.opts.name,
c.tick,
e.pos
);
push_sign(c, SignEvent::Ignored(e));
return;
}
if c.sign.is_some() {
close_sign_screen(c, Some(SignCloseReason::Replaced));
}
log::debug!(
"[{}] t{} sign editor at {:?} (front {})",
c.opts.name,
c.tick,
e.pos,
e.front
);
c.sign = Some(OpenSign {
editor: e,
check_first_tick: rules == SignRules::FirstTickCheck && here != Some(true),
});
c.rare = true;
push_sign(c, SignEvent::Opened(e));
}
pub(super) fn close_sign_screen(c: &mut Core, reason: Option<crate::sign::SignCloseReason>) {
if let Some(s) = c.sign.take() {
c.update_rare();
c.out.push(Outbound::UpdateSign {
pos: s.editor.pos,
front: s.editor.front,
lines: Box::default(),
});
if let Some(r) = reason {
push_sign(c, crate::sign::SignEvent::Closed(s.editor, r));
}
}
}
#[cold]
#[inline(never)]
fn game_mode_abilities(c: &mut Core, sim: &mut (impl Sim + ?Sized)) {
let mut a = c.abilities;
a.flags = match c.game_mode {
GameMode::Creative => a.flags | 1 | 4 | 8,
GameMode::Spectator => (a.flags & !8) | 1 | 2 | 4,
_ => a.flags & !(1 | 2 | 4 | 8),
};
c.abilities = a;
c.pose.flying = a.flying();
sim.abilities(a);
}
fn knockback(c: &mut Core, motion: Vec3, explosion: bool) {
let m = c.pending.more();
if m.knockback.len() < MAX_PENDING_KNOCKBACK {
m.knockback
.push(crate::common::Knockback { motion, explosion });
}
}
fn push_sign(c: &mut Core, e: crate::sign::SignEvent) {
let m = c.pending.more();
if m.signs.len() < MAX_PENDING_SIGNS {
m.signs.push(e);
}
}
#[cold]
#[inline(never)]
pub(super) fn sign_screen_tick(c: &mut Core, sim: &(impl Sim + ?Sized)) {
use crate::sign::{SignCloseReason, SignRules};
let Some(s) = c.sign else { return };
let reason = if s.check_first_tick {
let p = s.editor.pos;
let other =
sim.sign_at(p) == Some(false) && sim.block_query(p.x, p.y, p.z).is_some_and(|q| !q.air);
if let Some(o) = &mut c.sign {
o.check_first_tick = false;
}
other.then_some(SignCloseReason::BlockGone)
} else if c.opts.caps.sign_editor == SignRules::Sided {
if sim.sign_at(s.editor.pos) != Some(true) {
Some(SignCloseReason::BlockGone)
} else {
let eye = c.pose.pos.y + pick_eye_height(sim, c.opts.caps, c.pose.sneaking);
let p = s.editor.pos;
let d = |v: f64, lo: i32| (f64::from(lo) - v).max(v - f64::from(lo + 1)).max(0.0);
let (dx, dy, dz) = (d(c.pose.pos.x, p.x), d(eye, p.y), d(c.pose.pos.z, p.z));
let max = sim.block_interaction_range() + 4.0;
(dx * dx + dy * dy + dz * dz >= max * max).then_some(SignCloseReason::TooFar)
}
} else {
None
};
if reason.is_some() {
close_sign_screen(c, reason);
}
}
#[cold]
#[inline(never)]
pub(super) fn fell_asleep(c: &mut Core, bed: ghast_protocol::BlockPos) {
log::debug!(
"[{}] t{} asleep in the bed at {:?}",
c.opts.name,
c.tick,
bed
);
c.sleeping = Some(bed);
c.rare = true;
c.sleep_ticks = 0;
let m = c.pending.more();
m.sleep.push(crate::common::SleepEvent::FellAsleep(bed));
}
#[cold]
#[inline(never)]
pub(super) fn woke_up(c: &mut Core) {
if c.sleeping.take().is_some() {
c.update_rare();
log::debug!("[{}] t{} woke up", c.opts.name, c.tick);
let m = c.pending.more();
m.sleep.push(crate::common::SleepEvent::WokeUp);
}
}
#[cold]
#[inline(never)]
pub(super) fn rare_screens_tick(
c: &mut Core,
sim: &(impl Sim + ?Sized),
change: Option<Option<ghast_protocol::BlockPos>>,
) {
if c.sign.is_some() {
sign_screen_tick(c, sim);
}
if change.is_some() || c.sleeping.is_some() {
sleep_tick(c, change);
}
}
fn sleep_tick(c: &mut Core, change: Option<Option<ghast_protocol::BlockPos>>) {
match change {
Some(Some(bed)) => fell_asleep(c, bed),
Some(None) => woke_up(c),
None => {}
}
if c.sleeping.is_some() {
c.sleep_ticks = (c.sleep_ticks + 1).min(100);
c.gate_tick = true;
}
}
#[cold]
#[inline(never)]
pub(super) fn hud_countdown(h: &mut crate::hud::Hud, ev: &mut TickEvents) {
h.tick(|e| push_hud(ev, e));
}
impl<S: Sim> Engine<S> {
pub(crate) fn handle(&mut self, p: Inbound) {
let c = &mut self.core;
let sim = &mut self.sim;
match p {
Inbound::KeepAlive(id) => c.out.push(Outbound::KeepAlive(id)),
Inbound::JoinGame(j) => {
c.entity_id = j.entity_id;
c.sleeping = None;
c.update_rare();
sim.set_main_arm_left(c.opts.settings.main_hand == 0);
c.game_mode = j.game_mode;
c.respawn_screen = j.respawn_screen;
c.dimension = j.dimension;
c.joined = true;
if let Some(t) = &mut c.teams {
**t = crate::teams::Teams::default();
}
c.pending.joined = true;
c.dialog = None;
c.health = Health::default();
c.abilities = Abilities::default();
c.reset_player("join game");
sim.reset_player();
sim.spectator(c.game_mode == GameMode::Spectator);
game_mode_abilities(c, sim);
if !c.opts.caps.configuration_state {
c.out.push(Outbound::Settings(c.opts.settings.clone()));
if let Some(brand) = &c.opts.brand {
c.out.push(Outbound::Brand(brand.clone()));
}
}
log::info!(
"[{}] joined: entity {} {:?} dimension {}",
c.opts.name,
c.entity_id,
c.game_mode,
c.dimension
);
}
Inbound::Respawn {
dimension,
game_mode,
keep,
} => {
c.sleeping = None;
c.update_rare();
if dimension != c.dimension {
c.dimension = dimension;
}
c.game_mode = game_mode;
c.pending.respawned = true;
c.reset_player("respawn");
sim.respawn_player(keep);
sim.spectator(c.game_mode == GameMode::Spectator);
c.abilities = Abilities::default();
game_mode_abilities(c, sim);
}
Inbound::Teleport(t) => {
if c.teleported_once {
log::debug!(
"[{}] t{} teleport {:?} {:?} {:?} yaw {:?} pitch {:?} flags {}; we had sent \
{:?} {:?} {:?} yaw {:?} pitch {:?} ground {}",
c.opts.name,
c.tick,
t.x,
t.y,
t.z,
t.yaw,
t.pitch,
t.flags,
c.sent.pos.x,
c.sent.pos.y,
c.sent.pos.z,
c.sent.yaw,
c.sent.pitch,
c.sent.on_ground
);
}
let (sent_before, pose_before) = (c.sent, c.pose);
sim.teleport(&mut c.pose, &t);
sim.teleport_sequence(c.sequence);
if c.pending.teleports.len() < MAX_PENDING_TELEPORTS {
c.pending.teleports.push(TeleportEvent {
teleport: t,
sent_before,
pose_before,
after: c.pose,
});
}
if c.opts.caps.teleport_confirm_pose {
c.out.push(Outbound::TeleportConfirmPose {
id: t.teleport_id.unwrap_or(0),
pos: c.pose.pos,
yaw: c.pose.yaw,
pitch: c.pose.pitch,
});
c.hands.stop_destroy_block(&mut c.out);
} else {
if let Some(id) = t.teleport_id {
c.out.push(Outbound::TeleportConfirm(id));
}
c.out.push(Outbound::Move(MovePacket::PositionLook {
horizontal_collision: false,
pos: c.pose.pos,
yaw: c.pose.yaw,
pitch: c.pose.pitch,
on_ground: false,
}));
}
c.sent = Pose {
on_ground: false,
..c.pose
};
if !c.teleported_once {
log::debug!(
"[{}] t{} spawn position {:.3} {:.3} {:.3}",
c.opts.name,
c.tick,
c.pose.pos.x,
c.pose.pos.y,
c.pose.pos.z
);
}
c.teleported_once = true;
c.pending.teleported = true;
}
Inbound::Chat(m) => {
let m = if c.hud.is_some() {
match hud_chat(c, m) {
Some(m) => m,
None => return,
}
} else {
m
};
if c.pending.chat.len() < MAX_PENDING_CHAT {
c.pending.chat.push(m);
} else {
c.pending.chat_dropped += 1;
}
}
p @ (Inbound::BossBar(_)
| Inbound::Title(_)
| Inbound::ActionBar(_)
| Inbound::TabList { .. }
| Inbound::TabComplete(_)) => hud_packet(c, p),
Inbound::OpenSign(e) => open_sign(c, &*sim, e),
Inbound::UseBed { entity_id, bed } if entity_id == c.entity_id => {
sim.sleep_at(&mut c.pose, bed);
fell_asleep(c, bed);
}
Inbound::WakeUp(id) if id == c.entity_id => {
sim.wake_up();
woke_up(c);
}
Inbound::UseBed { .. } | Inbound::WakeUp(_) => {}
Inbound::Time(t) => {
c.clocks.apply(&t);
c.day_clock = sim.day_clock();
}
Inbound::Health(h) => {
let was_dead = c.dead;
c.health = Health {
absorption: c.health.absorption,
..h
};
sim.food(h.food);
sim.player_alive(h.health > 0.0);
c.pending.health_changed = true;
if h.health <= 0.0 && !was_dead {
c.dead = true;
c.rare = true;
c.pending.died = true;
log::info!("[{}] t{} died", c.opts.name, c.tick);
}
}
Inbound::Died { entity_id } => {
if entity_id == c.entity_id && !c.respawn_screen {
c.out.push(Outbound::Respawn);
}
}
Inbound::Death(d) => {
if d.entity_id == c.entity_id && !c.respawn_screen {
c.out.push(Outbound::Respawn);
}
c.pending.more().deaths.push(d);
}
Inbound::SpawnPoint(p) => c.spawn_point = Some(p),
Inbound::Teams(p) => {
if let Some(t) = &mut c.teams
&& !t.apply(&p)
{
log::debug!("[{}] t{} team packet not applied", c.opts.name, c.tick);
}
}
Inbound::Damage(h) => {
if h.entity_id == c.entity_id {
c.last_hurt = Some(c.tick + 1);
c.pending.more().hurt.push(h);
}
}
Inbound::EffectApplied(e) => {
if e.entity_id == c.entity_id {
c.effects.insert(e.id, e.amplifier);
sim.status_effects(&c.effects);
let a = crate::common::ActiveEffect {
id: e.id,
amplifier: e.amplifier,
duration: e.duration,
flags: e.flags,
received_tick: c.tick + 1,
};
match c.active_effects.iter_mut().find(|x| x.id == e.id) {
Some(x) => *x = a,
None => c.active_effects.push(a),
}
c.pending
.more()
.effects
.push(crate::common::EffectEvent::Applied(a));
}
}
Inbound::Abilities(a) => {
c.abilities = a;
c.pose.flying = a.flying();
sim.abilities(a);
}
Inbound::HeldSlot(s) => {
if (0..9).contains(&s) {
if c.held_slot != s as u8
&& c.opts.caps.use_stop == crate::version::UseStop::AtSelect
{
c.hands.stop_using();
}
c.held_slot = s as u8;
c.slot_from_server = true;
}
}
Inbound::GameState { reason, value } => match reason {
1 | 2 | 7 => sim.weather(reason, value),
3 => {
c.game_mode = GameMode::from_wire(value as u8);
sim.spectator(c.game_mode == GameMode::Spectator);
game_mode_abilities(c, sim);
if c.game_mode == GameMode::Spectator && c.opts.caps.spectator_switch_stops_use
{
c.hands.stop_using();
}
c.pending.game_mode_changed = true;
}
11 if c.opts.caps.immediate_respawn_rule => c.respawn_screen = value == 0.0,
13 if c.opts.caps.player_loaded_gate => {
c.level_load_started = true;
sim.level_load_start();
}
_ => {}
},
Inbound::Transaction { .. } => {}
Inbound::OpenWindow(id) => c.open_window = id,
Inbound::CloseWindow(_) => c.open_window = 0,
Inbound::Velocity { entity_id, motion } => {
if entity_id == c.entity_id {
sim.velocity(motion, false);
knockback(c, motion, false);
}
}
Inbound::ExplosionPush(motion) => {
sim.velocity(motion, true);
knockback(c, motion, true);
}
Inbound::MovementSpeed {
entity_id,
base,
modifiers,
} => {
if entity_id == c.entity_id {
movement_speed(c, sim, base, &modifiers);
}
}
Inbound::LegacyAttributes {
entity_id,
movement_speed: speed,
attack_speed,
} => {
if entity_id == c.entity_id {
if let Some((base, modifiers)) = speed {
movement_speed(c, sim, base, &modifiers);
}
if let Some((base, modifiers)) = attack_speed {
let mut m = ghast_physics::attribute::Modifiers::NONE;
for &(id, amount, op) in &modifiers {
m.insert(id.as_u128(), amount, op as u8);
}
c.attack_speed = m.value(base);
}
}
}
Inbound::Effect {
entity_id,
id,
amplifier,
} => {
if entity_id == c.entity_id {
c.effects.insert(id, amplifier);
sim.status_effects(&c.effects);
}
}
Inbound::EffectRemoved { entity_id, id } => {
if entity_id == c.entity_id {
c.effects.remove(&id);
sim.status_effects(&c.effects);
c.active_effects.retain(|x| x.id != id);
c.pending
.more()
.effects
.push(crate::common::EffectEvent::Removed(id));
}
}
Inbound::EntityStatus { entity_id, status } => {
if entity_id != c.entity_id {
sim.entity_event(entity_id, status);
}
if entity_id == c.entity_id && status == 9 {
if c.opts.caps.item_cooldowns == crate::version::ItemCooldownRules::Groups {
finish_cooldown(c);
}
finish_food(c);
finish_consumes(c);
c.hands.finish_using();
}
if entity_id == c.entity_id && matches!(status, 2 | 33 | 36 | 37 | 44) {
c.last_hurt = Some(c.tick + 1);
c.pending
.more()
.hurt
.push(crate::common::Hurt::from_status(entity_id, status));
}
}
Inbound::ItemCooldown { key, ticks } => server_cooldown(c, key, ticks),
Inbound::Attributes {
entity_id,
attributes,
} => {
if entity_id == c.entity_id {
if let Some(a) = attributes.iter().find(|a| a.name == "attack_speed") {
c.attack_speed = modern_attribute_value(a);
}
sim.attributes(&attributes);
} else {
sim.entity_attributes(entity_id, &attributes);
}
}
Inbound::Ping(id) => c.out.push(Outbound::Pong(id)),
Inbound::ChunkBatchStart => sim.chunk_batch_start(c.now_nanos()),
Inbound::ChunkBatchFinished(size) => {
let per_tick = sim.chunk_batch_finished(size, c.now_nanos());
c.out.push(Outbound::ChunkBatchReceived(per_tick));
}
Inbound::StartConfiguration => {
c.joined = false;
if let Some(h) = &mut c.hud {
let ev = &mut c.pending;
h.reset(|e| push_hud(ev, e));
}
c.dialog = None;
c.reset_player("reconfiguration");
sim.drop_level();
}
Inbound::ResourcePackPush { id, required } => {
if required && c.opts.accept_required_packs {
for result in [3, 4, 0] {
c.out.push(Outbound::ResourcePackStatus { id, result });
}
} else {
c.out.push(Outbound::ResourcePackStatus { id, result: 1 });
}
}
Inbound::CookieRequest(key) => {
c.out.push(Outbound::CookieResponse { key, value: None });
}
Inbound::StoreCookie { .. } => {}
Inbound::Transfer { .. } => {}
Inbound::Rotate {
yaw,
pitch,
relative_yaw,
relative_pitch,
} => {
let yaw = if relative_yaw { c.pose.yaw + yaw } else { yaw };
let pitch = if relative_pitch {
c.pose.pitch + pitch
} else {
pitch
};
c.pose.yaw = yaw;
c.pose.pitch = pitch.clamp(-90.0, 90.0);
c.rotation.reset(c.pose.yaw, c.pose.pitch);
c.out.push(Outbound::LookAnswer {
yaw: c.pose.yaw,
pitch: c.pose.pitch,
});
c.sent.yaw = c.pose.yaw;
c.sent.pitch = c.pose.pitch;
}
Inbound::ShowDialog(d) => {
log::debug!("[{}] t{} dialog \"{}\"", c.opts.name, c.tick, d.title);
c.dialog = Some(d.clone());
if c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
c.dialogs_pending.push(crate::dialog::DialogEvent::Shown(d));
}
}
Inbound::ClearDialog => {
if c.dialog.take().is_some() && c.dialogs_pending.len() < MAX_PENDING_DIALOGS {
c.dialogs_pending.push(crate::dialog::DialogEvent::Cleared);
}
}
Inbound::Disconnect(_) | Inbound::SetCompression(_) => {}
}
}
}