Skip to main content

ghast_entity/
store.rs

1//! Version-independent entity store shared by the per-version trackers.
2
3use std::collections::HashMap;
4use std::hash::{BuildHasherDefault, Hasher};
5
6use uuid::Uuid;
7
8use crate::entity::{Entity, EntityType, MetaValue};
9
10/// What the tracker keeps. Everything off costs nothing beyond position tracking; packets for a
11/// disabled part are not parsed (and the client should not even decode them, see the version
12/// modules' packet id lists).
13///
14/// `#[non_exhaustive]`: build it from [`Config::default`] with the `with_*` methods:
15///
16/// ```
17/// let c = ghast_entity::Config::default().with_equipment(false).with_skins(true);
18/// assert!(c.metadata && !c.equipment && c.skins);
19/// ```
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21#[non_exhaustive]
22pub struct Config {
23    /// Entity metadata (flags, health, item of item entities, names, ...). Default `true`.
24    pub metadata: bool,
25    /// Equipment. Default `true`.
26    pub equipment: bool,
27    /// Status effects. Default `true`.
28    pub effects: bool,
29    /// Tab list (`player_info`). Default `true`.
30    pub player_list: bool,
31    /// Queue [`Event`]s for [`Entities::drain_events`]. Default `false`.
32    pub events: bool,
33    /// Keep the base64 `"textures"` profile property (skin / cape URLs) of tab-list entries in
34    /// [`PlayerInfo::textures`]. Default `false`: properties are skipped without allocating.
35    pub skins: bool,
36    /// With [`Config::player_list`] off: still read the tab list, but keep only each entry's
37    /// profile name and game mode (inline, about 50 bytes per entry; no [`PlayerInfo`]). That is
38    /// what vanilla needs from it for entities: [`Entities::player_name`] (team rules use the
39    /// scoreboard name), spectators (not pickable, not pushed, never on the ground) and, on
40    /// 26.x, refusing a player spawn whose profile is not in the tab list. Ignored when
41    /// [`Config::player_list`] is on (the full list answers the same questions). Default `false`.
42    pub player_names: bool,
43    /// The client view of the other entities: what the vanilla client draws and picks
44    /// ([`Entity::drawn_position`], [`Entity::drawn_bounding_box`]) and the per-entity clocks
45    /// ([`Entity::position_tick`], [`Entity::spawn_tick`], [`Entity::last_hurt_tick`],
46    /// [`Entity::estimated_velocity`]); the same switch as each tracker's
47    /// `track_client_motion`. One small heap block per living entity. Default `false`.
48    pub client_motion: bool,
49    /// Entity types (`minecraft:entity_type` registry ids of the tracker's version) whose
50    /// equipment and status effects are kept even with [`Config::equipment`] /
51    /// [`Config::effects`] off: the packets of other types are dropped after their entity id
52    /// (one map lookup). Modern (26.x) trackers only; the older ones ignore it. Default empty.
53    pub kept_types: &'static [u16],
54    /// Entity types (`minecraft:entity_type` registry ids of the tracker's version) whose client
55    /// copy keeps its own motion between the server's packets ([`Entities::client_motion`]):
56    /// set by the spawn, `set_entity_motion` and teleport packets, slowed by 0.98 on each tick
57    /// without a running interpolation and cut under 0.003 per axis (`LivingEntity.aiStep`),
58    /// pushed by the local player (`Tracker::push_motion` of the modern trackers). What a mount carries into the
59    /// first tick the bot rides it. Modern (26.x) trackers only. Default empty.
60    pub motion_types: &'static [u16],
61}
62
63impl Config {
64    /// Sets [`Config::client_motion`].
65    #[must_use]
66    pub const fn with_client_motion(mut self, on: bool) -> Self {
67        self.client_motion = on;
68        self
69    }
70
71    /// Sets [`Config::metadata`].
72    #[must_use]
73    pub const fn with_metadata(mut self, on: bool) -> Self {
74        self.metadata = on;
75        self
76    }
77
78    /// Sets [`Config::equipment`].
79    #[must_use]
80    pub const fn with_equipment(mut self, on: bool) -> Self {
81        self.equipment = on;
82        self
83    }
84
85    /// Sets [`Config::effects`].
86    #[must_use]
87    pub const fn with_effects(mut self, on: bool) -> Self {
88        self.effects = on;
89        self
90    }
91
92    /// Sets [`Config::player_list`].
93    #[must_use]
94    pub const fn with_player_list(mut self, on: bool) -> Self {
95        self.player_list = on;
96        self
97    }
98
99    /// Sets [`Config::events`].
100    #[must_use]
101    pub const fn with_events(mut self, on: bool) -> Self {
102        self.events = on;
103        self
104    }
105
106    /// Sets [`Config::skins`].
107    #[must_use]
108    pub const fn with_skins(mut self, on: bool) -> Self {
109        self.skins = on;
110        self
111    }
112
113    /// Sets [`Config::kept_types`].
114    #[must_use]
115    pub const fn with_kept_types(mut self, types: &'static [u16]) -> Self {
116        self.kept_types = types;
117        self
118    }
119
120    /// Sets [`Config::motion_types`].
121    #[must_use]
122    pub const fn with_motion_types(mut self, types: &'static [u16]) -> Self {
123        self.motion_types = types;
124        self
125    }
126
127    /// Sets [`Config::player_names`].
128    #[must_use]
129    pub const fn with_player_names(mut self, on: bool) -> Self {
130        self.player_names = on;
131        self
132    }
133
134    /// `true` when the tracker reads the tab list (full or names only): its packets
135    /// (`PLAYER_LIST_IDS` of the version module) must reach the tracker.
136    #[must_use]
137    pub const fn reads_tab_list(&self) -> bool {
138        self.player_list || self.player_names
139    }
140}
141
142impl Default for Config {
143    fn default() -> Self {
144        Config {
145            metadata: true,
146            equipment: true,
147            effects: true,
148            player_list: true,
149            events: false,
150            skins: false,
151            player_names: false,
152            client_motion: false,
153            kept_types: &[],
154            motion_types: &[],
155        }
156    }
157}
158
159/// A change notification (only queued with [`Config::events`]).
160#[derive(Clone, Copy, Debug, PartialEq, Eq)]
161#[non_exhaustive]
162pub enum Event {
163    /// A new entity (or a replacement for an existing id).
164    Spawned(i32),
165    /// An entity was removed (destroy, pickup, world change).
166    Removed {
167        /// Id.
168        id: i32,
169        /// Its type.
170        ty: EntityType,
171    },
172    /// Server position or rotation changed (movement, teleport).
173    Moved(i32),
174    /// Velocity changed.
175    Velocity(i32),
176    /// `entity_status` (e.g. 2 hurt, 3 death).
177    Status {
178        /// Id.
179        id: i32,
180        /// Status byte.
181        status: i8,
182    },
183    /// Metadata changed.
184    Metadata(i32),
185    /// An entity was hurt: 1.8 – 1.16.5 the hurt statuses (2; 1.12+ also 33 thorns, 36
186    /// drowning, 37 burning; 1.16 44 sweet berry bush, each also queued as [`Event::Status`]),
187    /// 26.x a living entity's `damage_event`. The bot's own entity included.
188    Hurt {
189        /// Id.
190        id: i32,
191        /// 26.x: the entity that caused the damage (the shooter for projectiles), if any;
192        /// always `None` before 26.x (the status carries no source).
193        attacker: Option<i32>,
194    },
195    /// Equipment changed.
196    Equipment(i32),
197    /// Effects changed.
198    Effects(i32),
199    /// Riding changed: `id` now rides `vehicle`.
200    Mounted {
201        /// Rider.
202        id: i32,
203        /// Vehicle (`None` = dismounted).
204        vehicle: Option<i32>,
205    },
206    /// An item / orb / arrow was picked up (`collector` may be the bot).
207    Collected {
208        /// Picked-up entity.
209        collected: i32,
210        /// Collector.
211        collector: i32,
212    },
213    /// The tab list changed.
214    PlayerList,
215}
216
217/// A tab-list entry (`#[non_exhaustive]`: read-only for callers, fields may be added).
218#[derive(Clone, Debug, PartialEq, Eq)]
219#[non_exhaustive]
220pub struct PlayerInfo {
221    /// Profile name.
222    pub name: Box<str>,
223    /// Game mode.
224    pub game_mode: i32,
225    /// Latency in ms.
226    pub ping: i32,
227    /// Display name (raw chat JSON), if set (1.8 – 1.16; see
228    /// [`PlayerInfo::display_name_nbt`] for 26.1).
229    pub display_name: Option<Box<str>>,
230    /// The base64 `"textures"` profile property as sent (only with [`Config::skins`]; its
231    /// signature is not kept). Decoded it is JSON with the skin and cape URLs.
232    pub textures: Option<Box<str>>,
233    /// 26.1: the display name as its raw network NBT text component, if set.
234    pub display_name_nbt: Option<bytes::Bytes>,
235    /// Shown in the tab list (26.1 `UPDATE_LISTED`; always `true` before 26.1).
236    pub listed: bool,
237    /// 26.1 tab list order (`UPDATE_LIST_ORDER`; 0 before).
238    pub list_order: i32,
239    /// Which tab list object this is (26.1 player entities keep the one they first saw).
240    pub(crate) generation: u32,
241}
242
243#[derive(Default, Clone, Copy)]
244pub(crate) struct IdHasher(u64);
245
246impl Hasher for IdHasher {
247    #[inline]
248    fn finish(&self) -> u64 {
249        let h = self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15);
250        h ^ (h >> 29)
251    }
252
253    #[inline]
254    fn write(&mut self, bytes: &[u8]) {
255        for &b in bytes {
256            self.0 = (self.0 << 8) | u64::from(b);
257        }
258    }
259
260    #[inline]
261    fn write_i32(&mut self, v: i32) {
262        self.0 = u64::from(v as u32);
263    }
264
265    #[inline]
266    fn write_u64(&mut self, v: u64) {
267        self.0 = v;
268    }
269
270    #[inline]
271    fn write_u128(&mut self, v: u128) {
272        self.0 = (v as u64) ^ ((v >> 64) as u64);
273    }
274}
275
276pub(crate) type Fast<K, V> = HashMap<K, V, BuildHasherDefault<IdHasher>>;
277
278/// Gives memory back once a map holds less than a quarter of its capacity (a crowd left):
279/// shrinks to twice the live entries, so it neither keeps a peak's table forever nor rehashes
280/// back and forth around one size. Small maps are left alone.
281#[inline]
282pub(crate) fn shrink_map<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
283    let cap = m.capacity();
284    if cap > 64 && m.len() * 4 < cap {
285        m.shrink_to(m.len() * 2);
286    }
287}
288
289/// Call after an insert into `m`, with its `capacity()` before the insert (or after the last
290/// insert). hashbrown grows a table whose free slots ran out even when many of them are only
291/// deletion markers (ids that came and went), so a steady crowd with fresh ids doubles the
292/// table. A growth at least doubles `capacity()`; a real one leaves the table just over half
293/// full, one that leaves it at most half full was forced by markers and is undone at once: the
294/// table is rebuilt at its live size, which also drops the markers.
295#[inline]
296pub(crate) fn after_insert<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>, old_cap: usize) {
297    let cap = m.capacity();
298    if cap >= 2 * old_cap.max(1) && m.len() * 2 <= cap {
299        compact(m);
300    }
301}
302
303#[cold]
304#[inline(never)]
305fn compact<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
306    m.shrink_to(m.len());
307}
308
309/// A tab-list entry as [`Config::player_names`] keeps it: the profile name inline (a name longer
310/// than [`TabLite::INLINE`] bytes lives in `Entities::long_names`), the game mode and the tab
311/// list object generation (26.x).
312#[derive(Clone, Copy, Debug)]
313pub(crate) struct TabLite {
314    name: [u8; TabLite::INLINE],
315    /// Name length, or [`TabLite::LONG`].
316    len: u8,
317    pub(crate) game_mode: i32,
318    pub(crate) generation: u32,
319}
320
321impl TabLite {
322    /// Inline name bytes (vanilla profile names are at most 16 characters).
323    const INLINE: usize = 23;
324    const LONG: u8 = u8::MAX;
325}
326
327/// What the tab list says about one profile (full or names-only list).
328#[derive(Clone, Copy, Debug)]
329pub(crate) struct TabRef<'a> {
330    pub(crate) name: &'a str,
331    pub(crate) game_mode: i32,
332    pub(crate) generation: u32,
333}
334
335/// The tab lists of an [`Entities`] (borrowed field by field, so a caller can hold them while
336/// it changes entities).
337#[derive(Clone, Copy)]
338pub(crate) struct Tabs<'a> {
339    pub(crate) players: &'a Fast<Uuid, PlayerInfo>,
340    pub(crate) lite: &'a Fast<Uuid, TabLite>,
341    pub(crate) long_names: &'a Fast<Uuid, Box<str>>,
342}
343
344impl<'a> Tabs<'a> {
345    /// The entry of `uuid`.
346    #[inline]
347    pub(crate) fn get(self, uuid: &Uuid) -> Option<TabRef<'a>> {
348        if let Some(p) = self.players.get(uuid) {
349            return Some(TabRef {
350                name: &p.name,
351                game_mode: p.game_mode,
352                generation: p.generation,
353            });
354        }
355        if self.lite.is_empty() {
356            return None;
357        }
358        let t = self.lite.get(uuid)?;
359        let name = if t.len == TabLite::LONG {
360            self.long_names.get(uuid).map_or("", |n| &**n)
361        } else {
362            std::str::from_utf8(&t.name[..usize::from(t.len)]).unwrap_or("")
363        };
364        Some(TabRef {
365            name,
366            game_mode: t.game_mode,
367            generation: t.generation,
368        })
369    }
370}
371
372/// The tracked entities and tab list (queries are the same for every version).
373#[derive(Clone, Debug, Default)]
374pub struct Entities {
375    pub(crate) map: Fast<i32, Entity>,
376    pub(crate) self_id: Option<i32>,
377    pub(crate) config: Config,
378    pub(crate) events: Vec<Event>,
379    pub(crate) players: Fast<Uuid, PlayerInfo>,
380    /// The names-only tab list ([`Config::player_names`] without [`Config::player_list`]).
381    pub(crate) lite: Fast<Uuid, TabLite>,
382    /// Names-only entries whose name does not fit inline.
383    pub(crate) long_names: Fast<Uuid, Box<str>>,
384    pub(crate) scratch: Vec<(u8, MetaValue)>,
385    /// Set once any leash link exists (skips the leash scan on removal otherwise).
386    pub(crate) any_leash: bool,
387    /// The tracker's protocol family (selects the vanilla size table).
388    pub(crate) era: crate::entity::Era,
389    /// Modern trackers: a living mount the bot steers (the client set it; vanilla moves it
390    /// itself and ignores the server's relative moves of it).
391    pub(crate) steered: Option<i32>,
392    /// Last tab list object generation handed out.
393    pub(crate) generations: u32,
394    /// The client's tick clock ([`Entities::set_tick`]).
395    pub(crate) now: u64,
396    /// The client view is on (`track_client_motion`): living entities carry their drawn state
397    /// and clocks.
398    pub(crate) client_motion: bool,
399    /// Entities whose drawn state still changes on the next client tick (interpolation steps
400    /// left): a tick without any visits nothing.
401    pub(crate) lerping: u32,
402    /// The client view's chunk-section list counter (spawns and section changes).
403    pub(crate) order_seq: u32,
404    /// Scratch for the entities that changed sections in a tick.
405    pub(crate) order_scratch: Vec<(u32, i32, [i32; 3])>,
406    /// 26.3: the stepped interpolations of living entities, by id (empty for other versions).
407    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
408    pub(crate) stepped: Fast<i32, crate::modern_state::Stepped>,
409    /// 26.3: the sleeping positions of living entities, by id (only kept until the entity's
410    /// first tick checks its bed; empty for other versions).
411    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
412    pub(crate) sleeping: Fast<i32, [i32; 3]>,
413    /// The client copies' own motion of the [`Config::motion_types`] entities, by id (only
414    /// non-zero ones are kept).
415    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
416    pub(crate) motions: Fast<i32, [f64; 3]>,
417}
418
419impl Entities {
420    pub(crate) fn new(config: Config) -> Self {
421        Entities {
422            config,
423            client_motion: config.client_motion,
424            ..Default::default()
425        }
426    }
427
428    /// The entity with this id (including the bot's own entry, see [`Entities::self_id`]).
429    #[inline]
430    #[must_use]
431    pub fn get(&self, id: i32) -> Option<&Entity> {
432        self.map.get(&id)
433    }
434
435    /// Number of tracked entities (including the bot's own entry).
436    #[must_use]
437    pub fn len(&self) -> usize {
438        self.map.len()
439    }
440
441    /// `true` when nothing is tracked.
442    #[must_use]
443    pub fn is_empty(&self) -> bool {
444        self.map.is_empty()
445    }
446
447    /// Other entities (the bot's own entry is skipped), arbitrary order.
448    pub fn iter(&self) -> impl Iterator<Item = &Entity> {
449        let me = self.self_id;
450        self.map.values().filter(move |e| Some(e.id) != me)
451    }
452
453    /// The bot's own entity id (from `login`). Its entry carries metadata, equipment, riding
454    /// state and effects as far as the [`Config`] keeps them, but **no position**: the client
455    /// owns its own position. The ghast client tracks entities with [`Config::effects`] and
456    /// [`Config::equipment`] off: use `TickContext::effects` for the bot's own effects.
457    #[must_use]
458    pub fn self_id(&self) -> Option<i32> {
459        self.self_id
460    }
461
462    /// The bot's own entry (see [`Entities::self_id`] for what it carries).
463    #[must_use]
464    pub fn me(&self) -> Option<&Entity> {
465        self.map.get(&self.self_id?)
466    }
467
468    /// Entities whose server position is within `radius` of `p` (linear scan).
469    pub fn within(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
470        let r2 = radius * radius;
471        self.iter().filter(move |e| {
472            let d = [e.pos[0] - p[0], e.pos[1] - p[1], e.pos[2] - p[2]];
473            d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= r2
474        })
475    }
476
477    /// Alias of [`Entities::within`].
478    pub fn near(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
479        self.within(p, radius)
480    }
481
482    /// The tab list.
483    #[must_use]
484    pub fn player_info(&self, uuid: &Uuid) -> Option<&PlayerInfo> {
485        self.players.get(uuid)
486    }
487
488    /// All tab-list entries.
489    pub fn players(&self) -> impl Iterator<Item = (&Uuid, &PlayerInfo)> {
490        self.players.iter()
491    }
492
493    /// Name of a player entity (from the tab list: the full one, or the names-only one of
494    /// [`Config::player_names`]).
495    #[must_use]
496    pub fn player_name(&self, id: i32) -> Option<&str> {
497        let e = self.map.get(&id)?;
498        e.is_player()
499            .then(|| self.tab(&e.uuid).map(|t| t.name))
500            .flatten()
501    }
502
503    /// Profile name of a tab-list entry (full list or names only).
504    #[must_use]
505    pub fn tab_name(&self, uuid: &Uuid) -> Option<&str> {
506        self.tab(uuid).map(|t| t.name)
507    }
508
509    /// The motion (`getDeltaMovement`) of the client copy of entity `id` when its type is one of
510    /// [`Config::motion_types`]: zero once it has run out (or was never set), `None` for other
511    /// types and unknown ids. Modern (26.x) trackers only.
512    #[must_use]
513    pub fn client_motion(&self, id: i32) -> Option<[f64; 3]> {
514        let e = self.map.get(&id)?;
515        let EntityType::Registry(t) = e.ty else {
516            return None;
517        };
518        if !self.config.motion_types.contains(&t) {
519            return None;
520        }
521        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
522        if let Some(v) = self.motions.get(&id) {
523            return Some(*v);
524        }
525        Some([0.0; 3])
526    }
527
528    /// The local player pushed entity `id`: `delta` (x, z) is added to its client motion, for
529    /// a [`Config::motion_types`] entity (others: nothing).
530    pub(crate) fn push_motion(&mut self, id: i32, delta: [f64; 2]) {
531        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
532        if self.client_motion(id).is_some() {
533            let v = self.motions.entry(id).or_insert([0.0; 3]);
534            let n = [v[0] + delta[0], v[1], v[2] + delta[1]];
535            if n.iter().all(|c| c.is_finite()) {
536                *v = n;
537            }
538            if let Some(e) = self.map.get_mut(&id) {
539                e.m.set_flag(crate::modern_state::st::SETTLED, false);
540            }
541        }
542        #[cfg(not(any(feature = "v26_1", feature = "v26_2", feature = "v26_3")))]
543        let _ = (id, delta);
544    }
545
546    /// Sets the client motion of a [`Config::motion_types`] entity (`setDeltaMovement`).
547    #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
548    pub(crate) fn set_motion(&mut self, id: i32, ty: EntityType, v: [f64; 3]) {
549        let EntityType::Registry(t) = ty else {
550            return;
551        };
552        if !self.config.motion_types.contains(&t) {
553            return;
554        }
555        if v.iter().all(|c| c.to_bits() == 0) {
556            self.motions.remove(&id);
557        } else {
558            self.motions.insert(id, v);
559        }
560    }
561
562    /// The uuid of the tab-list entry (full list or names only) with profile name `name`.
563    #[must_use]
564    pub fn tab_uuid(&self, name: &str) -> Option<Uuid> {
565        let tabs = self.tabs();
566        self.players
567            .keys()
568            .chain(self.lite.keys())
569            .find(|u| tabs.get(u).is_some_and(|t| t.name == name))
570            .copied()
571    }
572
573    /// Game mode of a tab-list entry (full list or names only).
574    #[must_use]
575    pub fn tab_game_mode(&self, uuid: &Uuid) -> Option<i32> {
576        self.tab(uuid).map(|t| t.game_mode)
577    }
578
579    /// Number of tab-list entries kept (full list or names only).
580    #[must_use]
581    pub fn tab_len(&self) -> usize {
582        self.players.len() + self.lite.len()
583    }
584
585    /// The names-only list is in use.
586    #[inline]
587    pub(crate) fn lite_mode(&self) -> bool {
588        !self.config.player_list && self.config.player_names
589    }
590
591    /// The tab-list entry of `uuid` (full or names only).
592    #[inline]
593    pub(crate) fn tab(&self, uuid: &Uuid) -> Option<TabRef<'_>> {
594        self.tabs().get(uuid)
595    }
596
597    /// The tab lists, borrowed apart from the entity map.
598    #[inline]
599    pub(crate) fn tabs(&self) -> Tabs<'_> {
600        Tabs {
601            players: &self.players,
602            lite: &self.lite,
603            long_names: &self.long_names,
604        }
605    }
606
607    /// `true` when the tab list (full or names only) has `uuid`.
608    #[inline]
609    pub(crate) fn tab_has(&self, uuid: &Uuid) -> bool {
610        self.players.contains_key(uuid) || self.lite.contains_key(uuid)
611    }
612
613    /// Adds a names-only entry unless `uuid` has one (vanilla's `putIfAbsent`; 1.8 – 1.16
614    /// replace, `replace` = true). Returns `true` when an entry was added.
615    pub(crate) fn lite_add(
616        &mut self,
617        uuid: Uuid,
618        name: &str,
619        game_mode: i32,
620        generation: u32,
621        replace: bool,
622    ) -> bool {
623        if !replace && self.lite.contains_key(&uuid) {
624            return false;
625        }
626        let mut t = TabLite {
627            name: [0; TabLite::INLINE],
628            len: TabLite::LONG,
629            game_mode,
630            generation,
631        };
632        if name.len() <= TabLite::INLINE {
633            t.name[..name.len()].copy_from_slice(name.as_bytes());
634            t.len = name.len() as u8;
635            if self.long_names.remove(&uuid).is_some() {
636                shrink_map(&mut self.long_names);
637            }
638        } else {
639            self.long_names.insert(uuid, Box::from(name));
640        }
641        let cap = self.lite.capacity();
642        self.lite.insert(uuid, t);
643        after_insert(&mut self.lite, cap);
644        true
645    }
646
647    /// Removes `uuid` from the tab list (full or names only): its game mode and generation.
648    pub(crate) fn tab_remove(&mut self, uuid: &Uuid) -> Option<(i32, u32)> {
649        if let Some(p) = self.players.remove(uuid) {
650            shrink_map(&mut self.players);
651            return Some((p.game_mode, p.generation));
652        }
653        let t = self.lite.remove(uuid)?;
654        if t.len == TabLite::LONG && self.long_names.remove(uuid).is_some() {
655            shrink_map(&mut self.long_names);
656        }
657        shrink_map(&mut self.lite);
658        Some((t.game_mode, t.generation))
659    }
660
661    /// Sets the game mode of a names-only entry.
662    #[inline]
663    pub(crate) fn lite_game_mode(&mut self, uuid: &Uuid, game_mode: i32) {
664        if let Some(t) = self.lite.get_mut(uuid) {
665            t.game_mode = game_mode;
666        }
667    }
668
669    /// The configuration.
670    #[must_use]
671    pub fn config(&self) -> Config {
672        self.config
673    }
674
675    /// Takes the queued events (keeps the buffer's capacity).
676    pub fn drain_events(&mut self) -> std::vec::Drain<'_, Event> {
677        self.events.drain(..)
678    }
679
680    /// Removes every entity (keeps the tab list and the bot's id).
681    pub fn clear(&mut self) {
682        if self.config.events {
683            let me = self.self_id;
684            self.events.extend(
685                self.map
686                    .values()
687                    .filter(|e| Some(e.id) != me)
688                    .map(|e| Event::Removed { id: e.id, ty: e.ty }),
689            );
690        }
691        let me = self.self_id.and_then(|id| self.map.remove(&id));
692        self.map.clear();
693        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
694        {
695            self.stepped.clear();
696            shrink_map(&mut self.stepped);
697            self.sleeping.clear();
698            shrink_map(&mut self.sleeping);
699            self.motions.clear();
700            shrink_map(&mut self.motions);
701        }
702        self.lerping = 0;
703        shrink_map(&mut self.map);
704        if let Some(mut me) = me {
705            me.set_vehicle(None);
706            if let Some(l) = &mut me.links {
707                l.passengers.clear();
708                l.leash_holder = None;
709            }
710            me.tidy_links();
711            self.map.insert(me.id, me);
712        }
713    }
714
715    #[inline]
716    pub(crate) fn event(&mut self, e: Event) {
717        if self.config.events {
718            self.events.push(e);
719        }
720    }
721
722    pub(crate) fn set_self(&mut self, id: i32) {
723        if let Some(old) = self.self_id {
724            self.map.remove(&old);
725        }
726        self.self_id = Some(id);
727        let mut me = Entity::new(id, EntityType::Player);
728        self.resolve(&mut me);
729        self.map.insert(id, me);
730    }
731
732    /// Stamps the protocol family and resolves the vanilla size entry.
733    fn resolve(&self, e: &mut Entity) {
734        use crate::entity::Era;
735        e.era = self.era;
736        e.sizer = match self.era {
737            #[cfg(feature = "v1_8")]
738            Era::V1_8 => crate::v1_8::vanilla_size(e),
739            #[cfg(feature = "v1_12")]
740            Era::V1_12 => crate::v1_12::vanilla_size(e),
741            #[cfg(feature = "v1_16_5")]
742            Era::V1_16 => crate::v1_16_5::vanilla_size(e),
743            #[cfg(feature = "v26_1")]
744            Era::V26 => crate::v26_1::vanilla_size(e),
745            #[cfg(feature = "v26_2")]
746            Era::V26_2 => crate::v26_2::vanilla_size(e),
747            #[cfg(feature = "v26_3")]
748            Era::V26_3 => crate::v26_3::vanilla_size(e),
749            #[allow(unreachable_patterns)]
750            _ => None,
751        };
752    }
753
754    /// Sets the clock that stamps [`Entity::position_tick`], [`Entity::spawn_tick`] and
755    /// [`Entity::last_hurt_tick`] (the ghast client sets it to the tick in which the behaviour
756    /// first sees the packets that follow).
757    pub fn set_tick(&mut self, now: u64) {
758        self.now = now;
759    }
760
761    /// The clock set with [`Entities::set_tick`].
762    #[must_use]
763    pub fn tick(&self) -> u64 {
764        self.now
765    }
766
767    /// Attaches the client view's state to a spawning entity (living entities, with the view on).
768    #[inline]
769    fn attach_client(&mut self, e: &mut Entity) {
770        use crate::drawn::{Client, Lerp, legacy_lerp};
771        use crate::entity::Era;
772        let lerp = match e.era {
773            Era::V1_8 | Era::V1_12 => legacy_lerp(e),
774            _ if e.living => Some(Lerp::External),
775            // 1.16.5 boats (registry id 6), armor stands (1, living, spawned as objects) and
776            // minecarts interpolate in the client view.
777            Era::V1_16
778                if matches!(e.ty, EntityType::Registry(6 | 1))
779                    || e.sizer.is_some_and(|s| s.name.ends_with("minecart")) =>
780            {
781                Some(Lerp::External)
782            }
783            _ => None,
784        };
785        if let Some(l) = lerp {
786            self.order_seq = self.order_seq.wrapping_add(1);
787            e.client = Some(Box::new(Client::new(e, l, self.now, self.order_seq)));
788        }
789    }
790
791    /// Turns the client view on or off for every tracked entity (on: drawn where the server has
792    /// them now).
793    pub(crate) fn set_client_motion(&mut self, on: bool) {
794        if on == self.client_motion {
795            return;
796        }
797        self.client_motion = on;
798        self.lerping = 0;
799        let mut map = std::mem::take(&mut self.map);
800        for e in map.values_mut() {
801            if on && Some(e.id) != self.self_id {
802                self.attach_client(e);
803            } else {
804                e.client = None;
805            }
806        }
807        self.map = map;
808    }
809
810    /// One client tick of the legacy (1.8 / 1.12) drawn positions.
811    pub(crate) fn step_drawn(&mut self) {
812        if self.lerping == 0 {
813            return;
814        }
815        let mut ended = 0;
816        let mut moved = std::mem::take(&mut self.order_scratch);
817        for e in self.map.values_mut() {
818            let on_ground = e.on_ground;
819            if let Some(c) = e.client.as_deref_mut()
820                && c.busy()
821            {
822                ended += u32::from(c.step(on_ground));
823                // World.checkChunk after the entity's tick: another section's list takes it.
824                let sec = crate::drawn::section_of(c.pos);
825                if sec != c.section {
826                    moved.push((c.spawn_seq, e.id, sec));
827                }
828            }
829        }
830        self.lerping -= ended;
831        if matches!(
832            self.era,
833            crate::entity::Era::V1_8 | crate::entity::Era::V1_12
834        ) && self.map.values().any(Entity::rides)
835        {
836            self.seat_riders(&mut moved);
837        }
838        if !moved.is_empty() {
839            self.resection(&mut moved);
840        }
841        self.order_scratch = moved;
842    }
843
844    /// 1.8 `tickRiding`: after its vehicle's tick a rider sits where the vehicle's
845    /// `updatePassengerPosition` puts it, then its own chunk check follows its vehicle's.
846    #[cold]
847    #[inline(never)]
848    fn seat_riders(&mut self, moved: &mut Vec<(u32, i32, [i32; 3])>) {
849        let riders: Vec<(i32, i32)> = self
850            .map
851            .values()
852            .filter_map(|e| e.vehicle().map(|v| (e.id, v)))
853            .collect();
854        for (rid, vid) in riders {
855            let Some(v) = self.map.get(&vid) else {
856                continue;
857            };
858            let Some(vc) = v.client.as_deref() else {
859                continue;
860            };
861            let Some(r) = self.map.get(&rid) else {
862                continue;
863            };
864            let seat = if self.era == crate::entity::Era::V1_8 {
865                crate::drawn::seat_1_8(v, vc, r).map(|p| (p, None))
866            } else {
867                crate::drawn::seat_1_12(v, vc, r)
868            };
869            let Some((seat, yaw)) = seat else {
870                continue;
871            };
872            let vseq = vc.spawn_seq;
873            if let Some(rc) = self.map.get_mut(&rid).and_then(|e| e.client.as_deref_mut()) {
874                rc.pos = seat;
875                rc.bb = None;
876                if let Some(y) = yaw {
877                    rc.rot[0] = y;
878                }
879                let sec = crate::drawn::section_of(seat);
880                if sec != rc.section {
881                    // The rider's check runs right after its vehicle's.
882                    moved.retain(|m| m.1 != rid);
883                    moved.push((vseq, rid, sec));
884                }
885            }
886        }
887    }
888
889    /// The entities that changed sections in this tick join their new lists in the world's
890    /// tick order (spawn order).
891    #[cold]
892    #[inline(never)]
893    fn resection(&mut self, moved: &mut Vec<(u32, i32, [i32; 3])>) {
894        // Spawn order; a rider (keyed by its vehicle's) after its vehicle.
895        let riders: Vec<i32> = moved
896            .iter()
897            .filter(|m| self.map.get(&m.1).is_some_and(Entity::rides))
898            .map(|m| m.1)
899            .collect();
900        moved.sort_by_key(|m| (m.0, riders.contains(&m.1)));
901        for &(_, id, sec) in moved.iter() {
902            self.order_seq = self.order_seq.wrapping_add(1);
903            if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
904                c.section = sec;
905                c.seq = self.order_seq;
906            }
907        }
908        moved.clear();
909    }
910
911    /// The count of interpolating entities changed by `d` ([`crate::drawn::relative`] /
912    /// `teleport`).
913    #[inline]
914    pub(crate) fn lerp_changed(&mut self, d: i32) {
915        self.lerping = self.lerping.wrapping_add_signed(d);
916    }
917
918    /// An entity left the store: it no longer counts as interpolating.
919    #[inline]
920    fn forget_lerp(&mut self, e: &Entity) {
921        if e.client.as_ref().is_some_and(|c| c.busy()) {
922            self.lerping -= 1;
923        }
924    }
925
926    /// 1.8.9 / 1.12.2: a moving piston moved entity `id` on the client (`Entity.move`): the
927    /// client view draws it at `pos` with box `bb` (`[min_x, min_y, min_z, max_x, max_y,
928    /// max_z]`) until its next interpolation step, and keeps its ground and web state. `false`
929    /// when the client view does not keep the entity.
930    pub(crate) fn legacy_pushed(
931        &mut self,
932        id: i32,
933        pos: [f64; 3],
934        bb: [f64; 6],
935        on_ground: bool,
936        in_web: bool,
937    ) -> bool {
938        let Some(e) = self.map.get_mut(&id) else {
939            return false;
940        };
941        // A 1.12 shulker's attached block (entity data 13).
942        let attached = matches!(
943            e.meta.get(13),
944            Some(crate::entity::MetaValue::OptBlockPos(Some(_)))
945        );
946        let Some(c) = e.client.as_deref_mut() else {
947            return false;
948        };
949        if c.lerp == crate::drawn::Lerp::External {
950            return false;
951        }
952        let d = c.legacy_pushed(pos, bb, on_ground, in_web, attached);
953        self.lerp_changed(d);
954        true
955    }
956
957    /// The client's own hit on entity `id` pushed it (`Entity.addVelocity` after an attack the
958    /// client counts as landed): a 1.8 boat drifts by it in the client view.
959    pub(crate) fn knock(&mut self, id: i32, d: [f64; 3]) {
960        if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
961            let x = c.add_velocity(d);
962            self.lerp_changed(x);
963        }
964    }
965
966    /// A hurt (status or damage event) of entity `id`: stamps it and queues [`Event::Hurt`].
967    #[inline]
968    pub(crate) fn hurt(&mut self, id: i32, attacker: Option<i32>) {
969        let now = self.now;
970        if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
971            c.hurt = Some(now);
972        }
973        self.event(Event::Hurt { id, attacker });
974    }
975
976    /// Adds an entity, replacing (and unlinking) any entity with the same id, as vanilla does.
977    pub(crate) fn spawn(&mut self, mut e: Entity) {
978        let id = e.id;
979        self.resolve(&mut e);
980        if Some(id) == self.self_id {
981            return;
982        }
983        if self.client_motion {
984            self.attach_client(&mut e);
985        }
986        if self.map.contains_key(&id) {
987            self.unlink(id);
988        }
989        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
990        if !self.stepped.is_empty() {
991            self.stepped.remove(&id);
992        }
993        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
994        if !self.sleeping.is_empty() {
995            self.sleeping.remove(&id);
996        }
997        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
998        if !self.motions.is_empty() {
999            self.motions.remove(&id);
1000        }
1001        let cap = self.map.capacity();
1002        if let Some(old) = self.map.insert(id, e) {
1003            self.forget_lerp(&old);
1004        }
1005        after_insert(&mut self.map, cap);
1006        self.event(Event::Spawned(id));
1007    }
1008
1009    pub(crate) fn remove(&mut self, id: i32) -> bool {
1010        if Some(id) == self.self_id || !self.map.contains_key(&id) {
1011            return false;
1012        }
1013        self.unlink(id);
1014        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1015        if !self.stepped.is_empty() {
1016            self.stepped.remove(&id);
1017        }
1018        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1019        if !self.sleeping.is_empty() {
1020            self.sleeping.remove(&id);
1021        }
1022        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1023        if !self.motions.is_empty() {
1024            self.motions.remove(&id);
1025        }
1026        if let Some(e) = self.map.remove(&id) {
1027            self.forget_lerp(&e);
1028            self.event(Event::Removed { id, ty: e.ty });
1029        }
1030        shrink_map(&mut self.map);
1031        true
1032    }
1033
1034    /// Detaches `id` from its vehicle, passengers and leash links.
1035    fn unlink(&mut self, id: i32) {
1036        let Some(e) = self.map.get_mut(&id) else {
1037            return;
1038        };
1039        if e.links.is_none() && !e.rides() && !self.any_leash {
1040            return;
1041        }
1042        let vehicle = e.take_vehicle();
1043        let passengers = e.take_passengers();
1044        if let Some(v) = vehicle
1045            && let Some(v) = self.map.get_mut(&v)
1046        {
1047            v.remove_passenger(id);
1048        }
1049        for p in passengers {
1050            if let Some(p) = self.map.get_mut(&p)
1051                && p.vehicle() == Some(id)
1052            {
1053                p.set_vehicle(None);
1054            }
1055        }
1056        if self.any_leash {
1057            for other in self.map.values_mut() {
1058                if other.leash_holder() == Some(id) {
1059                    other.set_leash_holder(None);
1060                }
1061            }
1062        }
1063    }
1064
1065    /// `startRiding` in the client view: a 1.8 dismount puts the rider on top of its old
1066    /// vehicle (`refreshPositionAndAngles(x, minY + height, z)`); a mount seats it at the next
1067    /// tick (`updatePassengerPosition`).
1068    #[cold]
1069    #[inline(never)]
1070    fn seat_change(&mut self, rider: i32, old: Option<i32>, vehicle: Option<i32>) {
1071        let top = match (vehicle, old.and_then(|o| self.map.get(&o))) {
1072            // 1.12's client moves nothing at a dismount.
1073            (None, Some(o)) if self.era == crate::entity::Era::V1_8 => {
1074                o.client.as_deref().and_then(|c| {
1075                    let h = o.sizer.and_then(|s| s.registered).map(|(_, h)| h)?;
1076                    Some([c.pos[0], c.pos[1] + f64::from(h), c.pos[2]])
1077                })
1078            }
1079            _ => None,
1080        };
1081        let Some(c) = self
1082            .map
1083            .get_mut(&rider)
1084            .and_then(|e| e.client.as_deref_mut())
1085        else {
1086            return;
1087        };
1088        let idle = !c.busy();
1089        if let Some(p) = top {
1090            c.pos = p;
1091            c.bb = None;
1092        }
1093        c.order_pending = true;
1094        let d = i32::from(c.busy()) - i32::from(!idle);
1095        self.lerp_changed(d);
1096    }
1097
1098    /// `true` when `vehicle` is `rider` or (indirectly) rides `rider`.
1099    fn rides(&self, vehicle: i32, rider: i32) -> bool {
1100        let mut cur = Some(vehicle);
1101        let mut guard = 0;
1102        while let Some(c) = cur {
1103            if c == rider {
1104                return true;
1105            }
1106            guard += 1;
1107            if guard > 64 {
1108                return true;
1109            }
1110            cur = self.map.get(&c).and_then(Entity::vehicle);
1111        }
1112        false
1113    }
1114
1115    /// Makes `rider` ride `vehicle` (or dismount with `None`). `single` = 1.8 semantics (one
1116    /// rider per vehicle: a previous rider is dismounted). Returns `false` when ignored.
1117    pub(crate) fn mount(&mut self, rider: i32, vehicle: Option<i32>, single: bool) -> bool {
1118        if !self.map.contains_key(&rider) {
1119            return false;
1120        }
1121        if let Some(v) = vehicle
1122            && (!self.map.contains_key(&v) || self.rides(v, rider))
1123        {
1124            return false;
1125        }
1126        // Leave the old vehicle.
1127        let old = self.map.get_mut(&rider).and_then(Entity::take_vehicle);
1128        if let Some(o) = old
1129            && let Some(o) = self.map.get_mut(&o)
1130        {
1131            o.remove_passenger(rider);
1132        }
1133        if self.client_motion
1134            && matches!(
1135                self.era,
1136                crate::entity::Era::V1_8 | crate::entity::Era::V1_12
1137            )
1138        {
1139            self.seat_change(rider, old, vehicle);
1140        }
1141        if let Some(v) = vehicle {
1142            let prev: Vec<i32> = if single {
1143                self.map
1144                    .get_mut(&v)
1145                    .map(Entity::take_passengers)
1146                    .unwrap_or_default()
1147            } else {
1148                Vec::new()
1149            };
1150            for p in prev {
1151                if let Some(p) = self.map.get_mut(&p) {
1152                    p.set_vehicle(None);
1153                }
1154            }
1155            if let Some(ve) = self.map.get_mut(&v) {
1156                ve.push_passenger(rider);
1157            }
1158            if let Some(r) = self.map.get_mut(&rider) {
1159                r.set_vehicle(Some(v));
1160            }
1161        }
1162        self.event(Event::Mounted { id: rider, vehicle });
1163        true
1164    }
1165
1166    /// 1.16 `set_passengers`: ejects every current passenger of `vehicle`, then mounts `ids`.
1167    pub(crate) fn set_passengers(&mut self, vehicle: i32, ids: impl Iterator<Item = i32>) -> bool {
1168        let Some(v) = self.map.get_mut(&vehicle) else {
1169            return false;
1170        };
1171        let old = v.take_passengers();
1172        for p in &old {
1173            if let Some(p) = self.map.get_mut(p)
1174                && p.vehicle() == Some(vehicle)
1175            {
1176                p.set_vehicle(None);
1177            }
1178        }
1179        // Reuse the old buffer for the new list (no allocation in steady state).
1180        let mut old = old;
1181        old.clear();
1182        if let Some(v) = self.map.get_mut(&vehicle) {
1183            v.set_passengers(old);
1184        }
1185        for id in ids {
1186            self.mount(id, Some(vehicle), false);
1187        }
1188        true
1189    }
1190
1191    pub(crate) fn leash(&mut self, id: i32, holder: Option<i32>) -> bool {
1192        match self.map.get_mut(&id) {
1193            Some(e) => {
1194                e.set_leash_holder(holder);
1195                self.any_leash |= holder.is_some();
1196                true
1197            }
1198            None => false,
1199        }
1200    }
1201}
1202
1203#[cfg(test)]
1204mod tests {
1205    use super::*;
1206
1207    fn store() -> Entities {
1208        let mut s = Entities::new(Config {
1209            events: true,
1210            ..Config::default()
1211        });
1212        for id in 1..=4 {
1213            s.spawn(Entity::new(id, EntityType::Registry(6)));
1214        }
1215        s
1216    }
1217
1218    /// Bytes per tracked entity (the map slot adds the 4-byte key, padded).
1219    #[test]
1220    fn entity_size() {
1221        let n = std::mem::size_of::<Entity>();
1222        eprintln!("size_of::<Entity>() = {n}");
1223        // 0.3.0 – 0.4.3: 232 bytes. Riding, leash and effects sit behind one pointer, the
1224        // metadata is an exact-size block (pointer + length); the 26.x state is boxed.
1225        // 0.4.8: + 8 bytes, the pointer to the client view's drawn state and clocks.
1226        let modern = cfg!(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"));
1227        assert!(n <= if modern { 176 } else { 168 }, "{n}");
1228        #[cfg(any(feature = "v26_1", feature = "v26_2", feature = "v26_3"))]
1229        {
1230            let b = std::mem::size_of::<crate::modern_state::State>();
1231            eprintln!("size_of::<modern_state::State>() = {b} (heap, 26.x entities only)");
1232            assert!(b <= 120, "{b}");
1233        }
1234    }
1235
1236    #[test]
1237    fn mount_single_and_multi() {
1238        let mut s = store();
1239        assert!(s.mount(1, Some(2), true));
1240        assert!(s.mount(3, Some(2), true)); // 1.8: replaces rider 1
1241        assert_eq!(s.get(2).unwrap().passengers(), &[3]);
1242        assert_eq!(s.get(1).unwrap().vehicle(), None);
1243        assert!(!s.mount(2, Some(3), true), "cycle");
1244        assert!(s.set_passengers(4, [1, 3].into_iter()));
1245        assert_eq!(s.get(4).unwrap().passengers(), &[1, 3]);
1246        assert_eq!(s.get(2).unwrap().passengers(), &[] as &[i32]);
1247        assert_eq!(s.get(3).unwrap().vehicle(), Some(4));
1248        s.remove(4);
1249        assert_eq!(s.get(1).unwrap().vehicle(), None);
1250        assert_eq!(s.get(3).unwrap().vehicle(), None);
1251    }
1252
1253    #[test]
1254    fn self_entry_survives_clear() {
1255        let mut s = store();
1256        s.set_self(9);
1257        s.spawn(Entity::new(9, EntityType::Registry(1))); // ignored: own id
1258        assert_eq!(s.get(9).unwrap().entity_type(), EntityType::Player);
1259        assert!(!s.remove(9));
1260        s.drain_events().for_each(drop);
1261        s.clear();
1262        assert_eq!(s.len(), 1);
1263        assert!(s.me().is_some());
1264        assert_eq!(s.drain_events().count(), 4);
1265        assert_eq!(s.iter().count(), 0);
1266    }
1267}