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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
//! 1.12.2 (protocol 340) entity tracking: the first member of the 1.9 – 1.12 family (the
//! packets and client rules below are shared by 1.9 – 1.12; only 1.12.2 is implemented).
//!
//! Positions follow the vanilla client exactly. Every entity keeps a tracked position in 1/4096
//! blocks (vanilla `trackedX` = `lfloor(x * 4096)`). Spawns and teleports set it from the sent
//! doubles and the position to those doubles; a relative move adds the `i16` deltas to it and
//! the position becomes `tracked / 4096.0` on **every** axis (unlike 1.16, an axis with delta 0
//! also snaps to the 1/4096 grid, and so does the bare `entity` packet). Velocities are
//! `v / 8000.0` (double) except at mob spawn (`(float) v / 8000.0F`); an object spawn applies its
//! velocity only when its (possibly reset) object data is positive. Angles are
//! `(float)(b * 360) / 256.0F`.
//!
//! As in 1.8, mobs and objects are separate id spaces: mobs are [`EntityType::LegacyMob`] with
//! the 1.12 entity registry id, objects [`EntityType::LegacyObject`] with the spawn-object type.
//! A vehicle the bot steers (the bot is its first passenger of a boat, a horse, donkey, mule,
//! skeleton or zombie horse, or of a pig while the bot holds a carrot on a stick,
//! [`Tracker::set_steer_carrot`]) ignores relative moves and teleports for its position and
//! rotation (vanilla `canPassengerSteer`; only the tracked value moves). A llama never steers.
//! A pickup (`collect`) always removes the collected entity.
//!
//! Every packet is parsed by hand from the body; movement packets touch no allocator.

use std::ops::Deref;

use bytes::Bytes;
use ghast_data::EntityKind;
use ghast_protocol::types::PositionLayout;
use ghast_protocol::types::slot::legacy::Slot;
use ghast_protocol::v1_12_2::play::clientbound::id;
use ghast_protocol::{BlockPos, Decode, DecodeError, RawPacket, Reader};

use crate::Applied;
use crate::common::{
    IdMask, R, angle, for_each_varint, legacy_item, own_nbt, own_str, player_info,
};
use crate::common::{block_pos, remove_effect, set_effect, spawn_with_metadata, vel3};
use crate::entity::{Effect, Entity, EntityType, Era, Item, MetaValue};
use crate::store::{Config, Entities, Event};

/// Spawn, movement, destroy, riding, pickup, status packets, plus `login` / `respawn`.
pub const CORE_IDS: &[i32] = &[
    id::LOGIN,
    id::RESPAWN,
    id::NAMED_ENTITY_SPAWN,
    id::SPAWN_ENTITY,
    id::SPAWN_ENTITY_LIVING,
    id::SPAWN_ENTITY_PAINTING,
    id::SPAWN_ENTITY_EXPERIENCE_ORB,
    id::SPAWN_ENTITY_WEATHER,
    id::ENTITY_VELOCITY,
    id::ENTITY_DESTROY,
    id::ENTITY,
    id::REL_ENTITY_MOVE,
    id::ENTITY_LOOK,
    id::ENTITY_MOVE_LOOK,
    id::ENTITY_TELEPORT,
    id::ENTITY_HEAD_ROTATION,
    id::ENTITY_STATUS,
    id::ATTACH_ENTITY,
    id::SET_PASSENGERS,
    id::COLLECT,
];
/// `entity_metadata`.
pub const METADATA_IDS: &[i32] = &[id::ENTITY_METADATA];
/// `entity_equipment`.
pub const EQUIPMENT_IDS: &[i32] = &[id::ENTITY_EQUIPMENT];
/// `entity_effect`, `remove_entity_effect`.
pub const EFFECT_IDS: &[i32] = &[id::ENTITY_EFFECT, id::REMOVE_ENTITY_EFFECT];
/// `player_info`.
pub const PLAYER_LIST_IDS: &[i32] = &[id::PLAYER_INFO];
/// `animation` (arm swings, [`Event::Swing`]): wanted only with [`Config::events`].
pub const EVENT_IDS: &[i32] = &[id::ANIMATION];

/// Object types and registry ids used by the tracker's rules.
mod ty {
    /// Spawn-object type of a boat.
    pub const BOAT_OBJECT: u8 = 1;
    /// Spawn-object type of a fishing bobber (object data: the owner's entity id).
    pub const FISHING_BOBBER_OBJECT: u8 = 90;
    /// Spawn-object type of a llama spit (its constructor takes the velocity).
    pub const LLAMA_SPIT_OBJECT: u8 = 68;
    /// Mob ids of the horse family a rider steers: horse, skeleton horse, zombie horse, donkey,
    /// mule (not the llama, 103).
    pub const STEERED_HORSES: [u8; 5] = [100, 28, 29, 31, 32];
    /// Mob id of a pig (steered while the rider holds a carrot on a stick).
    pub const PIG: u8 = 90;
}

