ghast-entity 0.5.7

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, 26.2 and 26.3 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
//! The modern [`Tracker`]: construction, tick order and chunk membership, the tick entry points
//! and the packet dispatch (`apply*`).

use super::*;

impl Tracker {
    /// An empty tracker.
    #[must_use]
    pub fn new(config: Config) -> Self {
        let mut wanted = IdMask::default();
        wanted.add(CORE_IDS);
        // Kept types: their packets come, the others' stop after the entity id.
        if config.equipment || !config.kept_types.is_empty() {
            wanted.add(EQUIPMENT_IDS);
        }
        if config.effects || !config.kept_types.is_empty() {
            wanted.add(EFFECT_IDS);
        }
        if config.reads_tab_list() {
            wanted.add(PLAYER_LIST_IDS);
        }
        if config.events {
            wanted.add(EVENT_IDS);
        }
        Tracker {
            store: Entities {
                era: super::ERA,
                ..Entities::new(config)
            },
            dimension: String::new(),
            wanted,
            chunks: Fast::default(),
            ghosts: Fast::default(),
            order: Fast::default(),
            next_seq: 0,
            order_cap: 0,
            early: Vec::new(),
            order_dirty: false,
        }
    }

    /// `EntityTickList.add`: an id that is already a member keeps its place.
    pub(super) fn start_ticking(&mut self, id: i32) {
        let next = &mut self.next_seq;
        let mut added = false;
        self.order.entry(id).or_insert_with(|| {
            *next += 1;
            added = true;
            *next
        });
        if added {
            self.added_to_order();
        }
    }

    /// After a new tick list entry: undoes a growth forced by deletion markers, renumbers when
    /// the numbers ran out.
    #[cold]
    #[inline(never)]
    fn added_to_order(&mut self) {
        crate::store::after_insert(&mut self.order, self.order_cap);
        self.order_cap = self.order.capacity();
        if self.next_seq == u32::MAX {
            self.renumber();
        }
    }

    /// Renumbers the tick list from 1, keeping its order (the numbers are stored as `u32`; this
    /// runs once per four billion entries).
    #[cold]
    fn renumber(&mut self) {
        let mut v: Vec<(u32, i32)> = self.order.iter().map(|(&id, &q)| (q, id)).collect();
        v.sort_unstable();
        for (n, (_, id)) in v.iter().enumerate() {
            self.order.insert(*id, n as u32 + 1);
        }
        self.next_seq = v.len() as u32;
    }

    /// The entity's place in the client's tick list (`ClientLevel.tickingEntities`, the order
    /// `tickEntities` runs them in and, within a chunk section, the order `getEntities` lists
    /// them in): a number that grows with each entity that starts ticking; `None` while it does
    /// not tick. Entities start ticking when they spawn into a loaded chunk column, when their
    /// column loads, or when they move into a loaded column; they stop when removed or when their
    /// column unloads, and re-enter at the end. The local player (its id from the login packet)
    /// enters first at login and at a dimension change, and last at a respawn in the same
    /// dimension. Several entities entering at the same moment for a column load or a move are
    /// ordered by id (vanilla's order there follows its section storage). After 2³² − 1 entries
    /// the numbers restart from 1 with the order kept.
    #[must_use]
    pub fn tick_seq(&self, id: i32) -> Option<u64> {
        self.order
            .get(&id)
            .map(|&q| u64::from(q))
            .filter(|_| self.member(id))
    }

    /// The [`Tracker::tick_seq`] the next entity to start ticking gets: a clock of entries (an
    /// entity whose `tick_seq` is below a value read earlier was ticking by then).
    #[must_use]
    pub fn next_tick_seq(&self) -> u64 {
        u64::from(self.next_seq)
    }

    /// Still in the level (removed entities leave the tick list; [`Tracker::tick`] purges them).
    fn member(&self, id: i32) -> bool {
        Some(id) == self.store.self_id
            || self.store.map.contains_key(&id)
            || self.ghosts.contains_key(&id)
    }

    /// The ids of the ticking entities (the local player included) in the client's tick order
    /// (see [`Tracker::tick_seq`]).
    #[must_use]
    pub fn tick_order(&self) -> Vec<i32> {
        let mut v: Vec<(u32, i32)> = self
            .order
            .iter()
            .filter(|&(&id, _)| self.member(id))
            .map(|(&id, &q)| (q, id))
            .collect();
        v.sort_unstable();
        v.into_iter().map(|(_, id)| id).collect()
    }

