1use bytes::Bytes;
4use uuid::Uuid;
5
6#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
8#[non_exhaustive]
9pub enum EntityType {
10 Player,
12 LegacyMob(u8),
15 LegacyObject(u8),
18 ExperienceOrb,
20 Painting,
22 Registry(u16),
25}
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
29#[non_exhaustive]
30pub enum EntityClass {
31 Player,
33 Item,
35 ExperienceOrb,
37 Mob,
39 Object,
41 Painting,
43}
44
45#[derive(Clone, Debug, PartialEq, Eq)]
50pub struct Item {
51 pub id: i32,
53 pub count: i8,
55 pub damage: i16,
57 pub nbt: Option<Bytes>,
59}
60
61#[derive(Clone, Copy, Debug, PartialEq, Eq)]
63pub struct Effect {
64 pub id: u8,
66 pub amplifier: i8,
68 pub duration: i32,
70 pub flags: u8,
73}
74
75#[derive(Clone, Debug, PartialEq)]
78#[non_exhaustive]
79pub enum MetaValue {
80 Byte(i8),
82 Short(i16),
84 Int(i32),
86 VarInt(i32),
88 Float(f32),
90 String(Box<str>),
92 Chat(Box<str>),
94 OptChat(Option<Box<str>>),
96 Item(Option<Item>),
98 Bool(bool),
100 Rotation([f32; 3]),
102 BlockPos([i32; 3]),
104 OptBlockPos(Option<[i32; 3]>),
106 Direction(i32),
108 OptUuid(Option<Uuid>),
110 BlockState(i32),
112 Nbt(Bytes),
114 Particle(i32),
116 VillagerData([i32; 3]),
118 OptVarInt(i32),
120 Pose(i32),
122 Long(i64),
124 Component(Bytes),
126 OptComponent(Option<Bytes>),
128 #[cfg(any(feature = "v26_1", feature = "v26_2"))]
130 Stack(Option<ghast_protocol::types::slot::v775::ItemStack>),
131 Enum(u8, i32),
135 Vector3([f32; 3]),
137 Quaternion([f32; 4]),
139 Raw(u8, Bytes),
143}
144
145#[derive(Clone, Debug, Default, PartialEq)]
150pub struct Metadata {
151 entries: Box<[(u8, MetaValue)]>,
152}
153
154impl Metadata {
155 #[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 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 #[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 #[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 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 #[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 pub fn iter(&self) -> impl Iterator<Item = (u8, &MetaValue)> {
237 self.entries.iter().map(|(i, v)| (*i, v))
238 }
239
240 #[must_use]
242 pub fn len(&self) -> usize {
243 self.entries.len()
244 }
245
246 #[must_use]
248 pub fn is_empty(&self) -> bool {
249 self.entries.is_empty()
250 }
251
252 #[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 #[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 #[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 #[cfg(test)]
289 pub(crate) fn heap_bytes(&self) -> usize {
290 std::mem::size_of_val::<[(u8, MetaValue)]>(&self.entries)
291 }
292}
293
294#[derive(Clone, Debug, Default, PartialEq)]
297pub(crate) struct Links {
298 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}
305
306#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
308pub(crate) enum Era {
309 #[default]
311 V1_8,
312 V1_12,
314 V1_16,
316 V26,
318 V26_2,
320}
321
322const ITEM_1_16: u16 = 37;
324const XP_ORB_1_16: u16 = 24;
325const PAINTING_1_16: u16 = 55;
326
327pub const EQUIPMENT_SLOTS: usize = 6;
330
331#[derive(Clone, Debug)]
333pub struct Entity {
334 pub(crate) id: i32,
335 pub(crate) uuid: Uuid,
336 pub(crate) ty: EntityType,
337 pub(crate) living: bool,
338 pub(crate) era: Era,
340 pub(crate) sizer: Option<&'static ghast_data::VanillaEntitySize>,
342 pub(crate) pos: [f64; 3],
343 pub(crate) traced: [i64; 3],
347 pub(crate) yaw: f32,
348 pub(crate) pitch: f32,
349 pub(crate) head_yaw: f32,
350 pub(crate) velocity: [f64; 3],
351 pub(crate) on_ground: bool,
352 pub(crate) data: i32,
353 pub(crate) meta: Metadata,
354 pub(crate) equipment: Option<Box<[Option<Item>; EQUIPMENT_SLOTS]>>,
355 pub(crate) vehicle_id: i32,
357 pub(crate) bits: u8,
360 pub(crate) links: Option<Box<Links>>,
362 #[cfg(any(feature = "v26_1", feature = "v26_2"))]
365 pub(crate) m: crate::modern_state::Ext,
366}
367
368impl Entity {
369 pub(crate) fn new(id: i32, ty: EntityType) -> Self {
370 Entity {
371 id,
372 uuid: Uuid::nil(),
373 ty,
374 living: matches!(ty, EntityType::Player | EntityType::LegacyMob(_)),
375 era: Era::V1_8,
376 sizer: None,
377 pos: [0.0; 3],
378 traced: [0; 3],
379 yaw: 0.0,
380 pitch: 0.0,
381 head_yaw: 0.0,
382 velocity: [0.0; 3],
383 on_ground: false,
384 data: 0,
385 meta: Metadata::default(),
386 equipment: None,
387 links: None,
388 vehicle_id: 0,
389 bits: 0,
390 #[cfg(any(feature = "v26_1", feature = "v26_2"))]
391 m: crate::modern_state::Ext::default(),
392 }
393 }
394
395 pub(crate) const RIDES: u8 = 1;
396 pub(crate) const DEAD: u8 = 2;
397
398 #[inline]
400 pub(crate) fn rides(&self) -> bool {
401 self.bits & Self::RIDES != 0
402 }
403
404 #[inline]
406 pub(crate) fn mark_dead(&mut self) {
407 if self.living {
408 self.bits |= Self::DEAD;
409 }
410 }
411
412 #[inline]
414 pub(crate) fn links_mut(&mut self) -> &mut Links {
415 self.links.get_or_insert_with(Box::default)
416 }
417
418 #[inline]
420 pub(crate) fn set_vehicle(&mut self, v: Option<i32>) {
421 if v.is_some() {
422 self.bits |= Self::RIDES;
423 } else {
424 self.bits &= !Self::RIDES;
425 }
426 self.vehicle_id = v.unwrap_or(0);
427 }
428
429 #[inline]
431 pub(crate) fn take_vehicle(&mut self) -> Option<i32> {
432 let v = self.vehicle();
433 self.set_vehicle(None);
434 v
435 }
436
437 #[inline]
439 pub(crate) fn set_leash_holder(&mut self, h: Option<i32>) {
440 match (&mut self.links, h) {
441 (Some(l), h) => l.leash_holder = h,
442 (None, None) => {}
443 (None, Some(_)) => self.links_mut().leash_holder = h,
444 }
445 self.tidy_links();
446 }
447
448 #[inline]
450 pub(crate) fn take_passengers(&mut self) -> Vec<i32> {
451 let p = self
452 .links
453 .as_mut()
454 .map(|l| std::mem::take(&mut l.passengers))
455 .unwrap_or_default();
456 self.tidy_links();
457 p
458 }
459
460 #[inline]
462 pub(crate) fn remove_passenger(&mut self, id: i32) {
463 if let Some(l) = &mut self.links {
464 l.passengers.retain(|&p| p != id);
465 }
466 self.tidy_links();
467 }
468
469 #[inline]
471 pub(crate) fn set_passengers(&mut self, p: Vec<i32>) {
472 if !p.is_empty() || self.links.is_some() {
473 self.links_mut().passengers = p;
474 }
475 self.tidy_links();
476 }
477
478 #[inline]
480 pub(crate) fn push_passenger(&mut self, id: i32) {
481 self.links_mut().passengers.push(id);
482 }
483
484 #[inline]
486 pub(crate) fn clear_effects(&mut self) {
487 if let Some(l) = &mut self.links {
488 l.effects = Vec::new();
489 }
490 self.tidy_links();
491 }
492
493 #[inline]
495 pub(crate) fn tidy_links(&mut self) {
496 if self.links.as_ref().is_some_and(|l| {
497 l.leash_holder.is_none()
498 && l.profile_name.is_none()
499 && l.passengers.is_empty()
500 && l.effects.is_empty()
501 }) {
502 self.links = None;
503 }
504 }
505
506 #[cfg(test)]
509 pub(crate) fn heap_bytes(&self) -> usize {
510 let mut n = self.meta.heap_bytes();
511 if self.equipment.is_some() {
512 n += std::mem::size_of::<[Option<Item>; EQUIPMENT_SLOTS]>();
513 }
514 if let Some(l) = &self.links {
515 n += std::mem::size_of::<Links>()
516 + l.passengers.capacity() * 4
517 + l.effects.capacity() * std::mem::size_of::<Effect>();
518 }
519 #[cfg(any(feature = "v26_1", feature = "v26_2"))]
520 if self.m.0.is_some() {
521 n += std::mem::size_of::<crate::modern_state::State>();
522 }
523 n
524 }
525
526 #[must_use]
528 pub fn id(&self) -> i32 {
529 self.id
530 }
531
532 #[must_use]
534 pub fn uuid(&self) -> Uuid {
535 self.uuid
536 }
537
538 #[must_use]
540 pub fn entity_type(&self) -> EntityType {
541 self.ty
542 }
543
544 #[must_use]
551 pub fn is_alive(&self) -> bool {
552 if !self.living {
553 return true;
554 }
555 if self.bits & Self::DEAD != 0 {
556 return false;
557 }
558 let health: Option<f32> = match self.era {
559 #[cfg(feature = "v26_1")]
560 Era::V26 => return crate::v26_1::alive(self),
561 #[cfg(feature = "v26_2")]
562 Era::V26_2 => return crate::v26_2::alive(self),
563 #[cfg(feature = "v1_8")]
564 Era::V1_8 => crate::v1_8::health(self),
565 #[cfg(feature = "v1_12")]
566 Era::V1_12 => crate::v1_12::health(self),
567 #[cfg(feature = "v1_16_5")]
568 Era::V1_16 => crate::v1_16_5::health(self),
569 #[allow(unreachable_patterns)]
571 _ => None,
572 };
573 health.is_none_or(|h| h > 0.0)
575 }
576
577 #[must_use]
579 pub fn class(&self) -> EntityClass {
580 #[cfg(feature = "v26_1")]
581 if self.era == Era::V26 {
582 return crate::v26_1::class(self);
583 }
584 #[cfg(feature = "v26_2")]
585 if self.era == Era::V26_2 {
586 return crate::v26_2::class(self);
587 }
588 match self.ty {
589 EntityType::Player => EntityClass::Player,
590 EntityType::LegacyObject(2) | EntityType::Registry(ITEM_1_16) => EntityClass::Item,
591 EntityType::ExperienceOrb | EntityType::Registry(XP_ORB_1_16) => {
592 EntityClass::ExperienceOrb
593 }
594 EntityType::Painting | EntityType::Registry(PAINTING_1_16) => EntityClass::Painting,
595 _ if self.living => EntityClass::Mob,
596 _ => EntityClass::Object,
597 }
598 }
599
600 #[must_use]
604 pub fn item(&self) -> Option<&Item> {
605 if matches!(self.era, Era::V26 | Era::V26_2) {
606 return None;
607 }
608 let index = match self.ty {
609 EntityType::LegacyObject(2) if self.era == Era::V1_12 => 6,
610 EntityType::LegacyObject(2) => 10,
611 EntityType::Registry(ITEM_1_16) => 7,
612 _ => return None,
613 };
614 self.meta.item(index).flatten()
615 }
616
617 #[must_use]
625 pub fn dimensions(&self) -> Option<ghast_data::EntityDimensions> {
626 let vs = self.sizer?;
627 match self.era {
628 #[cfg(feature = "v1_8")]
629 Era::V1_8 => crate::v1_8::dimensions(self, vs),
630 #[cfg(feature = "v1_12")]
631 Era::V1_12 => crate::v1_12::dimensions(self, vs),
632 #[cfg(feature = "v1_16_5")]
633 Era::V1_16 => crate::v1_16_5::dimensions(self, vs),
634 #[cfg(feature = "v26_1")]
635 Era::V26 => {
636 let _ = vs;
637 crate::v26_1::dimensions(self)
638 }
639 #[cfg(feature = "v26_2")]
640 Era::V26_2 => {
641 let _ = vs;
642 crate::v26_2::dimensions(self)
643 }
644 #[allow(unreachable_patterns)]
646 _ => None,
647 }
648 }
649
650 #[must_use]
654 pub fn targeting_margin(&self) -> f32 {
655 self.sizer.map_or(0.0, |s| s.targeting_margin)
656 }
657
658 #[must_use]
660 pub fn size(&self) -> Option<(f32, f32)> {
661 self.dimensions().map(|d| (d.width, d.height))
662 }
663
664 #[must_use]
667 pub fn bounding_box(&self) -> Option<[f64; 6]> {
668 let [x, y, z] = self.pos;
669 let b = self.dimensions()?.bounding_box(x, y, z);
670 Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
671 }
672
673 #[must_use]
675 pub fn is_player(&self) -> bool {
676 self.ty == EntityType::Player
677 }
678
679 #[must_use]
691 pub fn position(&self) -> [f64; 3] {
692 self.pos
693 }
694
695 #[must_use]
697 pub fn fixed_position(&self) -> [i32; 3] {
698 if self.era == Era::V1_8 {
699 self.traced.map(|t| t as i32)
700 } else {
701 [0; 3]
702 }
703 }
704
705 #[must_use]
707 pub fn yaw(&self) -> f32 {
708 self.yaw
709 }
710
711 #[must_use]
713 pub fn pitch(&self) -> f32 {
714 self.pitch
715 }
716
717 #[must_use]
719 pub fn head_yaw(&self) -> f32 {
720 self.head_yaw
721 }
722
723 #[must_use]
726 pub fn velocity(&self) -> [f64; 3] {
727 self.velocity
728 }
729
730 #[must_use]
732 pub fn on_ground(&self) -> bool {
733 self.on_ground
734 }
735
736 #[must_use]
739 pub fn data(&self) -> i32 {
740 self.data
741 }
742
743 #[must_use]
745 pub fn vehicle(&self) -> Option<i32> {
746 self.rides().then_some(self.vehicle_id)
747 }
748
749 #[must_use]
751 pub fn passengers(&self) -> &[i32] {
752 self.links.as_ref().map_or(&[], |l| &l.passengers)
753 }
754
755 #[must_use]
757 pub fn leash_holder(&self) -> Option<i32> {
758 self.links.as_ref().and_then(|l| l.leash_holder)
759 }
760
761 #[must_use]
763 pub fn metadata(&self) -> &Metadata {
764 &self.meta
765 }
766
767 #[must_use]
769 pub fn equipment(&self, slot: usize) -> Option<&Item> {
770 self.equipment.as_ref()?.get(slot)?.as_ref()
771 }
772
773 #[must_use]
775 pub fn effects(&self) -> &[Effect] {
776 self.links.as_ref().map_or(&[], |l| &l.effects)
777 }
778
779 #[must_use]
781 pub fn effect(&self, id: u8) -> Option<&Effect> {
782 self.effects().iter().find(|e| e.id == id)
783 }
784}
785
786#[cfg(test)]
787mod tests {
788 use super::*;
789
790 #[test]
793 fn metadata_set_from_matches_set() {
794 let batches: [&[(u8, i8)]; 4] = [
795 &[(0, 1), (9, 2), (0, 3)],
796 &[(9, 4)],
797 &[(5, 5), (2, 6), (5, 7), (9, 8)],
798 &[(7, 9), (3, 10)],
799 ];
800 let keep = |i: u8| i != 3;
801 let (mut a, mut b) = (Metadata::default(), Metadata::default());
802 for batch in batches {
803 let mut src: Vec<(u8, MetaValue)> = batch
804 .iter()
805 .map(|&(i, v)| (i, MetaValue::Byte(v)))
806 .collect();
807 for (i, v) in src.clone() {
808 if keep(i) {
809 a.set(i, v);
810 }
811 }
812 b.set_from(&mut src, keep);
813 assert!(src.is_empty());
814 assert_eq!(a, b);
815 }
816 let got: Vec<(u8, i8)> = b
817 .iter()
818 .map(|(i, v)| match v {
819 MetaValue::Byte(x) => (i, *x),
820 _ => unreachable!(),
821 })
822 .collect();
823 assert_eq!(got, [(0, 3), (9, 8), (5, 7), (2, 6), (7, 9)]);
824 assert_eq!(b.heap_bytes(), 5 * std::mem::size_of::<(u8, MetaValue)>());
825 b.clear();
826 assert!(b.is_empty() && b.heap_bytes() == 0);
827 }
828
829 #[test]
830 fn links_are_freed_when_empty() {
831 let mut e = Entity::new(1, EntityType::Player);
832 e.set_vehicle(None);
833 e.set_leash_holder(None);
834 e.clear_effects();
835 assert!(e.links.is_none());
836 e.set_vehicle(Some(2));
837 e.push_passenger(3);
838 assert_eq!((e.vehicle(), e.passengers()), (Some(2), &[3][..]));
839 e.set_vehicle(None);
840 e.remove_passenger(3);
841 assert!(e.links.is_none());
842 assert_eq!(e.take_passengers(), Vec::<i32>::new());
843 }
844}