ghast-client 0.5.3

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
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
//! 1.12.2: the entities that push the player and that it collides with (the client's view of
//! them, their ticks) and the steps that use them.

use super::*;

impl Sim12 {
    /// The player's tick next to tracked entities: with the boxes of the boats and shulkers
    /// around it. Out of line, so the tick without entities stays the plain one.
    #[cold]
    #[inline(never)]
    pub(super) fn step_near(&mut self, pose: &Pose, controls: Controls, using_item: bool) {
        let input = ghast_physics::TickInput {
            keys: keys(controls),
            yaw: pose.yaw,
            pitch: pose.pitch,
            using_item,
        };
        let (Some(n), Some(t)) = (self.near.as_deref_mut(), self.entities.as_ref()) else {
            return;
        };
        n.solids(t, &self.world, &self.player);
        ghast_physics::v1_12::tick_in(
            &mut self.player,
            &input,
            &self.world,
            &ghast_physics::v1_12::Options::default(),
            &n.solids,
            &mut self.packets,
        );
    }

    /// `World.tickEntities` after the player: the entities interpolate, the boats break lily
    /// pads, then they push the player. In a boat we control, only the entities after the boat
    /// in the entity list (the ones before it ticked before it, [`Sim12::step_ride`]).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_near(&mut self, pose: &mut Pose) {
        let (Some(n), Some(t)) = (self.near.as_deref_mut(), self.entities.as_ref()) else {
            return;
        };
        if !n.watched.is_empty() {
            let ridden = self.ride.as_ref().map(|r| r.id);
            tick_watched_mounts(n, t, &self.world, ridden);
        }
        // The destroyed boats have left their chunks' entity lists.
        n.ghosts.clear();
        if n.list.is_empty() {
            return;
        }
        let seqs = match n.ridden.and_then(|id| n.index.get(&id)) {
            Some(&k) => n.list[k as usize].seq + 1..u64::MAX,
            None => 0..u64::MAX,
        };
        let p = &mut self.player;
        // `updateEntityWithOptionalForce` of the player: a new chunk entity list after its tick.
        if p.added_to_chunk {
            let sec = section_of(p.pos);
            if n.me.is_none_or(|m| m.0 != sec) {
                n.list_seq += 1;
                n.me = Some((sec, n.list_seq));
            }
        }
        // Only a ticking player is in its chunk's entity list, where the pushers find it; the
        // bot riding a vehicle the client does not move or carrying something is not pushed
        // (not modelled). In the boat we control, the entities after the boat push the
        // passenger: its next tick in the boat zeroes that motion, a walking one (the server
        // took it off in between) starts with it.
        let riding_ours = n.ridden.is_some();
        let pushing = self.entity_push
            && p.added_to_chunk
            && !p.removed
            && !t.me().is_some_and(|m| {
                (m.vehicle().is_some() && !riding_ours) || !m.passengers().is_empty()
            });
        n.tick(t, &self.world, &p.bb, pushing, &self.profile_name, seqs);
        let mut changed = false;
        for k in 0..n.pushers.len() {
            let (seq, pusher) = n.pushers[k];
            if let Some(v) = ghast_physics::v1_12::push_by_with(p, &self.world, &pusher) {
                changed = true;
                if !n.watched.is_empty() {
                    watched_mount_pushed(n, seq, v);
                }
            }
        }
        if changed {
            pose.motion = Vec3::new(p.vel[0], p.vel[1], p.vel[2]);
            if let Some(r) = &mut self.rec {
                r.amend_state(&crate::record::state_1_12(p));
            }
        }
        // A boat's tick breaks the lily pads it touches in the client's world.
        for &[x, y, z] in &n.lily_pads {
            self.world
                .set_block_state(x, y, z, ghast_data::v1_12::BlockState::AIR);
        }
    }
}

// ---- 1.12.2: entities pushing the player, entities it collides with --------------------------

/// What a tracked entity does to the 1.12 player on the client.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Class12 {
    /// A living entity: `tickCramming` pushes the player; interpolates over 3 ticks.
    Living,
    /// Another player: pushes like a living entity unless it is a spectator.
    Player,
    /// A boat: pushes from its tick, solid for the player; interpolates over 10 ticks.
    Boat,
    /// A shulker: pushes like a living entity, solid while alive; never interpolates (the
    /// client snaps it to its attached block).
    Shulker,
    /// A minecart (every kind): only blocks a boat the player rides; interpolates over 5 ticks.
    Cart,
    /// A parrot: only blocks a boat the player rides; interpolates over 3 ticks.
    Parrot,
}

