ghast-client 0.5.5

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
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
//! Modern versions: the client-side physics of the tracked non-living entities
//! ([`crate::Interests::ENTITY_PHYSICS`]): projectiles, item entities, experience orbs, primed
//! TNT and falling blocks run their own tick on the client every client tick
//! (`ClientLevel.tickNonPassenger`: `commonTick`, then the entity's `tick`), with the client's
//! side of the rules (`ghast_physics::modern::{projectile, drop}`, oracle-proven per kind).
//!
//! The tracker keeps doing what it did (packets, the `commonTick` interpolation step of orbs
//! and bobbers); after its tick each simulated entity runs one physics tick from the tracker's
//! state and writes position, motion, rotation and ground flag back
//! ([`super::entity::Tracker::client_simulated`]). The physics state keeps what packets do not
//! carry (water state, first tick, an arrow stuck in a block, an orb's skipped first tick, a
//! fuse); whatever a packet changed since the last tick (position, motion, rotation, ground) is
//! taken from the tracker before the tick, which is where a vanilla client's packet handler
//! puts it.
//!
//! Entity data that changes the tick: `NO_GRAVITY` (such an entity is not simulated: the
//! physics has no no-gravity rule yet, it stays where its packets put it), an arrow's
//! `IN_GROUND` and no-physics flag, a wither skull's `DANGEROUS`, a TNT's fuse, a bobber's hooked
//! entity (the bobber follows it at 0.8 of its height, from the entity's drawn position) and
//! `DATA_BITING` (the bite's jerk, applied when the packet arrives, and the pull while biting:
//! drawn from `FishingHook.syncronizedRandom`, which is seeded from the bobber's UUID and the
//! level's game time each tick, so a client can draw it exactly); `projectile_power` sets a
//! hurting projectile's acceleration. A motion packet with a non-zero motion frees a stuck arrow
//! (`AbstractArrow.lerpMotion`).
//!
//! An orb follows the nearest player within 8 blocks (`followNearbyPlayer`, which a client runs
//! too): the level's players are ours (where this tick's movement left it) and the tracked ones,
//! each where it is when the orb ticks (one that ticks after the orb is read before its own
//! interpolation step), with its pose's eye height, its tab-list spectator flag and its health.
//! An orb keeps following a player object that left the level (or was spawned again under the
//! same id) where its last tick left it, with the spectator flag of the tab-list object it
//! cached.
//!
//! The client does nothing itself for pickup, merging and hits on these entities (the server's
//! `take_item_entity` / remove packets do it); vanilla's client never runs them.
//!
//! Not simulated: entity hits, pickup, merging, passengers (they ride, `rideTick`), the
//! order of a hooked entity's own tick against the bobber's (the bobber reads the entity's
//! position as the tracker has it when the non-living entities tick), and the random draws of a
//! client entity (unseeded in vanilla: a bobber's bobbing differs between two vanilla clients
//! too; a bite flag before the bobber's first tick draws its jerk from an unseeded random).

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

use super::*;
use crate::sim::shared::PlayerFacts;
use ghast_physics::modern::Side;
use ghast_physics::modern::drop::{self, Drop, DropKind, OrbPlayer};
use ghast_physics::modern::projectile::{self, HookedEntity, Projectile, ProjectileKind};

/// Entity data indices (26.1 – 26.3: the `Entity` class defines 0 – 7, a subclass starts at 8).
mod data_index {
    pub(super) const NO_GRAVITY: u8 = 5;
    /// `AbstractArrow.ID_FLAGS` (0x02: no physics), `WitherSkull.DATA_DANGEROUS`,
    /// `PrimedTnt.DATA_FUSE_ID`, `FishingHook.DATA_HOOKED_ENTITY`.
    pub(super) const FIRST: u8 = 8;
    /// `FishingHook.DATA_BITING`.
    pub(super) const BITING: u8 = 9;
    /// `AbstractArrow.IN_GROUND`.
    pub(super) const ARROW_IN_GROUND: u8 = 10;
}

/// An identity hasher for entity ids.
#[derive(Default)]
pub(super) struct IdHasher(u64);