/// 1.12.2 metadata indices (vanilla data tracker registration order).
pub mod meta {
    /// Entity flags byte (0x01 on fire, 0x02 sneaking, 0x08 sprinting, 0x10 using an item,
    /// 0x20 invisible, 0x40 glowing, 0x80 elytra flying).
    pub const FLAGS: u8 = 0;
    /// Air (VarInt).
    pub const AIR: u8 = 1;
    /// Custom name (string).
    pub const CUSTOM_NAME: u8 = 2;
    /// Custom name visible (boolean).
    pub const CUSTOM_NAME_VISIBLE: u8 = 3;
    /// Silent (boolean).
    pub const SILENT: u8 = 4;
    /// No gravity (boolean).
    pub const NO_GRAVITY: u8 = 5;
    /// Item entity: the item stack.
    pub const ITEM: u8 = 6;
    /// Living: hand states byte (0x01 hand active, 0x02 off hand).
    pub const HAND_STATES: u8 = 6;
    /// Living: health (float).
    pub const HEALTH: u8 = 7;
    /// Mob: AI flags byte.
    pub const MOB_FLAGS: u8 = 11;
    /// Ageable mobs and zombies: baby (boolean); slimes: size (VarInt).
    pub const BABY: u8 = 12;
    /// Slime / magma cube size (VarInt).
    pub const SLIME_SIZE: u8 = 12;
    /// Armor stand flags byte (0x01 small, 0x04 arms, 0x08 no base plate, 0x10 marker).
    pub const ARMOR_STAND_FLAGS: u8 = 11;
}

/// The bot's entity view on a 1.12.2 connection. Dereferences to the shared [`Entities`].
#[derive(Clone, Debug)]
pub struct Tracker {
    store: Entities,
    dimension: i32,
    wanted: IdMask,
    /// The bot holds a carrot on a stick in either hand: a pig it rides steers.
    steer_carrot: bool,
}

impl Deref for Tracker {
    type Target = Entities;
    fn deref(&self) -> &Entities {
        &self.store
    }
}