impl Class12 {
    /// Only matters for a boat the player rides (not pushing, not solid for the player).
    fn boat_only(self) -> bool {
        matches!(self, Class12::Cart | Class12::Parrot)
    }
}

/// The 1.12 class of a tracked entity, `None` when it neither pushes nor collides nor blocks a
/// boat: bats, armor stands, the ender dragon, items, projectiles, …
fn class_12(e: &ghast_entity::Entity) -> Option<Class12> {
    use ghast_entity::EntityType as T;
    match e.entity_type() {
        T::Player => Some(Class12::Player),
        // Spawn-object type 1.
        T::LegacyObject(1) => Some(Class12::Boat),
        T::LegacyObject(10) => Some(Class12::Cart),
        t @ T::LegacyMob(_) => match ghast_entity::v1_12::info(t)?.name {
            "shulker" => Some(Class12::Shulker),
            "parrot" => Some(Class12::Parrot),
            "bat" | "armor_stand" | "ender_dragon" => None,
            _ => Some(Class12::Living),
        },
        _ => None,
    }
}

/// How far from the player boats break lily pads in the client's world here (vanilla: every
/// ticking boat; the server breaks them as well and sends the change).
const LILY_PAD_REACH: f64 = 16.0;

/// The client side of one entity that pushes the player or is solid for it.
#[derive(Clone, Debug)]
pub(super) struct Client12 {
    pub(super) id: i32,
    /// Order in the client's entity list (spawn order).
    pub(super) seq: u64,
    pub(super) class: Class12,
    /// Client position (`x`, `y`, `z` after the interpolation steps so far; a shulker's is
    /// the server's, see [`Client12::placed`]).
    pub(super) pos: [f64; 3],
    /// Interpolation target and remaining steps (`serverX`… / `bodyTrackingIncrements`, the
    /// boat's own fields).
    pub(super) target: [f64; 3],
    pub(super) steps: u8,
    /// Size (from the tracker at spawn and after each metadata packet).
    pub(super) dims: ghast_data::EntityDimensions,
    /// Position and box as the client has them now (from `pos`).
    pub(super) at: [f64; 3],
    pub(super) bb: ghast_physics::math::Aabb,
    /// A player's profile name from its tab-list entry at spawn (`OtherClientPlayerEntity`
    /// keeps that profile: its scoreboard name for the team rules).
    pub(super) name: Option<Box<str>>,
    /// A boat: the box and world version of its last lily pad scan (a boat that has not moved
    /// in an unchanged world breaks nothing new).
    pub(super) scanned: Option<(ghast_physics::math::Aabb, u32)>,
    /// `onGround` of the client copy: the last move packet's, or where a piston's push left it.
    pub(super) on_ground: bool,
    /// `isInWeb`, the piston budget of the current world tick (the client's own moves).
    pub(super) in_web: bool,
    pub(super) carry: ghast_physics::v1_12::PistonCarry,
    /// The chunk entity list it is filed in (chunk x, section y, chunk z) and its place there
    /// (`World.getEntitiesIn` order).
    pub(super) section: [i32; 3],
    pub(super) list_seq: u64,
    /// A piston moved it since its last tick (a shulker sits back on its block at its tick,
    /// after its own pushes).
    pub(super) pushed: bool,
    /// A shulker with an attached block (entity data 13): its tick puts it back there.
    pub(super) attached: bool,
}

/// A shulker's attached block (1.12 entity data 13, an optional block position) is set.
fn shulker_attached(e: &ghast_entity::Entity) -> bool {
    matches!(
        e.metadata().get(13),
        Some(ghast_entity::MetaValue::OptBlockPos(Some(_)))
    )
}

