use std::collections::HashMap;
use super::*;
use crate::sim::shared::PlayerFacts;
use ghast_physics::v1_16_5::Side;
use ghast_physics::v1_16_5::drop::{self, Drop, DropKind, OrbPlayer};
use ghast_physics::v1_16_5::projectile::{self, HookedEntity, Projectile, ProjectileKind};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
Projectile(ProjectileKind),
Drop(DropKind),
}
impl Kind {
fn of(name: &str) -> Option<Kind> {
if name == "potion" {
return Some(Kind::Projectile(ProjectileKind::SplashPotion));
}
ProjectileKind::from_entity_name(name)
.map(Kind::Projectile)
.or_else(|| DropKind::from_entity_name(name).map(Kind::Drop))
}
}
#[derive(Debug)]
enum State {
Projectile(Projectile),
Drop(Drop),
}
#[derive(Debug)]
struct Entry {
state: State,
no_physics: bool,
filed: bool,
hook: Option<i32>,
}
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);
#[derive(Debug, Default)]
pub(super) struct NonLiving16 {
map: HashMap<i32, Entry>,
updates: Vec<Update>,
discards: Vec<i32>,
idents: crate::sim::shared::PlayerIdents,
pub(super) own_before: [f64; 3],
pre: Vec<(i32, [f64; 3])>,
players: Vec<(OrbPlayer, [f64; 3], u32)>,
seen: Vec<OrbPlayer>,
}
impl NonLiving16 {
pub(super) fn clear(&mut self) {
self.map.clear();
self.idents.clear();
}
fn has_orbs(&self) -> bool {
self.map
.values()
.any(|en| matches!(&en.state, State::Drop(d) if d.kind() == DropKind::ExperienceOrb))
}
}
mod data_index {
pub(super) const NO_GRAVITY: u8 = 5;
pub(super) const FIRST: u8 = 7;
pub(super) const ARROW_COLOR: u8 = 9;
pub(super) const CAUGHT_FISH: u8 = 8;
}
impl Sim16 {
pub(super) fn set_nonliving(&mut self, on: bool) {
if on == self.nonliving.is_some() {
return;
}
self.nonliving = on.then(Box::default);
}
#[cold]
#[inline(never)]
pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
use ghast_protocol::defs::p754::types::EntityMetadataValue as V;
use ghast_protocol::v1_16_5::play::clientbound as cb;
let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
return Ok(());
};
let mut r = ghast_protocol::Reader::new(&raw.body);
let id = match raw.id {
cb::id::LOGIN => {
n.clear();
return Ok(());
}
cb::id::NAMED_ENTITY_SPAWN => {
let id = r.read_varint()?;
if t.get(id).is_some_and(ghast_entity::Entity::is_player) {
n.idents.spawned(id);
}
return Ok(());
}
cb::id::SPAWN_ENTITY | cb::id::SPAWN_ENTITY_EXPERIENCE_ORB => {
let id = r.read_varint()?;
n.map.remove(&id);
let me = self.rt.own_id;
if let Some(e) = t.get(id)
&& let Some(state) = spawned(e, |o| {
o == me || t.get(o).is_some_and(ghast_entity::Entity::is_player)
})
{
let filed = column_loaded(&self.world, e.position());
n.map.insert(
id,
Entry {
state,
no_physics: false,
filed,
hook: None,
},
);
} else {
return Ok(());
}
id
}
cb::id::ENTITY_VELOCITY => {
let id = r.read_varint()?;
let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
return Ok(());
};
match &mut en.state {
State::Projectile(p) => p.set_velocity_client(e.velocity()),
State::Drop(d) => d.set_vel(e.velocity()),
}
id
}
cb::id::REL_ENTITY_MOVE
| cb::id::ENTITY_MOVE_LOOK
| cb::id::ENTITY_LOOK
| cb::id::ENTITY
| cb::id::ENTITY_TELEPORT => {
let id = r.read_varint()?;
let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
return Ok(());
};
match &mut en.state {
_ if raw.id == cb::id::ENTITY => {}
State::Projectile(p) if p.kind() == ProjectileKind::FishingBobber => {}
State::Projectile(p) => {
p.set_pos(e.position());
p.set_rotation(e.yaw() % 360.0, e.pitch() % 360.0);
}
State::Drop(d) => d.set_pos(e.position()),
}
match &mut en.state {
State::Projectile(p) => p.set_on_ground(e.on_ground()),
State::Drop(d) => d.set_on_ground(e.on_ground()),
}
id
}
cb::id::ENTITY_METADATA => {
let id = r.read_varint()?;
if t.get(id).is_some_and(ghast_entity::Entity::is_player) {
n.idents
.eye_changed(id, t.client_eye_height(id).unwrap_or(1.62));
return Ok(());
}
let Some(en) = n.map.get_mut(&id) else {
return Ok(());
};
let p: cb::EntityMetadata = raw.decode_as()?;
let mut bitten = false;
for m in &p.metadata {
match (&mut en.state, m.key, &m.value) {
(State::Projectile(p), data_index::NO_GRAVITY, V::Boolean(b)) => {
p.set_no_gravity(*b);
}
(State::Drop(d), data_index::NO_GRAVITY, V::Boolean(b)) => {
d.set_no_gravity(*b);
}
(State::Projectile(p), data_index::FIRST, V::Byte(f))
if matches!(
p.kind(),
ProjectileKind::Arrow
| ProjectileKind::SpectralArrow
| ProjectileKind::Trident
) =>
{
en.no_physics = *f as u8 & 0x02 != 0;
}
(State::Projectile(p), data_index::ARROW_COLOR, V::VarInt(c))
if p.kind() == ProjectileKind::Arrow =>
{
p.set_tipped(*c != -1);
}
(State::Projectile(p), data_index::FIRST, V::Boolean(b))
if p.kind() == ProjectileKind::WitherSkull =>
{
p.set_dangerous(*b);
}
(State::Projectile(p), data_index::FIRST, V::VarInt(h))
if p.kind() == ProjectileKind::FishingBobber =>
{
en.hook = (*h > 0).then(|| *h - 1).filter(|&i| t.get(i).is_some());
if en.hook.is_none() {
p.set_hooked(None);
}
}
(State::Projectile(p), data_index::CAUGHT_FISH, V::Boolean(b))
if p.kind() == ProjectileKind::FishingBobber =>
{
p.set_biting(*b);
bitten = true;
}
(State::Drop(d), data_index::FIRST, V::VarInt(f))
if d.kind() == DropKind::PrimedTnt =>
{
d.set_fuse(*f);
}
(State::Drop(d), data_index::FIRST, V::Slot(s))
if d.kind() == DropKind::Item =>
{
d.set_fire_immune(fire_proof(s));
}
_ => {}
}
}
if !bitten {
return Ok(());
}
id
}
_ => return Ok(()),
};
if let Some(en) = n.map.get(&id) {
let (pos, vel, rot, g) = copy_of(&en.state, t.get(id));
t.client_simulated(id, pos, vel, rot, g);
}
Ok(())
}
#[cold]
#[inline(never)]
pub(super) fn nonliving_before_tick(n: &mut NonLiving16, t: &ghast_entity::v1_16_5::Tracker) {
n.pre.clear();
if !n.has_orbs() {
return;
}
n.pre.extend(
t.iter()
.filter(|e| e.is_player())
.map(|e| (e.id(), e.drawn_position())),
);
}
fn orb_players(&mut self) {
let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
return;
};
n.players.clear();
if !n.has_orbs() {
return;
}
let NonLiving16 {
map,
idents,
pre,
players,
own_before,
..
} = &mut **n;
let p = &self.player;
let me = t.self_id().unwrap_or(self.rt.own_id);
let own = OrbPlayer::new(me, p.pos, p.eye_height()).with_spectator(p.spectator);
let rank = |id| t.client_tick_rank(id).unwrap_or(u32::MAX);
players.push((own, *own_before, rank(me)));
for e in t.iter().filter(|e| e.is_player() && e.id() != me) {
let id = e.id();
let now = e.drawn_position();
let before = pre.iter().find(|q| q.0 == id).map_or(now, |q| q.1);
let ident = idents.of(id);
let uuid = e.uuid();
let spectator = t.tab_game_mode(&uuid) == Some(3);
let eye = t.client_eye_height(id).unwrap_or(1.62);
idents.seen(
ident,
PlayerFacts {
uuid,
#[cfg(ghast_modern)]
generation: 0,
spectator,
pos: now,
eye_height: eye,
},
);
players.push((
OrbPlayer::new(ident, now, eye).with_spectator(spectator),
before,
rank(id),
));
}
players[1..].sort_by_key(|q| q.2);
for en in map.values() {
let State::Drop(d) = &en.state else { continue };
let Some(ident) = d.following() else { continue };
if players.iter().any(|q| q.0.id == ident) {
continue;
}
let Some(mut f) = idents.facts(ident) else {
continue;
};
f.spectator = t.tab_game_mode(&f.uuid) == Some(3);
idents.seen(ident, f);
let gone = OrbPlayer::new(ident, f.pos, f.eye_height)
.with_spectator(f.spectator)
.with_removed(true);
players.push((gone, f.pos, u32::MAX));
}
idents.retain(|k| players.iter().any(|q| q.0.id == k));
}
#[cold]
#[inline(never)]
pub(super) fn tick_nonliving(&mut self) {
if self.nonliving.as_ref().is_none_or(|n| n.map.is_empty()) {
return;
}
self.orb_players();
let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
return;
};
let world = &self.world;
let me = self.rt.own_id;
let time = self.piston_time;
let NonLiving16 {
map,
updates,
discards,
players,
seen,
..
} = &mut **n;
updates.clear();
discards.clear();
map.retain(|&id, en| {
let Some(e) = t.get(id) else {
return false;
};
if e.vehicle().is_some() {
return true;
}
if !column_loaded(world, e.position()) {
en.filed = false;
return true;
}
if en.no_physics || !en.filed {
if let State::Projectile(p) = &mut en.state {
p.skip_tick();
}
en.filed = true;
return true;
}
match &mut en.state {
State::Projectile(p) => {
if p.kind() == ProjectileKind::FishingBobber {
let owner = e.data();
let pos = if owner == me {
Some([0.0; 3])
} else {
t.get(owner)
.filter(|o| o.is_player())
.map(ghast_entity::Entity::position)
};
p.set_owner_pos(pos);
p.set_game_time(time);
p.set_hooked(en.hook.map(|h| {
t.get(h)
.and_then(|he| {
he.size().map(|(_, height)| {
HookedEntity::new(he.drawn_position(), height)
})
})
.unwrap_or(HookedEntity::removed())
}));
}
projectile::tick_projectile(p, Side::Client, world);
if p.hooked().is_none() {
en.hook = None;
}
if p.removed() {
discards.push(id);
return false;
}
}
State::Drop(d) => {
seen.clear();
if d.kind() == DropKind::ExperienceOrb {
let at = t.client_tick_rank(id).unwrap_or(u32::MAX);
seen.extend(players.iter().map(|&(p, before, rank)| {
let mut p = p;
if rank > at {
p.pos = before;
}
p
}));
}
drop::tick_drop_near(d, Side::Client, world, seen);
if d.removed() {
discards.push(id);
return false;
}
}
}
let (pos, vel, rot, g) = copy_of(&en.state, Some(e));
en.filed = column_loaded(world, pos);
updates.push((id, pos, vel, rot, g));
true
});
for &(id, pos, vel, rot, g) in updates.iter() {
t.client_simulated(id, pos, vel, rot, g);
}
for &id in discards.iter() {
t.client_discarded(id);
}
}
}
fn column_loaded(w: &ghast_world::v1_16_5::World, pos: [f64; 3]) -> bool {
w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
}
fn copy_of(s: &State, e: Option<&ghast_entity::Entity>) -> ([f64; 3], [f64; 3], [f32; 2], bool) {
match s {
State::Projectile(p) => (p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()),
State::Drop(d) => (
d.pos(),
d.vel(),
e.map_or([0.0; 2], |e| [e.yaw(), e.pitch()]),
d.on_ground(),
),
}
}
fn spawned(e: &ghast_entity::Entity, owner_is_player: impl Fn(i32) -> bool) -> Option<State> {
let kind = Kind::of(ghast_entity::v1_16_5::info(e.entity_type())?.name)?;
let (pos, vel) = (e.position(), e.velocity());
let seed = i64::from(e.id());
Some(match kind {
Kind::Projectile(k) => {
if k == ProjectileKind::FishingBobber && !owner_is_player(e.data()) {
return None;
}
let mut p = Projectile::new(k, pos, vel).with_random_seed(seed);
if k == ProjectileKind::FishingBobber {
p = p.with_uuid_lsb(e.uuid().as_u64_pair().1 as i64);
}
p.set_vel([0.0; 3]);
p.set_rotation(e.yaw(), e.pitch());
State::Projectile(p)
}
Kind::Drop(k) => {
let d = Drop::new(
k,
pos,
if k == DropKind::FallingBlock {
[0.0; 3]
} else {
vel
},
)
.with_id(e.id())
.with_random_seed(seed);
State::Drop(if k == DropKind::FallingBlock {
d.with_block(
u16::try_from(e.data())
.ok()
.and_then(ghast_data::v1_16_5::BlockState::from_id)
.unwrap_or(ghast_data::v1_16_5::BlockState::AIR),
)
} else {
d
})
}
})
}
fn fire_proof(s: &ghast_protocol::types::slot::modern::Slot) -> bool {
s.item()
.and_then(|i| u16::try_from(i.id).ok())
.and_then(ghast_data::v1_16_5::Item::from_id)
.is_some_and(|i| {
let n = i.info().name;
n.starts_with("netherite_") || n == "ancient_debris"
})
}