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)]
8pub enum EntityType {
9    /// A player (`named_entity_spawn`).
10    Player,
11    /// 1.8 mob id (`spawn_entity_living`), e.g. 54 = zombie. See `ghast_data::v1_8::entity(EntityKind::Mob, id)`.
12    LegacyMob(u8),
13    /// 1.8 object id (`spawn_entity`), e.g. 2 = item, 1 = boat. See `ghast_data::v1_8::entity(EntityKind::Object, id)`.
14    LegacyObject(u8),
15    /// 1.8 experience orb (`spawn_entity_experience_orb`; orb value in [`Entity::data`]).
16    ExperienceOrb,
17    /// 1.8 painting (`spawn_entity_painting`).
18    Painting,
19    /// 1.13+ entity registry id (1.16.5: every spawn packet except players), see
20    /// `ghast_data::v1_16_5::entity`.
21    Registry(u16),
22}
23
24/// Version-independent classification of an entity.
25#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
26pub enum EntityClass {
27    /// A player.
28    Player,
29    /// A dropped item (stack: [`Entity::item`]).
30    Item,
31    /// An experience orb (value: [`Entity::data`]).
32    ExperienceOrb,
33    /// A living non-player entity (spawned with the mob-spawn packet).
34    Mob,
35    /// Any other spawned object (boats, minecarts, arrows, falling blocks, armor stands in 1.8, ...).
36    Object,
37    /// Paintings.
38    Painting,
39}
40
41/// An item stack (equipment, item entities, metadata).
42///
43/// `damage` is the 1.8 damage/metadata value (always 0 in 1.13+, where damage lives in NBT).
44/// `nbt` is a private copy of the raw NBT bytes (never a view into a packet buffer).
45#[derive(Clone, Debug, PartialEq, Eq)]
46pub struct Item {
47    /// Item id.
48    pub id: i32,
49    /// Stack size.
50    pub count: i8,
51    /// 1.8 damage / metadata.
52    pub damage: i16,
53    /// Raw NBT (`None` = no tag).
54    pub nbt: Option<Bytes>,
55}
56
57/// An active status effect as the server reported it.
58#[derive(Clone, Copy, Debug, PartialEq, Eq)]
59pub struct Effect {
60    /// Effect id (1 = speed, 8 = jump boost, ...).
61    pub id: u8,
62    /// Amplifier (level - 1).
63    pub amplifier: i8,
64    /// Duration in ticks at the time of the packet (not counted down here).
65    pub duration: i32,
66    /// 1.8: bit 0 = hide particles. 1.16: bit 0 ambient, bit 1 show particles, bit 2 show icon.
67    pub flags: u8,
68}
69
70/// One entity metadata value (union of the 1.8 and 1.16.5 serializer types).
71#[derive(Clone, Debug, PartialEq)]
72pub enum MetaValue {
73    /// Byte.
74    Byte(i8),
75    /// 1.8 short.
76    Short(i16),
77    /// 1.8 int.
78    Int(i32),
79    /// 1.16 VarInt.
80    VarInt(i32),
81    /// Float.
82    Float(f32),
83    /// String (1.8) / string (1.16).
84    String(Box<str>),
85    /// 1.16 chat component (raw JSON).
86    Chat(Box<str>),
87    /// 1.16 optional chat component (raw JSON).
88    OptChat(Option<Box<str>>),
89    /// Item stack (`None` = empty).
90    Item(Option<Item>),
91    /// 1.16 boolean.
92    Bool(bool),
93    /// Rotation (three floats).
94    Rotation([f32; 3]),
95    /// Block position.
96    BlockPos([i32; 3]),
97    /// 1.16 optional block position.
98    OptBlockPos(Option<[i32; 3]>),
99    /// 1.16 direction.
100    Direction(i32),
101    /// 1.16 optional UUID.
102    OptUuid(Option<Uuid>),
103    /// 1.16 optional block state (0 = none).
104    BlockState(i32),
105    /// 1.16 NBT (raw copy).
106    Nbt(Bytes),
107    /// 1.16 particle (only the particle type id is kept).
108    Particle(i32),
109    /// 1.16 villager data (type, profession, level).
110    VillagerData([i32; 3]),
111    /// 1.16 optional VarInt (0 = none, else value + 1).
112    OptVarInt(i32),
113    /// 1.16 pose.
114    Pose(i32),
115}
116
117/// The metadata of one entity: `(index, value)` pairs, at most one per index, in arrival order.
118///
119/// Scalar updates overwrite in place (no allocation).
120#[derive(Clone, Debug, Default, PartialEq)]
121pub struct Metadata {
122    entries: Vec<(u8, MetaValue)>,
123}
124
125impl Metadata {
126    /// The value at `index`.
127    #[must_use]
128    pub fn get(&self, index: u8) -> Option<&MetaValue> {
129        self.entries
130            .iter()
131            .find(|(i, _)| *i == index)
132            .map(|(_, v)| v)
133    }
134
135    /// Sets the value at `index`.
136    pub fn set(&mut self, index: u8, value: MetaValue) {
137        match self.entries.iter_mut().find(|(i, _)| *i == index) {
138            Some(slot) => slot.1 = value,
139            None => self.entries.push((index, value)),
140        }
141    }
142
143    /// All entries.
144    pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
145        self.entries.iter().map(|(i, v)| (*i, v))
146    }
147
148    /// Number of entries.
149    #[must_use]
150    pub fn len(&self) -> usize {
151        self.entries.len()
152    }
153
154    /// `true` when nothing has been received.
155    #[must_use]
156    pub fn is_empty(&self) -> bool {
157        self.entries.is_empty()
158    }
159
160    /// Byte at `index` (`Byte` values only).
161    #[must_use]
162    pub fn byte(&self, index: u8) -> Option<i8> {
163        match self.get(index)? {
164            MetaValue::Byte(b) => Some(*b),
165            _ => None,
166        }
167    }
168
169    /// Float at `index`.
170    #[must_use]
171    pub fn float(&self, index: u8) -> Option<f32> {
172        match self.get(index)? {
173            MetaValue::Float(f) => Some(*f),
174            _ => None,
175        }
176    }
177
178    /// Item at `index` (`Some(None)` = an empty stack was sent).
179    #[must_use]
180    pub fn item(&self, index: u8) -> Option<Option<&Item>> {
181        match self.get(index)? {
182            MetaValue::Item(i) => Some(i.as_ref()),
183            _ => None,
184        }
185    }
186
187    pub(crate) fn clear(&mut self) {
188        self.entries.clear();
189    }
190
191    pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
192        self.entries.iter_mut()
193    }
194}
195
196/// 1.16 registry ids used by [`Entity::class`].
197const ITEM_1_16: u16 = 37;
198const XP_ORB_1_16: u16 = 24;
199const PAINTING_1_16: u16 = 55;
200
201/// Number of equipment slots kept (1.16: main hand, off hand, feet, legs, chest, head;
202/// 1.8: held, boots, leggings, chestplate, helmet in slots 0..=4).
203pub const EQUIPMENT_SLOTS: usize = 6;
204
205/// A tracked entity, as the vanilla client knows it from the server's packets.
206#[derive(Clone, Debug)]
207pub struct Entity {
208    pub(crate) id: i32,
209    pub(crate) uuid: Uuid,
210    pub(crate) ty: EntityType,
211    pub(crate) living: bool,
212    /// Vanilla size table entry (resolved at spawn) and whether it is a 1.16 entry.
213    pub(crate) sizer: Option<(&'static ghast_data::VanillaEntitySize, bool)>,
214    pub(crate) pos: [f64; 3],
215    pub(crate) fixed: [i32; 3],
216    pub(crate) yaw: f32,
217    pub(crate) pitch: f32,
218    pub(crate) head_yaw: f32,
219    pub(crate) velocity: [f64; 3],
220    pub(crate) on_ground: bool,
221    pub(crate) data: i32,
222    pub(crate) vehicle: Option<i32>,
223    pub(crate) passengers: Vec<i32>,
224    pub(crate) leash_holder: Option<i32>,
225    pub(crate) meta: Metadata,
226    pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
227    pub(crate) effects: Vec<Effect>,
228}
229
230impl Entity {
231    pub(crate) fn new(id: i32, ty: EntityType) -> Self {
232        Entity {
233            id,
234            uuid: Uuid::nil(),
235            ty,
236            living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
237            sizer: None,
238            pos: [0.0; 3],
239            fixed: [0; 3],
240            yaw: 0.0,
241            pitch: 0.0,
242            head_yaw: 0.0,
243            velocity: [0.0; 3],
244            on_ground: false,
245            data: 0,
246            vehicle: None,
247            passengers: Vec::new(),
248            leash_holder: None,
249            meta: Metadata::default(),
250            equipment: None,
251            effects: Vec::new(),
252        }
253    }
254
255    /// Network entity id.
256    #[must_use]
257    pub fn id(&self) -> i32 {
258        self.id
259    }
260
261    /// UUID (nil for 1.8 entities other than players).
262    #[must_use]
263    pub fn uuid(&self) -> Uuid {
264        self.uuid
265    }
266
267    /// Type.
268    #[must_use]
269    pub fn entity_type(&self) -> EntityType {
270        self.ty
271    }
272
273    /// Version-independent class.
274    #[must_use]
275    pub fn class(&self) -> EntityClass {
276        match self.ty {
277            EntityType::Player => EntityClass::Player,
278            EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
279            EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
280                EntityClass::ExperienceOrb
281            }
282            EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
283            _ if self.living => EntityClass::Mob,
284            _ => EntityClass::Object,
285        }
286    }
287
288    /// The stack of an item entity (from metadata; `None` before the server sent it or when
289    /// metadata is not tracked; 1.16 always keeps it for item entities).
290    #[must_use]
291    pub fn item(&self) -> Option<&Item> {
292        let index = match self.ty {
293            EntityType::LegacyObject(2) => 10,
294            EntityType::Registry(ITEM_1_16) => 7,
295            _ => return None,
296        };
297        self.meta.item(index).flatten()
298    }
299
300    /// Vanilla client-side dimensions: the type's size from ghast-data (checked against the
301    /// oracle), with the variant the client applies from metadata (baby, slime size, wither
302    /// skeleton, elder guardian, small / marker armor stand, 1.16 player pose). `None` for
303    /// hanging entities (paintings, item frames, leash knots), whose box comes from facing.
304    ///
305    /// Variants vanilla applies on the entity's next client tick are applied immediately, and
306    /// the old-min-corner quirk after a resize is not modelled.
307    #[must_use]
308    pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
309        let (vs, modern) = self.sizer?;
310        if modern {
311            crate::v1_16_5::dimensions(self, vs)
312        } else {
313            crate::v1_8::dimensions(self, vs)
314        }
315    }
316
317    /// `(width, height)` of [`Entity::dimensions`].
318    #[must_use]
319    pub fn size(&self) -> Option<(f32, f32)> {
320        self.dimensions().map(|d| (d.width, d.height))
321    }
322
323    /// Vanilla bounding box at the server position, `[min_x, min_y, min_z, max_x, max_y,
324    /// max_z]` (bit-exact `EntityDimensions::bounding_box`).
325    #[must_use]
326    pub fn bounding_box(&self) -> Option<[f64; 6]> {
327        let [x, y, z] = self.pos;
328        let b = self.dimensions()?.bounding_box(x, y, z);
329        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
330    }
331
332    /// `true` for players.
333    #[must_use]
334    pub fn is_player(&self) -> bool {
335        self.ty == EntityType::Player
336    }
337
338    /// The **server position**: exactly the coordinates the vanilla client tracks from the
339    /// packets (1.8: `serverPos / 32.0`; 1.16: the packet coordinates, rel moves applied in
340    /// 1/4096 fixed point). The rendered position interpolates towards this over 3 ticks in
341    /// vanilla; a bot does not need that.
342    #[must_use]
343    pub fn position(&self) -> [f64; 3] {
344        self.pos
345    }
346
347    /// 1.8 only: the raw server position in 1/32 blocks (`[0; 3]` in 1.16).
348    #[must_use]
349    pub fn fixed_position(&self) -> [i32; 3] {
350        self.fixed
351    }
352
353    /// Body yaw in degrees as vanilla computes it from the angle byte (`b * 360 / 256f`).
354    #[must_use]
355    pub fn yaw(&self) -> f32 {
356        self.yaw
357    }
358
359    /// Pitch in degrees.
360    #[must_use]
361    pub fn pitch(&self) -> f32 {
362        self.pitch
363    }
364
365    /// Head yaw in degrees (from `entity_head_rotation`; mobs also at spawn).
366    #[must_use]
367    pub fn head_yaw(&self) -> f32 {
368        self.head_yaw
369    }
370
371    /// Last velocity the server sent (blocks per tick), from the spawn packet or
372    /// `entity_velocity`. Not integrated over time.
373    #[must_use]
374    pub fn velocity(&self) -> [f64; 3] {
375        self.velocity
376    }
377
378    /// On-ground flag of the last movement packet.
379    #[must_use]
380    pub fn on_ground(&self) -> bool {
381        self.on_ground
382    }
383
384    /// Spawn data: object data (1.8 objects / 1.16 `spawn_entity`), experience orb value,
385    /// painting direction.
386    #[must_use]
387    pub fn data(&self) -> i32 {
388        self.data
389    }
390
391    /// Entity this one rides.
392    #[must_use]
393    pub fn vehicle(&self) -> Option<i32> {
394        self.vehicle
395    }
396
397    /// Entities riding this one (1.8: at most one).
398    #[must_use]
399    pub fn passengers(&self) -> &[i32] {
400        &self.passengers
401    }
402
403    /// Entity holding this one's leash.
404    #[must_use]
405    pub fn leash_holder(&self) -> Option<i32> {
406        self.leash_holder
407    }
408
409    /// Metadata (empty unless metadata tracking is enabled).
410    #[must_use]
411    pub fn metadata(&self) -> &Metadata {
412        &self.meta
413    }
414
415    /// Equipment slot (see [`EQUIPMENT_SLOTS`]); `None` if never sent or empty.
416    #[must_use]
417    pub fn equipment(&self, slot: usize) -> Option<&Item> {
418        self.equipment.as_ref()?.get(slot)?.as_ref()
419    }
420
421    /// Active effects as last reported.
422    #[must_use]
423    pub fn effects(&self) -> &[Effect] {
424        &self.effects
425    }
426
427    /// The effect with this id, if active.
428    #[must_use]
429    pub fn effect(&self, id: u8) -> Option<&Effect> {
430        self.effects.iter().find(|e| e.id == id)
431    }
432}