impl Client12 {
    /// Recomputes [`Client12::at`] / [`Client12::bb`] from the position.
    fn placed(&mut self) {
        if self.class == Class12::Shulker {
            // ShulkerEntity.tick snaps it to its attached block (the server keeps that block
            // under the position it sends): the unit cube there.
            let [x, y, z] = self.pos;
            let (x, y, z) = (x.floor() + 0.5, y.floor(), z.floor() + 0.5);
            self.at = [x, y, z];
            self.bb =
                ghast_physics::math::Aabb::new(x - 0.5, y, z - 0.5, x + 0.5, y + 1.0, z + 0.5);
        } else {
            self.at = self.pos;
            self.bb = self
                .dims
                .bounding_box(self.pos[0], self.pos[1], self.pos[2]);
        }
    }

    /// The boat the client moves: its position and box as the move left them (the box is
    /// not the one its position would give).
    pub(super) fn follow(&mut self, pos: [f64; 3], bb: ghast_physics::math::Aabb) {
        self.pos = pos;
        self.at = pos;
        self.bb = bb;
    }

    /// `updateTrackedPositionAndAngles` with the client's step count: 10 for boats, 3 else.
    /// A shulker ignores it; the client snaps it to its attached block, which the server keeps
    /// under the position it sends (so it follows that position here).
    fn interpolate_to(&mut self, target: [f64; 3]) {
        match self.class {
            Class12::Shulker => {
                self.pos = target;
                self.target = target;
                self.placed();
            }
            Class12::Boat => {
                self.target = target;
                self.steps = 10;
            }
            Class12::Living | Class12::Player | Class12::Parrot => {
                self.target = target;
                self.steps = 3;
            }
            // AbstractMinecartEntity.updateTrackedPositionAndAngles: the packet's 3 steps + 2.
            Class12::Cart => {
                self.target = target;
                self.steps = 5;
            }
        }
    }

    /// One interpolation step of the entity's client tick.
    #[inline]
    fn step(&mut self) {
        let pushed = std::mem::take(&mut self.pushed);
        if (pushed && self.class == Class12::Shulker && self.attached)
            || (self.class == Class12::Cart && self.steps == 0)
        {
            // ShulkerEntity.tick: back on its attached block; a minecart's client tick sets
            // its position (the box follows it) when it does not interpolate.
            self.placed();
        }
        if self.steps > 0 {
            let n = f64::from(self.steps);
            for k in 0..3 {
                self.pos[k] += (self.target[k] - self.pos[k]) / n;
            }
            self.steps -= 1;
            self.placed();
        }
    }
}

/// `true` when box `b` is farther than `r` from the box `p`.
#[inline]
fn far(b: &ghast_physics::math::Aabb, p: &ghast_physics::math::Aabb, r: [f64; 3]) -> bool {
    b.max_x < p.min_x - r[0]
        || b.min_x > p.max_x + r[0]
        || b.max_y < p.min_y - r[1]
        || b.min_y > p.max_y + r[1]
        || b.max_z < p.min_z - r[2]
        || b.min_z > p.max_z + r[2]
}

/// 1.12 entities around the player as the client moves them: positions after the client's
/// interpolation (the tracker keeps the server's), pushes after the player's tick
/// (`World.tickEntities`: entities spawned after the player tick after it) and the boxes it
/// collides with (`World.doesBoxCollide`). Riding (the bot or the other entity) is not
/// modelled: such entities neither push nor collide here.
#[derive(Debug, Default)]
pub(crate) struct Near12 {
    /// Every tracked entity that pushes or collides (dense; `index` finds one by id).
    pub(super) list: Vec<Client12>,
    pub(super) index: std::collections::HashMap<i32, u32>,
    pub(super) seq: u64,
    /// Boats in `list`.
    pub(super) boats: usize,
    /// Entries in `list` that only matter for a ridden boat ([`Class12::boat_only`]).
    pub(super) boat_only: usize,
    /// Boats and minecarts destroyed since the player's last tick: vanilla's world keeps them in
    /// their chunk's entity list until its entity loop reaches them, after the player moved.
    pub(super) ghosts: Vec<Ghost12>,
    /// The boat the player rides and the client moves ([`Sim12`]'s): its entry follows the
    /// client's boat, the server's moves of it are ignored (`onEntityPosition` /
    /// `onEntityUpdate` skip an entity the client controls) and it is left out of the boxes.
    pub(in crate::sim) ridden: Option<i32>,
    /// Scratch: the boxes the ridden boat collides with.
    pub(super) boat_solids: Vec<ghast_physics::math::Aabb>,
    /// Scratch: this tick's solid boxes, pushers and broken lily pads.
    pub(super) solids: Vec<ghast_physics::math::Aabb>,
    pub(super) pushers: Vec<(u64, ghast_physics::v1_12::Pusher)>,
    pub(super) lily_pads: Vec<[i32; 3]>,
    /// Bumped by every block packet (lily pads may have appeared).
    pub(in crate::sim) world_version: u32,
    /// The teams' collision rules (`teams` packets).
    pub(in crate::sim) teams: super::teams::Teams,
    /// Insertions into chunk entity lists so far (orders the lists).
    pub(super) list_seq: u64,
    /// The local player's chunk entity list and place in it (`None` before its first tick
    /// in a loaded column).
    pub(in crate::sim) me: Option<([i32; 3], u64)>,
    /// The living mounts the client watches, from their spawn packets on (see
    /// [`ghast_physics::v1_12::Mount::watched`]): what the player boards.
    pub(super) watched: Vec<(i32, ghast_physics::v1_12::Mount)>,
}