impl Tracker {
    /// An empty tracker.
    #[must_use]
    pub fn new(config: Config) -> Self {
        let mut wanted = IdMask::default();
        wanted.add(CORE_IDS);
        // The client view reads a shulker's entity data.
        if config.metadata || config.client_motion {
            wanted.add(METADATA_IDS);
        }
        if config.equipment {
            wanted.add(EQUIPMENT_IDS);
        }
        if config.effects {
            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: Era::V1_12,
                ..Entities::new(config)
            },
            dimension: 0,
            wanted,
            steer_carrot: false,
        }
    }

    /// The bot holds a carrot on a stick in its main or off hand (kept by the caller): a pig
    /// whose first passenger is the bot is then steered by it (its position and rotation packets
    /// only move the tracked value). Off by default.
    pub fn set_steer_carrot(&mut self, on: bool) {
        self.steer_carrot = on;
    }

    /// Keeps what the vanilla client draws of the other entities from now on (off by default):
    /// [`Entity::drawn_position`] / [`Entity::drawn_bounding_box`] (the 3-step interpolation of
    /// players, mobs and armor stands; shulkers on their attached block, read from their entity
    /// data even without [`Config::metadata`]) and the clocks
    /// [`Entity::position_tick`], [`Entity::spawn_tick`], [`Entity::last_hurt_tick`] and
    /// [`Entity::estimated_velocity`]. Call [`Tracker::tick_client`] once per client tick and
    /// [`Entities::set_tick`] for the clock. Turning it on draws every entity at its server
    /// position.
    pub fn track_client_motion(&mut self, on: bool) {
        self.store.set_client_motion(on);
        if on {
            // The view reads a shulker's entity data (the other entities' is skipped).
            self.wanted.add(METADATA_IDS);
        }
    }

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

    /// One client tick of the drawn positions (`World.tickEntities`: every entity's
    /// interpolation step). Call it after the tick's crosshair pick, where vanilla ticks the
    /// world's entities.
    pub fn tick_client(&mut self) {
        self.store.step_drawn();
    }

    /// A moving piston moved entity `id` on the client itself (`Entity.move`): its new
    /// position, box `[min_x, min_y, min_z, max_x, max_y, max_z]`, ground and web state. The
    /// client view draws (and picks) it there until its next interpolation step moves it on
    /// toward the server's position ([`Entity::drawn_on_ground`], [`Entity::drawn_in_web`]).
    /// `false` when the client view ([`Tracker::track_client_motion`]) does not keep it.
    pub fn client_pushed(
        &mut self,
        id: i32,
        pos: [f64; 3],
        bb: [f64; 6],
        on_ground: bool,
        in_web: bool,
    ) -> bool {
        self.store.legacy_pushed(id, pos, bb, on_ground, in_web)
    }

    /// The client ran entity `id`'s own tick itself, or a packet handler changed its client copy
    /// differently from the packet coordinates (the client-side physics of a projectile, item,
    /// experience orb, primed TNT or falling block, `ghast_physics::v1_12`): its position,
    /// motion ([`Entity::velocity`] is then the client copy's motion), rotation and ground flag
    /// become the client's. [`Entity::position`] is then the client's position; the tracked
    /// position relative moves add to stays in [`Entity::traced`], and a move or teleport
    /// packet puts the entity at the new tracked position as before. `false`: not tracked (or
    /// our own entity).
    pub fn client_simulated(
        &mut self,
        id: i32,
        pos: [f64; 3],
        vel: [f64; 3],
        rot: [f32; 2],
        on_ground: bool,
    ) -> bool {
        if Some(id) == self.store.self_id {
            return false;
        }
        let Some(e) = self.store.map.get_mut(&id) else {
            return false;
        };
        e.pos = pos;
        e.velocity = vel;
        e.yaw = rot[0];
        e.pitch = rot[1];
        e.on_ground = on_ground;
        true
    }

    /// The client's own tick discarded entity `id` (a primed TNT whose fuse ran out, a falling
    /// block of air, a bobber without its player owner, an entity fallen into the void): it
    /// leaves the client world 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 {
        self.store.remove(id)
    }

    /// 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()
    }

    /// 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> {
        if !self.wants(packet_id) {
            return Ok(Applied::NotEntityPacket);
        }
        let r = &mut Reader::new(body);
        let carrot = self.steer_carrot;
        let s = &mut self.store;
        let changed = match packet_id {
            id::REL_ENTITY_MOVE => relative(s, r, true, false, carrot)?,
            id::ENTITY_MOVE_LOOK => relative(s, r, true, true, carrot)?,
            id::ENTITY_LOOK => relative(s, r, false, true, carrot)?,
            id::ENTITY => relative(s, r, false, false, carrot)?,
            id::ENTITY_TELEPORT => teleport(s, r, carrot)?,
            id::ENTITY_VELOCITY => {
                let eid = r.read_varint()?;
                let v = vel3(r)?;
                match s.map.get_mut(&eid) {
                    Some(e) => {
                        e.velocity = v.map(|c| f64::from(c) / 8000.0);
                        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) {
                    Some(e) => {
                        e.head_yaw = angle(b);
                        true
                    }
                    None => 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();
                            if keep {
                                e.meta.set(meta::HEALTH, MetaValue::Float(0.0));
                            }
                        }
                        true
                    }
                    None => false,
                };
                if known {
                    s.event(Event::Status { id: eid, status });
                    // LivingEntity.handleStatus: 2 hurt, 33 thorns, 36 drowning, 37 burning.
                    if matches!(status, 2 | 33 | 36 | 37) {
                        s.hurt(eid, None);
                    }
                }
                known
            }
            id::NAMED_ENTITY_SPAWN => {
                let mut e = Entity::new(r.read_varint()?, EntityType::Player);
                e.uuid = r.read_uuid()?;
                set_pos(&mut e, [r.read_f64()?, r.read_f64()?, r.read_f64()?]);
                e.yaw = angle(r.read_i8()?);
                e.pitch = angle(r.read_i8()?);
                e.head_yaw = e.yaw;
                spawn_with_metadata(s, r, e, read_metadata)?
            }
            id::SPAWN_ENTITY => spawn_object(s, r)?,
            id::SPAWN_ENTITY_LIVING => spawn_mob(s, r)?,
            id::SPAWN_ENTITY_EXPERIENCE_ORB => {
                let mut e = Entity::new(r.read_varint()?, EntityType::ExperienceOrb);
                set_pos(&mut e, [r.read_f64()?, r.read_f64()?, r.read_f64()?]);
                e.data = i32::from(r.read_i16()?);
                s.spawn(e);
                true
            }
            id::SPAWN_ENTITY_PAINTING => {
                let eid = r.read_varint()?;
                let uuid = r.read_uuid()?;
                let n = r.read_len_varint(r.remaining())?;
                let title = r.take(n)?;
                let p = BlockPos::read(r, PositionLayout::Xyz)?;
                let dir = r.read_u8()?;
                let mut e = Entity::new(eid, EntityType::Painting);
                e.uuid = uuid;
                e.data = i32::from(dir) | i32::from(crate::hanging::motive_1_8(title)) << 8;
                // `setDirection`: turned to the facing; its tracked position stays at the origin
                // (the spawn handler never sets it).
                e.yaw = f32::from(dir % 4) * 90.0;
                // Where it hangs (on the block, facing `dir`).
                e.pos = crate::hanging::attach_1_8(&e, [p.x, p.y, p.z], e.data).unwrap_or([
                    f64::from(p.x),
                    f64::from(p.y),
                    f64::from(p.z),
                ]);
                s.spawn(e);
                true
            }
            // Lightning goes to the world's weather effects, not the entity id map.
            id::SPAWN_ENTITY_WEATHER => false,
            id::ATTACH_ENTITY => {
                let eid = r.read_i32()?;
                let holder = r.read_i32()?;
                // Only mobs can be leashed; an unknown holder detaches.
                match s.map.get(&eid) {
                    Some(e) if matches!(e.ty, EntityType::LegacyMob(_)) => {
                        let holder = s.map.contains_key(&holder).then_some(holder);
                        s.leash(eid, holder)
                    }
                    _ => false,
                }
            }
            id::SET_PASSENGERS => {
                let vehicle = r.read_varint()?;
                // Validate the list first so a bad packet changes nothing.
                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());
                s.set_passengers(vehicle, ids)
            }
            id::COLLECT => {
                let collected = r.read_varint()?;
                let collector = r.read_varint()?;
                // The client sets an item's stack size to the count (for the pickup particle)
                // and removes the collected entity, whatever it is.
                let count = r.read_varint()?;
                let item = s
                    .map
                    .get(&collected)
                    .and_then(|e| e.item().map(|i| (i.id, i32::from(i.count))));
                let known = s.map.contains_key(&collected);
                if known {
                    s.picked_up(collected, collector, Some(count), item, true);
                    s.remove(collected);
                }
                known
            }
            id::ENTITY_METADATA => {
                let eid = r.read_varint()?;
                let Some(e) = s.map.get(&eid) else {
                    return Ok(Applied::Ignored);
                };
                // The client view reads a shulker's attached block, face and peek (wanted for
                // that even without `Config::metadata`).
                let shulker = e.client.as_ref().is_some_and(|c| c.shulker.is_some());
                let keep = s.config.metadata;
                if !keep && !shulker {
                    return Ok(Applied::Ignored);
                }
                let mut scratch = std::mem::take(&mut s.scratch);
                scratch.clear();
                let res = read_metadata(r, &mut scratch);
                if res.is_ok()
                    && let Some(e) = s.map.get_mut(&eid)
                {
                    if shulker {
                        let d = crate::drawn::shulker_data(e, &scratch);
                        s.lerp_changed(d);
                    }
                    if keep && let Some(e) = s.map.get_mut(&eid) {
                        // Updates mostly overwrite: `set` keeps that path tight.
                        for (i, v) in scratch.drain(..) {
                            e.meta.set(i, v);
                        }
                        s.event(Event::Metadata(eid));
                    }
                }
                s.scratch = scratch;
                res?;
                true
            }
            id::ENTITY_EQUIPMENT => {
                let eid = r.read_varint()?;
                let slot = r.read_varint()?;
                let item = legacy_item(Slot::decode(r)?);
                match s.map.get_mut(&eid) {
                    // 0 main hand, 1 off hand, 2 feet, 3 legs, 4 chest, 5 head (the 26.x
                    // body and saddle slots do not exist here).
                    Some(e) if (0..6).contains(&slot) => {
                        e.equipment.get_or_insert_with(Default::default)[slot as usize] = item;
                        s.event(Event::Equipment(eid));
                        true
                    }
                    _ => false,
                }
            }
            id::ENTITY_EFFECT => {
                let eid = r.read_varint()?;
                let effect = Effect {
                    id: r.read_i8()? as u8,
                    amplifier: r.read_i8()?,
                    duration: r.read_varint()?,
                    flags: r.read_i8()? as u8,
                };
                // Only living entities keep effects.
                match s.map.get(&eid) {
                    Some(e) if e.living => set_effect(s, eid, effect),
                    _ => false,
                }
            }
            id::REMOVE_ENTITY_EFFECT => {
                let eid = r.read_varint()?;
                let eff = r.read_i8()? as u8;
                match s.map.get(&eid) {
                    Some(e) if e.living => remove_effect(s, eid, eff),
                    _ => false,
                }
            }
            id::PLAYER_INFO => {
                player_info(s, r)?;
                true
            }
            id::LOGIN => {
                let eid = r.read_i32()?;
                let _game_mode = r.read_u8()?;
                let dim = r.read_i32()?;
                s.clear();
                s.set_self(eid);
                self.dimension = dim;
                true
            }
            id::RESPAWN => {
                let dim = r.read_i32()?;
                // A new player entity: effects and equipment start empty, the metadata is
                // copied over from the old one (as in 1.16).
                if let Some(me) = s.self_id.and_then(|i| s.map.get_mut(&i)) {
                    me.clear_effects();
                    me.equipment = None;
                }
                if dim != self.dimension {
                    s.clear();
                    self.dimension = dim;
                }
                true
            }
            _ => return Ok(Applied::NotEntityPacket),
        };
        Ok(if changed {
            Applied::Changed
        } else {
            Applied::Ignored
        })
    }
}