    /// The chunk that decides an entity's tick list membership: a passenger sits where its root
    /// vehicle puts it (`positionRider`; the tracker keeps a passenger's own last packet position).
    fn member_chunk(&self, e: &Entity) -> u64 {
        // `ClientLevel.tickPassenger` only positions passengers that tick already: one that does
        // not stays in its own section.
        if e.vehicle().is_some() && !self.order.contains_key(&e.id) {
            return chunk_of(e.pos);
        }
        let mut root = e;
        for _ in 0..16 {
            match root.vehicle().and_then(|v| self.store.map.get(&v)) {
                Some(v) => root = v,
                None => break,
            }
        }
        chunk_of(root.pos)
    }

    /// [`Tracker::member_chunk`] for the per-packet path: the common no-vehicle case inline,
    /// the vehicle walk out of line.
    #[inline]
    fn member_chunk_one(&self, e: &Entity) -> u64 {
        if e.vehicle().is_none() {
            return chunk_of(e.pos);
        }
        self.member_chunk_cold(e)
    }

    #[inline(never)]
    fn member_chunk_cold(&self, e: &Entity) -> u64 {
        self.member_chunk(e)
    }

    /// Re-checks tick list membership after positions changed (a move into or out of a loaded
    /// column), entering newcomers in id order.
    fn refresh_order(&mut self) {
        let me = self.store.self_id;
        let (map, ghosts) = (&self.store.map, &self.ghosts);
        self.order
            .retain(|id, _| Some(*id) == me || map.contains_key(id) || ghosts.contains_key(id));
        crate::store::shrink_map(&mut self.order);
        self.order_cap = self.order.capacity();
        let mut enter: Vec<i32> = Vec::new();
        let mut leave: Vec<i32> = Vec::new();
        for e in self.store.map.values() {
            let ticks = Some(e.id) == me
                || e.is_player()
                || self.chunks.contains_key(&self.member_chunk(e))
                || self.ghosts.contains_key(&e.id);
            match (ticks, self.order.contains_key(&e.id)) {
                (true, false) => enter.push(e.id),
                (false, true) => leave.push(e.id),
                _ => {}
            }
        }
        for id in leave {
            self.order.remove(&id);
        }
        enter.sort_unstable();
        for id in enter {
            self.start_ticking(id);
        }
    }

    /// Keeps the client view's clocks of living entities from now on (off by default):
    /// [`Entity::position_tick`], [`Entity::spawn_tick`], [`Entity::last_hurt_tick`] and
    /// [`Entity::estimated_velocity`] (set the clock with [`Entities::set_tick`]). The drawn
    /// position needs nothing: on 26.x it is [`Entity::position`].
    pub fn track_client_motion(&mut self, on: bool) {
        self.store.set_client_motion(on);
    }

    /// `true` while [`Tracker::track_client_motion`] is on.
    #[must_use]
    pub fn tracks_client_motion(&self) -> bool {
        self.store.client_motion
    }

    /// The shared store, mutable for [`Entities::drain_events`].
    pub fn store_mut(&mut self) -> &mut Entities {
        &mut self.store
    }

    /// `true` when this tracker wants packet `id` (for a `PacketFilter`).
    #[inline]
    #[must_use]
    pub fn wants(&self, id: i32) -> bool {
        self.wanted.contains(id)
    }