/// Where an entity of the piston phase is kept: the near-entity model's list, or only the
/// tracker (by id).
#[derive(Clone, Copy, Debug)]
pub(super) enum Kept {
    Near(usize),
    Extra(i32),
}

/// The chunk entity list of a position: chunk x, section y (0..16), chunk z.
pub(super) fn section_of(p: [f64; 3]) -> [i32; 3] {
    let f = |v: f64| (v.floor() as i32) >> 4;
    [f(p[0]), f(p[1]).clamp(0, 15), f(p[2])]
}

/// A destroyed boat or minecart still in its chunk's entity list (see [`Near12::ghosts`]).
#[derive(Clone, Copy, Debug)]
pub(super) struct Ghost12 {
    /// Its place in the entity list (it leaves the chunk when the loop reaches it).
    pub(super) seq: u64,
    pub(super) bb: ghast_physics::math::Aabb,
    /// A minecart (blocks a ridden boat only), else a boat.
    pub(super) cart: bool,
}

/// The first VarInt of a body (the entity id of spawn and move packets).
fn first_varint(body: &[u8]) -> Option<i32> {
    let mut v: u32 = 0;
    for (k, &b) in body.iter().take(5).enumerate() {
        v |= u32::from(b & 0x7f) << (7 * k);
        if b & 0x80 == 0 {
            return Some(v as i32);
        }
    }
    None
}

impl Near12 {
    /// Nothing that pushes the walking player or is solid for it.
    pub(super) fn idle(&self) -> bool {
        self.list.len() == self.boat_only && self.ghosts.iter().all(|g| g.cart)
    }

    /// Every entity in the model is one of `ids` (a recording's vehicles: representable).
    pub(super) fn only(&self, ids: &[i32]) -> bool {
        self.ghosts.is_empty() && self.list.iter().all(|c| ids.contains(&c.id))
    }

    pub(super) fn get_mut(&mut self, id: i32) -> Option<&mut Client12> {
        let &k = self.index.get(&id)?;
        self.list.get_mut(k as usize)
    }

