ghast-entity 0.4.11

Entity tracking for the ghast Minecraft Java Edition client library: zero-allocation parsing of 1.8.9, 1.12.2, 1.16.5, 26.1 and 26.2 entity packets, vanilla-exact positions, O(1) lookup
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
//! Version-independent entity store shared by the per-version trackers.

use std::collections::HashMap;
use std::hash::{BuildHasherDefault, Hasher};

use uuid::Uuid;

use crate::entity::{Entity, EntityType, MetaValue};

/// What the tracker keeps. Everything off costs nothing beyond position tracking; packets for a
/// disabled part are not parsed (and the client should not even decode them, see the version
/// modules' packet id lists).
///
/// `#[non_exhaustive]`: build it from [`Config::default`] with the `with_*` methods:
///
/// ```
/// let c = ghast_entity::Config::default().with_equipment(false).with_skins(true);
/// assert!(c.metadata && !c.equipment && c.skins);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct Config {
    /// Entity metadata (flags, health, item of item entities, names, ...). Default `true`.
    pub metadata: bool,
    /// Equipment. Default `true`.
    pub equipment: bool,
    /// Status effects. Default `true`.
    pub effects: bool,
    /// Tab list (`player_info`). Default `true`.
    pub player_list: bool,
    /// Queue [`Event`]s for [`Entities::drain_events`]. Default `false`.
    pub events: bool,
    /// Keep the base64 `"textures"` profile property (skin / cape URLs) of tab-list entries in
    /// [`PlayerInfo::textures`]. Default `false`: properties are skipped without allocating.
    pub skins: bool,
    /// With [`Config::player_list`] off: still read the tab list, but keep only each entry's
    /// profile name and game mode (inline, about 50 bytes per entry; no [`PlayerInfo`]). That is
    /// what vanilla needs from it for entities: [`Entities::player_name`] (team rules use the
    /// scoreboard name), spectators (not pickable, not pushed, never on the ground) and, on
    /// 26.x, refusing a player spawn whose profile is not in the tab list. Ignored when
    /// [`Config::player_list`] is on (the full list answers the same questions). Default `false`.
    pub player_names: bool,
    /// The client view of the other entities: what the vanilla client draws and picks
    /// ([`Entity::drawn_position`], [`Entity::drawn_bounding_box`]) and the per-entity clocks
    /// ([`Entity::position_tick`], [`Entity::spawn_tick`], [`Entity::last_hurt_tick`],
    /// [`Entity::estimated_velocity`]); the same switch as each tracker's
    /// `track_client_motion`. One small heap block per living entity. Default `false`.
    pub client_motion: bool,
}

impl Config {
    /// Sets [`Config::client_motion`].
    #[must_use]
    pub const fn with_client_motion(mut self, on: bool) -> Self {
        self.client_motion = on;
        self
    }

    /// Sets [`Config::metadata`].
    #[must_use]
    pub const fn with_metadata(mut self, on: bool) -> Self {
        self.metadata = on;
        self
    }

    /// Sets [`Config::equipment`].
    #[must_use]
    pub const fn with_equipment(mut self, on: bool) -> Self {
        self.equipment = on;
        self
    }

    /// Sets [`Config::effects`].
    #[must_use]
    pub const fn with_effects(mut self, on: bool) -> Self {
        self.effects = on;
        self
    }

    /// Sets [`Config::player_list`].
    #[must_use]
    pub const fn with_player_list(mut self, on: bool) -> Self {
        self.player_list = on;
        self
    }

    /// Sets [`Config::events`].
    #[must_use]
    pub const fn with_events(mut self, on: bool) -> Self {
        self.events = on;
        self
    }

    /// Sets [`Config::skins`].
    #[must_use]
    pub const fn with_skins(mut self, on: bool) -> Self {
        self.skins = on;
        self
    }

    /// Sets [`Config::player_names`].
    #[must_use]
    pub const fn with_player_names(mut self, on: bool) -> Self {
        self.player_names = on;
        self
    }

    /// `true` when the tracker reads the tab list (full or names only): its packets
    /// (`PLAYER_LIST_IDS` of the version module) must reach the tracker.
    #[must_use]
    pub const fn reads_tab_list(&self) -> bool {
        self.player_list || self.player_names
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            metadata: true,
            equipment: true,
            effects: true,
            player_list: true,
            events: false,
            skins: false,
            player_names: false,
            client_motion: false,
        }
    }
}