/// 1.12.2 health of a living entity (`None` without metadata).
#[must_use]
pub fn health(e: &Entity) -> Option<f32> {
    e.metadata().float(meta::HEALTH)
}

/// 1.12.2 item of an item entity (`None` without metadata).
#[must_use]
pub fn item(e: &Entity) -> Option<&Item> {
    e.metadata().item(meta::ITEM).flatten()
}

/// 1.12.2 entity flags byte (0 when unknown).
#[must_use]
pub fn flags(e: &Entity) -> u8 {
    e.metadata().byte(meta::FLAGS).unwrap_or(0) as u8
}

/// 1.12.2 custom name (plain string; empty means none).
#[must_use]
pub fn custom_name(e: &Entity) -> Option<&str> {
    match e.metadata().get(meta::CUSTOM_NAME)? {
        MetaValue::String(s) if !s.is_empty() => Some(s),
        _ => None,
    }
}

/// Static type information from ghast-data (`ghast_data::v1_12`; registry paths such as
/// `"zombie"`, players: `None`).
#[must_use]
pub fn info(ty: EntityType) -> Option<&'static ghast_data::EntityInfo> {
    match ty {
        EntityType::LegacyMob(id) => ghast_data::v1_12::entity(EntityKind::Mob, u16::from(id)),
        EntityType::LegacyObject(id) => {
            ghast_data::v1_12::entity(EntityKind::Object, u16::from(id))
        }
        EntityType::ExperienceOrb => ghast_data::v1_12::entity(EntityKind::Mob, 2),
        EntityType::Painting => ghast_data::v1_12::entity(EntityKind::Mob, 9),
        _ => None,
    }
}