    /// Follows one entity packet the tracker has just applied.
    pub(super) fn packet(&mut self, t: &ghast_entity::v1_12::Tracker, raw: &RawPacket) {
        use ghast_protocol::v1_12_2::play::clientbound::id;
        match raw.id {
            id::LOGIN | id::RESPAWN => {
                self.watched.clear();
                self.list.clear();
                self.index.clear();
                self.boats = 0;
                self.boat_only = 0;
                self.ghosts.clear();
                self.ridden = None;
                self.me = None;
                if raw.id == id::LOGIN {
                    // A new play phase: a new client scoreboard.
                    self.teams.clear();
                }
            }
            id::SPAWN_ENTITY | id::SPAWN_ENTITY_LIVING | id::NAMED_ENTITY_SPAWN => {
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                // ClientWorld.addEntity: an entity with the same id leaves the world first.
                self.remove(eid);
                if let Some(e) = t.get(eid)
                    && let Some(class) = class_12(e)
                    && let Some(dims) = e.dimensions()
                {
                    self.seq += 1;
                    self.boats += usize::from(class == Class12::Boat);
                    self.boat_only += usize::from(class.boat_only());
                    let pos = e.position();
                    let mut c = Client12 {
                        id: eid,
                        seq: self.seq,
                        class,
                        pos,
                        target: pos,
                        steps: 0,
                        dims,
                        at: pos,
                        bb: ghast_physics::math::Aabb::FULL,
                        name: t.player_name(eid).map(Into::into),
                        scanned: None,
                        on_ground: false,
                        in_web: false,
                        carry: Default::default(),
                        // `World.spawnEntity`: into its chunk's list at once.
                        section: section_of(pos),
                        list_seq: {
                            self.list_seq += 1;
                            self.list_seq
                        },
                        pushed: false,
                        attached: class == Class12::Shulker && shulker_attached(e),
                    };
                    c.placed();
                    self.index.insert(eid, self.list.len() as u32);
                    self.list.push(c);
                }
            }
            id::ENTITY_TELEPORT => {
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                if self.ridden == Some(eid) {
                    return;
                }
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid)) {
                    c.on_ground = e.on_ground();
                    let d = e.position();
                    // onEntityPosition: a teleport within 1/32 (1/64 vertically) of the client
                    // position keeps it and ends the interpolation.
                    #[allow(clippy::neg_cmp_op_on_partial_ord)]
                    let tiny = !((c.pos[0] - d[0]).abs() >= 0.03125)
                        && !((c.pos[1] - d[1]).abs() >= 0.015625)
                        && !((c.pos[2] - d[2]).abs() >= 0.03125);
                    if tiny && c.class != Class12::Shulker {
                        c.target = c.pos;
                        c.steps = 0;
                    } else {
                        c.interpolate_to(d);
                    }
                }
            }
            id::REL_ENTITY_MOVE | id::ENTITY_MOVE_LOOK | id::ENTITY_LOOK | id::ENTITY => {
                // onEntityUpdate: towards the tracked position (1/4096 grid on every axis).
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                if self.ridden == Some(eid) {
                    return;
                }
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid)) {
                    c.on_ground = e.on_ground();
                    c.interpolate_to(e.position());
                }
            }
            id::ENTITY_METADATA => {
                // Size variants (babies, slime sizes) follow the metadata.
                let Some(eid) = first_varint(&raw.body) else {
                    return;
                };
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid))
                    && c.class == Class12::Shulker
                {
                    c.attached = shulker_attached(e);
                }
                if let (Some(c), Some(e)) = (self.get_mut(eid), t.get(eid))
                    && let Some(d) = e.dimensions()
                    && d != c.dims
                {
                    c.dims = d;
                    c.placed();
                }
            }
            id::ENTITY_DESTROY => {
                let mut r = ghast_protocol::Reader::new(&raw.body);
                let Ok(n) = r.read_varint() else { return };
                for _ in 0..n.max(0) {
                    let Ok(eid) = r.read_varint() else { return };
                    self.remove(eid);
                }
            }
            _ => {}
        }
    }

    fn remove(&mut self, eid: i32) {
        let Some(k) = self.index.remove(&eid) else {
            return;
        };
        let c = self.list.swap_remove(k as usize);
        if let Some(moved) = self.list.get(k as usize) {
            self.index.insert(moved.id, k);
        }
        if c.class == Class12::Boat {
            self.boats -= 1;
        }
        self.boat_only -= usize::from(c.class.boat_only());
        if matches!(c.class, Class12::Boat | Class12::Cart) {
            self.ghosts.push(Ghost12 {
                seq: c.seq,
                bb: c.bb,
                cart: c.class == Class12::Cart,
            });
        }
    }

    /// The entity takes part (its column is loaded, it rides nothing and carries nothing).
    pub(super) fn present(
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        c: &Client12,
    ) -> bool {
        let Some(e) = t.get(c.id) else { return false };
        // A vehicle carrying others still pushes and is solid (the bot is not in it: its own
        // vehicle is left out by the callers); a rider sits where its vehicle puts it (players
        // in boats, see `seat_riders`), others are not modelled.
        e.vehicle().is_none()
            && world.is_column_loaded((c.at[0].floor() as i32) >> 4, (c.at[2].floor() as i32) >> 4)
    }

    /// `World.hasEntityIn(box)` over these entities: one of them (not riding, not a spectator
    /// player) overlaps `cube` at its client position (`Box.intersects`).
    pub(super) fn blocks_building(
        &self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        cube: &ghast_physics::math::Aabb,
    ) -> bool {
        self.list.iter().any(|c| {
            !c.class.boat_only()
                && crate::sim::predict::boxes_intersect(&c.bb, cube)
                && Self::present(t, world, c)
                && !(c.class == Class12::Player
                    && t.get(c.id)
                        .is_some_and(|e| t.tab_game_mode(&e.uuid()) == Some(3)))
        })
    }

    /// This tick's boxes the player collides with: boats and live shulkers within reach of any
    /// move of the tick, and the boats destroyed since the last tick. In the boat the client
    /// moves ([`Near12::ridden`], the passenger's tick at the boat's place in the entity list):
    /// the same without that boat, and only the destroyed boats after it in the list.
    pub(super) fn solids(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        p: &ghast_physics::v1_12::PlayerState,
    ) {
        self.solids.clear();
        let own = self
            .ridden
            .and_then(|id| self.index.get(&id).map(|&k| (id, k)));
        let after = own.map_or(0, |(_, k)| self.list[k as usize].seq);
        let riding = own.is_none() && t.me().is_some_and(|m| m.vehicle().is_some());
        let reach = |v: f64| v.abs() + 3.0;
        let r = [reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2])];
        for c in &self.list {
            if !matches!(c.class, Class12::Boat | Class12::Shulker)
                || own.is_some_and(|(id, _)| id == c.id)
                || far(&c.bb, &p.bb, r)
                || riding
                || !Self::present(t, world, c)
            {
                continue;
            }
            // ShulkerEntity.getBox: only while alive.
            if c.class == Class12::Shulker
                && !t
                    .get(c.id)
                    .and_then(ghast_entity::v1_12::health)
                    .is_none_or(|h| h > 0.0)
            {
                continue;
            }
            self.solids.push(c.bb);
        }
        self.solids.extend(
            self.ghosts
                .iter()
                .filter(|g| !g.cart && g.seq > after)
                .map(|g| g.bb),
        );
    }

    /// The boxes the ridden boat collides with when it ticks (`World.doesBoxCollide` for the
    /// boat, `v1_12::blocks_boat`): the entities within reach of its move (`bb` grown by
    /// `reach`) whose column is loaded, at their client positions (the ones before the boat in
    /// the entity list have stepped this tick), and the destroyed boats and minecarts after it
    /// in the list. Left out: the boat itself, entities riding it with the player, spectator
    /// players, and entities that ride something (their seat is not followed here).
    pub(super) fn boat_solids(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        bb: &ghast_physics::math::Aabb,
        reach: [f64; 3],
    ) {
        self.boat_solids.clear();
        let Some(own) = self.ridden else { return };
        let after = self
            .index
            .get(&own)
            .map_or(0, |&k| self.list[k as usize].seq);
        for c in &self.list {
            if c.id == own || far(&c.bb, bb, reach) {
                continue;
            }
            let Some(e) = t.get(c.id) else { continue };
            if e.vehicle().is_some()
                || !world
                    .is_column_loaded((c.at[0].floor() as i32) >> 4, (c.at[2].floor() as i32) >> 4)
            {
                continue;
            }
            let alive = || ghast_entity::v1_12::health(e).is_none_or(|h| h > 0.0);
            let blocks = match c.class {
                Class12::Boat => true,
                Class12::Cart => true,
                Class12::Parrot => true,
                Class12::Shulker => alive(),
                Class12::Player => {
                    t.tab_game_mode(&e.uuid()) != Some(3)
                        && alive()
                        && !ghast_physics::v1_12::entity_climbing(world, c.at, c.bb.min_y)
                }
                Class12::Living => {
                    let name = ghast_entity::v1_12::info(e.entity_type()).map_or("", |i| i.name);
                    ghast_physics::v1_12::blocks_boat(
                        name,
                        true,
                        alive(),
                        ghast_physics::v1_12::entity_climbing(world, c.at, c.bb.min_y),
                        !e.passengers().is_empty(),
                    )
                }
            };
            if blocks {
                self.boat_solids.push(c.bb);
            }
        }
        self.boat_solids.extend(
            self.ghosts
                .iter()
                .filter(|g| g.seq > after && !far(&g.bb, bb, reach))
                .map(|g| g.bb),
        );
    }

    /// The entities' client ticks after the player's: one interpolation step each, the lily
    /// pads the boats near the player break (`lily_pads_broken_by_boat`; farther ones are left
    /// to the server), and the entities whose tick pushes the player, in tick order, into
    /// `pushers` (when `pushing`).
    pub(super) fn tick(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        world: &ghast_world::v1_12::World,
        p: &ghast_physics::math::Aabb,
        pushing: bool,
        profile_name: &str,
        seqs: std::ops::Range<u64>,
    ) {
        use ghast_physics::v1_12::{PushKind, Pusher};
        self.pushers.clear();
        self.lily_pads.clear();
        let version = self.world_version;
        let ridden = self.ridden;
        let mut list_seq = self.list_seq;
        for c in &mut self.list {
            // The boat the client moves ticks with the player (the sim's).
            if !seqs.contains(&c.seq) || ridden == Some(c.id) {
                continue;
            }
            // A shulker a piston moved pushes from there before it sits back.
            let pre = (c.pushed && c.class == Class12::Shulker).then_some((c.at, c.bb));
            c.step();
            // `updateEntityWithOptionalForce`: a new chunk entity list after its tick.
            let sec = section_of(c.at);
            if sec != c.section {
                list_seq += 1;
                c.section = sec;
                c.list_seq = list_seq;
            }
            if c.class == Class12::Boat
                && c.scanned != Some((c.bb, version))
                && !far(&c.bb, p, [LILY_PAD_REACH; 3])
                && Self::present(t, world, c)
            {
                ghast_physics::v1_12::lily_pads_broken_by_boat(world, &c.bb, &mut self.lily_pads);
                c.scanned = Some((c.bb, version));
            }
            // Boats reach 0.2 farther; nothing else can touch the player.
            if !pushing
                || c.class.boat_only()
                || far(&pre.map_or(c.bb, |x| x.1), p, [0.25; 3])
                || !Self::present(t, world, c)
            {
                continue;
            }
            let Some(e) = t.get(c.id) else { continue };
            // A spectator player has noClip (set in its tick) and pushes nothing.
            if c.class == Class12::Player && t.tab_game_mode(&e.uuid()) == Some(3) {
                continue;
            }
            // EntityPredicate.method_13025: the pusher's and the player's team rules.
            if self.teams.any_rule() {
                let mut buf = [0u8; 36];
                let name: &str = match &c.name {
                    Some(n) => n,
                    None => e.uuid().hyphenated().encode_lower(&mut buf),
                };
                if !self.teams.may_push(name, profile_name) {
                    continue;
                }
            }
            let kind = if c.class == Class12::Boat {
                PushKind::Boat
            } else {
                PushKind::Living
            };
            let (at, bb) = pre.unwrap_or((c.at, c.bb));
            // Room after each entry for its passengers (they tick right after it).
            self.pushers.push((c.seq * 4, Pusher::new(at, bb, kind)));
        }
        self.list_seq = list_seq;
        if self.boats > 0 {
            self.seat_riders(t, p, pushing, profile_name, &seqs);
        }
        self.pushers.sort_unstable_by_key(|x| x.0);
    }

    /// `updatePassenger` of the ticked boats: their player passengers push the player (when it
    /// is not in the same boat) from where they were after their own interpolation step, then
    /// sit in their seats (`BoatEntity.updatePassengerPosition`, the boat's yaw as the server
    /// last sent it). Riders of other vehicles are not modelled.
    #[cold]
    #[inline(never)]
    fn seat_riders(
        &mut self,
        t: &ghast_entity::v1_12::Tracker,
        p: &ghast_physics::math::Aabb,
        pushing: bool,
        profile_name: &str,
        seqs: &std::ops::Range<u64>,
    ) {
        use ghast_physics::v1_12::{PushKind, Pusher};
        let me = t.self_id();
        for k in 0..self.list.len() {
            let c = &self.list[k];
            if c.class != Class12::Boat || !seqs.contains(&c.seq) || self.ridden == Some(c.id) {
                continue;
            }
            let Some(v) = t.get(c.id) else { continue };
            let n = v.passengers().len();
            if n == 0 || v.vehicle().is_some() {
                continue;
            }
            let ours = me.is_some_and(|me| v.passengers().contains(&me));
            let (vseq, vpos, vyaw) = (c.seq, c.at, v.yaw());
            for (i, &pid) in v.passengers().iter().enumerate() {
                let Some(&j) = self.index.get(&pid) else {
                    continue;
                };
                let r = &self.list[j as usize];
                if r.class != Class12::Player {
                    continue;
                }
                if pushing
                    && !ours
                    && !far(&r.bb, p, [0.25; 3])
                    && t.get(pid)
                        .is_some_and(|e| t.tab_game_mode(&e.uuid()) != Some(3))
                {
                    let allowed = !self.teams.any_rule() || {
                        let mut buf = [0u8; 36];
                        let name: &str = match &r.name {
                            Some(n) => n,
                            None => t
                                .get(pid)
                                .map_or("", |e| e.uuid().hyphenated().encode_lower(&mut buf)),
                        };
                        self.teams.may_push(name, profile_name)
                    };
                    if allowed {
                        let pusher = Pusher::new(r.at, r.bb, PushKind::Living);
                        self.pushers
                            .push((vseq * 4 + 1 + (i as u64).min(2), pusher));
                    }
                }
                // The seat: 0.2 forward / 0.6 back of two along the boat's yaw, the player's
                // -0.35 below the boat's -0.1.
                let g = (-0.1f64 + -0.35f64) as f32;
                let f: f32 = if n > 1 {
                    if i == 0 { 0.2 } else { -0.6 }
                } else {
                    0.0
                };
                let a = -vyaw * (std::f64::consts::PI / 180.0) as f32
                    - std::f64::consts::FRAC_PI_2 as f32;
                let (cs, sn) = (ghast_physics::math::cos(a), ghast_physics::math::sin(a));
                let fx = f64::from(f);
                let pos = [
                    vpos[0] + (fx * f64::from(cs) + 0.0 * f64::from(sn)),
                    vpos[1] + f64::from(g),
                    vpos[2] + (0.0 * f64::from(cs) - fx * f64::from(sn)),
                ];
                let r = &mut self.list[j as usize];
                r.pos = pos;
                r.placed();
            }
        }
    }
}

