Skip to main content

ghast_entity/
entity.rs

1//! Tracked entity state.
2
3use bytes::Bytes;
4use uuid::Uuid;
5
6/// What kind of entity this is, in the id space of the packet that spawned it.
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum EntityType {
10    /// A player (`named_entity_spawn`).
11    Player,
12    /// 1.8 – 1.12 mob id (`spawn_entity_living`; the entity registry id), e.g. 54 = zombie. See
13    /// `ghast_data::v1_8::entity(EntityKind::Mob, id)` / `ghast_data::v1_12::entity(..)`.
14    LegacyMob(u8),
15    /// 1.8 – 1.12 object type (`spawn_entity`), e.g. 2 = item, 1 = boat. See
16    /// `ghast_data::v1_8::entity(EntityKind::Object, id)` / `ghast_data::v1_12::entity(..)`.
17    LegacyObject(u8),
18    /// 1.8 – 1.12 experience orb (`spawn_entity_experience_orb`; orb value in [`Entity::data`]).
19    ExperienceOrb,
20    /// 1.8 – 1.12 painting (`spawn_entity_painting`).
21    Painting,
22    /// 1.13+ entity registry id (1.16.5: every spawn packet except players), see
23    /// `ghast_data::v1_16_5::entity`.
24    Registry(u16),
25}
26
27/// Version-independent classification of an entity.
28#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum EntityClass {
31    /// A player.
32    Player,
33    /// A dropped item (stack: [`Entity::item`]).
34    Item,
35    /// An experience orb (value: [`Entity::data`]).
36    ExperienceOrb,
37    /// A living non-player entity (spawned with the mob-spawn packet).
38    Mob,
39    /// Any other spawned object (boats, minecarts, arrows, falling blocks, armor stands in 1.8, ...).
40    Object,
41    /// Paintings.
42    Painting,
43}
44
45/// An item stack (equipment, item entities, metadata).
46///
47/// `damage` is the 1.8 damage/metadata value (always 0 in 1.13+, where damage lives in NBT).
48/// `nbt` is a private copy of the raw NBT bytes (never a view into a packet buffer).
49#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Item {
51    /// Item id.
52    pub id: i32,
53    /// Stack size.
54    pub count: i8,
55    /// 1.8 damage / metadata.
56    pub damage: i16,
57    /// Raw NBT (`None` = no tag).
58    pub nbt: Option<Bytes>,
59}
60
61/// An active status effect as the server reported it.
62#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Effect {
64    /// Effect id (1 = speed, 8 = jump boost, ...).
65    pub id: u8,
66    /// Amplifier (level - 1).
67    pub amplifier: i8,
68    /// Duration in ticks at the time of the packet (not counted down here).
69    pub duration: i32,
70    /// 1.8: bit 0 = hide particles. 1.12: bit 0 ambient, bit 1 show particles. 1.16: bit 0 ambient,
71    /// bit 1 show particles, bit 2 show icon.
72    pub flags: u8,
73}
74
75/// One entity metadata value (union of the 1.8, 1.12.2 and 1.16.5 serializer types; variants
76/// marked 1.16 also occur in 1.12 where 1.12 has that serializer).
77#[derive(Clone, Debug, PartialEq)]
78#[non_exhaustive]
79pub enum MetaValue {
80    /// Byte.
81    Byte(i8),
82    /// 1.8 short.
83    Short(i16),
84    /// 1.8 int.
85    Int(i32),
86    /// 1.16 VarInt.
87    VarInt(i32),
88    /// Float.
89    Float(f32),
90    /// String (1.8) / string (1.16).
91    String(Box<str>),
92    /// 1.16 chat component (raw JSON).
93    Chat(Box<str>),
94    /// 1.16 optional chat component (raw JSON).
95    OptChat(Option<Box<str>>),
96    /// Item stack (`None` = empty).
97    Item(Option<Item>),
98    /// 1.16 boolean.
99    Bool(bool),
100    /// Rotation (three floats).
101    Rotation([f32; 3]),
102    /// Block position.
103    BlockPos([i32; 3]),
104    /// 1.16 optional block position.
105    OptBlockPos(Option<[i32; 3]>),
106    /// 1.16 direction.
107    Direction(i32),
108    /// 1.16 optional UUID.
109    OptUuid(Option<Uuid>),
110    /// 1.16 optional block state (0 = none).
111    BlockState(i32),
112    /// 1.16 NBT (raw copy).
113    Nbt(Bytes),
114    /// 1.16 particle (only the particle type id is kept).
115    Particle(i32),
116    /// 1.16 villager data (type, profession, level).
117    VillagerData([i32; 3]),
118    /// 1.16 optional VarInt (0 = none, else value + 1).
119    OptVarInt(i32),
120    /// 1.16 / 26.1 pose.
121    Pose(i32),
122    /// 26.1 long (VarLong).
123    Long(i64),
124    /// 26.1 text component (the raw network NBT, copied).
125    Component(Bytes),
126    /// 26.1 optional text component (raw network NBT).
127    OptComponent(Option<Bytes>),
128    /// 26.1 item stack (`None` = empty; component patch copied out of the packet).
129    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
130    Stack(Option<ghast_protocol::types::slot::v775::ItemStack>),
131    /// 26.1 registry or enum value: `(serializer id, value)` (cat / cow / wolf / frog / pig /
132    /// chicken / zombie nautilus variants and sound variants, sniffer / armadillo / copper golem
133    /// states, humanoid arm).
134    Enum(u8, i32),
135    /// 26.1 vector (three floats).
136    Vector3([f32; 3]),
137    /// 26.1 quaternion (four floats).
138    Quaternion([f32; 4]),
139    /// 26.1 value kept as its raw wire bytes, copied: `(serializer id, bytes)` (optional block
140    /// state, particle, particle list, optional global position, painting variant, resolvable
141    /// profile).
142    Raw(u8, Bytes),
143}
144
145/// The metadata of one entity: `(index, value)` pairs, at most one per index, in arrival order.
146///
147/// Scalar updates overwrite in place (no allocation). The pairs live in one exact-size heap
148/// block (no spare capacity): an entity typically has a handful of entries, set once at spawn.
149#[derive(Clone, Debug, Default, PartialEq)]
150pub struct Metadata {
151    entries: Box<[(u8, MetaValue)]>,
152}
153
154impl Metadata {
155    /// The value at `index`.
156    #[must_use]
157    pub fn get(&self, index: u8) -> Option<&MetaValue> {
158        self.entries
159            .iter()
160            .find(|(i, _)| *i == index)
161            .map(|(_, v)| v)
162    }
163
164    /// Sets the value at `index`.
165    pub fn set(&mut self, index: u8, value: MetaValue) {
166        match self.entries.iter_mut().find(|(i, _)| *i == index) {
167            Some(slot) => slot.1 = value,
168            None => self.push_new(index, value),
169        }
170    }
171
172    /// Appends a new index (the block grows by exactly one entry).
173    #[cold]
174    #[inline(never)]
175    fn push_new(&mut self, index: u8, value: MetaValue) {
176        let mut v = Vec::with_capacity(self.entries.len() + 1);
177        v.extend(std::mem::take(&mut self.entries));
178        v.push((index, value));
179        self.entries = v.into_boxed_slice();
180    }
181
182    /// Applies `src` (drained) in order, as [`Metadata::set`] would one by one, skipping indices
183    /// `keep` refuses; grows the block at most once, to the exact size.
184    #[inline]
185    pub(crate) fn set_from(&mut self, src: &mut Vec<(u8, MetaValue)>, keep: impl Fn(u8) -> bool) {
186        let mut it = src.drain(..);
187        // Overwrites in place until the first index this entity does not have yet.
188        while let Some((i, v)) = it.next() {
189            if !keep(i) {
190                continue;
191            }
192            match self.entries.iter_mut().find(|(k, _)| *k == i) {
193                Some(slot) => slot.1 = v,
194                None => return self.grow_from((i, v), it, keep),
195            }
196        }
197    }
198
199    /// The rest of [`Metadata::set_from`] once a new index occurs: one exact-size block.
200    #[cold]
201    #[inline(never)]
202    fn grow_from(
203        &mut self,
204        first: (u8, MetaValue),
205        rest: std::vec::Drain<'_, (u8, MetaValue)>,
206        keep: impl Fn(u8) -> bool,
207    ) {
208        let tail = rest.as_slice();
209        let mut new = 1;
210        for (j, (i, _)) in tail.iter().enumerate() {
211            if keep(*i)
212                && *i != first.0
213                && !self.entries.iter().any(|(k, _)| k == i)
214                && !tail[..j].iter().any(|(k, _)| k == i)
215            {
216                new += 1;
217            }
218        }
219        let mut out = Vec::with_capacity(self.entries.len() + new);
220        out.extend(std::mem::take(&mut self.entries));
221        out.push(first);
222        for (i, v) in rest {
223            if !keep(i) {
224                continue;
225            }
226            match out.iter_mut().find(|(k, _)| *k == i) {
227                Some(slot) => slot.1 = v,
228                None => out.push((i, v)),
229            }
230        }
231        debug_assert_eq!(out.len(), out.capacity());
232        self.entries = out.into_boxed_slice();
233    }
234
235    /// All entries.
236    pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
237        self.entries.iter().map(|(i, v)| (*i, v))
238    }
239
240    /// Number of entries.
241    #[must_use]
242    pub fn len(&self) -> usize {
243        self.entries.len()
244    }
245
246    /// `true` when nothing has been received.
247    #[must_use]
248    pub fn is_empty(&self) -> bool {
249        self.entries.is_empty()
250    }
251
252    /// Byte at `index` (`Byte` values only).
253    #[must_use]
254    pub fn byte(&self, index: u8) -> Option<i8> {
255        match self.get(index)? {
256            MetaValue::Byte(b) => Some(*b),
257            _ => None,
258        }
259    }
260
261    /// Float at `index`.
262    #[must_use]
263    pub fn float(&self, index: u8) -> Option<f32> {
264        match self.get(index)? {
265            MetaValue::Float(f) => Some(*f),
266            _ => None,
267        }
268    }
269
270    /// Item at `index` (`Some(None)` = an empty stack was sent).
271    #[must_use]
272    pub fn item(&self, index: u8) -> Option<Option<&Item>> {
273        match self.get(index)? {
274            MetaValue::Item(i) => Some(i.as_ref()),
275            _ => None,
276        }
277    }
278
279    pub(crate) fn clear(&mut self) {
280        self.entries = Box::default();
281    }
282
283    pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
284        self.entries.iter_mut()
285    }
286
287    /// Heap bytes held (for the size tests).
288    #[cfg(test)]
289    pub(crate) fn heap_bytes(&self) -> usize {
290        std::mem::size_of_val::<[(u8, MetaValue)]>(&self.entries)
291    }
292}
293
294/// The rarely set parts of an entity (passengers, leash, effects), behind one pointer: most
295/// entities never have any of them.
296#[derive(Clone, Debug, Default, PartialEq)]
297pub(crate) struct Links {
298    /// 26.x players: the profile name the entity was created with, once its tab-list entry is
299    /// gone (vanilla's player keeps its `GameProfile`).
300    pub(crate) profile_name: Option<Box<str>>,
301    pub(crate) leash_holder: Option<i32>,
302    pub(crate) passengers: Vec<i32>,
303    pub(crate) effects: Vec<Effect>,
304    /// 1.16.5 leash knot moved by a position packet: the block it spawned on, whose box the
305    /// client keeps (only the knot's constructor builds one).
306    pub(crate) knot_block: Option<[i32; 3]>,
307}
308
309/// The protocol family an entity was tracked with (selects metadata indices and size rules).
310#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
311pub(crate) enum Era {
312    /// 1.8.x.
313    #[default]
314    V1_8,
315    /// 1.9 – 1.12 (implemented: 1.12.2).
316    V1_12,
317    /// 1.16.5.
318    V1_16,
319    /// 26.1.
320    V26,
321    /// 26.2 (the same modern state as 26.1, with 26.2's ids and sizes).
322    V26_2,
323    /// 26.3 (the same modern state, with 26.3's ids, sizes and movement model).
324    V26_3,
325}
326
327/// 1.16 registry ids used by [`Entity::class`].
328const ITEM_1_16: u16 = 37;
329const XP_ORB_1_16: u16 = 24;
330const PAINTING_1_16: u16 = 55;
331
332/// Number of equipment slots kept (1.16: main hand, off hand, feet, legs, chest, head;
333/// 26.x: also body (6) and saddle (7); 1.8: held, boots, leggings, chestplate, helmet in slots
334/// 0..=4).
335pub const EQUIPMENT_SLOTS: usize = 8;
336
337/// A tracked entity, as the vanilla client knows it from the server's packets.
338#[derive(Clone, Debug)]
339pub struct Entity {
340    pub(crate) id: i32,
341    pub(crate) uuid: Uuid,
342    pub(crate) ty: EntityType,
343    pub(crate) living: bool,
344    /// The tracker's protocol family.
345    pub(crate) era: Era,
346    /// Vanilla size table entry (resolved at spawn).
347    pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
348    pub(crate) pos: [f64; 3],
349    /// Per version: 1.8 the server position in 1/32 blocks (`serverPos`, i32 values); 1.9 – 1.12
350    /// the tracked position in 1/4096 blocks (`lfloor(x * 4096)`, plus moves); 26.1 the
351    /// `VecDeltaCodec` base (`f64` bits).
352    pub(crate) traced: [i64; 3],
353    pub(crate) yaw: f32,
354    pub(crate) pitch: f32,
355    pub(crate) head_yaw: f32,
356    pub(crate) velocity: [f64; 3],
357    pub(crate) on_ground: bool,
358    pub(crate) data: i32,
359    pub(crate) meta: Metadata,
360    pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
361    /// The vehicle's id (valid with `rides`; an `Option<i32>` would take 8 bytes here).
362    pub(crate) vehicle_id: i32,
363    /// [`Entity::RIDES`] (`vehicle_id` is valid), [`Entity::DEAD`] (a living entity's death
364    /// event: `LivingEntity.handleEntityEvent(3)` sets its health to 0), [`Entity::SIMULATED`]
365    /// (1.16: `pos` is the client's own copy, `traced` the tracked position's bits).
366    pub(crate) bits: u8,
367    /// Passengers, leash and effects (`None` = none of them).
368    pub(crate) links: Option<Box<Links>>,
369    /// The client view's drawn state and clocks (`None` without `track_client_motion`, and for
370    /// entities it does not keep).
371    pub(crate) client: Option<Box<crate::drawn::Client>>,
372    /// 26.1 client state (codec base, interpolation, size keys), boxed: one pointer for the
373    /// other versions.
374    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
375    pub(crate) m: crate::modern_state::Ext,
376}
377
378impl Entity {
379    pub(crate) fn new(id: i32, ty: EntityType) -> Self {
380        Entity {
381            id,
382            uuid: Uuid::nil(),
383            ty,
384            living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
385            era: Era::V1_8,
386            sizer: None,
387            pos: [0.0; 3],
388            traced: [0; 3],
389            yaw: 0.0,
390            pitch: 0.0,
391            head_yaw: 0.0,
392            velocity: [0.0; 3],
393            on_ground: false,
394            data: 0,
395            meta: Metadata::default(),
396            equipment: None,
397            links: None,
398            client: None,
399            vehicle_id: 0,
400            bits: 0,
401            #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
402            m: crate::modern_state::Ext::default(),
403        }
404    }
405
406    pub(crate) const RIDES: u8 = 1;
407    pub(crate) const DEAD: u8 = 2;
408    /// The client ran the entity's own tick (1.16 tracker's `client_simulated`): `pos` is the
409    /// client's position, the tracked (packet) position is kept in `traced` as `f64` bits.
410    #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
411    pub(crate) const SIMULATED: u8 = 4;
412
413    /// Whether it rides a vehicle.
414    #[inline]
415    pub(crate) fn rides(&self) -> bool {
416        self.bits & Self::RIDES != 0
417    }
418
419    /// A living entity's death event arrived ([`Entity::is_alive`]).
420    #[inline]
421    pub(crate) fn mark_dead(&mut self) {
422        if self.living {
423            self.bits |= Self::DEAD;
424        }
425    }
426
427    /// The links, allocated on first use.
428    #[inline]
429    pub(crate) fn links_mut(&mut self) -> &mut Links {
430        self.links.get_or_insert_with(Box::default)
431    }
432
433    /// Sets the vehicle (dismounting allocates nothing).
434    #[inline]
435    pub(crate) fn set_vehicle(&mut self, v: Option<i32>) {
436        if v.is_some() {
437            self.bits |= Self::RIDES;
438        } else {
439            self.bits &= !Self::RIDES;
440        }
441        self.vehicle_id = v.unwrap_or(0);
442    }
443
444    /// Takes the vehicle.
445    #[inline]
446    pub(crate) fn take_vehicle(&mut self) -> Option<i32> {
447        let v = self.vehicle();
448        self.set_vehicle(None);
449        v
450    }
451
452    /// Sets the leash holder.
453    #[inline]
454    pub(crate) fn set_leash_holder(&mut self, h: Option<i32>) {
455        match (&mut self.links, h) {
456            (Some(l), h) => l.leash_holder = h,
457            (None, None) => {}
458            (None, Some(_)) => self.links_mut().leash_holder = h,
459        }
460        self.tidy_links();
461    }
462
463    /// Takes the passenger list (no allocation when there is none).
464    #[inline]
465    pub(crate) fn take_passengers(&mut self) -> Vec<i32> {
466        let p = self
467            .links
468            .as_mut()
469            .map(|l| std::mem::take(&mut l.passengers))
470            .unwrap_or_default();
471        self.tidy_links();
472        p
473    }
474
475    /// Removes `id` from the passengers.
476    #[inline]
477    pub(crate) fn remove_passenger(&mut self, id: i32) {
478        if let Some(l) = &mut self.links {
479            l.passengers.retain(|&p| p != id);
480        }
481        self.tidy_links();
482    }
483
484    /// Replaces the passenger list.
485    #[inline]
486    pub(crate) fn set_passengers(&mut self, p: Vec<i32>) {
487        if !p.is_empty() || self.links.is_some() {
488            self.links_mut().passengers = p;
489        }
490        self.tidy_links();
491    }
492
493    /// Adds a passenger.
494    #[inline]
495    pub(crate) fn push_passenger(&mut self, id: i32) {
496        self.links_mut().passengers.push(id);
497    }
498
499    /// Clears the effects.
500    #[inline]
501    pub(crate) fn clear_effects(&mut self) {
502        if let Some(l) = &mut self.links {
503            l.effects = Vec::new();
504        }
505        self.tidy_links();
506    }
507
508    /// Frees the links once they are all empty.
509    #[inline]
510    pub(crate) fn tidy_links(&mut self) {
511        if self.links.as_ref().is_some_and(|l| {
512            l.leash_holder.is_none()
513                && l.profile_name.is_none()
514                && l.passengers.is_empty()
515                && l.effects.is_empty()
516                && l.knot_block.is_none()
517        }) {
518            self.links = None;
519        }
520    }
521
522    /// Heap bytes this entity holds (metadata block, equipment, links with their buffers, the
523    /// modern state; for the size tests).
524    #[cfg(test)]
525    pub(crate) fn heap_bytes(&self) -> usize {
526        let mut n = self.meta.heap_bytes();
527        if self.equipment.is_some() {
528            n += std::mem::size_of::<[Option<Item>; EQUIPMENT_SLOTS]>();
529        }
530        if let Some(l) = &self.links {
531            n += std::mem::size_of::<Links>()
532                + l.passengers.capacity() * 4
533                + l.effects.capacity() * std::mem::size_of::<Effect>();
534        }
535        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
536        if self.m.0.is_some() {
537            n += std::mem::size_of::<crate::modern_state::State>();
538        }
539        if self.client.is_some() {
540            n += std::mem::size_of::<crate::drawn::Client>();
541        }
542        n
543    }
544
545    /// Network entity id.
546    #[must_use]
547    pub fn id(&self) -> i32 {
548        self.id
549    }
550
551    /// UUID (nil for 1.8 entities other than players).
552    #[must_use]
553    pub fn uuid(&self) -> Uuid {
554        self.uuid
555    }
556
557    /// Type.
558    #[must_use]
559    pub fn entity_type(&self) -> EntityType {
560        self.ty
561    }
562
563    /// Vanilla `isAlive` as far as the packets tell: `false` for a living entity once it died
564    /// (its death event, which sets the health to 0 like `LivingEntity.handleEntityEvent(3)`, with
565    /// or without [`crate::Config::metadata`]; or the server's health is not above 0) — it stays
566    /// tracked during the death animation (about 20 ticks) until the server removes it, and
567    /// the vanilla client can still pick and hit it then (the hit does no damage). `true` for
568    /// other entities.
569    #[must_use]
570    pub fn is_alive(&self) -> bool {
571        if !self.living {
572            return true;
573        }
574        if self.bits & Self::DEAD != 0 {
575            return false;
576        }
577        let health: Option<f32> = match self.era {
578            #[cfg(feature = "v26_1")]
579            Era::V26 => return crate::v26_1::alive(self),
580            #[cfg(feature = "v26_2")]
581            Era::V26_2 => return crate::v26_2::alive(self),
582            #[cfg(feature = "v26_3")]
583            Era::V26_3 => return crate::v26_3::alive(self),
584            #[cfg(feature = "v1_8")]
585            Era::V1_8 => crate::v1_8::health(self),
586            #[cfg(feature = "v1_12")]
587            Era::V1_12 => crate::v1_12::health(self),
588            #[cfg(feature = "v1_16_5")]
589            Era::V1_16 => crate::v1_16_5::health(self),
590            // A tracker only stamps eras of versions compiled in.
591            #[allow(unreachable_patterns)]
592            _ => None,
593        };
594        // getHealth() > 0 (NaN is not alive)
595        health.is_none_or(|h| h > 0.0)
596    }
597
598    /// Version-independent class.
599    #[must_use]
600    pub fn class(&self) -> EntityClass {
601        #[cfg(feature = "v26_1")]
602        if self.era == Era::V26 {
603            return crate::v26_1::class(self);
604        }
605        #[cfg(feature = "v26_2")]
606        if self.era == Era::V26_2 {
607            return crate::v26_2::class(self);
608        }
609        #[cfg(feature = "v26_3")]
610        if self.era == Era::V26_3 {
611            return crate::v26_3::class(self);
612        }
613        match self.ty {
614            EntityType::Player => EntityClass::Player,
615            EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
616            EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
617                EntityClass::ExperienceOrb
618            }
619            EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
620            _ if self.living => EntityClass::Mob,
621            _ => EntityClass::Object,
622        }
623    }
624
625    /// The stack of an item entity (from metadata; `None` before the server sent it or when
626    /// metadata is not tracked; 1.16 always keeps it for item entities). Always `None` on 26.1,
627    /// whose stacks carry data components: see `v26_1::item_stack` / `v26_1::item_count`.
628    #[must_use]
629    pub fn item(&self) -> Option<&Item> {
630        if matches!(self.era, Era::V26 | Era::V26_2 | Era::V26_3) {
631            return None;
632        }
633        let index = match self.ty {
634            EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
635            EntityType::LegacyObject(2) => 10,
636            EntityType::Registry(ITEM_1_16) => 7,
637            _ => return None,
638        };
639        self.meta.item(index).flatten()
640    }
641
642    /// Vanilla client-side dimensions: the type's size from ghast-data (checked against the
643    /// oracle), with the variant the client applies from metadata (baby, slime size, wither
644    /// skeleton, elder guardian, small / marker armor stand, 1.16 player pose). `None` for
645    /// hanging entities (paintings, item frames, leash knots), whose box comes from facing.
646    ///
647    /// Variants vanilla applies on the entity's next client tick are applied immediately, and
648    /// the old-min-corner quirk after a resize is not modelled.
649    #[must_use]
650    pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
651        let vs = self.sizer?;
652        match self.era {
653            #[cfg(feature = "v1_8")]
654            Era::V1_8 => crate::v1_8::dimensions(self, vs),
655            #[cfg(feature = "v1_12")]
656            Era::V1_12 => crate::v1_12::dimensions(self, vs),
657            #[cfg(feature = "v1_16_5")]
658            Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
659            #[cfg(feature = "v26_1")]
660            Era::V26 => {
661                let _ = vs;
662                crate::v26_1::dimensions(self)
663            }
664            #[cfg(feature = "v26_2")]
665            Era::V26_2 => {
666                let _ = vs;
667                crate::v26_2::dimensions(self)
668            }
669            #[cfg(feature = "v26_3")]
670            Era::V26_3 => {
671                let _ = vs;
672                crate::v26_3::dimensions(self)
673            }
674            // A tracker only stamps eras of versions compiled in.
675            #[allow(unreachable_patterns)]
676            _ => None,
677        }
678    }
679
680    /// How much the crosshair pick grows this entity's box (vanilla `getCollisionBorderSize` /
681    /// `getTargetingMargin`, from the type's size table: 0.1 for most 1.8 types, 0 since 1.9,
682    /// 1.0 for fireballs); 0 when the type has no size entry.
683    #[must_use]
684    pub fn targeting_margin(&self) -> f32 {
685        #[cfg(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5"))]
686        if self.sizer.is_none()
687            && let Some(m) = crate::hanging::margin(self)
688        {
689            return m;
690        }
691        self.sizer.map_or(0.0, |s| s.targeting_margin)
692    }
693
694    /// `(width, height)` of [`Entity::dimensions`].
695    #[must_use]
696    pub fn size(&self) -> Option<(f32, f32)> {
697        self.dimensions().map(|d| (d.width, d.height))
698    }
699
700    /// Vanilla bounding box at the server position, `[min_x, min_y, min_z, max_x, max_y,
701    /// max_z]` (bit-exact `EntityDimensions::bounding_box`).
702    #[must_use]
703    pub fn bounding_box(&self) -> Option<[f64; 6]> {
704        let [x, y, z] = self.pos;
705        let Some(d) = self.dimensions() else {
706            return self.hanging_box(self.pos);
707        };
708        let b = d.bounding_box(x, y, z);
709        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
710    }
711
712    /// `true` for players.
713    #[must_use]
714    pub fn is_player(&self) -> bool {
715        self.ty == EntityType::Player
716    }
717
718    /// The **server position**: exactly the coordinates the vanilla client tracks from the
719    /// packets (1.8: `serverPos / 32.0`; 1.12: spawn / teleport coordinates, after a relative
720    /// move the tracked 1/4096 position; 1.16: the packet coordinates, rel moves applied in
721    /// 1/4096 fixed point). The vanilla client draws and picks the entity at a position that
722    /// interpolates towards this over 3 ticks: [`Entity::drawn_position`].
723    ///
724    /// **26.1** is different: this is the entity's *current* position as the client holds it
725    /// (`Entity.position()`): position packets of interpolated entities (living entities, boats,
726    /// minecarts) set a target the entity reaches over 3 calls of `v26_1::Tracker::tick`, others
727    /// move at once. That is the position vanilla's crosshair pick reads at tick time (with
728    /// [`Entity::bounding_box`]); the packet coordinates are `v26_1::server_position`.
729    #[must_use]
730    pub fn position(&self) -> [f64; 3] {
731        self.pos
732    }
733
734    /// The position the vanilla client draws this entity at and its crosshair pick reads: the
735    /// server position ([`Entity::position`]) followed over the client's interpolation steps.
736    ///
737    /// - **1.8.9 / 1.12.2** players, mobs and armor stands: a position packet sets a target that
738    ///   the entity reaches over 3 client ticks (1/3, 1/2, then the rest of the remaining way;
739    ///   every move, look or bare `entity` packet restarts the 3 steps), as
740    ///   `LivingEntity.tickMovement` / `OtherClientPlayerEntity.tickMovement` move it.
741    /// - **1.16.5** living entities, boats and shulkers: the 1.16 client view's position.
742    /// - **26.x**: [`Entity::position`] (the 26.x tracker already holds the client's position).
743    ///
744    /// Needs the tracker's `track_client_motion` (the ghast client turns it on with entity
745    /// tracking) and its `tick_client` once per client tick; otherwise, and for the entities the
746    /// view does not interpolate, this is [`Entity::position`].
747    #[must_use]
748    #[inline]
749    pub fn drawn_position(&self) -> [f64; 3] {
750        match &self.client {
751            Some(c) if c.lerp != crate::drawn::Lerp::External || c.bb.is_some() => c.pos,
752            _ => self.pos,
753        }
754    }
755
756    /// 1.8.9 / 1.12.2 client view: `onGround` of the client's copy — the last position packet's
757    /// flag ([`Entity::on_ground`]) unless a moving piston moved the copy since (its move sets
758    /// it). Without the client view: [`Entity::on_ground`].
759    #[must_use]
760    #[inline]
761    pub fn drawn_on_ground(&self) -> bool {
762        self.client
763            .as_deref()
764            .and_then(|c| c.ground)
765            .unwrap_or(self.on_ground)
766    }
767
768    /// 1.8.9 / 1.12.2 client view: `inWeb` of the client's copy (a moving piston's push into a
769    /// cobweb sets it, its next push uses and clears it). `false` without the client view.
770    #[must_use]
771    #[inline]
772    pub fn drawn_in_web(&self) -> bool {
773        self.client.as_deref().is_some_and(|c| c.in_web)
774    }
775
776    /// The bounding box at [`Entity::drawn_position`] (1.16.5: the client view's box, which
777    /// keeps its minimum corner after a growing resize until the next move), `[min_x, min_y,
778    /// min_z, max_x, max_y, max_z]`. This is the box vanilla's crosshair pick tests.
779    #[must_use]
780    #[inline]
781    pub fn drawn_bounding_box(&self) -> Option<[f64; 6]> {
782        let [x, y, z] = match self.client.as_deref() {
783            None => self.pos,
784            Some(c) if c.bb.is_some() => return c.bb,
785            Some(c) if c.lerp != crate::drawn::Lerp::External => c.pos,
786            Some(_) => self.pos,
787        };
788        let Some(d) = self.dimensions() else {
789            return self.hanging_box([x, y, z]);
790        };
791        let b = d.bounding_box(x, y, z);
792        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
793    }
794
795    /// The box of an entity without a centred dimensions box: 1.8 – 1.16 hanging entities
796    /// (paintings, item frames, leash knots: from the facing); 26.x also shulkers, interaction
797    /// entities and wind charges (`crate::modern_boxes`, at the entity's own position).
798    #[inline]
799    fn hanging_box(&self, p: [f64; 3]) -> Option<[f64; 6]> {
800        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
801        if let Some(k) = crate::modern_boxes::kind(self.m.td) {
802            return crate::modern_boxes::bounding_box(self, k);
803        }
804        #[cfg(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5"))]
805        {
806            crate::hanging::hanging_box(self, p)
807        }
808        #[cfg(not(any(feature = "v1_8", feature = "v1_12", feature = "v1_16_5")))]
809        {
810            let _ = p;
811            None
812        }
813    }
814
815    /// 1.8.9 / 1.12.2 client view: where vanilla's entity searches (`World.getEntitiesIn`, the
816    /// crosshair pick) meet this entity, as a sort key — chunk x, chunk z, section, then the
817    /// order in which the section's list took it (entities move between lists at their tick).
818    /// Entities overlapping on the pick ray are chosen by this order. `None` without the view.
819    #[must_use]
820    pub fn search_order(&self) -> Option<(i32, i32, i32, u32)> {
821        match &self.client {
822            Some(c) if c.lerp != crate::drawn::Lerp::External => Some(c.order()),
823            _ => None,
824        }
825    }
826
827    /// The drawn `(yaw, pitch)` (1.8.9 / 1.12.2 interpolated like [`Entity::drawn_position`];
828    /// otherwise [`Entity::yaw`] / [`Entity::pitch`]).
829    #[must_use]
830    pub fn drawn_rotation(&self) -> (f32, f32) {
831        match &self.client {
832            Some(c)
833                if matches!(
834                    c.lerp,
835                    crate::drawn::Lerp::Player
836                        | crate::drawn::Lerp::Living
837                        | crate::drawn::Lerp::Boat
838                        | crate::drawn::Lerp::Minecart
839                        | crate::drawn::Lerp::Boat12
840                        | crate::drawn::Lerp::Shulker
841                ) || (c.lerp == crate::drawn::Lerp::External && c.bb.is_some()) =>
842            {
843                (c.rot[0], c.rot[1])
844            }
845            _ => (self.yaw, self.pitch),
846        }
847    }
848
849    /// 1.8.9 / 1.12.2: the interpolation target and the client ticks left to reach it (`None`
850    /// when the drawn position is not interpolating or the view is off).
851    #[must_use]
852    pub fn interpolation(&self) -> Option<([f64; 3], u8)> {
853        let c = self.client.as_ref()?;
854        (c.steps > 0
855            && matches!(
856                c.lerp,
857                crate::drawn::Lerp::Player | crate::drawn::Lerp::Living
858            ))
859        .then_some((c.target, c.steps))
860    }
861
862    /// Estimated velocity in blocks per tick: the change between the last two server positions
863    /// divided by the ticks between them (players are often updated every 2 ticks). It is not
864    /// reset when the updates stop (compare [`Entity::position_tick`] with the current tick).
865    /// `None` without the client view (living entities only).
866    #[must_use]
867    pub fn estimated_velocity(&self) -> Option<[f64; 3]> {
868        self.client.as_ref().map(|c| c.velocity())
869    }
870
871    /// The tick (the clock the client sets with `Entities::set_tick`; the ghast client uses
872    /// `TickContext::tick`) of the last server position change (the spawn tick before the
873    /// first one). `None` without the client view (living entities only).
874    #[must_use]
875    pub fn position_tick(&self) -> Option<u64> {
876        self.client.as_ref().map(|c| c.moved)
877    }
878
879    /// The tick this entity spawned (a re-spawn with the same id is a new entity with a new
880    /// spawn tick). `None` without the client view (living entities only).
881    #[must_use]
882    pub fn spawn_tick(&self) -> Option<u64> {
883        self.client.as_ref().map(|c| c.spawned)
884    }
885
886    /// The tick of the last hurt (1.8: entity status 2; 1.12 / 1.16 also the thorns, drowning,
887    /// burning and berry-bush statuses; 26.x the damage event). `None` before the first one and
888    /// without the client view (living entities only).
889    #[must_use]
890    pub fn last_hurt_tick(&self) -> Option<u64> {
891        self.client.as_ref()?.hurt
892    }
893
894    /// The tracked server position in packet units (`tracedX` ...): 1.8 1/32 blocks, 1.12 1/4096
895    /// blocks (relative moves add to it even while the bot steers the entity). Not kept in 1.16
896    /// and later (1.16: `[0; 3]`, or the tracked position's `f64` bits for an entity the client
897    /// simulates, `v1_16_5::Tracker::client_simulated`).
898    #[must_use]
899    pub fn traced(&self) -> [i64; 3] {
900        self.traced
901    }
902
903    /// 1.8 only: the raw server position in 1/32 blocks (`[0; 3]` in 1.12 and 1.16).
904    #[must_use]
905    pub fn fixed_position(&self) -> [i32; 3] {
906        if self.era == Era::V1_8 {
907            self.traced.map(|t| t as i32)
908        } else {
909            [0; 3]
910        }
911    }
912
913    /// Body yaw in degrees as vanilla computes it from the angle byte (`b * 360 / 256f`).
914    #[must_use]
915    pub fn yaw(&self) -> f32 {
916        self.yaw
917    }
918
919    /// Pitch in degrees.
920    #[must_use]
921    pub fn pitch(&self) -> f32 {
922        self.pitch
923    }
924
925    /// Head yaw in degrees (from `entity_head_rotation`; mobs also at spawn).
926    #[must_use]
927    pub fn head_yaw(&self) -> f32 {
928        self.head_yaw
929    }
930
931    /// Last velocity the server sent (blocks per tick), from the spawn packet or
932    /// `entity_velocity`. Not integrated over time.
933    #[must_use]
934    pub fn velocity(&self) -> [f64; 3] {
935        self.velocity
936    }
937
938    /// On-ground flag of the last movement packet.
939    #[must_use]
940    pub fn on_ground(&self) -> bool {
941        self.on_ground
942    }
943
944    /// Spawn data: object data (1.8 objects / 1.16 `spawn_entity`), experience orb value,
945    /// painting direction.
946    #[must_use]
947    pub fn data(&self) -> i32 {
948        // Paintings keep their motive's size above the direction byte.
949        if matches!(
950            self.ty,
951            EntityType::Painting | EntityType::Registry(PAINTING_1_16)
952        ) {
953            return self.data & 0xff;
954        }
955        self.data
956    }
957
958    /// Entity this one rides.
959    #[must_use]
960    pub fn vehicle(&self) -> Option<i32> {
961        self.rides().then_some(self.vehicle_id)
962    }
963
964    /// Entities riding this one (1.8: at most one).
965    #[must_use]
966    pub fn passengers(&self) -> &[i32] {
967        self.links.as_ref().map_or(&[], |l| &l.passengers)
968    }
969
970    /// Entity holding this one's leash.
971    #[must_use]
972    pub fn leash_holder(&self) -> Option<i32> {
973        self.links.as_ref().and_then(|l| l.leash_holder)
974    }
975
976    /// Metadata (empty unless metadata tracking is enabled).
977    #[must_use]
978    pub fn metadata(&self) -> &Metadata {
979        &self.meta
980    }
981
982    /// Equipment slot (see [`EQUIPMENT_SLOTS`]); `None` if never sent or empty.
983    #[must_use]
984    pub fn equipment(&self, slot: usize) -> Option<&Item> {
985        self.equipment.as_ref()?.get(slot)?.as_ref()
986    }
987
988    /// Active effects as last reported.
989    #[must_use]
990    pub fn effects(&self) -> &[Effect] {
991        self.links.as_ref().map_or(&[], |l| &l.effects)
992    }
993
994    /// The effect with this id, if active.
995    #[must_use]
996    pub fn effect(&self, id: u8) -> Option<&Effect> {
997        self.effects().iter().find(|e| e.id == id)
998    }
999}
1000
1001#[cfg(test)]
1002mod tests {
1003    use super::*;
1004
1005    /// `set_from` is `set` applied in order: overwrites, new indices appended once, the last
1006    /// duplicate wins, refused indices are skipped; the block is exact-size.
1007    #[test]
1008    fn metadata_set_from_matches_set() {
1009        let batches: [&[(u8, i8)]; 4] = [
1010            &[(0, 1), (9, 2), (0, 3)],
1011            &[(9, 4)],
1012            &[(5, 5), (2, 6), (5, 7), (9, 8)],
1013            &[(7, 9), (3, 10)],
1014        ];
1015        let keep = |i: u8| i != 3;
1016        let (mut a, mut b) = (Metadata::default(), Metadata::default());
1017        for batch in batches {
1018            let mut src: Vec<(u8, MetaValue)> = batch
1019                .iter()
1020                .map(|&(i, v)| (i, MetaValue::Byte(v)))
1021                .collect();
1022            for (i, v) in src.clone() {
1023                if keep(i) {
1024                    a.set(i, v);
1025                }
1026            }
1027            b.set_from(&mut src, keep);
1028            assert!(src.is_empty());
1029            assert_eq!(a, b);
1030        }
1031        let got: Vec<(u8, i8)> = b
1032            .iter()
1033            .map(|(i, v)| match v {
1034                MetaValue::Byte(x) => (i, *x),
1035                _ => unreachable!(),
1036            })
1037            .collect();
1038        assert_eq!(got, [(0, 3), (9, 8), (5, 7), (2, 6), (7, 9)]);
1039        assert_eq!(b.heap_bytes(), 5 * std::mem::size_of::<(u8, MetaValue)>());
1040        b.clear();
1041        assert!(b.is_empty() && b.heap_bytes() == 0);
1042    }
1043
1044    #[test]
1045    fn links_are_freed_when_empty() {
1046        let mut e = Entity::new(1, EntityType::Player);
1047        e.set_vehicle(None);
1048        e.set_leash_holder(None);
1049        e.clear_effects();
1050        assert!(e.links.is_none());
1051        e.set_vehicle(Some(2));
1052        e.push_passenger(3);
1053        assert_eq!((e.vehicle(), e.passengers()), (Some(2), &[3][..]));
1054        e.set_vehicle(None);
1055        e.remove_passenger(3);
1056        assert!(e.links.is_none());
1057        assert_eq!(e.take_passengers(), Vec::<i32>::new());
1058    }
1059}