/// `lfloor(x * 4096)` (vanilla `EntityTracker` position encoding).
#[inline]
fn encode(x: f64) -> i64 {
    let d = x * 4096.0;
    let l = d as i64;
    if d < l as f64 { l.wrapping_sub(1) } else { l }
}

/// Spawn / teleport: the position is the sent doubles, the tracked value their encoding.
#[inline]
fn set_pos(e: &mut Entity, p: [f64; 3]) {
    e.pos = p;
    e.traced = p.map(encode);
}

/// `true` when the bot steers the entity (`canPassengerSteer`: the bot is the first passenger of
/// a boat, a steered horse, or a pig while it holds a carrot on a stick).
fn controlled(s: &Entities, e: &Entity, carrot: bool) -> bool {
    let steerable = match e.ty {
        EntityType::LegacyObject(t) => t == ty::BOAT_OBJECT,
        EntityType::LegacyMob(m) => ty::STEERED_HORSES.contains(&m) || (carrot && m == ty::PIG),
        _ => false,
    };
    steerable && s.self_id.is_some() && e.passengers().first().copied() == s.self_id
}

/// `entity`, `rel_entity_move`, `entity_look`, `entity_move_look` (vanilla `onEntityUpdate`:
/// the tracked position moves by the deltas and the position becomes `tracked / 4096.0` on all
/// three axes; the bare `entity` packet also sets `on_ground = false`).
#[inline]
fn relative(s: &mut Entities, r: &mut Reader<'_>, pos: bool, look: bool, carrot: bool) -> R<bool> {
    let eid = r.read_varint()?;
    let d = if pos {
        [r.read_i16()?, r.read_i16()?, r.read_i16()?]
    } else {
        [0; 3]
    };
    let rot = if look {
        Some((r.read_i8()?, r.read_i8()?))
    } else {
        None
    };
    let on_ground = if pos || look { r.read_bool()? } else { false };
    if Some(eid) == s.self_id {
        return Ok(false);
    }
    let Some(e) = s.map.get(&eid) else {
        return Ok(false);
    };
    let ctl = controlled(s, e, carrot);
    let now = s.now;
    let Some(e) = s.map.get_mut(&eid) else {
        return Ok(false);
    };
    for (t, d) in e.traced.iter_mut().zip(d) {
        *t = t.wrapping_add(i64::from(d));
    }
    if ctl {
        return Ok(false);
    }
    let t = e.traced.map(|t| t as f64 / 4096.0);
    if crate::hanging::is_hanging(e) {
        // Paintings, item frames, knots hang from the tracked position (look-only and bare
        // packets too); a painting never turns.
        crate::hanging::tracked_move(e, t);
        if let Some((y, p)) = rot
            && !crate::hanging::is_painting(e)
        {
            e.yaw = angle(y);
            e.pitch = angle(p);
        }
    } else {
        e.pos = t;
        if let Some((y, p)) = rot {
            e.yaw = angle(y);
            e.pitch = angle(p);
        }
    }
    e.on_ground = on_ground;
    let d = crate::drawn::relative(e, rot.is_some(), now);
    s.lerp_changed(d);
    s.event(Event::Moved(eid));
    Ok(true)
}