/// A change notification (only queued with [`Config::events`]).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Event {
    /// A new entity (or a replacement for an existing id).
    Spawned(i32),
    /// An entity was removed (destroy, pickup, world change).
    Removed {
        /// Id.
        id: i32,
        /// Its type.
        ty: EntityType,
    },
    /// Server position or rotation changed (movement, teleport).
    Moved(i32),
    /// Velocity changed.
    Velocity(i32),
    /// `entity_status` (e.g. 2 hurt, 3 death).
    Status {
        /// Id.
        id: i32,
        /// Status byte.
        status: i8,
    },
    /// Metadata changed.
    Metadata(i32),
    /// An entity was hurt: 1.8 – 1.16.5 the hurt statuses (2; 1.12+ also 33 thorns, 36
    /// drowning, 37 burning; 1.16 44 sweet berry bush, each also queued as [`Event::Status`]),
    /// 26.x a living entity's `damage_event`. The bot's own entity included.
    Hurt {
        /// Id.
        id: i32,
        /// 26.x: the entity that caused the damage (the shooter for projectiles), if any;
        /// always `None` before 26.x (the status carries no source).
        attacker: Option<i32>,
    },
    /// Equipment changed.
    Equipment(i32),
    /// Effects changed.
    Effects(i32),
    /// Riding changed: `id` now rides `vehicle`.
    Mounted {
        /// Rider.
        id: i32,
        /// Vehicle (`None` = dismounted).
        vehicle: Option<i32>,
    },
    /// An item / orb / arrow was picked up (`collector` may be the bot).
    Collected {
        /// Picked-up entity.
        collected: i32,
        /// Collector.
        collector: i32,
    },
    /// The tab list changed.
    PlayerList,
}

/// A tab-list entry (`#[non_exhaustive]`: read-only for callers, fields may be added).
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct PlayerInfo {
    /// Profile name.
    pub name: Box<str>,
    /// Game mode.
    pub game_mode: i32,
    /// Latency in ms.
    pub ping: i32,
    /// Display name (raw chat JSON), if set (1.8 – 1.16; see
    /// [`PlayerInfo::display_name_nbt`] for 26.1).
    pub display_name: Option<Box<str>>,
    /// The base64 `"textures"` profile property as sent (only with [`Config::skins`]; its
    /// signature is not kept). Decoded it is JSON with the skin and cape URLs.
    pub textures: Option<Box<str>>,
    /// 26.1: the display name as its raw network NBT text component, if set.
    pub display_name_nbt: Option<bytes::Bytes>,
    /// Shown in the tab list (26.1 `UPDATE_LISTED`; always `true` before 26.1).
    pub listed: bool,
    /// 26.1 tab list order (`UPDATE_LIST_ORDER`; 0 before).
    pub list_order: i32,
    /// Which tab list object this is (26.1 player entities keep the one they first saw).
    pub(crate) generation: u32,
}

#[derive(Default, Clone, Copy)]
pub(crate) struct IdHasher(u64);

impl Hasher for IdHasher {
    #[inline]
    fn finish(&self) -> u64 {
        let h = self.0.wrapping_mul(0x9E37_79B9_7F4A_7C15);
        h ^ (h >> 29)
    }

    #[inline]
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = (self.0 << 8) | u64::from(b);
        }
    }

    #[inline]
    fn write_i32(&mut self, v: i32) {
        self.0 = u64::from(v as u32);
    }

    #[inline]
    fn write_u64(&mut self, v: u64) {
        self.0 = v;
    }

    #[inline]
    fn write_u128(&mut self, v: u128) {
        self.0 = (v as u64) ^ ((v >> 64) as u64);
    }
}

pub(crate) type Fast<K, V> = HashMap<K, V, BuildHasherDefault<IdHasher>>;

/// Gives memory back once a map holds less than a quarter of its capacity (a crowd left):
/// shrinks to twice the live entries, so it neither keeps a peak's table forever nor rehashes
/// back and forth around one size. Small maps are left alone.
#[inline]
pub(crate) fn shrink_map<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
    let cap = m.capacity();
    if cap > 64 && m.len() * 4 < cap {
        m.shrink_to(m.len() * 2);
    }
}

/// Call after an insert into `m`, with its `capacity()` before the insert (or after the last
/// insert). hashbrown grows a table whose free slots ran out even when many of them are only
/// deletion markers (ids that came and went), so a steady crowd with fresh ids doubles the
/// table. A growth at least doubles `capacity()`; a real one leaves the table just over half
/// full, one that leaves it at most half full was forced by markers and is undone at once: the
/// table is rebuilt at its live size, which also drops the markers.
#[inline]
pub(crate) fn after_insert<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>, old_cap: usize) {
    let cap = m.capacity();
    if cap >= 2 * old_cap.max(1) && m.len() * 2 <= cap {
        compact(m);
    }
}

#[cold]
#[inline(never)]
fn compact<K: Eq + std::hash::Hash, V>(m: &mut Fast<K, V>) {
    m.shrink_to(m.len());
}