impl Hasher for IdHasher {
    fn finish(&self) -> u64 {
        self.0
    }
    fn write(&mut self, bytes: &[u8]) {
        for &b in bytes {
            self.0 = self.0.rotate_left(8) ^ u64::from(b);
        }
    }
    fn write_i32(&mut self, i: i32) {
        self.0 = u64::from(i as u32).wrapping_mul(0x9E37_79B9_7F4A_7C15);
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Kind {
    Projectile(ProjectileKind),
    Drop(DropKind),
}

impl Kind {
    fn of(name: &str) -> Option<Kind> {
        ProjectileKind::from_entity_name(name)
            .map(Kind::Projectile)
            .or_else(|| DropKind::from_entity_name(name).map(Kind::Drop))
    }
    fn arrow(self) -> bool {
        matches!(
            self,
            Kind::Projectile(
                ProjectileKind::Arrow | ProjectileKind::SpectralArrow | ProjectileKind::Trident
            )
        )
    }
}

#[derive(Debug)]
enum State {
    Projectile(Projectile),
    Drop(Drop),
}

/// One simulated entity.
#[derive(Debug)]
struct Entry {
    kind: Kind,
    /// The physics state (`None` until its first tick: built from the tracker then).
    state: Option<State>,
    no_gravity: bool,
    /// An arrow's no-physics flag, a bobber hooked to an entity.
    no_physics: bool,
    /// Entity data and packets that arrived before the first tick.
    in_ground: Option<bool>,
    dangerous: Option<bool>,
    fuse: Option<i32>,
    power: Option<f64>,
    /// Position and rotation before this tick's interpolation step (orbs and bobbers).
    pre: Option<([f64; 3], [f32; 2])>,
    /// A bobber's hooked entity (`hookedIn`: the synced id named an entity the client has).
    hook: Option<i32>,
    /// A bobber's bite flag that arrived before its first tick.
    biting: Option<bool>,
}

impl Entry {
    fn new(kind: Kind) -> Entry {
        Entry {
            kind,
            state: None,
            no_gravity: false,
            no_physics: false,
            in_ground: None,
            dangerous: None,
            fuse: None,
            power: None,
            pre: None,
            hook: None,
            biting: None,
        }
    }

    fn projectile(&mut self) -> Option<&mut Projectile> {
        match &mut self.state {
            Some(State::Projectile(p)) => Some(p),
            _ => None,
        }
    }
}

/// 26.3+: the client's interpolation takes over the moves of a client-simulated entity
/// (`Entity.recordMovement` for `MoveSimulationType.SERVER_AND_CLIENT`, the same version step
/// as [`modern::Rules::SIMULATED_ON_CLIENT`]).
const PREDICTED: bool = <Rules as modern::Rules>::SIMULATED_ON_CLIENT;

/// A position / motion / rotation / ground update for the tracker.
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);

/// The simulated entities (a side table: only while [`crate::Interests::ENTITY_PHYSICS`] is on).
#[derive(Debug, Default)]
pub(super) struct NonLiving {
    map: HashMap<i32, Entry, BuildHasherDefault<IdHasher>>,
    updates: Vec<Update>,
    /// 26.3: the moves of this tick's entity ticks (`recordMovement`).
    moves: Vec<(i32, [f64; 3])>,
    discards: Vec<i32>,
    /// Orbs are simulated: the other players' positions before this tick's entity ticks.
    pre: Vec<(i32, [f64; 3])>,
    /// The level's players after the entity ticks, with the position before and the tick
    /// order (what an orb reads of them depends on whether they ticked before it).
    players: Vec<(OrbPlayer, [f64; 3], u64)>,
    /// The players one orb sees.
    seen: Vec<OrbPlayer>,
    /// Player objects: a player spawned again under the same id is a new object (an orb keeps
    /// following the old one), so each player spawn gets its own identity.
    idents: crate::sim::shared::PlayerIdents,
}

impl NonLiving {
    /// Forgets every entity (a new level, a new tracker).
    pub(super) fn clear(&mut self) {
        self.map.clear();
        self.idents.clear();
    }
}

impl ModernSim {
    /// Switches the client-side physics of the non-living entities on or off.
    pub(super) fn set_nonliving(&mut self, on: bool) {
        if on == self.nonliving.is_some() {
            return;
        }
        // Entities spawned before are known again once the server sends them again.
        self.nonliving = on.then(Box::default);
        self.filter_dirty = true;
    }

