use bytes::Bytes;
use uuid::Uuid;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EntityType {
Player,
LegacyMob(u8),
LegacyObject(u8),
ExperienceOrb,
Painting,
Registry(u16),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EntityClass {
Player,
Item,
ExperienceOrb,
Mob,
Object,
Painting,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Item {
pub id: i32,
pub count: i8,
pub damage: i16,
pub nbt: Option<Bytes>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Effect {
pub id: u8,
pub amplifier: i8,
pub duration: i32,
pub flags: u8,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum MetaValue {
Byte(i8),
Short(i16),
Int(i32),
VarInt(i32),
Float(f32),
String(Box<str>),
Chat(Box<str>),
OptChat(Option<Box<str>>),
Item(Option<Item>),
Bool(bool),
Rotation([f32; 3]),
BlockPos([i32; 3]),
OptBlockPos(Option<[i32; 3]>),
Direction(i32),
OptUuid(Option<Uuid>),
BlockState(i32),
Nbt(Bytes),
Particle(i32),
VillagerData([i32; 3]),
OptVarInt(i32),
Pose(i32),
Long(i64),
Component(Bytes),
OptComponent(Option<Bytes>),
#[cfg(any(feature = "v26_1", feature = "v26_2"))]
Stack(Option<ghast_protocol::types::slot::v775::ItemStack>),
Enum(u8, i32),
Vector3([f32; 3]),
Quaternion([f32; 4]),
Raw(u8, Bytes),
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Metadata {
entries: Box<[(u8, MetaValue)]>,
}
impl Metadata {
#[must_use]
pub fn get(&self, index: u8) -> Option<&MetaValue> {
self.entries
.iter()
.find(|(i, _)| *i == index)
.map(|(_, v)| v)
}
pub fn set(&mut self, index: u8, value: MetaValue) {
match self.entries.iter_mut().find(|(i, _)| *i == index) {
Some(slot) => slot.1 = value,
None => self.push_new(index, value),
}
}
#[cold]
#[inline(never)]
fn push_new(&mut self, index: u8, value: MetaValue) {
let mut v = Vec::with_capacity(self.entries.len() + 1);
v.extend(std::mem::take(&mut self.entries));
v.push((index, value));
self.entries = v.into_boxed_slice();
}
#[inline]
pub(crate) fn set_from(&mut self, src: &mut Vec<(u8, MetaValue)>, keep: impl Fn(u8) -> bool) {
let mut it = src.drain(..);
while let Some((i, v)) = it.next() {
if !keep(i) {
continue;
}
match self.entries.iter_mut().find(|(k, _)| *k == i) {
Some(slot) => slot.1 = v,
None => return self.grow_from((i, v), it, keep),
}
}
}
#[cold]
#[inline(never)]
fn grow_from(
&mut self,
first: (u8, MetaValue),
rest: std::vec::Drain<'_, (u8, MetaValue)>,
keep: impl Fn(u8) -> bool,
) {
let tail = rest.as_slice();
let mut new = 1;
for (j, (i, _)) in tail.iter().enumerate() {
if keep(*i)
&& *i != first.0
&& !self.entries.iter().any(|(k, _)| k == i)
&& !tail[..j].iter().any(|(k, _)| k == i)
{
new += 1;
}
}
let mut out = Vec::with_capacity(self.entries.len() + new);
out.extend(std::mem::take(&mut self.entries));
out.push(first);
for (i, v) in rest {
if !keep(i) {
continue;
}
match out.iter_mut().find(|(k, _)| *k == i) {
Some(slot) => slot.1 = v,
None => out.push((i, v)),
}
}
debug_assert_eq!(out.len(), out.capacity());
self.entries = out.into_boxed_slice();
}
pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
self.entries.iter().map(|(i, v)| (*i, v))
}
#[must_use]
pub fn len(&self) -> usize {
self.entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
#[must_use]
pub fn byte(&self, index: u8) -> Option<i8> {
match self.get(index)? {
MetaValue::Byte(b) => Some(*b),
_ => None,
}
}
#[must_use]
pub fn float(&self, index: u8) -> Option<f32> {
match self.get(index)? {
MetaValue::Float(f) => Some(*f),
_ => None,
}
}
#[must_use]
pub fn item(&self, index: u8) -> Option<Option<&Item>> {
match self.get(index)? {
MetaValue::Item(i) => Some(i.as_ref()),
_ => None,
}
}
pub(crate) fn clear(&mut self) {
self.entries = Box::default();
}
pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
self.entries.iter_mut()
}
#[cfg(test)]
pub(crate) fn heap_bytes(&self) -> usize {
std::mem::size_of_val::<[(u8, MetaValue)]>(&self.entries)
}
}
#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct Links {
pub(crate) profile_name: Option<Box<str>>,
pub(crate) leash_holder: Option<i32>,
pub(crate) passengers: Vec<i32>,
pub(crate) effects: Vec<Effect>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub(crate) enum Era {
#[default]
V1_8,
V1_12,
V1_16,
V26,
V26_2,
}
const ITEM_1_16: u16 = 37;
const XP_ORB_1_16: u16 = 24;
const PAINTING_1_16: u16 = 55;
pub const EQUIPMENT_SLOTS: usize = 6;
#[derive(Clone, Debug)]
pub struct Entity {
pub(crate) id: i32,
pub(crate) uuid: Uuid,
pub(crate) ty: EntityType,
pub(crate) living: bool,
pub(crate) era: Era,
pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
pub(crate) pos: [f64; 3],
pub(crate) traced: [i64; 3],
pub(crate) yaw: f32,
pub(crate) pitch: f32,
pub(crate) head_yaw: f32,
pub(crate) velocity: [f64; 3],
pub(crate) on_ground: bool,
pub(crate) data: i32,
pub(crate) meta: Metadata,
pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
pub(crate) vehicle_id: i32,
pub(crate) bits: u8,
pub(crate) links: Option<Box<Links>>,
#[cfg(any(feature = "v26_1", feature = "v26_2"))]
pub(crate) m: crate::modern_state::Ext,
}
impl Entity {
pub(crate) fn new(id: i32, ty: EntityType) -> Self {
Entity {
id,
uuid: Uuid::nil(),
ty,
living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
era: Era::V1_8,
sizer: None,
pos: [0.0; 3],
traced: [0; 3],
yaw: 0.0,
pitch: 0.0,
head_yaw: 0.0,
velocity: [0.0; 3],
on_ground: false,
data: 0,
meta: Metadata::default(),
equipment: None,
links: None,
vehicle_id: 0,
bits: 0,
#[cfg(any(feature = "v26_1", feature = "v26_2"))]
m: crate::modern_state::Ext::default(),
}
}
pub(crate) const RIDES: u8 = 1;
pub(crate) const DEAD: u8 = 2;
#[inline]
pub(crate) fn rides(&self) -> bool {
self.bits & Self::RIDES != 0
}
#[inline]
pub(crate) fn mark_dead(&mut self) {
if self.living {
self.bits |= Self::DEAD;
}
}
#[inline]
pub(crate) fn links_mut(&mut self) -> &mut Links {
self.links.get_or_insert_with(Box::default)
}
#[inline]
pub(crate) fn set_vehicle(&mut self, v: Option<i32>) {
if v.is_some() {
self.bits |= Self::RIDES;
} else {
self.bits &= !Self::RIDES;
}
self.vehicle_id = v.unwrap_or(0);
}
#[inline]
pub(crate) fn take_vehicle(&mut self) -> Option<i32> {
let v = self.vehicle();
self.set_vehicle(None);
v
}
#[inline]
pub(crate) fn set_leash_holder(&mut self, h: Option<i32>) {
match (&mut self.links, h) {
(Some(l), h) => l.leash_holder = h,
(None, None) => {}
(None, Some(_)) => self.links_mut().leash_holder = h,
}
self.tidy_links();
}
#[inline]
pub(crate) fn take_passengers(&mut self) -> Vec<i32> {
let p = self
.links
.as_mut()
.map(|l| std::mem::take(&mut l.passengers))
.unwrap_or_default();
self.tidy_links();
p
}
#[inline]
pub(crate) fn remove_passenger(&mut self, id: i32) {
if let Some(l) = &mut self.links {
l.passengers.retain(|&p| p != id);
}
self.tidy_links();
}
#[inline]
pub(crate) fn set_passengers(&mut self, p: Vec<i32>) {
if !p.is_empty() || self.links.is_some() {
self.links_mut().passengers = p;
}
self.tidy_links();
}
#[inline]
pub(crate) fn push_passenger(&mut self, id: i32) {
self.links_mut().passengers.push(id);
}
#[inline]
pub(crate) fn clear_effects(&mut self) {
if let Some(l) = &mut self.links {
l.effects = Vec::new();
}
self.tidy_links();
}
#[inline]
pub(crate) fn tidy_links(&mut self) {
if self.links.as_ref().is_some_and(|l| {
l.leash_holder.is_none()
&& l.profile_name.is_none()
&& l.passengers.is_empty()
&& l.effects.is_empty()
}) {
self.links = None;
}
}
#[cfg(test)]
pub(crate) fn heap_bytes(&self) -> usize {
let mut n = self.meta.heap_bytes();
if self.equipment.is_some() {
n += std::mem::size_of::<[Option<Item>; EQUIPMENT_SLOTS]>();
}
if let Some(l) = &self.links {
n += std::mem::size_of::<Links>()
+ l.passengers.capacity() * 4
+ l.effects.capacity() * std::mem::size_of::<Effect>();
}
#[cfg(any(feature = "v26_1", feature = "v26_2"))]
if self.m.0.is_some() {
n += std::mem::size_of::<crate::modern_state::State>();
}
n
}
#[must_use]
pub fn id(&self) -> i32 {
self.id
}
#[must_use]
pub fn uuid(&self) -> Uuid {
self.uuid
}
#[must_use]
pub fn entity_type(&self) -> EntityType {
self.ty
}
#[must_use]
pub fn is_alive(&self) -> bool {
if !self.living {
return true;
}
if self.bits & Self::DEAD != 0 {
return false;
}
let health: Option<f32> = match self.era {
#[cfg(feature = "v26_1")]
Era::V26 => return crate::v26_1::alive(self),
#[cfg(feature = "v26_2")]
Era::V26_2 => return crate::v26_2::alive(self),
#[cfg(feature = "v1_8")]
Era::V1_8 => crate::v1_8::health(self),
#[cfg(feature = "v1_12")]
Era::V1_12 => crate::v1_12::health(self),
#[cfg(feature = "v1_16_5")]
Era::V1_16 => crate::v1_16_5::health(self),
#[allow(unreachable_patterns)]
_ => None,
};
health.is_none_or(|h| h > 0.0)
}
#[must_use]
pub fn class(&self) -> EntityClass {
#[cfg(feature = "v26_1")]
if self.era == Era::V26 {
return crate::v26_1::class(self);
}
#[cfg(feature = "v26_2")]
if self.era == Era::V26_2 {
return crate::v26_2::class(self);
}
match self.ty {
EntityType::Player => EntityClass::Player,
EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
EntityClass::ExperienceOrb
}
EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
_ if self.living => EntityClass::Mob,
_ => EntityClass::Object,
}
}
#[must_use]
pub fn item(&self) -> Option<&Item> {
if matches!(self.era, Era::V26 | Era::V26_2) {
return None;
}
let index = match self.ty {
EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
EntityType::LegacyObject(2) => 10,
EntityType::Registry(ITEM_1_16) => 7,
_ => return None,
};
self.meta.item(index).flatten()
}
#[must_use]
pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
let vs = self.sizer?;
match self.era {
#[cfg(feature = "v1_8")]
Era::V1_8 => crate::v1_8::dimensions(self, vs),
#[cfg(feature = "v1_12")]
Era::V1_12 => crate::v1_12::dimensions(self, vs),
#[cfg(feature = "v1_16_5")]
Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
#[cfg(feature = "v26_1")]
Era::V26 => {
let _ = vs;
crate::v26_1::dimensions(self)
}
#[cfg(feature = "v26_2")]
Era::V26_2 => {
let _ = vs;
crate::v26_2::dimensions(self)
}
#[allow(unreachable_patterns)]
_ => None,
}
}
#[must_use]
pub fn targeting_margin(&self) -> f32 {
self.sizer.map_or(0.0, |s| s.targeting_margin)
}
#[must_use]
pub fn size(&self) -> Option<(f32, f32)> {
self.dimensions().map(|d| (d.width, d.height))
}
#[must_use]
pub fn bounding_box(&self) -> Option<[f64; 6]> {
let [x, y, z] = self.pos;
let b = self.dimensions()?.bounding_box(x, y, z);
Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
}
#[must_use]
pub fn is_player(&self) -> bool {
self.ty == EntityType::Player
}
#[must_use]
pub fn position(&self) -> [f64; 3] {
self.pos
}
#[must_use]
pub fn fixed_position(&self) -> [i32; 3] {
if self.era == Era::V1_8 {
self.traced.map(|t| t as i32)
} else {
[0; 3]
}
}
#[must_use]
pub fn yaw(&self) -> f32 {
self.yaw
}
#[must_use]
pub fn pitch(&self) -> f32 {
self.pitch
}
#[must_use]
pub fn head_yaw(&self) -> f32 {
self.head_yaw
}
#[must_use]
pub fn velocity(&self) -> [f64; 3] {
self.velocity
}
#[must_use]
pub fn on_ground(&self) -> bool {
self.on_ground
}
#[must_use]
pub fn data(&self) -> i32 {
self.data
}
#[must_use]
pub fn vehicle(&self) -> Option<i32> {
self.rides().then_some(self.vehicle_id)
}
#[must_use]
pub fn passengers(&self) -> &[i32] {
self.links.as_ref().map_or(&[], |l| &l.passengers)
}
#[must_use]
pub fn leash_holder(&self) -> Option<i32> {
self.links.as_ref().and_then(|l| l.leash_holder)
}
#[must_use]
pub fn metadata(&self) -> &Metadata {
&self.meta
}
#[must_use]
pub fn equipment(&self, slot: usize) -> Option<&Item> {
self.equipment.as_ref()?.get(slot)?.as_ref()
}
#[must_use]
pub fn effects(&self) -> &[Effect] {
self.links.as_ref().map_or(&[], |l| &l.effects)
}
#[must_use]
pub fn effect(&self, id: u8) -> Option<&Effect> {
self.effects().iter().find(|e| e.id == id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn metadata_set_from_matches_set() {
let batches: [&[(u8, i8)]; 4] = [
&[(0, 1), (9, 2), (0, 3)],
&[(9, 4)],
&[(5, 5), (2, 6), (5, 7), (9, 8)],
&[(7, 9), (3, 10)],
];
let keep = |i: u8| i != 3;
let (mut a, mut b) = (Metadata::default(), Metadata::default());
for batch in batches {
let mut src: Vec<(u8, MetaValue)> = batch
.iter()
.map(|&(i, v)| (i, MetaValue::Byte(v)))
.collect();
for (i, v) in src.clone() {
if keep(i) {
a.set(i, v);
}
}
b.set_from(&mut src, keep);
assert!(src.is_empty());
assert_eq!(a, b);
}
let got: Vec<(u8, i8)> = b
.iter()
.map(|(i, v)| match v {
MetaValue::Byte(x) => (i, *x),
_ => unreachable!(),
})
.collect();
assert_eq!(got, [(0, 3), (9, 8), (5, 7), (2, 6), (7, 9)]);
assert_eq!(b.heap_bytes(), 5 * std::mem::size_of::<(u8, MetaValue)>());
b.clear();
assert!(b.is_empty() && b.heap_bytes() == 0);
}
#[test]
fn links_are_freed_when_empty() {
let mut e = Entity::new(1, EntityType::Player);
e.set_vehicle(None);
e.set_leash_holder(None);
e.clear_effects();
assert!(e.links.is_none());
e.set_vehicle(Some(2));
e.push_passenger(3);
assert_eq!((e.vehicle(), e.passengers()), (Some(2), &[3][..]));
e.set_vehicle(None);
e.remove_passenger(3);
assert!(e.links.is_none());
assert_eq!(e.take_passengers(), Vec::<i32>::new());
}
}