/// A tab-list entry as [`Config::player_names`] keeps it: the profile name inline (a name longer
/// than [`TabLite::INLINE`] bytes lives in `Entities::long_names`), the game mode and the tab
/// list object generation (26.x).
#[derive(Clone, Copy, Debug)]
pub(crate) struct TabLite {
    name: [u8; TabLite::INLINE],
    /// Name length, or [`TabLite::LONG`].
    len: u8,
    pub(crate) game_mode: i32,
    pub(crate) generation: u32,
}

impl TabLite {
    /// Inline name bytes (vanilla profile names are at most 16 characters).
    const INLINE: usize = 23;
    const LONG: u8 = u8::MAX;
}

/// What the tab list says about one profile (full or names-only list).
#[derive(Clone, Copy, Debug)]
pub(crate) struct TabRef<'a> {
    pub(crate) name: &'a str,
    pub(crate) game_mode: i32,
    pub(crate) generation: u32,
}

/// The tab lists of an [`Entities`] (borrowed field by field, so a caller can hold them while
/// it changes entities).
#[derive(Clone, Copy)]
pub(crate) struct Tabs<'a> {
    pub(crate) players: &'a Fast<Uuid, PlayerInfo>,
    pub(crate) lite: &'a Fast<Uuid, TabLite>,
    pub(crate) long_names: &'a Fast<Uuid, Box<str>>,
}

impl<'a> Tabs<'a> {
    /// The entry of `uuid`.
    #[inline]
    pub(crate) fn get(self, uuid: &Uuid) -> Option<TabRef<'a>> {
        if let Some(p) = self.players.get(uuid) {
            return Some(TabRef {
                name: &p.name,
                game_mode: p.game_mode,
                generation: p.generation,
            });
        }
        if self.lite.is_empty() {
            return None;
        }
        let t = self.lite.get(uuid)?;
        let name = if t.len == TabLite::LONG {
            self.long_names.get(uuid).map_or("", |n| &**n)
        } else {
            std::str::from_utf8(&t.name[..usize::from(t.len)]).unwrap_or("")
        };
        Some(TabRef {
            name,
            game_mode: t.game_mode,
            generation: t.generation,
        })
    }
}

/// The tracked entities and tab list (queries are the same for every version).
#[derive(Clone, Debug, Default)]
pub struct Entities {
    pub(crate) map: Fast<i32, Entity>,
    pub(crate) self_id: Option<i32>,
    pub(crate) config: Config,
    pub(crate) events: Vec<Event>,
    pub(crate) players: Fast<Uuid, PlayerInfo>,
    /// The names-only tab list ([`Config::player_names`] without [`Config::player_list`]).
    pub(crate) lite: Fast<Uuid, TabLite>,
    /// Names-only entries whose name does not fit inline.
    pub(crate) long_names: Fast<Uuid, Box<str>>,
    pub(crate) scratch: Vec<(u8, MetaValue)>,
    /// Set once any leash link exists (skips the leash scan on removal otherwise).
    pub(crate) any_leash: bool,
    /// The tracker's protocol family (selects the vanilla size table).
    pub(crate) era: crate::entity::Era,
    /// Last tab list object generation handed out.
    pub(crate) generations: u32,
    /// The client's tick clock ([`Entities::set_tick`]).
    pub(crate) now: u64,
    /// The client view is on (`track_client_motion`): living entities carry their drawn state
    /// and clocks.
    pub(crate) client_motion: bool,
    /// Entities whose drawn state still changes on the next client tick (interpolation steps
    /// left): a tick without any visits nothing.
    pub(crate) lerping: u32,
    /// The client view's chunk-section list counter (spawns and section changes).
    pub(crate) order_seq: u32,
    /// Scratch for the entities that changed sections in a tick.
    pub(crate) order_scratch: Vec<(u32, i32, [i32; 3])>,
}

impl Entities {
    pub(crate) fn new(config: Config) -> Self {
        Entities {
            config,
            client_motion: config.client_motion,
            ..Default::default()
        }
    }

    /// The entity with this id (including the bot's own entry, see [`Entities::self_id`]).
    #[inline]
    #[must_use]
    pub fn get(&self, id: i32) -> Option<&Entity> {
        self.map.get(&id)
    }

    /// Number of tracked entities (including the bot's own entry).
    #[must_use]
    pub fn len(&self) -> usize {
        self.map.len()
    }

