ghast-entity 0.4.9

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
//! The 1.16.5 client's own view of the entities around the bot, as far as the local player's
//! pushes and entity collisions read it (opt-in, [`crate::v1_16_5::Tracker::track_client_motion`]):
//!
//! * **Tick order.** `ClientWorld.tickEntities` walks the client world's entity map, a fastutil
//!   `Int2ObjectOpenHashMap<Entity>` keyed by entity id: its iteration order is the order of the
//!   hash table's slots (the id 0 first, then the slots from the top down), which depends on
//!   every id added and removed since the world was created. [`ClientMap`] keeps the same table
//!   (keys only) with fastutil 8.2.1's hashing, probing, removal shifting and resizing.
//! * **Positions and boxes.** Position packets do not move a living entity or a boat at once:
//!   the client interpolates over 3 ticks (living) or 10 ticks (boats), each step one
//!   `setPosition` that also re-centres the box. A shulker ignores position packets and sits on
//!   its attached block. Entity data that changes the size (pose, baby, slime size, armor stand
//!   flags) runs `calculateDimensions`: a box that does not get narrower keeps its minimum corner
//!   (`maxX = minX + width`, not `x + width / 2`) until the next `setPosition`.
//! * **Passengers.** A rider does not tick on its own: right after its vehicle's tick it takes
//!   its own interpolation step and is then seated by the vehicle's `updatePassengerPosition`
//!   (boats and minecarts; a boat also keeps its passengers' yaw within 105 degrees of its own).
//!
//! Not modelled: entities that remove themselves on the client (a dying mob after 20 ticks,
//! an item without a stack, old experience orbs; the server's destroy comes at about the same
//! time), a sleeping entity's bed position, pufferfish and phantom sizes, the seats of vehicles
//! other than boats and minecarts (horses, pigs, striders, llamas: their riders keep their own
//! interpolation), an open shulker's lid.

use crate::entity::{Entity, EntityType, MetaValue};
use crate::store::{Entities, Fast};

/// fastutil `HashCommon.INT_PHI`.
const INT_PHI: i32 = 0x9E37_79B9_u32 as i32;
/// `Hash.DEFAULT_INITIAL_SIZE`.
const DEFAULT_INITIAL_SIZE: usize = 16;
/// `Hash.DEFAULT_LOAD_FACTOR`.
const LOAD_FACTOR: f32 = 0.75;

/// fastutil `HashCommon.mix(int)`.
#[inline]
fn mix(x: i32) -> i32 {
    let h = x.wrapping_mul(INT_PHI);
    h ^ ((h as u32) >> 16) as i32
}

/// fastutil `HashCommon.arraySize(expected, f)` (float division, rounded up to a power of two).
fn array_size(expected: usize, f: f32) -> usize {
    let s = (expected as f32 / f).ceil() as u64;
    s.next_power_of_two().max(2) as usize
}

/// fastutil `HashCommon.maxFill(n, f)`.
fn max_fill(n: usize, f: f32) -> usize {
    ((n as f32 * f).ceil() as usize).min(n - 1)
}

/// The keys of the client world's `Int2ObjectOpenHashMap` (fastutil 8.2.1), slot for slot.
#[derive(Clone, Debug)]
pub(crate) struct ClientMap {
    /// Slots `0..n` (0 = free); the null key (id 0) lives outside them.
    key: Vec<i32>,
    n: usize,
    mask: usize,
    size: usize,
    max_fill: usize,
    min_n: usize,
    has_null: bool,
}

impl Default for ClientMap {
    fn default() -> Self {
        // `new Int2ObjectOpenHashMap<>()`: expected 16, load factor 0.75.
        let n = array_size(DEFAULT_INITIAL_SIZE, LOAD_FACTOR);
        ClientMap {
            key: vec![0; n],
            n,
            mask: n - 1,
            size: 0,
            max_fill: max_fill(n, LOAD_FACTOR),
            min_n: n,
            has_null: false,
        }
    }
}

impl ClientMap {
    /// The slot of `k`, or `None`.
    fn find(&self, k: i32) -> Option<usize> {
        if k == 0 {
            return self.has_null.then_some(self.n);
        }
        let mut pos = (mix(k) as usize) & self.mask;
        loop {
            let cur = self.key[pos];
            if cur == 0 {
                return None;
            }
            if cur == k {
                return Some(pos);
            }
            pos = (pos + 1) & self.mask;
        }
    }