fn teleport(s: &mut Entities, r: &mut Reader<'_>, carrot: bool) -> R<bool> {
    let eid = r.read_varint()?;
    let p = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
    let (y, pi) = (r.read_i8()?, r.read_i8()?);
    let on_ground = r.read_bool()?;
    if Some(eid) == s.self_id {
        return Ok(false);
    }
    let Some(e) = s.map.get(&eid) else {
        return Ok(false);
    };
    let ctl = controlled(s, e, carrot);
    let now = s.now;
    let Some(e) = s.map.get_mut(&eid) else {
        return Ok(false);
    };
    if ctl {
        // Only the tracked value follows a vehicle the bot steers.
        e.traced = p.map(encode);
        return Ok(false);
    }
    if crate::hanging::is_hanging(e) {
        // `onEntityPosition`: within 1/32 (y 1/64) of the client's position it stays put.
        e.traced = p.map(encode);
        let far = |a: f64, t: f64| a.partial_cmp(&t).is_some_and(|o| o.is_ge());
        if far((e.pos[0] - p[0]).abs(), 0.031_25)
            || far((e.pos[1] - p[1]).abs(), 0.015_625)
            || far((e.pos[2] - p[2]).abs(), 0.031_25)
        {
            crate::hanging::tracked_move(e, p);
        }
        if !crate::hanging::is_painting(e) {
            e.yaw = angle(y);
            e.pitch = angle(pi);
        }
    } else {
        set_pos(e, p);
        e.yaw = angle(y);
        e.pitch = angle(pi);
    }
    e.on_ground = on_ground;
    let d = crate::drawn::teleport(e, now);
    s.lerp_changed(d);
    s.event(Event::Moved(eid));
    Ok(true)
}

/// Object types the 1.12 client creates an entity for.
fn known_object(t: u8) -> bool {
    matches!(
        t,
        1 | 2 | 3 | 10 | 50 | 51 | 60..=68 | 70..=73 | 75..=79 | 90 | 91 | 93
    )
}

/// Object types whose object data vanilla resets to 0 before deciding about the velocity.
fn data_reset(t: u8) -> bool {
    matches!(t, 63 | 64 | 66 | 67 | 70 | 71 | 73 | 75 | 77 | 90 | 93)
}

fn spawn_object(s: &mut Entities, r: &mut Reader<'_>) -> R<bool> {
    let eid = r.read_varint()?;
    let uuid = r.read_uuid()?;
    let t = r.read_i8()? as u8;
    let p = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
    let pitch = r.read_i8()?;
    let yaw = r.read_i8()?;
    let data = r.read_i32()?;
    let v = vel3(r)?;
    if !known_object(t) {
        return Ok(false); // vanilla creates no entity for other types
    }
    // A fishing bobber needs its owner: a player the client knows (our own one too:
    // `getEntityById` answers the client player for its id).
    if t == ty::FISHING_BOBBER_OBJECT
        && Some(data) != s.self_id
        && !s.map.get(&data).is_some_and(|o| o.ty == EntityType::Player)
    {
        return Ok(false);
    }
    let mut e = Entity::new(eid, EntityType::LegacyObject(t));
    e.uuid = uuid;
    set_pos(&mut e, p);
    e.pitch = angle(pitch);
    e.yaw = angle(yaw);
    e.head_yaw = e.yaw;
    e.data = data;
    let effective = if data_reset(t) { 0 } else { data };
    if effective > 0 || t == ty::LLAMA_SPIT_OBJECT {
        e.velocity = v.map(|c| f64::from(c) / 8000.0);
    }
    // Item frames and leash knots hang on the block of the packet's position.
    if t == 71 || t == 77 {
        let b = e.pos.map(|c| c.floor() as i32);
        e.pos = if t == 77 {
            crate::hanging::knot_1_8(b)
        } else {
            crate::hanging::attach_1_8(&e, b, data).unwrap_or(e.pos)
        };
    }
    s.spawn(e);
    Ok(true)
}

fn spawn_mob(s: &mut Entities, r: &mut Reader<'_>) -> R<bool> {
    let eid = r.read_varint()?;
    let uuid = r.read_uuid()?;
    let t = r.read_varint()?;
    let p = [r.read_f64()?, r.read_f64()?, r.read_f64()?];
    let yaw = r.read_i8()?;
    let pitch = r.read_i8()?;
    let head = r.read_i8()?;
    let v = vel3(r)?;
    // Unknown registry ids spawn nothing (vanilla logs "Skipping Entity").
    let Some(t) = u8::try_from(t)
        .ok()
        .filter(|&t| ghast_data::v1_12::entity(EntityKind::Mob, u16::from(t)).is_some())
    else {
        return Ok(false);
    };
    let mut e = Entity::new(eid, EntityType::LegacyMob(t));
    e.uuid = uuid;
    set_pos(&mut e, p);
    e.yaw = angle(yaw);
    e.pitch = angle(pitch);
    e.head_yaw = angle(head);
    // Mob spawn divides in float: (double)((float) v / 8000.0F).
    e.velocity = v.map(|c| f64::from(f32::from(c) / 8000.0));
    if t == SHULKER && s.client_motion {
        return spawn_shulker(s, r, e);
    }
    spawn_with_metadata(s, r, e, read_metadata)
}