    /// `true` when nothing is tracked.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.map.is_empty()
    }

    /// Other entities (the bot's own entry is skipped), arbitrary order.
    pub fn iter(&self) -> impl Iterator<Item = &Entity> {
        let me = self.self_id;
        self.map.values().filter(move |e| Some(e.id) != me)
    }

    /// The bot's own entity id (from `login`). Its entry carries metadata, equipment, riding
    /// state and effects as far as the [`Config`] keeps them, but **no position**: the client
    /// owns its own position. The ghast client tracks entities with [`Config::effects`] and
    /// [`Config::equipment`] off: use `TickContext::effects` for the bot's own effects.
    #[must_use]
    pub fn self_id(&self) -> Option<i32> {
        self.self_id
    }

    /// The bot's own entry (see [`Entities::self_id`] for what it carries).
    #[must_use]
    pub fn me(&self) -> Option<&Entity> {
        self.map.get(&self.self_id?)
    }

    /// Entities whose server position is within `radius` of `p` (linear scan).
    pub fn within(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
        let r2 = radius * radius;
        self.iter().filter(move |e| {
            let d = [e.pos[0] - p[0], e.pos[1] - p[1], e.pos[2] - p[2]];
            d[0] * d[0] + d[1] * d[1] + d[2] * d[2] <= r2
        })
    }

    /// Alias of [`Entities::within`].
    pub fn near(&self, p: [f64; 3], radius: f64) -> impl Iterator<Item = &Entity> {
        self.within(p, radius)
    }

    /// The tab list.
    #[must_use]
    pub fn player_info(&self, uuid: &Uuid) -> Option<&PlayerInfo> {
        self.players.get(uuid)
    }

    /// All tab-list entries.
    pub fn players(&self) -> impl Iterator<Item = (&Uuid, &PlayerInfo)> {
        self.players.iter()
    }

    /// Name of a player entity (from the tab list: the full one, or the names-only one of
    /// [`Config::player_names`]).
    #[must_use]
    pub fn player_name(&self, id: i32) -> Option<&str> {
        let e = self.map.get(&id)?;
        e.is_player()
            .then(|| self.tab(&e.uuid).map(|t| t.name))
            .flatten()
    }

    /// Profile name of a tab-list entry (full list or names only).
    #[must_use]
    pub fn tab_name(&self, uuid: &Uuid) -> Option<&str> {
        self.tab(uuid).map(|t| t.name)
    }

    /// Game mode of a tab-list entry (full list or names only).
    #[must_use]
    pub fn tab_game_mode(&self, uuid: &Uuid) -> Option<i32> {
        self.tab(uuid).map(|t| t.game_mode)
    }

    /// Number of tab-list entries kept (full list or names only).
    #[must_use]
    pub fn tab_len(&self) -> usize {
        self.players.len() + self.lite.len()
    }

    /// The names-only list is in use.
    #[inline]
    pub(crate) fn lite_mode(&self) -> bool {
        !self.config.player_list && self.config.player_names
    }

    /// The tab-list entry of `uuid` (full or names only).
    #[inline]
    pub(crate) fn tab(&self, uuid: &Uuid) -> Option<TabRef<'_>> {
        self.tabs().get(uuid)
    }

    /// The tab lists, borrowed apart from the entity map.
    #[inline]
    pub(crate) fn tabs(&self) -> Tabs<'_> {
        Tabs {
            players: &self.players,
            lite: &self.lite,
            long_names: &self.long_names,
        }
    }

    /// `true` when the tab list (full or names only) has `uuid`.
    #[inline]
    pub(crate) fn tab_has(&self, uuid: &Uuid) -> bool {
        self.players.contains_key(uuid) || self.lite.contains_key(uuid)
    }

    /// Adds a names-only entry unless `uuid` has one (vanilla's `putIfAbsent`; 1.8 – 1.16
    /// replace, `replace` = true). Returns `true` when an entry was added.
    pub(crate) fn lite_add(
        &mut self,
        uuid: Uuid,
        name: &str,
        game_mode: i32,
        generation: u32,
        replace: bool,
    ) -> bool {
        if !replace && self.lite.contains_key(&uuid) {
            return false;
        }
        let mut t = TabLite {
            name: [0; TabLite::INLINE],
            len: TabLite::LONG,
            game_mode,
            generation,
        };
        if name.len() <= TabLite::INLINE {
            t.name[..name.len()].copy_from_slice(name.as_bytes());
            t.len = name.len() as u8;
            if self.long_names.remove(&uuid).is_some() {
                shrink_map(&mut self.long_names);
            }
        } else {
            self.long_names.insert(uuid, Box::from(name));
        }
        let cap = self.lite.capacity();
        self.lite.insert(uuid, t);
        after_insert(&mut self.lite, cap);
        true
    }

    /// Removes `uuid` from the tab list (full or names only): its game mode and generation.
    pub(crate) fn tab_remove(&mut self, uuid: &Uuid) -> Option<(i32, u32)> {
        if let Some(p) = self.players.remove(uuid) {
            shrink_map(&mut self.players);
            return Some((p.game_mode, p.generation));
        }
        let t = self.lite.remove(uuid)?;
        if t.len == TabLite::LONG && self.long_names.remove(uuid).is_some() {
            shrink_map(&mut self.long_names);
        }
        shrink_map(&mut self.lite);
        Some((t.game_mode, t.generation))
    }

    /// Sets the game mode of a names-only entry.
    #[inline]
    pub(crate) fn lite_game_mode(&mut self, uuid: &Uuid, game_mode: i32) {
        if let Some(t) = self.lite.get_mut(uuid) {
            t.game_mode = game_mode;
        }
    }

    /// The configuration.
    #[must_use]
    pub fn config(&self) -> Config {
        self.config
    }

    /// Takes the queued events (keeps the buffer's capacity).
    pub fn drain_events(&mut self) -> std::vec::Drain<'_, Event> {
        self.events.drain(..)
    }

    /// Removes every entity (keeps the tab list and the bot's id).
    pub fn clear(&mut self) {
        if self.config.events {
            let me = self.self_id;
            self.events.extend(
                self.map
                    .values()
                    .filter(|e| Some(e.id) != me)
                    .map(|e| Event::Removed { id: e.id, ty: e.ty }),
            );
        }
        let me = self.self_id.and_then(|id| self.map.remove(&id));
        self.map.clear();
        self.lerping = 0;
        shrink_map(&mut self.map);
        if let Some(mut me) = me {
            me.set_vehicle(None);
            if let Some(l) = &mut me.links {
                l.passengers.clear();
                l.leash_holder = None;
            }
            me.tidy_links();
            self.map.insert(me.id, me);
        }
    }

    #[inline]
    pub(crate) fn event(&mut self, e: Event) {
        if self.config.events {
            self.events.push(e);
        }
    }

    pub(crate) fn set_self(&mut self, id: i32) {
        if let Some(old) = self.self_id {
            self.map.remove(&old);
        }
        self.self_id = Some(id);
        let mut me = Entity::new(id, EntityType::Player);
        self.resolve(&mut me);
        self.map.insert(id, me);
    }

    /// Stamps the protocol family and resolves the vanilla size entry.
    fn resolve(&self, e: &mut Entity) {
        use crate::entity::Era;
        e.era = self.era;
        e.sizer = match self.era {
            #[cfg(feature = "v1_8")]
            Era::V1_8 => crate::v1_8::vanilla_size(e),
            #[cfg(feature = "v1_12")]
            Era::V1_12 => crate::v1_12::vanilla_size(e),
            #[cfg(feature = "v1_16_5")]
            Era::V1_16 => crate::v1_16_5::vanilla_size(e),
            #[cfg(feature = "v26_1")]
            Era::V26 => crate::v26_1::vanilla_size(e),
            #[cfg(feature = "v26_2")]
            Era::V26_2 => crate::v26_2::vanilla_size(e),
            #[allow(unreachable_patterns)]
            _ => None,
        };
    }

    /// Sets the clock that stamps [`Entity::position_tick`], [`Entity::spawn_tick`] and
    /// [`Entity::last_hurt_tick`] (the ghast client sets it to the tick in which the behaviour
    /// first sees the packets that follow).
    pub fn set_tick(&mut self, now: u64) {
        self.now = now;
    }

    /// The clock set with [`Entities::set_tick`].
    #[must_use]
    pub fn tick(&self) -> u64 {
        self.now
    }

    /// Attaches the client view's state to a spawning entity (living entities, with the view on).
    #[inline]
    fn attach_client(&mut self, e: &mut Entity) {
        use crate::drawn::{Client, Lerp, legacy_lerp};
        use crate::entity::Era;
        let lerp = match e.era {
            Era::V1_8 | Era::V1_12 => legacy_lerp(e),
            _ if e.living => Some(Lerp::External),
            // 1.16.5 boats (registry id 6), armor stands (1, living, spawned as objects) and
            // minecarts interpolate in the client view.
            Era::V1_16
                if matches!(e.ty, EntityType::Registry(6 | 1))
                    || e.sizer.is_some_and(|s| s.name.ends_with("minecart")) =>
            {
                Some(Lerp::External)
            }
            _ => None,
        };
        if let Some(l) = lerp {
            self.order_seq = self.order_seq.wrapping_add(1);
            e.client = Some(Box::new(Client::new(e, l, self.now, self.order_seq)));
        }
    }

    /// Turns the client view on or off for every tracked entity (on: drawn where the server has
    /// them now).
    pub(crate) fn set_client_motion(&mut self, on: bool) {
        if on == self.client_motion {
            return;
        }
        self.client_motion = on;
        self.lerping = 0;
        let mut map = std::mem::take(&mut self.map);
        for e in map.values_mut() {
            if on && Some(e.id) != self.self_id {
                self.attach_client(e);
            } else {
                e.client = None;
            }
        }
        self.map = map;
    }

    /// One client tick of the legacy (1.8 / 1.12) drawn positions.
    pub(crate) fn step_drawn(&mut self) {
        if self.lerping == 0 {
            return;
        }
        let mut ended = 0;
        let mut moved = std::mem::take(&mut self.order_scratch);
        for e in self.map.values_mut() {
            let on_ground = e.on_ground;
            if let Some(c) = e.client.as_deref_mut()
                && c.busy()
            {
                ended += u32::from(c.step(on_ground));
                // World.checkChunk after the entity's tick: another section's list takes it.
                let sec = crate::drawn::section_of(c.pos);
                if sec != c.section {
                    moved.push((c.spawn_seq, e.id, sec));
                }
            }
        }
        self.lerping -= ended;
        if matches!(
            self.era,
            crate::entity::Era::V1_8 | crate::entity::Era::V1_12
        ) && self.map.values().any(Entity::rides)
        {
            self.seat_riders(&mut moved);
        }
        if !moved.is_empty() {
            self.resection(&mut moved);
        }
        self.order_scratch = moved;
    }

    /// 1.8 `tickRiding`: after its vehicle's tick a rider sits where the vehicle's
    /// `updatePassengerPosition` puts it, then its own chunk check follows its vehicle's.
    #[cold]
    #[inline(never)]
    fn seat_riders(&mut self, moved: &mut Vec<(u32, i32, [i32; 3])>) {
        let riders: Vec<(i32, i32)> = self
            .map
            .values()
            .filter_map(|e| e.vehicle().map(|v| (e.id, v)))
            .collect();
        for (rid, vid) in riders {
            let Some(v) = self.map.get(&vid) else {
                continue;
            };
            let Some(vc) = v.client.as_deref() else {
                continue;
            };
            let Some(r) = self.map.get(&rid) else {
                continue;
            };
            let seat = if self.era == crate::entity::Era::V1_8 {
                crate::drawn::seat_1_8(v, vc, r).map(|p| (p, None))
            } else {
                crate::drawn::seat_1_12(v, vc, r)
            };
            let Some((seat, yaw)) = seat else {
                continue;
            };
            let vseq = vc.spawn_seq;
            if let Some(rc) = self.map.get_mut(&rid).and_then(|e| e.client.as_deref_mut()) {
                rc.pos = seat;
                rc.bb = None;
                if let Some(y) = yaw {
                    rc.rot[0] = y;
                }
                let sec = crate::drawn::section_of(seat);
                if sec != rc.section {
                    // The rider's check runs right after its vehicle's.
                    moved.retain(|m| m.1 != rid);
                    moved.push((vseq, rid, sec));
                }
            }
        }
    }

    /// The entities that changed sections in this tick join their new lists in the world's
    /// tick order (spawn order).
    #[cold]
    #[inline(never)]
    fn resection(&mut self, moved: &mut Vec<(u32, i32, [i32; 3])>) {
        // Spawn order; a rider (keyed by its vehicle's) after its vehicle.
        let riders: Vec<i32> = moved
            .iter()
            .filter(|m| self.map.get(&m.1).is_some_and(Entity::rides))
            .map(|m| m.1)
            .collect();
        moved.sort_by_key(|m| (m.0, riders.contains(&m.1)));
        for &(_, id, sec) in moved.iter() {
            self.order_seq = self.order_seq.wrapping_add(1);
            if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
                c.section = sec;
                c.seq = self.order_seq;
            }
        }
        moved.clear();
    }

    /// The count of interpolating entities changed by `d` ([`crate::drawn::relative`] /
    /// `teleport`).
    #[inline]
    pub(crate) fn lerp_changed(&mut self, d: i32) {
        self.lerping = self.lerping.wrapping_add_signed(d);
    }

    /// An entity left the store: it no longer counts as interpolating.
    #[inline]
    fn forget_lerp(&mut self, e: &Entity) {
        if e.client.as_ref().is_some_and(|c| c.busy()) {
            self.lerping -= 1;
        }
    }

    /// 1.8.9 / 1.12.2: a moving piston moved entity `id` on the client (`Entity.move`): the
    /// client view draws it at `pos` with box `bb` (`[min_x, min_y, min_z, max_x, max_y,
    /// max_z]`) until its next interpolation step, and keeps its ground and web state. `false`
    /// when the client view does not keep the entity.
    pub(crate) fn legacy_pushed(
        &mut self,
        id: i32,
        pos: [f64; 3],
        bb: [f64; 6],
        on_ground: bool,
        in_web: bool,
    ) -> bool {
        let Some(e) = self.map.get_mut(&id) else {
            return false;
        };
        // A 1.12 shulker's attached block (entity data 13).
        let attached = matches!(
            e.meta.get(13),
            Some(crate::entity::MetaValue::OptBlockPos(Some(_)))
        );
        let Some(c) = e.client.as_deref_mut() else {
            return false;
        };
        if c.lerp == crate::drawn::Lerp::External {
            return false;
        }
        let d = c.legacy_pushed(pos, bb, on_ground, in_web, attached);
        self.lerp_changed(d);
        true
    }

    /// The client's own hit on entity `id` pushed it (`Entity.addVelocity` after an attack the
    /// client counts as landed): a 1.8 boat drifts by it in the client view.
    pub(crate) fn knock(&mut self, id: i32, d: [f64; 3]) {
        if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
            let x = c.add_velocity(d);
            self.lerp_changed(x);
        }
    }

    /// A hurt (status or damage event) of entity `id`: stamps it and queues [`Event::Hurt`].
    #[inline]
    pub(crate) fn hurt(&mut self, id: i32, attacker: Option<i32>) {
        let now = self.now;
        if let Some(c) = self.map.get_mut(&id).and_then(|e| e.client.as_deref_mut()) {
            c.hurt = Some(now);
        }
        self.event(Event::Hurt { id, attacker });
    }

    /// Adds an entity, replacing (and unlinking) any entity with the same id, as vanilla does.
    pub(crate) fn spawn(&mut self, mut e: Entity) {
        let id = e.id;
        self.resolve(&mut e);
        if Some(id) == self.self_id {
            return;
        }
        if self.client_motion {
            self.attach_client(&mut e);
        }
        if self.map.contains_key(&id) {
            self.unlink(id);
        }
        let cap = self.map.capacity();
        if let Some(old) = self.map.insert(id, e) {
            self.forget_lerp(&old);
        }
        after_insert(&mut self.map, cap);
        self.event(Event::Spawned(id));
    }

    pub(crate) fn remove(&mut self, id: i32) -> bool {
        if Some(id) == self.self_id || !self.map.contains_key(&id) {
            return false;
        }
        self.unlink(id);
        if let Some(e) = self.map.remove(&id) {
            self.forget_lerp(&e);
            self.event(Event::Removed { id, ty: e.ty });
        }
        shrink_map(&mut self.map);
        true
    }

    /// Detaches `id` from its vehicle, passengers and leash links.
    fn unlink(&mut self, id: i32) {
        let Some(e) = self.map.get_mut(&id) else {
            return;
        };
        if e.links.is_none() && !e.rides() && !self.any_leash {
            return;
        }
        let vehicle = e.take_vehicle();
        let passengers = e.take_passengers();
        if let Some(v) = vehicle
            && let Some(v) = self.map.get_mut(&v)
        {
            v.remove_passenger(id);
        }
        for p in passengers {
            if let Some(p) = self.map.get_mut(&p)
                && p.vehicle() == Some(id)
            {
                p.set_vehicle(None);
            }
        }
        if self.any_leash {
            for other in self.map.values_mut() {
                if other.leash_holder() == Some(id) {
                    other.set_leash_holder(None);
                }
            }
        }
    }

    /// `startRiding` in the client view: a 1.8 dismount puts the rider on top of its old
    /// vehicle (`refreshPositionAndAngles(x, minY + height, z)`); a mount seats it at the next
    /// tick (`updatePassengerPosition`).
    #[cold]
    #[inline(never)]
    fn seat_change(&mut self, rider: i32, old: Option<i32>, vehicle: Option<i32>) {
        let top = match (vehicle, old.and_then(|o| self.map.get(&o))) {
            // 1.12's client moves nothing at a dismount.
            (None, Some(o)) if self.era == crate::entity::Era::V1_8 => {
                o.client.as_deref().and_then(|c| {
                    let h = o.sizer.and_then(|s| s.registered).map(|(_, h)| h)?;
                    Some([c.pos[0], c.pos[1] + f64::from(h), c.pos[2]])
                })
            }
            _ => None,
        };
        let Some(c) = self
            .map
            .get_mut(&rider)
            .and_then(|e| e.client.as_deref_mut())
        else {
            return;
        };
        let idle = !c.busy();
        if let Some(p) = top {
            c.pos = p;
            c.bb = None;
        }
        c.order_pending = true;
        let d = i32::from(c.busy()) - i32::from(!idle);
        self.lerp_changed(d);
    }

    /// `true` when `vehicle` is `rider` or (indirectly) rides `rider`.
    fn rides(&self, vehicle: i32, rider: i32) -> bool {
        let mut cur = Some(vehicle);
        let mut guard = 0;
        while let Some(c) = cur {
            if c == rider {
                return true;
            }
            guard += 1;
            if guard > 64 {
                return true;
            }
            cur = self.map.get(&c).and_then(Entity::vehicle);
        }
        false
    }

    /// Makes `rider` ride `vehicle` (or dismount with `None`). `single` = 1.8 semantics (one
    /// rider per vehicle: a previous rider is dismounted). Returns `false` when ignored.
    pub(crate) fn mount(&mut self, rider: i32, vehicle: Option<i32>, single: bool) -> bool {
        if !self.map.contains_key(&rider) {
            return false;
        }
        if let Some(v) = vehicle
            && (!self.map.contains_key(&v) || self.rides(v, rider))
        {
            return false;
        }
        // Leave the old vehicle.
        let old = self.map.get_mut(&rider).and_then(Entity::take_vehicle);
        if let Some(o) = old
            && let Some(o) = self.map.get_mut(&o)
        {
            o.remove_passenger(rider);
        }
        if self.client_motion
            && matches!(
                self.era,
                crate::entity::Era::V1_8 | crate::entity::Era::V1_12
            )
        {
            self.seat_change(rider, old, vehicle);
        }
        if let Some(v) = vehicle {
            let prev: Vec<i32> = if single {
                self.map
                    .get_mut(&v)
                    .map(Entity::take_passengers)
                    .unwrap_or_default()
            } else {
                Vec::new()
            };
            for p in prev {
                if let Some(p) = self.map.get_mut(&p) {
                    p.set_vehicle(None);
                }
            }
            if let Some(ve) = self.map.get_mut(&v) {
                ve.push_passenger(rider);
            }
            if let Some(r) = self.map.get_mut(&rider) {
                r.set_vehicle(Some(v));
            }
        }
        self.event(Event::Mounted { id: rider, vehicle });
        true
    }

    /// 1.16 `set_passengers`: ejects every current passenger of `vehicle`, then mounts `ids`.
    pub(crate) fn set_passengers(&mut self, vehicle: i32, ids: impl Iterator<Item = i32>) -> bool {
        let Some(v) = self.map.get_mut(&vehicle) else {
            return false;
        };
        let old = v.take_passengers();
        for p in &old {
            if let Some(p) = self.map.get_mut(p)
                && p.vehicle() == Some(vehicle)
            {
                p.set_vehicle(None);
            }
        }
        // Reuse the old buffer for the new list (no allocation in steady state).
        let mut old = old;
        old.clear();
        if let Some(v) = self.map.get_mut(&vehicle) {
            v.set_passengers(old);
        }
        for id in ids {
            self.mount(id, Some(vehicle), false);
        }
        true
    }

    pub(crate) fn leash(&mut self, id: i32, holder: Option<i32>) -> bool {
        match self.map.get_mut(&id) {
            Some(e) => {
                e.set_leash_holder(holder);
                self.any_leash |= holder.is_some();
                true
            }
            None => false,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn store() -> Entities {
        let mut s = Entities::new(Config {
            events: true,
            ..Config::default()
        });
        for id in 1..=4 {
            s.spawn(Entity::new(id, EntityType::Registry(6)));
        }
        s
    }

    /// Bytes per tracked entity (the map slot adds the 4-byte key, padded).
    #[test]
    fn entity_size() {
        let n = std::mem::size_of::<Entity>();
        eprintln!("size_of::<Entity>() = {n}");
        // 0.3.0 – 0.4.3: 232 bytes. Riding, leash and effects sit behind one pointer, the
        // metadata is an exact-size block (pointer + length); the 26.x state is boxed.
        // 0.4.8: + 8 bytes, the pointer to the client view's drawn state and clocks.
        let modern = cfg!(any(feature = "v26_1", feature = "v26_2"));
        assert!(n <= if modern { 176 } else { 168 }, "{n}");
        #[cfg(any(feature = "v26_1", feature = "v26_2"))]
        {
            let b = std::mem::size_of::<crate::modern_state::State>();
            eprintln!("size_of::<modern_state::State>() = {b} (heap, 26.x entities only)");
            assert!(b <= 120, "{b}");
        }
    }

    #[test]
    fn mount_single_and_multi() {
        let mut s = store();
        assert!(s.mount(1, Some(2), true));
        assert!(s.mount(3, Some(2), true)); // 1.8: replaces rider 1
        assert_eq!(s.get(2).unwrap().passengers(), &[3]);
        assert_eq!(s.get(1).unwrap().vehicle(), None);
        assert!(!s.mount(2, Some(3), true), "cycle");
        assert!(s.set_passengers(4, [1, 3].into_iter()));
        assert_eq!(s.get(4).unwrap().passengers(), &[1, 3]);
        assert_eq!(s.get(2).unwrap().passengers(), &[] as &[i32]);
        assert_eq!(s.get(3).unwrap().vehicle(), Some(4));
        s.remove(4);
        assert_eq!(s.get(1).unwrap().vehicle(), None);
        assert_eq!(s.get(3).unwrap().vehicle(), None);
    }

    #[test]
    fn self_entry_survives_clear() {
        let mut s = store();
        s.set_self(9);
        s.spawn(Entity::new(9, EntityType::Registry(1))); // ignored: own id
        assert_eq!(s.get(9).unwrap().entity_type(), EntityType::Player);
        assert!(!s.remove(9));
        s.drain_events().for_each(drop);
        s.clear();
        assert_eq!(s.len(), 1);
        assert!(s.me().is_some());
        assert_eq!(s.drain_events().count(), 4);
        assert_eq!(s.iter().count(), 0);
    }
}