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 pose.
121 Pose(i32),
122}
123
124/// The metadata of one entity: `(index, value)` pairs, at most one per index, in arrival order.
125///
126/// Scalar updates overwrite in place (no allocation).
127#[derive(Clone, Debug, Default, PartialEq)]
128pub struct Metadata {
129 entries: Vec<(u8, MetaValue)>,
130}
131
132impl Metadata {
133 /// The value at `index`.
134 #[must_use]
135 pub fn get(&self, index: u8) -> Option<&MetaValue> {
136 self.entries
137 .iter()
138 .find(|(i, _)| *i == index)
139 .map(|(_, v)| v)
140 }
141
142 /// Sets the value at `index`.
143 pub fn set(&mut self, index: u8, value: MetaValue) {
144 match self.entries.iter_mut().find(|(i, _)| *i == index) {
145 Some(slot) => slot.1 = value,
146 None => self.entries.push((index, value)),
147 }
148 }
149
150 /// All entries.
151 pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
152 self.entries.iter().map(|(i, v)| (*i, v))
153 }
154
155 /// Number of entries.
156 #[must_use]
157 pub fn len(&self) -> usize {
158 self.entries.len()
159 }
160
161 /// `true` when nothing has been received.
162 #[must_use]
163 pub fn is_empty(&self) -> bool {
164 self.entries.is_empty()
165 }
166
167 /// Byte at `index` (`Byte` values only).
168 #[must_use]
169 pub fn byte(&self, index: u8) -> Option<i8> {
170 match self.get(index)? {
171 MetaValue::Byte(b) => Some(*b),
172 _ => None,
173 }
174 }
175
176 /// Float at `index`.
177 #[must_use]
178 pub fn float(&self, index: u8) -> Option<f32> {
179 match self.get(index)? {
180 MetaValue::Float(f) => Some(*f),
181 _ => None,
182 }
183 }
184
185 /// Item at `index` (`Some(None)` = an empty stack was sent).
186 #[must_use]
187 pub fn item(&self, index: u8) -> Option<Option<&Item>> {
188 match self.get(index)? {
189 MetaValue::Item(i) => Some(i.as_ref()),
190 _ => None,
191 }
192 }
193
194 pub(crate) fn clear(&mut self) {
195 self.entries.clear();
196 }
197
198 pub(crate) fn entries_mut(&mut self) -> impl Iterator<Item = &mut (u8, MetaValue)> {
199 self.entries.iter_mut()
200 }
201}
202
203/// The protocol family an entity was tracked with (selects metadata indices and size rules).
204#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
205pub(crate) enum Era {
206 /// 1.8.x.
207 #[default]
208 V1_8,
209 /// 1.9 – 1.12 (implemented: 1.12.2).
210 V1_12,
211 /// 1.16.5.
212 V1_16,
213}
214
215/// 1.16 registry ids used by [`Entity::class`].
216const ITEM_1_16: u16 = 37;
217const XP_ORB_1_16: u16 = 24;
218const PAINTING_1_16: u16 = 55;
219
220/// Number of equipment slots kept (1.16: main hand, off hand, feet, legs, chest, head;
221/// 1.8: held, boots, leggings, chestplate, helmet in slots 0..=4).
222pub const EQUIPMENT_SLOTS: usize = 6;
223
224/// A tracked entity, as the vanilla client knows it from the server's packets.
225#[derive(Clone, Debug)]
226pub struct Entity {
227 pub(crate) id: i32,
228 pub(crate) uuid: Uuid,
229 pub(crate) ty: EntityType,
230 pub(crate) living: bool,
231 /// The tracker's protocol family.
232 pub(crate) era: Era,
233 /// Vanilla size table entry (resolved at spawn).
234 pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
235 pub(crate) pos: [f64; 3],
236 pub(crate) fixed: [i32; 3],
237 /// 1.9 – 1.12: the tracked position in 1/4096 blocks (`lfloor(x * 4096)`, plus moves).
238 pub(crate) traced: [i64; 3],
239 pub(crate) yaw: f32,
240 pub(crate) pitch: f32,
241 pub(crate) head_yaw: f32,
242 pub(crate) velocity: [f64; 3],
243 pub(crate) on_ground: bool,
244 pub(crate) data: i32,
245 pub(crate) vehicle: Option<i32>,
246 pub(crate) passengers: Vec<i32>,
247 pub(crate) leash_holder: Option<i32>,
248 pub(crate) meta: Metadata,
249 pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
250 pub(crate) effects: Vec<Effect>,
251}
252
253impl Entity {
254 pub(crate) fn new(id: i32, ty: EntityType) -> Self {
255 Entity {
256 id,
257 uuid: Uuid::nil(),
258 ty,
259 living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
260 era: Era::V1_8,
261 sizer: None,
262 pos: [0.0; 3],
263 fixed: [0; 3],
264 traced: [0; 3],
265 yaw: 0.0,
266 pitch: 0.0,
267 head_yaw: 0.0,
268 velocity: [0.0; 3],
269 on_ground: false,
270 data: 0,
271 vehicle: None,
272 passengers: Vec::new(),
273 leash_holder: None,
274 meta: Metadata::default(),
275 equipment: None,
276 effects: Vec::new(),
277 }
278 }
279
280 /// Network entity id.
281 #[must_use]
282 pub fn id(&self) -> i32 {
283 self.id
284 }
285
286 /// UUID (nil for 1.8 entities other than players).
287 #[must_use]
288 pub fn uuid(&self) -> Uuid {
289 self.uuid
290 }
291
292 /// Type.
293 #[must_use]
294 pub fn entity_type(&self) -> EntityType {
295 self.ty
296 }
297
298 /// Version-independent class.
299 #[must_use]
300 pub fn class(&self) -> EntityClass {
301 match self.ty {
302 EntityType::Player => EntityClass::Player,
303 EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
304 EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
305 EntityClass::ExperienceOrb
306 }
307 EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
308 _ if self.living => EntityClass::Mob,
309 _ => EntityClass::Object,
310 }
311 }
312
313 /// The stack of an item entity (from metadata; `None` before the server sent it or when
314 /// metadata is not tracked; 1.16 always keeps it for item entities).
315 #[must_use]
316 pub fn item(&self) -> Option<&Item> {
317 let index = match self.ty {
318 EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
319 EntityType::LegacyObject(2) => 10,
320 EntityType::Registry(ITEM_1_16) => 7,
321 _ => return None,
322 };
323 self.meta.item(index).flatten()
324 }
325
326 /// Vanilla client-side dimensions: the type's size from ghast-data (checked against the
327 /// oracle), with the variant the client applies from metadata (baby, slime size, wither
328 /// skeleton, elder guardian, small / marker armor stand, 1.16 player pose). `None` for
329 /// hanging entities (paintings, item frames, leash knots), whose box comes from facing.
330 ///
331 /// Variants vanilla applies on the entity's next client tick are applied immediately, and
332 /// the old-min-corner quirk after a resize is not modelled.
333 #[must_use]
334 pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
335 let vs = self.sizer?;
336 match self.era {
337 Era::V1_8 => crate::v1_8::dimensions(self, vs),
338 Era::V1_12 => crate::v1_12::dimensions(self, vs),
339 Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
340 }
341 }
342
343 /// `(width, height)` of [`Entity::dimensions`].
344 #[must_use]
345 pub fn size(&self) -> Option<(f32, f32)> {
346 self.dimensions().map(|d| (d.width, d.height))
347 }
348
349 /// Vanilla bounding box at the server position, `[min_x, min_y, min_z, max_x, max_y,
350 /// max_z]` (bit-exact `EntityDimensions::bounding_box`).
351 #[must_use]
352 pub fn bounding_box(&self) -> Option<[f64; 6]> {
353 let [x, y, z] = self.pos;
354 let b = self.dimensions()?.bounding_box(x, y, z);
355 Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
356 }
357
358 /// `true` for players.
359 #[must_use]
360 pub fn is_player(&self) -> bool {
361 self.ty == EntityType::Player
362 }
363
364 /// The **server position**: exactly the coordinates the vanilla client tracks from the
365 /// packets (1.8: `serverPos / 32.0`; 1.12: spawn / teleport coordinates, after a relative
366 /// move the tracked 1/4096 position; 1.16: the packet coordinates, rel moves applied in
367 /// 1/4096 fixed point). The rendered position interpolates towards this over 3 ticks in
368 /// vanilla; a bot does not need that.
369 #[must_use]
370 pub fn position(&self) -> [f64; 3] {
371 self.pos
372 }
373
374 /// 1.8 only: the raw server position in 1/32 blocks (`[0; 3]` in 1.12 and 1.16).
375 #[must_use]
376 pub fn fixed_position(&self) -> [i32; 3] {
377 self.fixed
378 }
379
380 /// Body yaw in degrees as vanilla computes it from the angle byte (`b * 360 / 256f`).
381 #[must_use]
382 pub fn yaw(&self) -> f32 {
383 self.yaw
384 }
385
386 /// Pitch in degrees.
387 #[must_use]
388 pub fn pitch(&self) -> f32 {
389 self.pitch
390 }
391
392 /// Head yaw in degrees (from `entity_head_rotation`; mobs also at spawn).
393 #[must_use]
394 pub fn head_yaw(&self) -> f32 {
395 self.head_yaw
396 }
397
398 /// Last velocity the server sent (blocks per tick), from the spawn packet or
399 /// `entity_velocity`. Not integrated over time.
400 #[must_use]
401 pub fn velocity(&self) -> [f64; 3] {
402 self.velocity
403 }
404
405 /// On-ground flag of the last movement packet.
406 #[must_use]
407 pub fn on_ground(&self) -> bool {
408 self.on_ground
409 }
410
411 /// Spawn data: object data (1.8 objects / 1.16 `spawn_entity`), experience orb value,
412 /// painting direction.
413 #[must_use]
414 pub fn data(&self) -> i32 {
415 self.data
416 }
417
418 /// Entity this one rides.
419 #[must_use]
420 pub fn vehicle(&self) -> Option<i32> {
421 self.vehicle
422 }
423
424 /// Entities riding this one (1.8: at most one).
425 #[must_use]
426 pub fn passengers(&self) -> &[i32] {
427 &self.passengers
428 }
429
430 /// Entity holding this one's leash.
431 #[must_use]
432 pub fn leash_holder(&self) -> Option<i32> {
433 self.leash_holder
434 }
435
436 /// Metadata (empty unless metadata tracking is enabled).
437 #[must_use]
438 pub fn metadata(&self) -> &Metadata {
439 &self.meta
440 }
441
442 /// Equipment slot (see [`EQUIPMENT_SLOTS`]); `None` if never sent or empty.
443 #[must_use]
444 pub fn equipment(&self, slot: usize) -> Option<&Item> {
445 self.equipment.as_ref()?.get(slot)?.as_ref()
446 }
447
448 /// Active effects as last reported.
449 #[must_use]
450 pub fn effects(&self) -> &[Effect] {
451 &self.effects
452 }
453
454 /// The effect with this id, if active.
455 #[must_use]
456 pub fn effect(&self, id: u8) -> Option<&Effect> {
457 self.effects.iter().find(|e| e.id == id)
458 }
459}