    /// `put(k, v)` for a key not in the map (vanilla removes the old entity first).
    pub(crate) fn insert(&mut self, k: i32) {
        if k == 0 {
            if self.has_null {
                return;
            }
            self.has_null = true;
        } else {
            let mut pos = (mix(k) as usize) & self.mask;
            loop {
                let cur = self.key[pos];
                if cur == 0 {
                    break;
                }
                if cur == k {
                    return;
                }
                pos = (pos + 1) & self.mask;
            }
            self.key[pos] = k;
        }
        let before = self.size;
        self.size += 1;
        if before >= self.max_fill {
            self.rehash(array_size(self.size + 1, LOAD_FACTOR));
        }
    }

    /// `remove(k)`; `false` when `k` was not in the map.
    pub(crate) fn remove(&mut self, k: i32) -> bool {
        if k == 0 {
            if !self.has_null {
                return false;
            }
            self.has_null = false;
        } else {
            let Some(pos) = self.find(k) else {
                return false;
            };
            self.shift_keys(pos);
        }
        self.size -= 1;
        if self.n > self.min_n && self.size < self.max_fill / 4 && self.n > DEFAULT_INITIAL_SIZE {
            self.rehash(self.n / 2);
        }
        true
    }

    /// fastutil `shiftKeys`: closes the gap at `pos` (linear probing).
    fn shift_keys(&mut self, mut pos: usize) {
        loop {
            let last = pos;
            pos = (last + 1) & self.mask;
            let cur = loop {
                let cur = self.key[pos];
                if cur == 0 {
                    self.key[last] = 0;
                    return;
                }
                let slot = (mix(cur) as usize) & self.mask;
                let stays = if last <= pos {
                    last >= slot || slot > pos
                } else {
                    last >= slot && slot > pos
                };
                if stays {
                    break cur;
                }
                pos = (pos + 1) & self.mask;
            };
            self.key[last] = cur;
        }
    }

    /// fastutil `rehash(newN)`: the keys from the top slot down into a new table.
    fn rehash(&mut self, new_n: usize) {
        let mask = new_n - 1;
        let mut next = vec![0; new_n];
        for i in (0..self.n).rev() {
            let k = self.key[i];
            if k == 0 {
                continue;
            }
            let mut pos = (mix(k) as usize) & mask;
            while next[pos] != 0 {
                pos = (pos + 1) & mask;
            }
            next[pos] = k;
        }
        self.key = next;
        self.n = new_n;
        self.mask = mask;
        self.max_fill = max_fill(new_n, LOAD_FACTOR);
    }

    /// The iteration order (`int2ObjectEntrySet().iterator()`): the id 0, then the slots from
    /// the top down.
    pub(crate) fn order(&self) -> impl Iterator<Item = i32> + '_ {
        self.has_null
            .then_some(0)
            .into_iter()
            .chain(self.key.iter().rev().copied().filter(|&k| k != 0))
    }

    /// `true` when `a` comes before `b` in the iteration order (both in the map).
    pub(crate) fn before(&self, a: i32, b: i32) -> bool {
        match (self.find(a), self.find(b)) {
            (Some(x), Some(y)) => x > y,
            _ => false,
        }
    }

    /// The place of `k` in the iteration order as a sort key (smaller ticks earlier).
    pub(crate) fn rank(&self, k: i32) -> Option<u32> {
        self.find(k).map(|slot| (self.n - slot) as u32)
    }

    #[cfg(test)]
    pub(crate) fn len(&self) -> usize {
        self.size
    }
}

/// How the client moves an entity after a position packet.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Lerp {
    /// `LivingEntity.updateTrackedPositionAndAngles`: the packet's steps (3).
    Living,
    /// `BoatEntity.updateTrackedPositionAndAngles`: 10 steps.
    Boat,
    /// `ShulkerEntity`: position packets do nothing.
    Still,
    /// `AbstractMinecartEntity`: the packet's 3 steps + 2.
    Minecart,
}