impl Sim12 {
    /// Test hook: record the session into `path` (written when the sim is dropped). Gated like
    /// the engine replay modules that use it.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_record(&mut self, path: &std::path::Path) {
        self.rec = Some(crate::record::Recorder::create(path).expect("recording file"));
    }

    /// Test hook: sets one block.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_set_block(
        &mut self,
        x: i32,
        y: i32,
        z: i32,
        st: ghast_data::v1_12::BlockState,
    ) {
        self.world.set_block_state(x, y, z, st);
    }

    /// Test hook: the player state (from an oracle record).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_set_player(&mut self, p: ghast_physics::v1_12::PlayerState) {
        self.player = p;
        self.piston_uncertain_at = None;
        // The oracle's player is in its chunk's entity list from the setup on.
        if let Some(n) = self.near.as_deref_mut()
            && p.added_to_chunk
        {
            n.list_seq += 1;
            n.me = Some((section_of(p.pos), n.list_seq));
        }
    }

    /// Test hook: the client position and box of a tracked entity that pushes or collides.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_near_box(&self, id: i32) -> Option<([f64; 3], ghast_physics::math::Aabb)> {
        let n = self.near.as_deref()?;
        let &k = n.index.get(&id)?;
        let c = &n.list[k as usize];
        Some((c.at, c.bb))
    }

    /// Test hook: the chunk store.
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_world(&self) -> &ghast_world::v1_12::World {
        &self.world
    }

    /// Test hook: the player state.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_player(&self) -> &ghast_physics::v1_12::PlayerState {
        &self.player
    }

    /// Test hook: the player's scoreboard name (team rules).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_set_profile_name(&mut self, name: &str) {
        self.profile_name = name.into();
    }

    /// Test hook: our flags and rockets are read from now on (as after a jump press in the air
    /// with an elytra on).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_watch_glide(&mut self) {
        self.glide.watch = true;
        self.glide.own_id = 1;
    }

    /// Test hook: the bits of our shared flags byte movement reads.
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    pub(crate) fn test_shared_flags_1_12(&self) -> u8 {
        self.ext.shared_flags(&self.player)
    }
}