/// 1.12 mob id of a shulker.
const SHULKER: u8 = 69;

/// A shulker spawn with the client view on: the entity data of the packet reaches the view after
/// the spawn (`writeUpdatedEntries` after `addEntity`: attached-block data puts it on the block).
#[cold]
#[inline(never)]
fn spawn_shulker(s: &mut Entities, r: &mut Reader<'_>, mut e: Entity) -> R<bool> {
    let eid = e.id;
    let mut scratch = std::mem::take(&mut s.scratch);
    scratch.clear();
    if let Err(err) = read_metadata(r, &mut scratch) {
        s.scratch = scratch;
        return Err(err);
    }
    if s.config.metadata {
        e.meta.set_from(&mut scratch.clone(), |_| true);
    }
    s.spawn(e);
    if let Some(e) = s.map.get_mut(&eid) {
        let d = crate::drawn::shulker_data(e, &scratch);
        s.lerp_changed(d);
    }
    s.scratch = scratch;
    Ok(true)
}

/// 1.9 – 1.12 metadata: index byte (`0xFF` ends), VarInt serializer id, value.
fn read_metadata(r: &mut Reader<'_>, out: &mut Vec<(u8, MetaValue)>) -> R<()> {
    loop {
        let index = r.read_u8()?;
        if index == 0xFF {
            return Ok(());
        }
        let v = match r.read_varint()? {
            0 => MetaValue::Byte(r.read_i8()?),
            1 => MetaValue::VarInt(r.read_varint()?),
            2 => MetaValue::Float(r.read_f32()?),
            3 => MetaValue::String(own_str(r)?),
            4 => MetaValue::Chat(own_str(r)?),
            5 => MetaValue::Item(legacy_item(Slot::decode(r)?)),
            6 => MetaValue::Bool(r.read_bool()?),
            7 => MetaValue::Rotation([r.read_f32()?, r.read_f32()?, r.read_f32()?]),
            8 => MetaValue::BlockPos(block_pos(BlockPos::read(r, PositionLayout::Xyz)?)),
            9 => MetaValue::OptBlockPos(if r.read_bool()? {
                Some(block_pos(BlockPos::read(r, PositionLayout::Xyz)?))
            } else {
                None
            }),
            10 => MetaValue::Direction(r.read_varint()?),
            11 => MetaValue::OptUuid(if r.read_bool()? {
                Some(r.read_uuid()?)
            } else {
                None
            }),
            12 => MetaValue::BlockState(r.read_varint()?),
            13 => MetaValue::Nbt(
                own_nbt(Some(ghast_protocol::nbt::RawNbt::read(r)?)).unwrap_or_default(),
            ),
            _ => return Err(DecodeError::Invalid("unknown metadata serializer")),
        };
        out.push((index, v));
    }
}

/// The vanilla 1.12.2 size entry for an entity (`None` for paintings and hanging objects).
pub(crate) fn vanilla_size(e: &Entity) -> Option<&'static ghast_data::VanillaEntitySize> {
    let all = ghast_data::v1_12::vanilla_entity_sizes();
    match e.ty {
        EntityType::Player => ghast_data::v1_12::vanilla_entity_size("player"),
        EntityType::LegacyMob(id) => all
            .iter()
            .find(|v| v.spawn == "mob" && v.registry_id == i32::from(id)),
        // Item frame and leash knot are hanging entities.
        EntityType::LegacyObject(71 | 77) => None,
        EntityType::LegacyObject(t) => {
            let t = i32::from(t);
            all.iter()
                .find(|v| v.spawn == "object" && v.object_types.contains(&(t, e.data)))
                .or_else(|| {
                    all.iter().find(|v| {
                        v.spawn == "object" && v.object_types.iter().any(|&(ty, _)| ty == t)
                    })
                })
        }
        EntityType::ExperienceOrb => all.iter().find(|v| v.spawn == "xp_orb"),
        _ => None,
    }
}