/// An entity's client position, interpolation and box.
#[derive(Clone, Debug)]
pub(crate) struct Motion {
    pub(crate) pos: [f64; 3],
    target: [f64; 3],
    /// Drawn `(yaw, pitch)` and the interpolation's target rotation.
    pub(crate) rot: [f32; 2],
    target_rot: [f32; 2],
    steps: u8,
    lerp: Lerp,
    pub(crate) bb: [f64; 6],
    /// `this.dimensions` (width, height).
    dims: (f32, f32),
    pose: i32,
    slime: i32,
    stand: u8,
    baby: bool,
    /// Shulkers: the attached block.
    attached: Option<[i32; 3]>,
    /// Living: the last health the server sent is not above 0 (`isAlive` is false).
    pub(crate) dead: bool,
    /// `isOnGround` of the client copy: set by the server's move packets and by moves the
    /// client makes itself (a piston's push).
    pub(crate) on_ground: bool,
    /// Players: the profile name (the tab-list entry the client spawned it with).
    pub(crate) name: Option<Box<str>>,
}

/// Registry ids of the 1.16.5 types the client state reads.
pub(crate) mod ty {
    pub(crate) const ARMOR_STAND: u16 = 1;
    pub(crate) const BOAT: u16 = 6;
    pub(crate) const MAGMA_CUBE: u16 = 44;
    pub(crate) const PIGLIN: u16 = 60;
    pub(crate) const SHULKER: u16 = 70;
    pub(crate) const SLIME: u16 = 75;
}

fn box_at(dims: (f32, f32), p: [f64; 3]) -> [f64; 6] {
    // EntityDimensions.getBoxAt: half width in float.
    let f = f64::from(dims.0 / 2.0);
    let g = f64::from(dims.1);
    [p[0] - f, p[1], p[2] - f, p[0] + f, p[1] + g, p[2] + f]
}

impl Motion {
    fn set_position(&mut self, p: [f64; 3]) {
        self.pos = p;
        self.bb = box_at(self.dims, p);
    }

    /// `updateTrackedPositionAndAngles(target, rot, 3)` (`None`: the drawn rotation).
    fn retarget(&mut self, target: [f64; 3], rot: Option<[f32; 2]>) {
        let steps = match self.lerp {
            Lerp::Living => 3,
            Lerp::Boat => 10,
            Lerp::Minecart => 5,
            Lerp::Still => return,
        };
        self.target = target;
        self.target_rot = rot.unwrap_or(self.rot);
        self.steps = steps;
    }

    /// `calculateDimensions` with the size data as it is now.
    fn resize(&mut self, e: &Entity) {
        let Some(vs) = e.sizer else { return };
        let Some(d) =
            crate::v1_16_5::dims_with(e.ty, vs, self.pose, Some(self.slime), self.stand, self.baby)
        else {
            return;
        };
        let new = (d.width, d.height);
        let old = self.dims;
        self.dims = new;
        if new.0 < old.0 {
            let h = f64::from(new.0) / 2.0;
            let [x, y, z] = self.pos;
            self.bb = [x - h, y, z - h, x + h, y + f64::from(new.1), z + h];
        } else {
            let b = self.bb;
            self.bb = [
                b[0],
                b[1],
                b[2],
                b[0] + f64::from(new.0),
                b[1] + f64::from(new.1),
                b[2] + f64::from(new.0),
            ];
        }
        // Slimes, magma cubes and armor stands set their position again afterwards.
        if matches!(
            e.ty,
            EntityType::Registry(ty::SLIME | ty::MAGMA_CUBE | ty::ARMOR_STAND)
        ) {
            let p = self.pos;
            self.set_position(p);
        }
    }
}

/// The client view (see the module docs).
#[derive(Clone, Debug, Default)]
pub(crate) struct Client16 {
    pub(crate) map: ClientMap,
    pub(crate) motion: Fast<i32, Motion>,
    /// Every entity's chunk section list and its place in it (`checkEntityChunkPos` at its
    /// tick): unclamped section, insertion counter.
    pub(crate) order: Fast<i32, ([i32; 3], u32)>,
    order_seq: u32,
    /// Entities moved by a packet without interpolation since the last tick (their section is
    /// checked at their next tick).
    moved_now: Vec<i32>,
    /// Ticked vehicles whose passengers tick next (reused).
    carriers: Vec<i32>,
}