    /// Every packet id this tracker wants.
    pub fn packet_ids(&self) -> impl Iterator<Item = i32> + '_ {
        self.wanted.iter()
    }

    /// `true` when the chunk column holding `p` is loaded (its entities tick).
    #[must_use]
    pub fn chunk_loaded(&self, p: [f64; 3]) -> bool {
        self.chunks.contains_key(&chunk_of(p))
    }

    /// A chunk column became loaded (what a `map_chunk` packet does here; for a tracker started
    /// while chunks are already loaded): its entities tick again.
    pub fn mark_column_loaded(&mut self, x: i32, z: i32) {
        self.order_dirty = true;
        let k = chunk_key(x, z);
        let cap = self.chunks.capacity();
        let new = self.chunks.insert(k, ()).is_none();
        crate::store::after_insert(&mut self.chunks, cap);
        if new {
            let mut ids: Vec<i32> = self
                .store
                .map
                .values()
                .filter(|e| self.member_chunk(e) == k)
                .map(|e| e.id)
                .collect();
            ids.sort_unstable();
            for id in ids {
                self.start_ticking(id);
            }
        }
        if !self.ghosts.is_empty() {
            // startTicking: the column's entities take their ids' tick list slots.
            for e in self.store.map.values() {
                if chunk_of(e.pos) == k {
                    self.ghosts.remove(&e.id);
                }
            }
        }
    }

    /// A chunk column was unloaded (`unload_chunk`): its entities stop ticking.
    pub fn mark_column_unloaded(&mut self, x: i32, z: i32) {
        self.order_dirty = true;
        let k = chunk_key(x, z);
        self.chunks.remove(&k);
        self.column_unloaded(k);
    }

    fn column_unloaded(&mut self, k: u64) {
        let me = self.store.self_id;
        let leave: Vec<i32> = self
            .store
            .map
            .values()
            .filter(|e| Some(e.id) != me && !e.is_player() && self.member_chunk(e) == k)
            .map(|e| e.id)
            .collect();
        for id in leave {
            self.order.remove(&id);
        }
        crate::store::shrink_map(&mut self.order);
        self.order_cap = self.order.capacity();
        crate::store::shrink_map(&mut self.chunks);
    }

    /// `ClientLevel.isTickingEntity`: players always tick, other entities while their chunk
    /// column is loaded.
    #[must_use]
    pub fn is_ticking(&self, e: &Entity) -> bool {
        e.is_player()
            || self.chunks.contains_key(&chunk_of(e.pos))
            || self.ghosts.contains_key(&e.id)
    }

    /// Whether vanilla's crosshair pick can hit `e`: its type is pickable (`isPickable`), it is
    /// not an armor stand marker, and not a spectator (players: tab list game mode 3).
    #[must_use]
    pub fn pickable(&self, e: &Entity) -> bool {
        let Some(t) = e.m.td else { return false };
        if !t.is_pickable() {
            return false;
        }
        if t.flags_meta.is_some() && e.m.stand_flags & 0x10 != 0 {
            return false;
        }
        !(e.is_player() && self.player_spectator(e))
    }

    /// [`Tracker::is_spectator`] of a player entity, out of line: callers that test every
    /// entity pay only the player check.
    #[inline(never)]
    fn player_spectator(&self, e: &Entity) -> bool {
        game_mode(self.store.tabs(), e) == Some(3)
    }

    /// The game mode vanilla's client knows for player entity `e`
    /// (`AbstractClientPlayer.getPlayerInfo`): its tab-list entry (full list or
    /// [`Config::player_names`]); an entity that already looked its entry up keeps that entry's
    /// last game mode after the entry left the tab list. `None` for other entities, or without a
    /// tab list.
    #[must_use]
    pub fn game_mode(&self, e: &Entity) -> Option<i32> {
        if !e.is_player() {
            return None;
        }
        game_mode(self.store.tabs(), e)
    }

    /// `isSpectator` of a player entity (game mode 3, see [`Tracker::game_mode`]): spectators are
    /// not pickable, not pushable and never on the ground. `false` for other entities.
    #[must_use]
    pub fn is_spectator(&self, e: &Entity) -> bool {
        e.is_player() && self.player_spectator(e)
    }

    /// `getScoreboardName` (what team rules match): a player's profile name (the tab-list entry
    /// it spawned with, kept after the entry left), else `None`; vanilla uses the UUID string
    /// for other entities. Needs the full tab list or [`Config::player_names`].
    #[must_use]
    pub fn scoreboard_name<'a>(&'a self, e: &'a Entity) -> Option<&'a str> {
        if !e.is_player() {
            return None;
        }
        if let Some(n) = e.links.as_ref().and_then(|l| l.profile_name.as_deref()) {
            return Some(n);
        }
        let t = self.store.tab(&e.uuid)?;
        (e.m.info_gen == 0 || t.generation == e.m.info_gen).then_some(t.name)
    }

    /// One client tick of the tracked entities (`ClientLevel.tickEntities`): every entity in a
    /// loaded chunk takes one interpolation step and one head-rotation step. Call it once per
    /// client tick, **after** the tick's crosshair pick (see the module docs). Assumes the
    /// moved interpolation target never collides; use [`Tracker::tick_with`] for vanilla's check.
    pub fn tick(&mut self) {
        self.tick_with(|_, _| true);
    }

    /// [`Tracker::tick`] with vanilla's collision test: when an entity moved since its last
    /// interpolation step (a snap, a teleport, a bed position), the step first moves the target
    /// along, but only if `no_collision(entity, box)` says the entity's box at the moved target
    /// (`[min_x, min_y, min_z, max_x, max_y, max_z]`) is free (`Level.noCollision`: blocks,
    /// collidable entities, world border).
    pub fn tick_with(&mut self, no_collision: impl FnMut(&Entity, [f64; 6]) -> bool) {
        self.tick_in(no_collision, |_| None);
    }

    /// [`Tracker::tick_with`] with the world's beds (`sleep_height` as in
    /// [`Tracker::apply_body_in`]): since 26.3 a living entity's first tick wakes it up
    /// (`LivingEntity.stopSleeping`: standing pose, no sleeping position) when its sleeping
    /// position has no bed. Before 26.3 `sleep_height` is not called.
    pub fn tick_in(
        &mut self,
        mut no_collision: impl FnMut(&Entity, [f64; 6]) -> bool,
        mut sleep_height: impl FnMut([i32; 3]) -> Option<f64>,
    ) {
        // The full membership re-check, only when packets were applied since the last one.
        if std::mem::take(&mut self.order_dirty) {
            self.refresh_order();
        }
        let early = std::mem::take(&mut self.early);
        // Entities whose column changed in this tick (interpolation steps).
        let mut moved: Vec<i32> = Vec::new();
        let mut moved_vehicle = false;
        let me = self.store.self_id;
        let chunks = &self.chunks;
        // Vehicles whose first passenger is a mob (their body control skips the idle turn).
        let mut carrying: Vec<i32> = Vec::new();
        for e in self.store.map.values() {
            if let Some(v) = e.vehicle()
                && e.m.td.is_some_and(|t| t.flags & type_flags::MOB != 0)
                && self
                    .store
                    .map
                    .get(&v)
                    .is_some_and(|v| v.passengers().first() == Some(&e.id))
            {
                carrying.push(v);
            }
        }
        let mut discard: Vec<i32> = Vec::new();
        for e in self.store.map.values_mut() {
            if e.m.flag(st::SETTLED)
                || Some(e.id) == me
                || (!early.is_empty() && early.contains(&e.id))
            {
                continue;
            }
            if !e.is_player() && !chunks.contains_key(&chunk_of(e.pos)) {
                continue;
            }
            if !self.ghosts.is_empty() {
                self.ghosts.remove(&e.id);
            }
            if e.ty == EntityType::Registry(data::ITEM) && e.m.item_count <= 0 {
                // ItemEntity.tick: an empty stack discards the entity.
                discard.push(e.id);
                continue;
            }
            if e.is_player() {
                let tabs = crate::store::Tabs {
                    players: &self.store.players,
                    lite: &self.store.lite,
                    long_names: &self.store.long_names,
                };
                player_tick(e, tabs);
            }
            let c = !carrying.is_empty() && carrying.contains(&e.id);
            let before = chunk_of(e.pos);
            let side = (
                &mut self.store.stepped,
                &mut self.store.sleeping,
                &mut self.store.motions,
            );
            tick_entity(e, side, &mut sleep_height, c, &mut no_collision);
            if chunk_of(e.pos) != before {
                moved.push(e.id);
                moved_vehicle |= !e.passengers().is_empty();
            }
        }
        for id in discard {
            self.store.remove(id);
        }
        // Moves made by the tick (interpolation): only when some entity changed its column.
        if !moved.is_empty() || moved_vehicle {
            self.refresh_order();
        }
    }

    /// Ticks entity `id` now, ahead of the rest of this client tick (a vehicle ticks before
    /// its passenger: the local player riding a vehicle the server moves reads where the vehicle
    /// is after its tick). The next [`Tracker::tick_with`] skips it once. Returns its position
    /// after the tick (`None`: not tracked).
    pub fn tick_early(
        &mut self,
        id: i32,
        mut no_collision: impl FnMut(&Entity, [f64; 6]) -> bool,
    ) -> Option<[f64; 3]> {
        let again = self.early.contains(&id);
        let e = self.store.map.get_mut(&id)?;
        if !again
            && !e.m.flag(st::SETTLED)
            && (e.is_player() || self.chunks.contains_key(&chunk_of(e.pos)))
        {
            let side = (
                &mut self.store.stepped,
                &mut self.store.sleeping,
                &mut self.store.motions,
            );
            tick_entity(e, side, &mut |_| None, false, &mut no_collision);
        }
        if !self.early.contains(&id) {
            self.early.push(id);
        }
        Some(e.pos)
    }

    /// The local player pushed entity `id` (`Entity.push(Entity)` of the player's box against
    /// the entity's, from the entity's tick): `delta` (x, z) is added to its client motion
    /// ([`Entities::client_motion`]) when its type is one of [`Config::motion_types`] (others:
    /// nothing). The caller decides whether the entity is pushable (no passengers, alive, not on
    /// a climbable).
    pub fn push_motion(&mut self, id: i32, delta: [f64; 2]) {
        self.store.push_motion(id, delta);
    }

    /// The living mount the bot steers (`None`: none): vanilla moves it on the client and only
    /// keeps the server's relative moves and position syncs of it as the packet base (as for a
    /// boat the bot steers, which the tracker knows from the passengers).
    pub fn set_steered(&mut self, id: Option<i32>) {
        self.store.steered = id;
    }

    /// The client moved its copy of vehicle `id` itself (a vehicle the bot steers): position,
    /// rotation and ground flag become the client's, so an interpolation after the bot stops
    /// steering starts from there, as in vanilla. `false`: not tracked.
    pub fn client_moved(
        &mut self,
        id: i32,
        pos: [f64; 3],
        yaw: f32,
        pitch: f32,
        on_ground: bool,
    ) -> bool {
        if !self.client_pushed(id, pos, on_ground) {
            return false;
        }
        if let Some(e) = self.store.map.get_mut(&id) {
            e.yaw = yaw;
            e.pitch = pitch;
        }
        true
    }

    /// A moving piston moved the client copy of entity `id` (`PistonMovingBlockEntity` moves the
    /// client's copies itself, outside its packets): its position becomes `pos` and its ground
    /// flag `on_ground` (a vertical piston move sets it). An interpolation in progress goes on
    /// from there: its next step moves the target by the same delta when that is free, as
    /// after any other move. `false`: not tracked.
    pub fn client_pushed(&mut self, id: i32, pos: [f64; 3], on_ground: bool) -> bool {
        let Some(e) = self.store.map.get_mut(&id) else {
            return false;
        };
        if chunk_of(e.pos) != chunk_of(pos) {
            self.order_dirty = true;
        }
        e.pos = pos;
        e.on_ground = on_ground;
        e.m.set_flag(st::SETTLED, false);
        true
    }

    /// The client ran entity `id`'s own tick itself (the client-side physics of a projectile,
    /// item, experience orb, primed TNT or falling block, `ghast_physics::modern`): its
    /// position, motion ([`Entity::velocity`] is then the client copy's `getDeltaMovement`),
    /// rotation and ground flag become the client's. Call it after [`Tracker::tick`] (vanilla's
    /// `commonTick` interpolation step comes before the entity's own tick); an interpolation in
    /// progress goes on from the new position as after any other move. `false`: not tracked.
    pub fn client_simulated(
        &mut self,
        id: i32,
        pos: [f64; 3],
        vel: [f64; 3],
        rot: [f32; 2],
        on_ground: bool,
    ) -> bool {
        if !self.client_pushed(id, pos, on_ground) {
            return false;
        }
        if let Some(e) = self.store.map.get_mut(&id) {
            e.velocity = vel;
            e.yaw = rot[0];
            e.pitch = rot[1];
        }
        true
    }

    /// 26.3 `Entity.recordMovement` of a client-simulated entity (`MoveSimulationType`
    /// `SERVER_AND_CLIENT`): its own tick moved it by `delta` (one `Entity.move`), and an
    /// interpolation in progress takes the move over at once
    /// (`AbstractInterpolationHandler.applyPredictedMovement`): the target moves by `delta` when
    /// `no_collision(entity, box)` says the entity's box there is free, and the next step does
    /// not count the move again. Call it after [`Tracker::client_simulated`], once per move.
    /// `false`: not tracked.
    pub fn client_predicted_move(
        &mut self,
        id: i32,
        delta: [f64; 3],
        mut no_collision: impl FnMut(&Entity, [f64; 6]) -> bool,
    ) -> bool {
        let Some(e) = self.store.map.get_mut(&id) else {
            return false;
        };
        if e.m.steps == 0 {
            return true;
        }
        let t = e.m.target;
        let moved = [t[0] + delta[0], t[1] + delta[1], t[2] + delta[2]];
        let bb = dimensions(e).map(|dm| {
            let b = dm.bounding_box(moved[0], moved[1], moved[2]);
            [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]
        });
        if bb.is_none_or(|bb| no_collision(&*e, bb)) {
            e.m.target = moved;
        }
        let p = e.m.prev;
        e.m.prev = [p[0] + delta[0], p[1] + delta[1], p[2] + delta[2]];
        true
    }

    /// The client's own tick discarded entity `id` (a primed TNT whose fuse ran out, a fishing
    /// bobber without its player owner, a falling block of air): it leaves the client level as
    /// in vanilla, with a [`Event::Removed`] when events are on. `false`: not tracked (or our own
    /// entity).
    pub fn client_discarded(&mut self, id: i32) -> bool {
        let removed = self.store.remove(id);
        if removed {
            self.order_dirty = true;
        }
        removed
    }

    /// Applies one clientbound play packet.
    ///
    /// # Errors
    /// A malformed body (multi-entry packets may be partly applied).
    pub fn apply(&mut self, raw: &RawPacket) -> Result<Applied, DecodeError> {
        self.apply_body(raw.id, &raw.body)
    }

    /// [`Tracker::apply`] with the packet id and body.
    ///
    /// # Errors
    /// See [`Tracker::apply`].
    pub fn apply_body(&mut self, packet_id: i32, body: &Bytes) -> Result<Applied, DecodeError> {
        self.apply_body_in(packet_id, body, &mut |_| None)
    }

    /// [`Tracker::apply_body`] with the world's beds: `sleep_height(bed)` is the sleep height of
    /// the bed block at `bed` (`AbstractBedBlock.getSleepHeight`: the top of its shape, 0.5625 for
    /// a bed), `None` when there is no bed there. Since 26.3 a sleeping position moves a living
    /// entity onto the bed (`y + height + 0.125`) only when a bed is there, and its first tick
    /// wakes it up when none is (see [`Tracker::tick_in`]); [`Tracker::apply_body`] assumes no
    /// beds. Before 26.3 the client puts the entity at `y + 0.6875` without looking, and
    /// `sleep_height` is not called.
    ///
    /// # Errors
    /// See [`Tracker::apply`].
    pub fn apply_body_in(
        &mut self,
        packet_id: i32,
        body: &Bytes,
        sleep_height: &mut dyn FnMut([i32; 3]) -> Option<f64>,
    ) -> Result<Applied, DecodeError> {
        if !self.wants(packet_id) {
            return Ok(Applied::NotEntityPacket);
        }
        // A packet that moves one entity: its tick list membership follows the move at once
        // (the entity section changes in setPos), in packet order.
        let mover = matches!(
            packet_id,
            id::REL_ENTITY_MOVE
                | id::ENTITY_MOVE_LOOK
                | id::SYNC_ENTITY_POSITION
                | id::ENTITY_TELEPORT
                | id::ENTITY_LOOK
                | id::ENTITY_VELOCITY
                | id::ENTITY_METADATA
        )
        .then(|| Reader::new(body).read_varint().ok())
        .flatten();
        let out = self.apply_inner(packet_id, body, sleep_height);
        self.order_dirty = true;
        if let Some(eid) = mover {
            self.refresh_one(eid);
        }
        out
    }

    /// Tick list membership of one entity after it moved (a vehicle carries its passengers).
    fn refresh_one(&mut self, id: i32) {
        let Some(e) = self.store.map.get(&id) else {
            return;
        };

        if Some(id) == self.store.self_id || e.is_player() || self.ghosts.contains_key(&id) {
            return;
        }
        if self.chunks.contains_key(&self.member_chunk_one(e)) {
            self.start_ticking(id);
        } else {
            self.order.remove(&id);
        }
    }

    fn apply_inner(
        &mut self,
        packet_id: i32,
        body: &Bytes,
        sleep_height: &mut dyn FnMut([i32; 3]) -> Option<f64>,
    ) -> Result<Applied, DecodeError> {
        let r = &mut Reader::new(body);
        let ticking = (&self.chunks, &self.ghosts);
        let s = &mut self.store;
        let changed = match packet_id {
            id::DAMAGE_EVENT => {
                // LivingEntity.handleDamageEvent: the hurt animation (other entities: nothing).
                let eid = r.read_varint()?;
                let _source_type = r.read_varint()?;
                let cause = r.read_varint()? - 1;
                let known = s.map.get(&eid).is_some_and(|e| e.living);
                if known {
                    s.hurt(eid, (cause >= 0).then_some(cause));
                }
                known
            }
            id::REL_ENTITY_MOVE => relative(s, r, true, false)?,
            id::ENTITY_MOVE_LOOK => relative(s, r, true, true)?,
            id::ENTITY_LOOK => relative(s, r, false, true)?,
            id::SYNC_ENTITY_POSITION => sync(s, r, ticking)?,
            id::ENTITY_TELEPORT => teleport(s, r)?,
            id::ENTITY_VELOCITY => {
                let eid = r.read_varint()?;
                let v = LpVec3::read(r)?.to_vec3();
                match s.map.get_mut(&eid) {
                    Some(e) => {
                        e.velocity = v;
                        let ty = e.ty;
                        if !s.config.motion_types.is_empty() {
                            // lerpMotion -> setDeltaMovement.
                            e.m.set_flag(st::SETTLED, false);
                            s.set_motion(eid, ty, v);
                        }
                        s.event(Event::Velocity(eid));
                        true
                    }
                    None => false,
                }
            }
            id::ENTITY_HEAD_ROTATION => {
                let eid = r.read_varint()?;
                let b = r.read_i8()?;
                match s.map.get_mut(&eid) {
                    // `lerpHeadTo(yRot, 3)`; a no-op for non-living entities.
                    Some(e) if living(e) => {
                        e.m.head_target = angle(b);
                        e.m.head_steps = 3;
                        e.m.set_flag(st::SETTLED, false);
                        true
                    }
                    _ => false,
                }
            }
            id::ENTITY_DESTROY => {
                let mut any = false;
                for_each_varint(r, |eid| any |= s.remove(eid))?;
                any
            }
            id::ANIMATION => {
                let eid = r.read_varint()?;
                let action = r.read_u8()?;
                if (action == 0 || action == 3) && s.map.contains_key(&eid) {
                    s.event(Event::Swing {
                        id: eid,
                        off_hand: action == 3,
                    });
                }
                false
            }
            id::ENTITY_STATUS => {
                let eid = r.read_i32()?;
                let status = r.read_i8()?;
                let keep = s.config.metadata;
                let known = match s.map.get_mut(&eid) {
                    Some(e) => {
                        // LivingEntity.handleEntityEvent(3): setHealth(0), die.
                        if status == 3 && e.living {
                            e.mark_dead();
                            e.m.set_flag(st::DEAD, true);
                            if keep {
                                e.meta.set(meta::HEALTH, MetaValue::Float(0.0));
                            }
                        }
                        true
                    }
                    None => false,
                };
                if known {
                    s.event(Event::Status { id: eid, status });
                }
                known
            }
            id::SPAWN_ENTITY => {
                let eid = r.clone().read_varint()?;
                let old = s.map.get(&eid).map(|e| e.uuid);
                let (applied, slot) = spawn(s, r, &self.chunks)?;
                let now = self.store.map.get(&eid).map(|e| e.uuid);
                match slot {
                    TickSlot::Ghost(id) => {
                        // A refused spawn: its id's slot (kept if already a member). An entity
                        // it replaced left the tick list first (`ClientLevel.removeEntity`), so
                        // the ghost then enters at the end.
                        if old.is_some() {
                            self.order.remove(&id);
                        }
                        self.ghosts.insert(id, ());
                        self.start_ticking(id);
                    }
                    TickSlot::Taken(id) => {
                        // A new entity enters at the end (one over a known id removes the old
                        // one first); a ghost's slot keeps its place.
                        if self.ghosts.remove(&id).is_none() {
                            self.order.remove(&id);
                        }
                        self.start_ticking(id);
                    }
                    TickSlot::None => {
                        if old.is_some() && now != old {
                            self.order.remove(&eid);
                        }
                    }
                }
                return Ok(applied);
            }
            id::ATTACH_ENTITY => {
                let eid = r.read_i32()?;
                let holder = r.read_i32()?;
                s.leash(eid, (holder != 0).then_some(holder))
            }
            id::SET_PASSENGERS => {
                let vehicle = r.read_varint()?;
                let start = r.position();
                for_each_varint(r, |_| {})?;
                let mut again = Reader::new(body);
                again.skip(start)?;
                if !s.map.contains_key(&vehicle) {
                    return Ok(Applied::Ignored);
                }
                let n = again.read_varint()?.max(0);
                let ids = (0..n).map_while(|_| again.read_varint().ok());
                let r = s.set_passengers(vehicle, ids);
                // Riding changes the body turn of mob vehicles: let every entity tick again.
                for e in s.map.values_mut() {
                    e.m.set_flag(st::SETTLED, false);
                }
                r
            }
            id::COLLECT => {
                let collected = r.read_varint()?;
                let collector = r.read_varint()?;
                let amount = r.read_varint()?;
                match s.map.get_mut(&collected) {
                    None => false,
                    Some(e) => {
                        let t = match e.ty {
                            EntityType::Registry(t) => t,
                            _ => u16::MAX,
                        };
                        let held = (t == data::ITEM)
                            .then(|| item_stack(e).map(|st| (st.id, st.count)))
                            .flatten();
                        let gone = match t {
                            data::ITEM => {
                                if e.m.item_count > 0 {
                                    e.m.item_count = e.m.item_count.wrapping_sub(amount);
                                    shrink_stack(e, amount);
                                }
                                e.m.item_count <= 0
                            }
                            data::EXPERIENCE_ORB => false,
                            _ => true,
                        };
                        s.picked_up(collected, collector, Some(amount), held, gone);
                        if gone {
                            s.remove(collected);
                        }
                        true
                    }
                }
            }
            id::ENTITY_METADATA => metadata(s, r, sleep_height)?,
            id::ENTITY_UPDATE_ATTRIBUTES => attributes(s, r)?,
            id::ENTITY_EQUIPMENT => {
                let eid = r.read_varint()?;
                if !s.config.equipment && !kept(s, eid) {
                    return Ok(Applied::Ignored);
                }
                let mut list: [Option<(usize, Option<Item>)>; 8] = Default::default();
                let mut n = 0;
                loop {
                    let b = r.read_u8()?;
                    let item = read_stack(r)?.map(|i| Item {
                        id: i.id,
                        count: i.count.clamp(0, 127) as i8,
                        damage: 0,
                        nbt: None,
                    });
                    if n < list.len() {
                        list[n] = Some((usize::from(b & 0x7F), item));
                        n += 1;
                    }
                    if b & 0x80 == 0 {
                        break;
                    }
                }
                match s.map.get_mut(&eid) {
                    Some(e) => {
                        let eq = e.equipment.get_or_insert_with(Default::default);
                        for (slot, item) in list.into_iter().flatten() {
                            if let Some(dst) = eq.get_mut(slot) {
                                *dst = item;
                            }
                        }
                        s.event(Event::Equipment(eid));
                        true
                    }
                    None => false,
                }
            }
            id::ENTITY_EFFECT => {
                let eid = r.read_varint()?;
                if !s.config.effects && !kept(s, eid) {
                    return Ok(Applied::Ignored);
                }
                let effect = Effect {
                    id: r.read_varint()? as u8,
                    amplifier: r.read_varint()?.clamp(-128, 127) as i8,
                    duration: r.read_varint()?,
                    flags: r.read_u8()?,
                };
                set_effect(s, eid, effect)
            }
            id::REMOVE_ENTITY_EFFECT => {
                let eid = r.read_varint()?;
                if !s.config.effects && !kept(s, eid) {
                    return Ok(Applied::Ignored);
                }
                let eff = r.read_varint()? as u8;
                remove_effect(s, eid, eff)
            }
            id::PLAYER_INFO => {
                player_info(s, r)?;
                // Game modes feed Player.tick (spectators leave the ground).
                for e in s.map.values_mut() {
                    if e.is_player() {
                        e.m.set_flag(st::SETTLED, false);
                    }
                }
                true
            }
            id::PLAYER_REMOVE => {
                let n = r.read_varint()?;
                let n = r.check_count(i64::from(n), 16)?;
                for _ in 0..n {
                    let uuid = r.read_uuid()?;
                    let Some(t) = s.tab(&uuid) else {
                        continue;
                    };
                    let (gm, generation) = (t.game_mode, t.generation);
                    let name: Box<str> = Box::from(t.name);
                    // Player entities keep their profile (the name) and, once they looked the
                    // entry up, the tab list object (frozen game mode).
                    for e in s.map.values_mut() {
                        if e.m.info_gen == generation {
                            e.m.frozen_game_mode = gm as i8;
                        }
                        if e.is_player()
                            && e.uuid == uuid
                            && (e.m.info_gen == 0 || e.m.info_gen == generation)
                            && e.links.as_ref().is_none_or(|l| l.profile_name.is_none())
                        {
                            e.links_mut().profile_name = Some(name.clone());
                        }
                    }
                    s.tab_remove(&uuid);
                }
                s.event(Event::PlayerList);
                true
            }
            id::MAP_CHUNK => {
                let (x, z) = (r.read_i32()?, r.read_i32()?);
                self.mark_column_loaded(x, z);
                return Ok(Applied::Ignored);
            }
            id::UNLOAD_CHUNK => {
                let k = r.read_i64()? as u64;
                self.chunks.remove(&k);
                self.column_unloaded(k);
                return Ok(Applied::Ignored);
            }
            id::LOGIN => {
                let p = Login::decode(r)?;
                s.clear();
                s.set_self(p.entity_id);
                self.chunks.clear();
                self.ghosts.clear();
                self.order.clear();
                self.start_ticking(p.entity_id);
                self.dimension = p.world_state.name.to_string();
                true
            }
            id::RESPAWN => {
                let p = Respawn::decode(r)?;
                // A new client player: effects and equipment reset; metadata is copied only with
                // the keep-entity-data flag (2).
                if let Some(me) = s.self_id.and_then(|i| s.map.get_mut(&i)) {
                    me.clear_effects();
                    me.equipment = None;
                    if p.copy_metadata & 2 == 0 {
                        me.meta.clear();
                    }
                }
                let me = s.self_id;
                if *p.world_state.name != *self.dimension {
                    s.clear();
                    self.chunks.clear();
                    self.ghosts.clear();
                    self.order.clear();
                    self.dimension = p.world_state.name.to_string();
                } else if let Some(me) = me {
                    // The new player object is added after the others.
                    self.order.remove(&me);
                }
                if let Some(me) = me {
                    self.start_ticking(me);
                }
                true
            }
            _ => return Ok(Applied::NotEntityPacket),
        };
        Ok(if changed {
            Applied::Changed
        } else {
            Applied::Ignored
        })
    }
}