    /// The packet ids the non-living physics reads beyond the tracker's.
    pub(super) fn nonliving_packet_ids(&self) -> &'static [i32] {
        use super::proto::play::clientbound as cb;
        if self.nonliving.is_some() && self.entities.is_some() {
            &[cb::id::SET_PROJECTILE_POWER]
        } else {
            &[]
        }
    }

    /// A packet the simulated entities care about, after the tracker applied it.
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use super::proto::play::clientbound as cb;
        use super::proto::types::EntityMetadataEntryValue as V;
        let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
            return Ok(());
        };
        let mut r = ghast_protocol::Reader::new(&raw.body);
        match raw.id {
            cb::id::LOGIN | cb::id::RESPAWN => n.clear(),
            cb::id::SPAWN_ENTITY => {
                let id = r.read_varint()?;
                r.skip(16)?; // uuid
                let ty = r.read_varint()?;
                let data = u16::try_from(ty).ok().and_then(super::data::entity_type);
                if data.is_some_and(|t| t.name == "player")
                    && t.get(id).is_some_and(|e| e.is_player())
                {
                    n.idents.spawned(id);
                }
                let kind = data.and_then(|t| Kind::of(t.name));
                // A spawn is a new entity: a fresh state (or none, for another type).
                match kind {
                    Some(k) if t.get(id).is_some() => {
                        n.map.insert(id, Entry::new(k));
                    }
                    _ => {
                        n.map.remove(&id);
                    }
                }
            }
            cb::id::ENTITY_METADATA => {
                let id = r.read_varint()?;
                // A followed player's pose (eye height) changes at once.
                if let Some(e) = t.get(id).filter(|e| e.is_player()) {
                    n.idents
                        .eye_changed(id, e.dimensions().map_or(1.62, |d| d.eye_height));
                    return Ok(());
                }
                let Some(en) = n.map.get_mut(&id) else {
                    return Ok(());
                };
                let p: cb::EntityMetadata = raw.decode_as()?;
                let mut bitten = None;
                for m in &p.metadata {
                    match (&m.value, m.key, en.kind) {
                        (V::Boolean(b), data_index::NO_GRAVITY, _) => en.no_gravity = *b,
                        (V::Byte(f), data_index::FIRST, k) if k.arrow() => {
                            en.no_physics = *f as u8 & 0x02 != 0;
                        }
                        (V::Boolean(b), data_index::ARROW_IN_GROUND, k) if k.arrow() => {
                            match en.projectile() {
                                Some(p) => p.set_in_ground(*b),
                                None => en.in_ground = Some(*b),
                            }
                        }
                        (
                            V::Boolean(b),
                            data_index::FIRST,
                            Kind::Projectile(ProjectileKind::WitherSkull),
                        ) => match en.projectile() {
                            Some(p) => p.set_dangerous(*b),
                            None => en.dangerous = Some(*b),
                        },
                        (V::Int(f), data_index::FIRST, Kind::Drop(DropKind::PrimedTnt)) => {
                            match &mut en.state {
                                Some(State::Drop(d)) => d.set_fuse(*f),
                                _ => en.fuse = Some(*f),
                            }
                        }
                        (
                            V::Int(h),
                            data_index::FIRST,
                            Kind::Projectile(ProjectileKind::FishingBobber),
                        ) => {
                            // onSyncedDataUpdated: hookedIn = level.getEntity(id - 1)
                            en.hook = (*h > 0).then(|| *h - 1).filter(|&i| t.get(i).is_some());
                            if en.hook.is_none()
                                && let Some(p) = en.projectile()
                            {
                                p.set_hooked(None);
                            }
                        }
                        (
                            V::Boolean(b),
                            data_index::BITING,
                            Kind::Projectile(ProjectileKind::FishingBobber),
                        ) => match en.projectile() {
                            // the jerk, seen by the tracker at once
                            Some(p) => {
                                p.set_biting(*b);
                                let (pos, vel, rot, g) =
                                    (p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground());
                                bitten = Some((id, pos, vel, rot, g));
                            }
                            None => en.biting = Some(*b),
                        },
                        _ => {}
                    }
                }
                if let Some((id, pos, vel, rot, g)) = bitten
                    && let Some(t) = &mut self.entities
                {
                    t.client_simulated(id, pos, vel, rot, g);
                }
            }
            cb::id::ENTITY_VELOCITY => {
                // AbstractArrow.lerpMotion: a non-zero motion frees a stuck arrow.
                let id = r.read_varint()?;
                let Some(en) = n.map.get_mut(&id).filter(|en| en.kind.arrow()) else {
                    return Ok(());
                };
                let moving = t.get(id).is_some_and(|e| {
                    let v = e.velocity();
                    v[0] * v[0] + v[1] * v[1] + v[2] * v[2] > 0.0
                });
                if moving {
                    match en.projectile() {
                        Some(p) => {
                            if p.in_ground() {
                                p.set_in_ground(false);
                            }
                        }
                        None => {
                            if en.in_ground == Some(true) {
                                en.in_ground = Some(false);
                            }
                        }
                    }
                }
            }
            cb::id::SET_PROJECTILE_POWER => {
                let p: cb::SetProjectilePower = raw.decode_as()?;
                if let Some(en) = n.map.get_mut(&p.id) {
                    match en.projectile() {
                        Some(s) => s.set_acceleration_power(p.acceleration_power),
                        None => en.power = Some(p.acceleration_power),
                    }
                }
            }
            _ => {}
        }
        Ok(())
    }

    /// Before the tracker's tick: `setOldPosAndRot` of the interpolating ones (orbs and
    /// bobbers), which the interpolation step then moves.
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_before_tick(&mut self) {
        let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
            return;
        };
        let mut orbs = false;
        for (&id, en) in &mut n.map {
            orbs |= en.kind == Kind::Drop(DropKind::ExperienceOrb);
            en.pre = t
                .get(id)
                .filter(|e| super::entity::interpolation_target(e).is_some())
                .map(|e| (e.position(), [e.yaw(), e.pitch()]));
        }
        // An orb reads the players that tick after it where they were before their tick.
        n.pre.clear();
        if orbs {
            let me = self.own.id;
            n.pre.extend(
                t.iter()
                    .filter(|e| e.is_player() && e.id() != me)
                    .map(|e| (e.id(), e.position())),
            );
        }
    }

    /// The level's players for the orbs (`ClientLevel.players()`: ours first, then the others
    /// in tick order), after the entity ticks, each with its position before them.
    fn orb_players(&mut self) {
        let (Some(n), Some(t)) = (&mut self.nonliving, &self.entities) else {
            return;
        };
        let NonLiving {
            map,
            pre,
            players,
            idents,
            ..
        } = &mut **n;
        players.clear();
        let orb = |en: &Entry| en.kind == Kind::Drop(DropKind::ExperienceOrb);
        if !map.values().any(orb) {
            return;
        }
        let me = self.own.id;
        let p = &self.player;
        let own = OrbPlayer::new(me, p.pos, p.dims.eye_height)
            .with_spectator(p.spectator)
            .with_dead(self.gate.player_dead());
        players.push((own, self.old_pos, t.tick_seq(me).unwrap_or(0)));
        for e in t.iter().filter(|e| e.is_player() && e.id() != me) {
            let id = e.id();
            let now = e.position();
            let before = pre.iter().find(|q| q.0 == id).map_or(now, |q| q.1);
            let eye = e.dimensions().map_or(1.62, |d| d.eye_height);
            let ident = idents.of(id);
            let spectator = t.is_spectator(e);
            idents.seen(
                ident,
                PlayerFacts {
                    uuid: e.uuid(),
                    generation: super::entity::tab_generation(e),
                    spectator,
                    pos: now,
                    eye_height: eye,
                },
            );
            let o = OrbPlayer::new(ident, now, eye)
                .with_spectator(spectator)
                .with_dead(!super::entity::alive(e));
            players.push((o, before, t.tick_seq(id).unwrap_or(u64::MAX)));
        }
        players[1..].sort_by_key(|q| q.2);
        // Followed players that left the level: `isSpectator` through the tab-list object they
        // cached (once the server removed it, its last game mode).
        for en in map.values() {
            let Some(State::Drop(d)) = &en.state else {
                continue;
            };
            let Some(ident) = d.following() else {
                continue;
            };
            if players.iter().any(|q| q.0.id == ident) {
                continue;
            }
            let Some(mut f) = idents.facts(ident) else {
                continue;
            };
            if let Some(g) = t.tab_generation(&f.uuid)
                && (f.generation == 0 || g == f.generation)
            {
                f.spectator = t.tab_game_mode(&f.uuid) == Some(3);
                f.generation = g;
            }
            idents.seen(ident, f);
            let gone = OrbPlayer::new(ident, f.pos, f.eye_height)
                .with_spectator(f.spectator)
                .with_removed(true);
            players.push((gone, f.pos, u64::MAX));
        }
        idents.retain(|k| players.iter().any(|q| q.0.id == k));
    }

    /// One client tick of the simulated entities, after the tracker's tick.
    #[cold]
    #[inline(never)]
    pub(super) fn tick_nonliving(&mut self) {
        // The level's game time while the entities tick (a bobber seeds its bite random with it).
        let game_time = self.game_time();
        if self.nonliving.as_ref().is_none_or(|n| n.map.is_empty()) {
            return;
        }
        self.orb_players();
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return;
        };
        let world = &self.world;
        let me = self.own.id;
        let NonLiving {
            map,
            updates,
            moves,
            discards,
            players,
            seen,
            ..
        } = &mut **n;
        updates.clear();
        moves.clear();
        discards.clear();
        map.retain(|&id, en| {
            let Some(e) = t.get(id) else {
                return false;
            };
            if !t.is_ticking(e) || en.no_gravity || en.no_physics || e.vehicle().is_some() {
                return true;
            }
            let st = en.state.get_or_insert_with(|| build(en.kind, e));
            match st {
                State::Projectile(p) => {
                    // Entity data and packets that came before the first tick.
                    if let Some(g) = en.in_ground.take() {
                        p.set_in_ground(g);
                    }
                    if let Some(d) = en.dangerous.take() {
                        p.set_dangerous(d);
                    }
                    if let Some(a) = en.power.take() {
                        p.set_acceleration_power(a);
                    }
                    // FishingHook.getPlayerOwner: the spawn's owner must be a player.
                    let bobber = p.kind() == ProjectileKind::FishingBobber;
                    if bobber {
                        let owner = e.data();
                        let pos = if owner == me {
                            Some([0.0; 3])
                        } else {
                            t.get(owner)
                                .filter(|o| o.is_player())
                                .map(ghast_entity::Entity::position)
                        };
                        p.set_owner_pos(pos);
                    }
                    take_packets_p(p, e);
                    if bobber {
                        // a bite flag from before the first tick (its jerk's random unseeded in
                        // vanilla: here the seed of a fresh bobber)
                        if let Some(b) = en.biting.take() {
                            p.set_biting(b);
                        }
                        p.set_game_time(game_time);
                        // hookedIn: where the hooked entity is now; gone from the level, it lets go
                        p.set_hooked(en.hook.map(|h| {
                            t.get(h)
                                .and_then(|he| {
                                    he.size().map(|(_, height)| {
                                        HookedEntity::new(he.drawn_position(), height)
                                    })
                                })
                                .unwrap_or(HookedEntity::removed())
                        }));
                    }
                    if let Some((pos, r)) = en.pre.take() {
                        p.set_interpolation_start(pos, r[0], r[1]);
                    }
                    projectile::tick_projectile::<Rules, _>(p, Side::Client, world);
                    if bobber && p.hooked().is_none() {
                        en.hook = None;
                    }
                    if p.removed() {
                        discards.push(id);
                        return false;
                    }
                    updates.push((id, p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()));
                    if PREDICTED {
                        moves.extend(p.moved_last_tick().iter().map(|&m| (id, m)));
                    }
                }
                State::Drop(d) => {
                    // FallingBlockEntity.tick: a falling block of air (the spawn's state id 0)
                    // is discarded.
                    if d.kind() == DropKind::FallingBlock && e.data() == 0 {
                        discards.push(id);
                        return false;
                    }
                    if let Some(f) = en.fuse.take() {
                        d.set_fuse(f);
                    }
                    take_packets_d(d, e);
                    if let Some((pos, r)) = en.pre.take() {
                        d.set_interpolation_start(pos, r[0], r[1]);
                    }
                    seen.clear();
                    if d.kind() == DropKind::ExperienceOrb {
                        // A player that ticks before the orb has moved already.
                        let at = t.tick_seq(id).unwrap_or(u64::MAX);
                        seen.extend(players.iter().map(|&(p, before, seq)| {
                            let mut p = p;
                            if seq > at {
                                p.pos = before;
                            }
                            p
                        }));
                    }
                    drop::tick_drop_near::<Rules, _>(d, Side::Client, world, seen);
                    if d.removed() {
                        discards.push(id);
                        return false;
                    }
                    updates.push((id, d.pos(), d.vel(), [e.yaw(), e.pitch()], d.on_ground()));
                    if PREDICTED {
                        moves.extend(d.moved_last_tick().iter().map(|&m| (id, m)));
                    }
                }
            }
            true
        });
        for &(id, pos, vel, rot, g) in updates.iter() {
            t.client_simulated(id, pos, vel, rot, g);
        }
        // 26.3 (`MoveSimulationType.SERVER_AND_CLIENT`): each move goes into the interpolation
        // in progress at once (`recordMovement`).
        let level = &self.player.level;
        for &(id, m) in moves.iter() {
            t.client_predicted_move(id, m, |e, bb| block_free(world, level, e, bb));
        }
        for &id in discards.iter() {
            t.client_discarded(id);
        }
    }
}