impl Client16 {
    /// A new client world holding only the local player.
    pub(crate) fn new_world(&mut self, self_id: Option<i32>) {
        self.map = ClientMap::default();
        self.motion.clear();
        crate::store::shrink_map(&mut self.motion);
        self.order.clear();
        crate::store::shrink_map(&mut self.order);
        self.moved_now.clear();
        if let Some(id) = self_id {
            self.map.insert(id);
            // `addPlayer`: the new player entity at the origin, in that section's list.
            self.order_seq = self.order_seq.wrapping_add(1);
            self.order.insert(id, ([0, 0, 0], self.order_seq));
        }
    }

    /// The local player's `checkEntityChunkPos` at the position its last tick left it: a new
    /// section puts it at the end of that section's list.
    pub(crate) fn self_filed(&mut self, id: i32, pos: [f64; 3]) {
        let sec = crate::drawn::section_of(pos);
        match self.order.get_mut(&id) {
            Some(o) if o.0 == sec => {}
            Some(o) => {
                self.order_seq = self.order_seq.wrapping_add(1);
                *o = (sec, self.order_seq);
            }
            None => {
                self.order_seq = self.order_seq.wrapping_add(1);
                self.order.insert(id, (sec, self.order_seq));
            }
        }
    }

    /// `addEntityPrivate`: the old entity of that id leaves the map first.
    pub(crate) fn add(&mut self, id: i32) {
        self.map.remove(id);
        self.map.insert(id);
        self.motion.remove(&id);
    }

    /// `removeEntity`.
    pub(crate) fn remove(&mut self, id: i32) {
        self.map.remove(id);
        if self.motion.remove(&id).is_some() {
            crate::store::shrink_map(&mut self.motion);
        }
        if self.order.remove(&id).is_some() {
            crate::store::shrink_map(&mut self.order);
        }
    }

    /// The pick's order key of entity `id` (see `Entity::search_order`).
    pub(crate) fn search_order(&self, id: i32) -> Option<(i32, i32, i32, u32)> {
        self.order
            .get(&id)
            .map(|(s, q)| (s[0], s[2], s[1].clamp(0, 15), *q))
    }

    /// A spawned entity at its spawn position (`setPosition`), with the type's registered size.
    pub(crate) fn spawned(&mut self, e: &Entity, name: Option<Box<str>>) {
        // `World.spawnEntity` puts it into its chunk section's list at once.
        self.order_seq = self.order_seq.wrapping_add(1);
        let cap = self.order.capacity();
        self.order
            .insert(e.id, (crate::drawn::section_of(e.pos), self.order_seq));
        crate::store::after_insert(&mut self.order, cap);
        let lerp = match e.ty {
            EntityType::Registry(ty::BOAT) => Lerp::Boat,
            EntityType::Registry(ty::SHULKER) => Lerp::Still,
            // A living entity spawned as an object.
            EntityType::Registry(ty::ARMOR_STAND) => Lerp::Living,
            EntityType::Player => Lerp::Living,
            _ if e.living => Lerp::Living,
            _ if e.sizer.is_some_and(|s| s.name.ends_with("minecart")) => Lerp::Minecart,
            _ => return,
        };
        let Some((w, h)) = e.sizer.and_then(|s| s.registered) else {
            return;
        };
        let mut m = Motion {
            pos: e.pos,
            target: e.pos,
            rot: [e.yaw, e.pitch],
            target_rot: [e.yaw, e.pitch],
            steps: 0,
            lerp,
            bb: [0.0; 6],
            dims: (w, h),
            pose: 0,
            slime: 1,
            stand: 0,
            baby: false,
            attached: None,
            dead: false,
            on_ground: false,
            name,
        };
        m.set_position(e.pos);
        let cap = self.motion.capacity();
        self.motion.insert(e.id, m);
        crate::store::after_insert(&mut self.motion, cap);
    }

    /// A teleport or a relative move to `target` (the tracked position).
    pub(crate) fn moved(&mut self, id: i32, target: [f64; 3], rot: Option<[f32; 2]>) {
        if let Some(m) = self.motion.get_mut(&id) {
            m.retarget(target, rot);
        } else if self.order.contains_key(&id) {
            // Not interpolated: at the target at once, in its old section until its tick.
            self.moved_now.push(id);
        }
    }

    /// A move or look packet's `onGround` (`setOnGround`).
    pub(crate) fn ground(&mut self, id: i32, on_ground: bool) {
        if let Some(m) = self.motion.get_mut(&id) {
            m.on_ground = on_ground;
        }
    }