/// 1.12.2 dimensions with the metadata variants the client applies.
pub(crate) fn dimensions(
    e: &Entity,
    vs: &'static ghast_data::VanillaEntitySize,
) -> Option<ghast_data::EntityDimensions> {
    let base = vs.default_dimensions()?;
    let m = &e.meta;
    let pick = |name: &str| Some(vs.variant(name).map_or(base, |v| v.dimensions));
    match e.ty {
        // Players: 0.6 x 1.65 while sneaking (applied by the next size update).
        EntityType::Player if m.byte(meta::FLAGS).is_some_and(|f| f & 0x02 != 0) => {
            pick("sneaking")
        }
        // Slime / magma cube: size VarInt at 12.
        EntityType::LegacyMob(55 | 62) => match m.get(meta::SLIME_SIZE) {
            Some(MetaValue::VarInt(n)) => Some(ghast_data::v1_12::slime_dimensions(*n)),
            _ => Some(base),
        },
        // Ageable mobs and zombies: baby boolean at 12.
        EntityType::LegacyMob(_) if matches!(m.get(meta::BABY), Some(MetaValue::Bool(true))) => {
            Some(vs.baby().unwrap_or(base))
        }
        // A llama: its constructor sizes it twice (the horse's 1.3964844 x 1.6, then 0.9 x 1.87);
        // the box keeps the first until the baby flag arrives (`PassiveEntity.setScale` from the
        // last size), which every spawn carries.
        EntityType::LegacyMob(103) if matches!(m.get(meta::BABY), Some(MetaValue::Bool(false))) => {
            Some(ghast_data::EntityDimensions {
                width: 0.9,
                height: 1.87,
                eye_height: 1.87,
            })
        }
        // Armor stand flags byte at 11: 0x01 small, 0x10 marker.
        EntityType::LegacyObject(78) => {
            let f = m.byte(meta::ARMOR_STAND_FLAGS).unwrap_or(0) as u8;
            match (f & 0x01 != 0, f & 0x10 != 0) {
                (true, true) => pick("small_marker"),
                (false, true) => pick("marker"),
                (true, false) => pick("small"),
                _ => Some(base),
            }
        }
        _ => Some(base),
    }
}

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

    #[test]
    fn encode_floors() {
        assert_eq!(encode(1.0), 4096);
        assert_eq!(encode(-0.0001), -1);
        assert_eq!(encode(0.5 / 4096.0), 0);
        assert_eq!(encode(-1.0), -4096);
    }

    #[test]
    fn item_object_id() {
        assert!(known_object(2));
        assert!(!known_object(4));
    }

    fn body(parts: &[&[u8]]) -> Bytes {
        Bytes::from(parts.concat())
    }

    /// The store counts the interpolating entities exactly: moves start it, the third step,
    /// a near teleport (0 steps on 1.12) and a destroy end it; a tick with none visits nothing.
    #[test]
    fn interpolating_count() {
        let mut t = Tracker::new(Config::default().with_client_motion(true));
        let mob = |eid: u8, x: f64| {
            let mut b = vec![eid];
            b.extend_from_slice(&[0; 16]); // uuid
            b.push(54); // zombie
            for v in [x, 64.0, 0.5] {
                b.extend_from_slice(&v.to_be_bytes());
            }
            b.extend_from_slice(&[0; 9]);
            b.push(0xff);
            Bytes::from(b)
        };
        let mv = |eid: u8, dz: i16| body(&[&[eid], &[0, 0, 0, 0], &dz.to_be_bytes(), &[1]]);
        let tp = |eid: u8, x: f64, z: f64| {
            let mut b = vec![eid];
            for v in [x, 64.0, z] {
                b.extend_from_slice(&v.to_be_bytes());
            }
            b.extend_from_slice(&[0, 0, 1]);
            Bytes::from(b)
        };
        t.apply_body(id::SPAWN_ENTITY_LIVING, &mob(5, 0.5)).unwrap();
        t.apply_body(id::SPAWN_ENTITY_LIVING, &mob(6, 3.5)).unwrap();
        assert_eq!(t.store.lerping, 0);
        t.apply_body(id::REL_ENTITY_MOVE, &mv(5, 4096)).unwrap();
        t.apply_body(id::REL_ENTITY_MOVE, &mv(5, 4096)).unwrap();
        t.apply_body(id::REL_ENTITY_MOVE, &mv(6, 4096)).unwrap();
        assert_eq!(t.store.lerping, 2);
        for _ in 0..3 {
            t.tick_client();
        }
        assert_eq!(t.store.lerping, 0);
        assert_eq!(t.get(5).unwrap().drawn_position()[2], 2.5);
        // A far teleport starts it, a near one (within 1/32 of the drawn position) ends it.
        t.apply_body(id::ENTITY_TELEPORT, &tp(5, 0.5, 8.0)).unwrap();
        assert_eq!(t.store.lerping, 1);
        t.tick_client();
        let z = t.get(5).unwrap().drawn_position()[2];
        t.apply_body(id::ENTITY_TELEPORT, &tp(5, 0.5, z + 0.01))
            .unwrap();
        assert_eq!(t.store.lerping, 0);
        // A destroy while interpolating.
        t.apply_body(id::REL_ENTITY_MOVE, &mv(6, 4096)).unwrap();
        assert_eq!(t.store.lerping, 1);
        t.apply_body(id::ENTITY_DESTROY, &Bytes::from_static(&[1, 6]))
            .unwrap();
        assert_eq!(t.store.lerping, 0);
        // A re-spawn of an interpolating id.
        t.apply_body(id::REL_ENTITY_MOVE, &mv(5, 4096)).unwrap();
        assert_eq!(t.store.lerping, 1);
        t.apply_body(id::SPAWN_ENTITY_LIVING, &mob(5, 0.5)).unwrap();
        assert_eq!(t.store.lerping, 0);
    }
}