/// The physics state of a freshly spawned entity (`EntityType.create` + `recreateFromPacket`):
/// the tracker's position, motion, rotation and ground flag. Vanilla's client entity random is
/// unseeded (a bobber's bobbing, an orb's hop in lava differ between two clients); here it is
/// seeded with the entity id.
fn build(kind: Kind, e: &ghast_entity::Entity) -> State {
    let (pos, vel) = (e.position(), e.velocity());
    let seed = i64::from(e.id());
    match kind {
        Kind::Projectile(k) => {
            let p = Projectile::new(k, pos, vel)
                .with_rotation(e.yaw(), e.pitch())
                .with_on_ground(e.on_ground())
                .with_random_seed(seed);
            State::Projectile(if k == ProjectileKind::FishingBobber {
                // FishingHook.syncronizedRandom's seed: the UUID's least significant bits
                p.with_uuid_lsb(e.uuid().as_u64_pair().1 as i64)
            } else {
                p
            })
        }
        Kind::Drop(k) => State::Drop(
            Drop::new(k, pos, vel)
                .with_id(e.id())
                .with_on_ground(e.on_ground())
                .with_random_seed(seed),
        ),
    }
}

fn same(a: [f64; 3], b: [f64; 3]) -> bool {
    (0..3).all(|i| a[i].to_bits() == b[i].to_bits())
}

/// What packets changed since the last tick (the tracker holds it): position, motion, rotation,
/// ground flag.
fn take_packets_p(p: &mut Projectile, e: &ghast_entity::Entity) {
    if !same(p.pos(), e.position()) {
        p.set_pos(e.position());
    }
    if !same(p.vel(), e.velocity()) {
        p.set_vel(e.velocity());
    }
    if p.yaw().to_bits() != e.yaw().to_bits() || p.pitch().to_bits() != e.pitch().to_bits() {
        p.set_rotation(e.yaw(), e.pitch());
    }
    if p.on_ground() != e.on_ground() {
        p.set_on_ground(e.on_ground());
    }
}

fn take_packets_d(d: &mut Drop, e: &ghast_entity::Entity) {
    if !same(d.pos(), e.position()) {
        d.set_pos(e.position());
    }
    if !same(d.vel(), e.velocity()) {
        d.set_vel(e.velocity());
    }
    if d.on_ground() != e.on_ground() {
        d.set_on_ground(e.on_ground());
    }
}