    /// A move the client makes itself (a moving block's push, `Entity.move`): the new position
    /// and box (the box moved as a whole, the position its bottom centre) and the ground state.
    /// The interpolation goes on from there; the section is checked at the entity's next tick.
    pub(crate) fn pushed(&mut self, id: i32, pos: [f64; 3], bb: [f64; 6], on_ground: bool) -> bool {
        let Some(m) = self.motion.get_mut(&id) else {
            return false;
        };
        m.pos = pos;
        m.bb = bb;
        m.on_ground = on_ground;
        self.moved_now.push(id);
        true
    }

    /// A look-only packet: the interpolation target becomes the current position.
    pub(crate) fn looked(&mut self, id: i32, rot: [f32; 2]) {
        if let Some(m) = self.motion.get_mut(&id) {
            let p = m.pos;
            m.retarget(p, Some(rot));
        }
    }

    /// Entity data entries in packet order: the ones that change the size run
    /// `calculateDimensions` one after the other.
    pub(crate) fn data(&mut self, e: &Entity, entries: &[(u8, MetaValue)]) {
        let Some(m) = self.motion.get_mut(&e.id) else {
            return;
        };
        let id = match e.ty {
            EntityType::Registry(id) => Some(id),
            _ => None,
        };
        let baby_index = if id == Some(ty::PIGLIN) { 16 } else { 15 };
        let has_baby = e.sizer.is_some_and(|s| s.baby().is_some());
        for (i, v) in entries {
            let resize = match (*i, v) {
                (6, MetaValue::Pose(p)) => {
                    m.pose = *p;
                    true
                }
                (8, MetaValue::Float(h)) if e.living || e.ty == EntityType::Player => {
                    // Vanilla isAlive is `health > 0`: NaN counts as dead.
                    m.dead = h.is_nan() || *h <= 0.0;
                    false
                }
                (15, MetaValue::VarInt(n)) if matches!(id, Some(ty::SLIME | ty::MAGMA_CUBE)) => {
                    m.slime = *n;
                    true
                }
                (14, MetaValue::Byte(b)) if id == Some(ty::ARMOR_STAND) => {
                    m.stand = *b as u8;
                    true
                }
                (16, MetaValue::OptBlockPos(p)) if id == Some(ty::SHULKER) => {
                    m.attached = *p;
                    false
                }
                (i, MetaValue::Bool(b)) if has_baby && i == baby_index => {
                    m.baby = *b;
                    true
                }
                _ => false,
            };
            if resize {
                m.resize(e);
            }
        }
    }

    /// One client tick of every entity that ticks (`ticks(entity, client position)`): one
    /// interpolation step;
    /// a shulker sits on its attached block.
    /// The drawn state ([`Entity::drawn_position`]) of every ticked entity follows.
    pub(crate) fn tick(&mut self, store: &mut Entities, ticks: impl Fn(&Entity, [f64; 3]) -> bool) {
        let mut moved = std::mem::take(&mut self.moved_now);
        let mut carriers = std::mem::take(&mut self.carriers);
        for (id, m) in &mut self.motion {
            let Some(e) = store.map.get_mut(id) else {
                continue;
            };
            // Riders tick after their vehicles; others: ClientChunkManager.shouldTickEntity at
            // the client position.
            if e.rides() || !(e.is_player() || ticks(e, m.pos)) {
                continue;
            }
            if !e.passengers().is_empty() {
                carriers.push(*id);
            }
            let steps = m.steps > 0 || m.attached.is_some();
            m.tick_one();
            if let Some(c) = e.client.as_deref_mut() {
                c.pos = m.pos;
                c.rot = m.rot;
                c.bb = Some(m.bb);
            }
            if steps {
                moved.push(*id);
            }
        }
        let mut k = 0;
        while k < carriers.len() {
            let v = carriers[k];
            k += 1;
            self.tick_passengers(store, v, &ticks, &mut carriers, &mut moved);
        }
        carriers.clear();
        self.carriers = carriers;
        if !moved.is_empty() {
            self.resection(store, &mut moved, &ticks);
        }
        moved.clear();
        self.moved_now = moved;
    }

    /// `tickPassenger` for each passenger of ticked vehicle `v`: a player or a passenger in a
    /// loaded column takes its own tick (one interpolation step), then the vehicle seats it.
    #[cold]
    #[inline(never)]
    fn tick_passengers(
        &mut self,
        store: &mut Entities,
        v: i32,
        ticks: &impl Fn(&Entity, [f64; 3]) -> bool,
        carriers: &mut Vec<i32>,
        moved: &mut Vec<i32>,
    ) {
        let Some(ve) = store.map.get(&v) else { return };
        let Some(vm) = self.motion.get(&v) else {
            return;
        };
        let vehicle = (ve.ty, ve.sizer.map(|s| s.name), vm.pos, vm.rot[0]);
        let n = ve.passengers().len();
        for i in 0..n {
            let Some(&pid) = store.map.get(&v).and_then(|e| e.passengers().get(i)) else {
                break;
            };
            let Some(e) = store.map.get_mut(&pid) else {
                continue;
            };
            if e.vehicle() != Some(v) {
                continue;
            }
            let Some(m) = self.motion.get_mut(&pid) else {
                continue;
            };
            if !(e.is_player() || ticks(e, m.pos)) {
                continue;
            }
            m.tick_one();
            if let Some((p, yaw)) = seat(vehicle, i, n, e, m) {
                m.set_position(p);
                if let Some(y) = yaw {
                    m.rot[0] = y;
                }
            }
            if let Some(c) = e.client.as_deref_mut() {
                c.pos = m.pos;
                c.rot = m.rot;
                c.bb = Some(m.bb);
            }
            moved.push(pid);
            if !e.passengers().is_empty() {
                carriers.push(pid);
            }
        }
    }

    /// `checkEntityChunkPos` after each moved entity's tick, in the client world's tick order:
    /// an entity whose section changed joins the end of the new section's list.
    #[cold]
    #[inline(never)]
    fn resection(
        &mut self,
        store: &Entities,
        moved: &mut Vec<i32>,
        ticks: &impl Fn(&Entity, [f64; 3]) -> bool,
    ) {
        moved.sort_unstable();
        moved.dedup();
        moved.sort_by_key(|id| self.map.rank(*id).unwrap_or(u32::MAX));
        for &id in moved.iter() {
            let Some(e) = store.map.get(&id) else {
                continue;
            };
            let p = self.motion.get(&id).map_or(e.pos, |m| m.pos);
            if !ticks(e, p) {
                continue;
            }
            let sec = crate::drawn::section_of(p);
            if let Some(o) = self.order.get_mut(&id)
                && o.0 != sec
            {
                self.order_seq = self.order_seq.wrapping_add(1);
                *o = (sec, self.order_seq);
            }
        }
    }

    /// The drawn position and box of entity `id`.
    pub(crate) fn drawn(&self, id: i32) -> Option<([f64; 3], [f64; 6])> {
        self.motion.get(&id).map(|m| (m.pos, m.bb))
    }
}

impl Motion {
    /// One client tick: one interpolation step; a shulker sits on its attached block.
    fn tick_one(&mut self) {
        if let Some(b) = self.attached {
            // ShulkerEntity.tick: resetPosition (no box) and the closed shell's box.
            let (x, y, z) = (f64::from(b[0]), f64::from(b[1]), f64::from(b[2]));
            self.pos = [x + 0.5, y, z + 0.5];
            self.bb = [
                self.pos[0] - 0.5,
                y,
                self.pos[2] - 0.5,
                self.pos[0] + 0.5,
                y + 1.0,
                self.pos[2] + 0.5,
            ];
            return;
        }
        if self.steps > 0 && self.lerp != Lerp::Still {
            let n = f64::from(self.steps);
            let p = [
                self.pos[0] + (self.target[0] - self.pos[0]) / n,
                self.pos[1] + (self.target[1] - self.pos[1]) / n,
                self.pos[2] + (self.target[2] - self.pos[2]) / n,
            ];
            // `MathHelper.wrapDegrees(double)` of the yaw step, then setRotation's `% 360`.
            let mut g = (f64::from(self.target_rot[0]) - f64::from(self.rot[0])) % 360.0;
            if g >= 180.0 {
                g -= 360.0;
            }
            if g < -180.0 {
                g += 360.0;
            }
            let yaw = (f64::from(self.rot[0]) + g / n) as f32;
            let pitch = (f64::from(self.rot[1])
                + (f64::from(self.target_rot[1]) - f64::from(self.rot[1])) / n)
                as f32;
            self.rot = [yaw % 360.0, pitch % 360.0];
            self.steps -= 1;
            self.set_position(p);
        }
    }
}

/// `getHeightOffset` of a passenger (1.16.5 classes by registry name) and whether it is an
/// `AnimalEntity` (it sits 0.2 further ahead on a boat with two passengers).
fn height_offset(e: &Entity, m: &Motion) -> (f64, bool) {
    if e.is_player() {
        return (-0.35, false);
    }
    let name = e.sizer.map_or("", |s| s.name);
    let o = match name {
        "zombie" | "husk" | "drowned" | "zombie_villager" if m.baby => 0.0,
        "zombie" | "husk" | "drowned" | "zombie_villager" => -0.45,
        "zombified_piglin" | "piglin" | "piglin_brute" if m.baby => -0.05,
        "zombified_piglin" | "piglin" | "piglin_brute" => -0.45,
        "skeleton" | "stray" | "wither_skeleton" => -0.6,
        "pillager" | "vindicator" | "evoker" | "illusioner" | "ravager" | "witch" => -0.45,
        "silverfish" | "endermite" => 0.1,
        // Not a marker (flag 0x10).
        "armor_stand" if m.stand & 0x10 == 0 => f64::from(0.1_f32),
        _ if is_animal(name) => return (0.14, true),
        _ => 0.0,
    };
    (o, false)
}

/// `AnimalEntity` and its subclasses in 1.16.5.
fn is_animal(name: &str) -> bool {
    matches!(
        name,
        "cow"
            | "mooshroom"
            | "rabbit"
            | "strider"
            | "donkey"
            | "horse"
            | "mule"
            | "skeleton_horse"
            | "zombie_horse"
            | "llama"
            | "trader_llama"
            | "bee"
            | "sheep"
            | "panda"
            | "ocelot"
            | "cat"
            | "wolf"
            | "parrot"
            | "pig"
            | "polar_bear"
            | "fox"
            | "chicken"
            | "turtle"
            | "hoglin"
    )
}

/// The vehicle's `updatePassengerPosition` for passenger `i` of `n`: the seat and, on a boat,
/// the passenger's yaw (`copyEntityData`). `None`: a vehicle with its own seats (not modelled).
fn seat(
    (ty, name, pos, yaw): (EntityType, Option<&'static str>, [f64; 3], f32),
    i: usize,
    n: usize,
    e: &Entity,
    m: &Motion,
) -> Option<([f64; 3], Option<f32>)> {
    let (offset, animal) = height_offset(e, m);
    let [x, y, z] = pos;
    if ty == EntityType::Registry(ty::BOAT) {
        let g = (-0.1 + offset) as f32;
        let mut f = 0.0_f32;
        if n > 1 {
            f = if i == 0 { 0.2 } else { -0.6 };
            if animal {
                f = (f64::from(f) + 0.2) as f32;
            }
        }
        // Vec3d(f, 0, 0).rotateY(-yaw * PI / 180 - PI / 2) with MathHelper's table.
        let a = -yaw * (std::f64::consts::PI / 180.0) as f32 - (std::f64::consts::PI / 2.0) as f32;
        let (c, s) = crate::drawn::table_cos_sin(a);
        let fx = f64::from(f);
        let (dx, dz) = (fx * f64::from(c), -fx * f64::from(s));
        let d = crate::drawn::wrap_degrees_f32(m.rot[0] - yaw);
        let k = d.clamp(-105.0, 105.0);
        return Some(([x + dx, y + f64::from(g), z + dz], Some(m.rot[0] + (k - d))));
    }
    if name.is_some_and(|n| n.ends_with("minecart")) {
        return Some(([x, y + offset, z], None));
    }
    None
}

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

    /// A plain model of the table, written from fastutil's documented behaviour, against
    /// [`ClientMap`] over random adds and removes (orders must agree).
    #[test]
    fn grows_and_shrinks() {
        let mut m = ClientMap::default();
        for k in 1..=100 {
            m.insert(k * 7);
        }
        assert_eq!(m.len(), 100);
        assert_eq!(m.n, 256);
        for k in 1..=95 {
            assert!(m.remove(k * 7));
        }
        assert_eq!(m.len(), 5);
        assert!(m.n < 256);
        let order: Vec<i32> = m.order().collect();
        assert_eq!(order.len(), 5);
        m.insert(0);
        assert_eq!(m.order().next(), Some(0));
        assert!(m.before(0, 96 * 7));
    }
}