ghast-client 0.5.4

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
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
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
//! The world and movement of the modern versions (26.1+): the chunk store of `ghast-world` and
//! the modern physics (`ghast_physics::modern`, bit-exact against each version's client),
//! written once and mounted per version by `sim/v26_x.rs` (the parent module, `super`), which
//! supplies the version's crates (`data`, `world`, `entity`, `inv`, `proto`, `pick`), its
//! physics rule set (`Rules`) and its tables. Entity type ids are resolved by name from the
//! version's data set ([`EntityIds`]).

use super::Rules;
use super::data::BlockState;
use ghast_physics::modern::{self, AttributeKind, ModifierId};
use ghast_protocol::{BlockPos, RawPacket};

use crate::common::{Abilities, AttributeUpdate, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};
use crate::sim::shared::aabb;
use crate::sim::*;

// The topic files below are children of this module, so they are mounted once per modern
// version with it; their `super::<row item>` paths reach the row through these imports.
use super::{
    GAME, SLEEP_ON_BED_ONLY, TEAM_LAYOUT, data, effects, entity, exact_dig, inv,
    inv_trident_strength, pick, pistons, proto,
};

mod blocks;
mod elytra;
mod entities;
mod fishing;
mod hooks;
mod nonliving;
mod piston;
mod records;
#[cfg(test)]
mod tests;
mod vehicles;

/// A modern version's chunk store and vanilla-exact modern physics.
pub(crate) struct ModernSim {
    world: super::world::World,
    player: modern::PlayerState,
    packets: ghast_physics::Packets,
    /// 26.3 (`Rules::SEND_AFTER_ENTITIES`): this tick's player tick ran among moving blocks,
    /// so its movement packets are built after the block-entity phase.
    piston_step: bool,
    /// Those packets are built and wait for [`Sim::send_changes`].
    send_due: bool,
    /// Block changes since the last drain (position, state id), when collected.
    updates: BlockUpdates,
    /// `mining_efficiency`, `block_break_speed`, `submerged_mining_speed` (digging).
    mining: [modern::Attribute; 3],
    /// Conduit power amplifier (digging).
    conduit_power: Option<i32>,
    /// `block_interaction_range`, `entity_interaction_range` (the crosshair).
    ranges: [modern::Attribute; 2],
    /// `Entity.xo/yo/zo`: the position at the start of the last tick (the pick's eye lerps
    /// from it).
    old_pos: [f64; 3],
    /// The entity tracker, when entities are tracked.
    entities: Option<super::entity::Tracker>,
    /// Join / respawn packets, replayed into a tracker started mid-session.
    session: SessionPackets,
    /// The level-load gate (`player_loaded`), oracle-proven on `joins.jsonl.gz`.
    gate: modern::LoadGate,
    /// `use_effects` of the item in use (see [`ModernSim::use_effects`]).
    use_effects: Option<(bool, f32)>,
    /// Movement state beyond `player`: gliding, attached rockets (and later mechanics).
    ext: modern::PlayerExt,
    /// What the client knows about entities that drive `ext` (own id, rockets).
    own: OwnEntity,
    /// `Level.rainLevel` from the weather game events (1 START_RAINING, 2 STOP_RAINING,
    /// 7 RAIN_LEVEL_CHANGE); the level rains above 0.2.
    rain_level: f32,
    /// The extension state can act this tick (gliding, a glider to start a glide, rockets, the
    /// riptide spin or counter, a launch made before the tick): set wherever `ext` gains such a
    /// state, recomputed after each extended tick. One flag keeps the plain tick's path lean.
    ext_active: bool,
    /// Riptide strength of the trident in the main / off hand (`held_use_inputs`).
    riptide: [f32; 2],
    /// With entity tracking: the boxes the player collides with this tick and the entities
    /// that push it after its tick (buffers kept between ticks).
    around: Around,
    /// With entity tracking: the scoreboard teams' collision rules (`set_player_team`).
    teams: Option<Box<crate::sim::teams::Teams>>,
    /// The player's scoreboard name (its team membership).
    profile_name: Box<str>,
    /// The vehicle the player rides and controls (`set_passengers` naming us).
    riding: Option<Riding>,
    /// Without entity tracking: a tracker of the vehicles only (boats and minecarts the player
    /// may ride), fed their spawn, move and passenger packets.
    vehicles: Option<Box<super::entity::Tracker>>,
    /// The boat the player left: it stays where the player drove it (the client moved it; the
    /// server sends no move for it) until the server moves it.
    parked: Option<Parked>,
    /// The mount the player controlled and left (parked): the client keeps ticking it (it slows
    /// down and is pushed off the player) and a boarding while it is parked rides it on.
    left_mount: Option<Box<modern::Mount>>,
    /// The answer to a server packet that goes out at once (`move_vehicle`).
    reply: Option<Outbound>,
    /// Grim compatibility (not vanilla, off by default): send the position on a tick whose
    /// feet height changed although the move stayed under the resend threshold.
    force_step: ForceStepPosition,
    /// Movement recording ([`crate::Client::record`]).
    rec: Option<Box<crate::record::Recorder>>,
    /// 26.2+: a movement attribute of `ext` (friction / air drag modifier, bounciness) is not
    /// at its default, so the extended tick runs (the plain tick reads the defaults).
    movement_attributes: bool,
    /// The packets the sim reads changed (boats appeared / are gone): rebuild the filter.
    filter_dirty: bool,
    /// Entities push the player (vanilla; off only by the client's non-vanilla opt-in).
    entity_push: bool,
    /// The level's `BlockStatePredictionHandler`: blocks broken on the client and the server's
    /// state of them until its `block_changed_ack`.
    predictions: crate::sim::predict::Sequenced<BlockState>,
    /// An ack moved the player back ([`Sim::take_snap`]).
    snapped: bool,
    /// The shared flags byte (entity data index 0) the server last sent for our entity.
    server_flags: Option<u8>,
    /// The absorption the server last sent for our entity (player entity data; 0 before any).
    absorption: f32,
    /// `absorption` changed since the engine last took it.
    absorption_dirty: bool,
    /// Our sleeping position changed in the entity data (`take_sleep`).
    sleep: Option<Option<ghast_protocol::BlockPos>>,
    /// Blocks pistons move (the client runs the piston itself on a block-event packet).
    pistons: super::pistons::Pistons,
    /// World changes of the pistons, applied right away (kept to reuse the allocation).
    piston_edits: super::pistons::Edits,
    /// An unmodelled piston condition in the last tick (its packets, its step or its block
    /// entities): the player's `age` when it was raised ([`WorldView::piston_uncertain`]).
    piston_uncertain_at: Option<i32>,
    /// The client level's game time (`update_time`, one more per tick: the piston move limit),
    /// kept as `(time, age)`: the game time of the block-entity phase of the tick in which the
    /// player's `age` becomes `age + 1` (it counts on with the player's ticks).
    piston_clock: (i64, i32),
    /// What the pistons' moves of other entities carry between ticks, by entity id.
    piston_carry: Vec<(i32, super::pistons::PistonCarry)>,
    /// With entity tracking: the player's entity section and the tracker's entry clock
    /// ([`super::entity::Tracker::next_tick_seq`]) when it entered it (a section lists its
    /// entities in the order they entered it).
    /// `None` until the first tick in a level (the player enters it first).
    player_section: Option<((i32, u64), (u64, u64))>,
    /// Entities a piston moved into another entity section: the section and when (entry
    /// clock, then a counter): they come last in it.
    section_moves: Vec<SectionMove>,
    /// The counter of [`ModernSim::section_moves`] entries.
    section_moves_n: u64,
    /// With entity tracking and [`crate::Interests::ENTITY_PHYSICS`]: the client-side physics
    /// of the tracked non-living entities (`None`: off, nothing runs for them).
    nonliving: Option<Box<nonliving::NonLiving>>,
    /// The bot's own fishing bobber ([`crate::fishing`]).
    fishing: crate::fishing::Fishing,
}

/// An entity a piston moved into another entity section: its id, the section
/// ([`section_order`]) and when (entry clock, counter).
type SectionMove = (i32, (i32, u64), (u64, u64));

/// A vehicle the player rides.
#[derive(Debug)]
enum Riding {
    /// A boat or raft: client-authoritative (`modern::tick_boat`).
    Boat { id: i32, boat: Box<modern::Boat> },
    /// A minecart: the server moves it, the player sits on it (`modern::tick_passenger`).
    Seat { id: i32 },
    /// A living mount (a horse): client-authoritative while the player controls it, else the
    /// server moves it (`modern::tick_mount` either way).
    Mount {
        id: i32,
        mount: Box<modern::Mount>,
        /// The tracker's position of it last tick: a change is a server move.
        tracked: Option<[f64; 3]>,
    },
}

impl Riding {
    fn id(&self) -> i32 {
        match self {
            Riding::Boat { id, .. } | Riding::Seat { id } | Riding::Mount { id, .. } => *id,
        }
    }
}

/// A boat or a mount the player drove and left.
#[derive(Debug, Clone, Copy)]
struct Parked {
    id: i32,
    pos: [f64; 3],
    bb: [f64; 6],
    /// The tracker's position of it when the player left (a different one: the server moved it).
    tracked: Option<[f64; 3]>,
    /// A living mount (it pushes like a mob and does not collide), not a boat.
    living: bool,
}

impl Parked {
    /// The parked position and box when `e` is the parked boat and the server has not moved it.
    fn of(this: Option<&Parked>, e: &ghast_entity::Entity) -> Option<([f64; 3], [f64; 6])> {
        let p = this?;
        (p.id == e.id() && p.tracked == Some(e.position())).then_some((p.pos, p.bb))
    }
}

/// The vehicle kinds the player can ride with modelled physics.
fn vehicle_kind(name: &str) -> Option<VehicleKind> {
    if let Some(k) = modern::BoatKind::from_entity_name(name) {
        Some(VehicleKind::Boat(k))
    } else if let Some(k) = modern::MountKind::from_entity_name(name) {
        Some(VehicleKind::Mount(k))
    } else if name.ends_with("minecart") {
        Some(VehicleKind::Cart)
    } else {
        None
    }
}

#[derive(Debug, Clone, Copy)]
enum VehicleKind {
    Boat(modern::BoatKind),
    Mount(modern::MountKind),
    Cart,
}

/// Entity collision and pushing around the player (only with entity tracking).
#[derive(Debug, Default)]
struct Around {
    /// Collidable entity boxes (`canBeCollidedWith`), in `getEntities` section order.
    boxes: Vec<ghast_physics::math::Aabb>,
    /// Pushers of this tick: order key, push.
    /// Tick order, the pusher, and the id of a mount whose client motion takes the other half
    /// of the push (`None`: no such entity).
    pushers: Vec<(i64, modern::Pusher, Option<i32>)>,
    /// The player ticked since the last entity tick (pushes come after its tick).
    player_ticked: bool,
    /// The entities near the player that tick before it in the client's tick list (ticked
    /// early: their boxes are post-tick, their pushes come before the player's tick).
    pre: Vec<i32>,
}

/// Per entity type: the player collides with it (the version's `collides`).
const COLLIDES: u8 = 1;
/// Per entity type: its tick pushes the player like a living entity.
const PUSH_LIVING: u8 = 2;
/// Per entity type: its tick pushes the player like a boat.
const PUSH_BOAT: u8 = 4;

/// [`COLLIDES`] / [`PUSH_LIVING`] / [`PUSH_BOAT`] by entity type id.
fn entity_bits(e: &ghast_entity::Entity) -> u8 {
    static BITS: std::sync::OnceLock<Box<[u8]>> = std::sync::OnceLock::new();
    let bits = BITS.get_or_init(|| {
        let types = super::data::entity_types();
        let mut v = vec![
            0u8;
            types
                .iter()
                .map(|t| usize::from(t.id) + 1)
                .max()
                .unwrap_or(0)
        ];
        for t in types {
            let mut b = 0;
            if super::collides(t.name) {
                b |= COLLIDES;
            }
            match super::push_kind(t.name, t.is_living()) {
                Some(modern::PushKind::Living) => b |= PUSH_LIVING,
                Some(modern::PushKind::Boat) => b |= PUSH_BOAT,
                _ => {}
            }
            v[usize::from(t.id)] = b;
        }
        v.into_boxed_slice()
    });
    super::entity::entity_type(e).map_or(0, |t| bits.get(usize::from(t.id)).copied().unwrap_or(0))
}

/// The boxes the player may collide with this tick (`canBeCollidedWith`: boats, rafts, living
/// shulkers; its own vehicle excluded), and while riding the boxes its boat collides with
/// (`canVehicleCollide`: those and every living entity, not the player), near enough for any
/// move of this tick, each in `getEntities` section order. Only with entity tracking.
#[inline(never)]
#[allow(clippy::too_many_arguments)]
fn collect_colliders(
    t: Option<&super::entity::Tracker>,
    parked: Option<&Parked>,
    p: &modern::PlayerState,
    vehicle: Option<i32>,
    boxes: &mut Vec<ghast_physics::math::Aabb>,
    boat_boxes: &mut Vec<ghast_physics::math::Aabb>,
    mounts: &[Mount],
) {
    boxes.clear();
    boat_boxes.clear();
    // Farther than any move of one tick can reach (the physics filters exactly); a boat moves
    // up to ~2 blocks a tick on ice.
    let extra = if vehicle.is_some() { 4.0 } else { 3.0 };
    let reach = |v: f64| v.abs() + extra;
    let (rx, ry, rz) = (reach(p.vel[0]), reach(p.vel[1]), reach(p.vel[2]));
    let mut found: Vec<((i32, u64), [f64; 6], bool)> = Vec::new();
    // The boat the player left, where it drove it (without the tracker it is the only one).
    if let Some(k) = parked
        && t.is_none_or(|t| t.get(k.id).is_none())
    {
        found.push((section_order(k.pos), k.bb, !k.living));
    }
    // Adult happy ghasts collide under conditions (`HappyGhast.canBeCollidedWith`).
    let ghast_ty = EntityIds::get().happy_ghast;
    let ghasts = mounts.iter().any(|m| m.ty == ghast_ty);
    let on_ghast =
        ghasts && vehicle.is_some_and(|v| mounts.iter().any(|m| m.id == v && m.ty == ghast_ty));
    for e in t.into_iter().flat_map(|t| t.iter()) {
        let bits = entity_bits(e);
        let living =
            vehicle.is_some() && super::entity::entity_type(e).is_some_and(|t| t.is_living());
        let ghast = if ghasts {
            mounts
                .iter()
                .find(|m| m.id == e.id() && m.ty == ghast_ty && !m.baby)
        } else {
            None
        };
        if bits & COLLIDES == 0 && !living && ghast.is_none() {
            continue;
        }
        if Some(e.id()) == vehicle {
            continue;
        }
        let Some((pos, b)) = Parked::of(parked, e).or_else(|| entity_box(e)) else {
            continue;
        };
        if b[3] < p.bb.min_x - rx
            || b[0] > p.bb.max_x + rx
            || b[4] < p.bb.min_y - ry
            || b[1] > p.bb.max_y + ry
            || b[5] < p.bb.min_z - rz
            || b[2] > p.bb.max_z + rz
        {
            continue;
        }
        // isAlive: a dying shulker (health not above 0, NaN included) no longer collides.
        if !super::entity::alive(e) {
            continue;
        }
        let collides = bits & COLLIDES != 0
            || ghast.is_some_and(|g| {
                if vehicle.is_some() {
                    // The vehicle's move (a mount): kept still, or (for a ridden happy ghast)
                    // another ghast with passengers. A passenger's own move is not modelled.
                    g.stays_still || on_ghast && !e.passengers().is_empty()
                } else {
                    modern::happy_ghast_collides(g.stays_still, &aabb(b), p.pos[1])
                }
            });
        if !collides && !living {
            continue;
        }
        found.push((section_order(pos), b, collides));
    }
    // getEntities walks sections by x, then z / y.
    found.sort_by_key(|f| f.0);
    for (_, b, collides) in found {
        if collides {
            boxes.push(aabb(b));
        }
        if vehicle.is_some() {
            boat_boxes.push(aabb(b));
        }
    }
}

/// `Level.noCollision` without the entity part, for a tracked entity's moved interpolation
/// target: free of blocks and the border.
fn block_free(
    world: &super::world::World,
    level: &modern::LevelInfo,
    e: &ghast_entity::Entity,
    bb: [f64; 6],
) -> bool {
    let pos = e.position();
    modern::no_block_collision::<Rules, _>(
        world,
        level,
        pos,
        bb,
        &modern::CollisionContext {
            feet_y: pos[1],
            ..Default::default()
        },
    )
}

/// 26.3 `AbstractBedBlock.getSleepHeight` of the block at `pos`: the top of its outline shape
/// for a bed (`BedBlock`) or a straw bed (`StrawBedBlock`: the head half reads the foot half it
/// is connected to, `None` without one), `None` for any other block or an empty shape. The
/// entity tracker asks only on 26.3.
#[cold]
fn sleep_height(world: &super::world::World, pos: [i32; 3]) -> Option<f64> {
    use super::data::Property;
    let s = world.block_state(pos[0], pos[1], pos[2])?;
    let b = s.block();
    let shape_of = if b.data().flags & ghast_data::modern::block_flags::BED != 0 {
        s
    } else if b.name() == "straw_bed" {
        if s.get(Property::Part) == Some("head") {
            // getConnectedDirection: the head's foot lies opposite its facing
            let [dx, dz] = match s.get(Property::Facing)? {
                "north" => [0, 1],
                "south" => [0, -1],
                "west" => [1, 0],
                "east" => [-1, 0],
                _ => return None,
            };
            let foot = world.block_state(pos[0] + dx, pos[1], pos[2] + dz)?;
            if foot.block() != b || foot.get(Property::Part) != Some("foot") {
                return None;
            }
            foot
        } else {
            s
        }
    } else {
        return None;
    };
    let shape = shape_of.outline_shape();
    if shape.sizes == [0, 0, 0] {
        return None;
    }
    shape.ys.last().copied()
}

/// `SectionPos` of a position, as `getEntities` orders sections: x, then z, then y.
fn section_order(pos: [f64; 3]) -> (i32, u64) {
    let b = |v: f64| (v.floor() as i32) >> 4;
    let (x, y, z) = (b(pos[0]), b(pos[1]), b(pos[2]));
    (
        x,
        (u64::from(z as u32 & 0x3F_FFFF) << 20) | u64::from(y as u32 & 0xF_FFFF),
    )
}

/// Position and box of an entity, with the shulker's own rules where the tracker has no box (its
/// size follows the peek): `Shulker.setPos` snaps to the block (`floor(x) + 0.5`,
/// `floor(y + 0.5)`, `floor(z) + 0.5`) and the closed shell is the unit cube there
/// (`Shulker.makeBoundingBox` at peek 0, scale 1; an open shell, taller toward its attach face,
/// and a scaled shulker are not modelled).
fn entity_box(e: &ghast_entity::Entity) -> Option<([f64; 3], [f64; 6])> {
    if let Some(b) = e.bounding_box() {
        return Some((e.position(), b));
    }
    let t = super::entity::entity_type(e)?;
    (t.name == "shulker" && e.vehicle().is_none()).then(|| {
        let [x, y, z] = e.position();
        let (x, y, z) = (x.floor() + 0.5, (y + 0.5).floor(), z.floor() + 0.5);
        ([x, y, z], [x - 0.5, y, z - 0.5, x + 0.5, y + 1.0, z + 0.5])
    })
}

/// The entity packets the modern movement reads without entity tracking: the player's own
/// shared flags and main arm, and firework rockets attached to it. Only those are decoded: a
/// packet is decoded past its entity id only when the id is ours or a rocket's.
#[derive(Debug, Default)]
struct OwnEntity {
    /// Our entity id (from the login packet).
    id: i32,
    /// The main arm per our own entity data (`DATA_PLAYER_MAIN_HAND`), else the client option.
    main_arm_left: bool,
    /// Firework rockets spawned but not (yet) known as attached to us: id, spawn position.
    rockets: Vec<(i32, [f64; 3])>,
    /// Mountable animals with an inventory screen (horses, llamas, nautili …): what their
    /// screen reads off them (`canUseSlot(SADDLE / BODY)`); pigs and striders (their saddle and
    /// boost).
    mounts: Vec<Mount>,
    /// The player holds a carrot on a stick / a warped fungus on a stick (either hand), as the
    /// engine reported before the step ([`Sim::hand_items`]).
    sticks: (bool, bool),
    /// The item ids in the main and the off hand the sticks were last read from.
    hands: [Option<i32>; 2],
    /// Some mount has a dash clock running (its position packets are looked at).
    dash_watch: bool,
}

/// A mount entity's screen facts, and what its ride reads off it.
#[derive(Debug, Clone)]
struct Mount {
    id: i32,
    /// `minecraft:entity_type` registry id.
    ty: i32,
    /// `AgeableMob.DATA_BABY_ID`.
    baby: bool,
    /// Index 18: `AbstractHorse.DATA_ID_FLAGS` (tamed = 2) or `TamableAnimal.DATA_FLAGS_ID`
    /// (tame = 4).
    flags: u8,
    /// Something is in its saddle slot (`entity_equipment` slot 7).
    saddled: bool,
    /// Its movement attributes, in packet order (applied when the player boards it).
    attrs: Vec<AttributeUpdate>,
    /// A pig's or strider's last boost time (`DATA_BOOST_TIME`; a boost started then).
    boost: Option<i32>,
    /// A happy ghast's `STAYS_STILL` (the server keeps it still: nobody steers it).
    stays_still: bool,
    /// A camel's pose is `SITTING` (`DATA_POSE`) and its `LAST_POSE_CHANGE_TICK`.
    camel_pose: (bool, i64),
    /// The player's age when the spawn packet came (the entity's first client tick comes after).
    spawned: i32,
    /// A camel's or nautilus' dash cooldown and `DASH` flag as of the player's age `dash.2`, and
    /// whether the client has it on the ground then (the last position packet's flag): run on
    /// lazily ([`modern::Mount::dash_clock`]) to the boarding.
    dash: (i32, bool, i32),
    grounded: bool,
}

impl OwnEntity {
    /// The server's `DASH` entity data for mount `k` nobody on this client rides: its dash
    /// state run on to now, then `onSyncedDataUpdated` (no cooldown before the entity's first
    /// tick).
    #[cold]
    fn dash_synced(&mut self, k: usize, dashing: bool, now: i32, grounded: bool) {
        let m = &mut self.mounts[k];
        if !(m.dash.0 > 0 || m.dash.1) {
            // No clock ran: the ground flag only matters from now on.
            m.grounded = grounded;
        }
        let state = m.dash_now(now);
        let Some(kind) = u16::try_from(m.ty)
            .ok()
            .and_then(super::data::entity_type)
            .and_then(|t| modern::MountKind::from_entity_name(t.name))
        else {
            return;
        };
        let (cd, on) = modern::Mount::dash_synced(kind, state, dashing, now != m.spawned);
        m.dash = (cd, on, now);
        self.dash_watch = true;
    }

    /// A position packet for mount `id` (its ground flag from the tracker now): a running dash
    /// clock is brought up to now with the flag it had before.
    #[cold]
    fn mount_moved(&mut self, id: i32, on_ground: bool, now: i32) {
        if let Some(m) = self.mounts.iter_mut().find(|m| m.id == id)
            && m.grounded != on_ground
        {
            let (cd, on) = m.dash_now(now);
            m.dash = (cd, on, now);
            m.grounded = on_ground;
        }
        self.dash_watch = self.mounts.iter().any(|m| m.dash.0 > 0 || m.dash.1);
    }
}

impl Mount {
    /// The dash state run on to the player's age `now`.
    fn dash_now(&self, now: i32) -> (i32, bool) {
        let Some(kind) = u16::try_from(self.ty)
            .ok()
            .and_then(super::data::entity_type)
            .and_then(|t| modern::MountKind::from_entity_name(t.name))
        else {
            return (self.dash.0, self.dash.1);
        };
        let ticks = u32::try_from(now.wrapping_sub(self.dash.2)).unwrap_or(0);
        modern::Mount::dash_clock(kind, (self.dash.0, self.dash.1), ticks, self.grounded)
    }
}

/// The entity type ids the modern movement reads, resolved by registry name from the version's
/// data set (each version numbers its entity types itself).
#[derive(Debug, Clone, Copy)]
struct EntityIds {
    /// Entity types whose screen is a mount screen: horse, donkey, mule, skeleton / zombie
    /// horse, camel, camel husk (`AbstractHorse`).
    horses: [i32; 7],
    /// llama, trader llama (`Llama`).
    llamas: [i32; 2],
    /// nautilus, zombie nautilus (`AbstractNautilus`).
    nautili: [i32; 2],
    /// pig, strider (`ItemSteerable`: no screen; their saddle and boost).
    steered: [i32; 2],
    /// `minecraft:happy_ghast` (no screen; its harness and `STAYS_STILL`).
    happy_ghast: i32,
    /// `minecraft:firework_rocket`.
    firework_rocket: i32,
}

impl EntityIds {
    /// The ids of this version (`-1`: a type the version does not have).
    fn get() -> &'static EntityIds {
        static IDS: std::sync::OnceLock<EntityIds> = std::sync::OnceLock::new();
        IDS.get_or_init(|| {
            let id = |name: &str| super::data::entity_by_name(name).map_or(-1, |t| i32::from(t.id));
            EntityIds {
                horses: [
                    "horse",
                    "donkey",
                    "mule",
                    "skeleton_horse",
                    "zombie_horse",
                    "camel",
                    "camel_husk",
                ]
                .map(id),
                llamas: ["llama", "trader_llama"].map(id),
                nautili: ["nautilus", "zombie_nautilus"].map(id),
                steered: ["pig", "strider"].map(id),
                happy_ghast: id("happy_ghast"),
                firework_rocket: id("firework_rocket"),
            }
        })
    }

    #[cfg(test)]
    fn tuple(&self) -> ([i32; 7], [i32; 2], [i32; 2], i32) {
        (self.horses, self.llamas, self.nautili, self.firework_rocket)
    }

    fn is_mount(&self, ty: i32) -> bool {
        self.horses.contains(&ty)
            || self.llamas.contains(&ty)
            || self.nautili.contains(&ty)
            || self.steered.contains(&ty)
            || ty == self.happy_ghast
    }

    /// The mount and boat types as the entity trackers' motion types (`Config::motion_types`):
    /// their client copies keep the motion a boarding starts from (a boat's only until its next
    /// tick).
    fn motion_types() -> &'static [u16] {
        static TYPES: std::sync::OnceLock<Box<[u16]>> = std::sync::OnceLock::new();
        TYPES.get_or_init(|| {
            let ids = EntityIds::get();
            let mut v: Vec<u16> = ids
                .horses
                .iter()
                .chain(&ids.llamas)
                .chain(&ids.nautili)
                .chain(&ids.steered)
                .chain(std::iter::once(&ids.happy_ghast))
                .filter_map(|&t| u16::try_from(t).ok())
                .collect();
            v.extend(
                (0..=u16::MAX)
                    .map_while(super::data::entity_type)
                    .filter_map(|t| {
                        matches!(vehicle_kind(t.name), Some(VehicleKind::Boat(_))).then_some(t.id)
                    }),
            );
            v.sort_unstable();
            v.into_boxed_slice()
        })
    }
}

/// The level's game time during the entity tick (`ClientLevel.getGameTime`: the server's time,
/// one more per client tick since), from the clock `(server time, player age then)` and the
/// player's age before its tick.
/// A teleport-entity packet's motion and position as absolute values (`calculateAbsolute`:
/// relative flags add to the current motion / position), from the vehicle's `vel` and `pos`.
fn teleport_values(
    t: &super::proto::play::clientbound::EntityTeleport,
    vel: [f64; 3],
    pos: [f64; 3],
) -> ([f64; 3], [f64; 3]) {
    let has = |bit: u32| t.flags.0 & (1 << bit) != 0;
    let delta = [
        if has(5) { vel[0] + t.dx } else { t.dx },
        if has(6) { vel[1] + t.dy } else { t.dy },
        if has(7) { vel[2] + t.dz } else { t.dz },
    ];
    let to = [
        if has(0) { pos[0] + t.x } else { t.x },
        if has(1) { pos[1] + t.y } else { t.y },
        if has(2) { pos[2] + t.z } else { t.z },
    ];
    (delta, to)
}

/// A teleport too far to interpolate (more than 64 blocks).
fn far(a: [f64; 3], b: [f64; 3]) -> bool {
    let d: f64 = (0..3).map(|k| (a[k] - b[k]) * (a[k] - b[k])).sum();
    d > 4096.0
}

fn level_time(clock: (i64, i32), age: i32) -> i64 {
    clock.0.wrapping_add(i64::from(age.wrapping_sub(clock.1)))
}

/// Mounts remembered at most (nearest first is not known: the oldest are dropped).
const MAX_MOUNTS: usize = 128;

impl Mount {
    /// `canUseSlot(SADDLE)`, `canUseSlot(BODY)` (alive: the entity is still in the level).
    fn slots(&self, ids: &EntityIds) -> (bool, bool) {
        if ids.llamas.contains(&self.ty) {
            (true, true)
        } else if ids.nautili.contains(&self.ty) {
            let ok = !self.baby && self.flags & 4 != 0;
            (ok, ok)
        } else {
            (!self.baby && self.flags & 2 != 0, true)
        }
    }
}

// Entity data indices of the version (read from its real classes).
use super::meta::{
    ATTACHED_TO_TARGET as DATA_ATTACHED_TO_TARGET, BABY as DATA_BABY,
    BOOST_TIME as DATA_BOOST_TIME, CAMEL_DASH as DATA_CAMEL_DASH,
    CAMEL_LAST_POSE as DATA_CAMEL_LAST_POSE, LIVING_FLAGS as DATA_LIVING_FLAGS,
    MOUNT_FLAGS as DATA_MOUNT_FLAGS, PLAYER_MAIN_HAND as DATA_PLAYER_MAIN_HAND, POSE as DATA_POSE,
    SHARED_FLAGS as DATA_SHARED_FLAGS, SLEEPING_POS as DATA_SLEEPING_POS,
};
use super::meta::{NAUTILUS_DASH as DATA_NAUTILUS_DASH, STAYS_STILL as DATA_STAYS_STILL};
/// Rockets spawned near us that may still get attached (a bound against a flood of rockets).
const MAX_PENDING_ROCKETS: usize = 32;

/// The interaction ranges with vanilla's defaults and ranges.
fn range_attributes() -> [modern::Attribute; 2] {
    [
        modern::Attribute::new(4.5, 0.0, 64.0),
        modern::Attribute::new(3.0, 0.0, 64.0),
    ]
}

/// The mining attributes with vanilla's defaults and ranges.
fn mining_attributes() -> [modern::Attribute; 3] {
    [
        modern::Attribute::new(0.0, 0.0, 1024.0),
        modern::Attribute::new(1.0, 0.0, 1024.0),
        modern::Attribute::new(0.2, 0.0, 20.0),
    ]
}

impl std::fmt::Debug for ModernSim {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ModernSim")
            .field("world", &self.world)
            .field("pos", &self.player.pos)
            .finish_non_exhaustive()
    }
}

/// `Player.canGlide` equipment part: some equipment slot holds a stack that can glide using that
/// slot (`LivingEntity.canGlideUsing`: the `glider` component, `equippable` naming that slot,
/// the next point of damage will not break it).
fn glider_equipped(inv: &ghast_inventory::Inventory) -> bool {
    use super::inv::{Equip, can_glide_using};
    let slots = [
        (inv.held(), Equip::MainHand),
        (inv.offhand(), Equip::Offhand),
        (inv.armor(0), Equip::Head),
        (inv.armor(1), Equip::Chest),
        (inv.armor(2), Equip::Legs),
        (inv.armor(3), Equip::Feet),
    ];
    slots
        .into_iter()
        .any(|(s, slot)| s.is_some_and(|s| can_glide_using(s, slot)))
}

/// A world with `c`. Tests: `GHAST_TEST_SHARED=1` gives every world of the test binary one
/// shared section store, so the whole suite can be replayed with sharing on.
fn new_world(c: ghast_world::WorldConfig) -> super::world::World {
    #[cfg_attr(not(test), allow(unused_mut))]
    let mut w = super::world::World::new(c);
    #[cfg(test)]
    if std::env::var_os("GHAST_TEST_SHARED").is_some() {
        static STORE: std::sync::OnceLock<ghast_world::SharedChunks> = std::sync::OnceLock::new();
        w.set_shared_chunks(Some(STORE.get_or_init(Default::default).clone()));
    }
    w
}

impl ModernSim {
    /// Something in `ext` acts next tick (see [`ModernSim::ext_active`]).
    #[inline]
    fn ext_wanted(&self) -> bool {
        let x = &self.ext;
        x.fall_flying
            || x.glider
            || x.rocket_count() > 0
            || x.spin_attack
            || x.auto_spin_ticks > 0
            || x.sleeping
            || self.movement_attributes
    }

    pub(crate) fn new() -> Self {
        ModernSim {
            world: new_world(config()),
            player: modern::PlayerState::new([0.0; 3], 0.0, 0.0),
            packets: ghast_physics::Packets::new(),
            piston_step: false,
            send_due: false,
            updates: BlockUpdates::default(),
            mining: mining_attributes(),
            conduit_power: None,
            ranges: range_attributes(),
            old_pos: [0.0; 3],
            entities: None,
            use_effects: None,
            ext: modern::PlayerExt::default(),
            own: OwnEntity::default(),
            rain_level: 0.0,
            ext_active: false,
            riptide: [0.0; 2],
            around: Around::default(),
            teams: None,
            profile_name: "".into(),
            riding: None,
            vehicles: None,
            parked: None,
            left_mount: None,
            reply: None,
            force_step: ForceStepPosition::Off,
            rec: None,
            movement_attributes: false,
            filter_dirty: false,
            session: SessionPackets::default(),
            gate: modern::LoadGate::waiting(),
            entity_push: true,
            predictions: Default::default(),
            snapped: false,
            server_flags: None,
            absorption: 0.0,
            absorption_dirty: false,
            sleep: None,
            pistons: super::pistons::Pistons::new(),
            piston_edits: super::pistons::Edits::new(),
            piston_uncertain_at: None,
            piston_clock: (0, 0),
            piston_carry: Vec::new(),
            player_section: None,
            section_moves: Vec::new(),
            section_moves_n: 0,
            nonliving: None,
            fishing: crate::fishing::Fishing::default(),
        }
    }

    /// A sim with options (world contents, entity tracking, Grim step compatibility, movement
    /// recording).
    pub(crate) fn with(opts: &SimOptions) -> Self {
        let mut s = Self::new();
        if let Some(c) = opts.world {
            s.world = new_world(c);
        }
        if let Some(cache) = &opts.shared_chunks {
            s.world.set_shared_chunks(Some(cache.clone()));
        }
        if let Some(p) = opts.record.as_deref() {
            match crate::record::Recorder::create(p) {
                Ok(r) => s.rec = Some(Box::new(r)),
                Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
            }
        }
        s.entities = opts.entities.map(super::entity::Tracker::new);
        s.teams = s.entities.is_some().then(Box::default);
        if let Some(n) = &opts.profile_name {
            s.profile_name = n.as_str().into();
        }
        s.force_step = opts.force_step_position;
        s
    }

    /// Test hook: a world in the vanilla nether (registries as with known packs).
    #[cfg(all(test, feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_nether() -> Self {
        let mut s = Self::new();
        s.world.apply_registry(
            "minecraft:dimension_type",
            [
                ("minecraft:overworld", None),
                ("minecraft:the_nether", None),
            ]
            .into_iter(),
        );
        s.world.apply_registry(
            "minecraft:worldgen/biome",
            [("minecraft:plains", None)].into_iter(),
        );
        s.world.enter_dimension("minecraft:the_nether", 1, 8);
        s.sync_level();
        s
    }

    /// Test hook: share the world's sections through `cache` (the engine bench).
    #[cfg(all(
        test,
        feature = "v1_8",
        feature = "v1_12_2",
        feature = "v1_16_5",
        feature = "v26_1"
    ))]
    // the bench mounts some versions only
    #[allow(dead_code)]
    pub(crate) fn test_share_chunks(&mut self, cache: Option<ghast_world::SharedChunks>) {
        self.world.set_shared_chunks(cache);
    }

    /// Test hook: a world in the vanilla overworld (registries as with known packs).
    #[cfg(test)]
    pub(crate) fn test_overworld() -> Self {
        Self::test_overworld_with(&SimOptions::default())
    }

    /// Test hook: [`ModernSim::test_overworld`] with options (a recording).
    #[cfg(test)]
    pub(crate) fn test_overworld_with(opts: &SimOptions) -> Self {
        let mut s = Self::with(opts);
        s.world.apply_registry(
            "minecraft:dimension_type",
            [("minecraft:overworld", None)].into_iter(),
        );
        s.world.apply_registry(
            "minecraft:worldgen/biome",
            [("minecraft:plains", None)].into_iter(),
        );
        s.world.enter_dimension("minecraft:overworld", 0, 8);
        s.sync_level();
        s
    }
}
/// Grim compatibility (see [`ForceStepPosition`]): the tick's movement packet carries no
/// position although the feet height changed since the last sent position (a landing, a bounce
/// or a step-up under the resend threshold): it gets the position, and the sent bookkeeping
/// follows.
#[cold]
#[inline(never)]
fn force_modern_position(
    packets: &mut ghast_physics::Packets,
    p: &mut modern::PlayerState,
    mode: ForceStepPosition,
) {
    use ghast_physics::Packet as P;
    let cur = p.pos;
    if cur[1] == p.sent.pos[1] {
        return;
    }
    let Some(&P::Move {
        pos: None,
        look,
        on_ground,
        horizontal_collision,
    }) = packets
        .as_slice()
        .iter()
        .rev()
        .find(|q| matches!(q, P::Move { .. }))
    else {
        return;
    };
    if mode == ForceStepPosition::StepUpOnly && !(on_ground && cur[1] > p.sent.pos[1]) {
        return;
    }
    let mut out = ghast_physics::Packets::new();
    for q in packets.as_slice() {
        out.push(match *q {
            P::Move { pos: None, .. } => P::Move {
                pos: Some(cur),
                look,
                on_ground,
                horizontal_collision,
            },
            other => other,
        });
    }
    *packets = out;
    p.sent.pos = cur;
    p.sent.position_reminder = 0;
}

sync_pose_fn!(sync_pose_26(p: modern::PlayerState), y: p.pos[1], sneaking: shift);

/// [`held_item_facts`] of this version's data set.
pub(crate) fn held_item_facts(id: u16, count: u8, efficiency: u8) -> HeldItem {
    let item = super::data::Item::from_id(id);
    let name = item.map_or("", super::data::Item::name);
    let food = item.and_then(super::data::Item::food);
    HeldItem {
        id,
        count,
        efficiency,
        places_block: item.is_some_and(|i| i.block().is_some()),
        usable: food.is_some()
            || matches!(
                name,
                "potion"
                    | "milk_bucket"
                    | "honey_bottle"
                    | "bow"
                    | "crossbow"
                    | "shield"
                    | "trident"
                    | "spyglass"
                    | "goat_horn"
            ),
        food: food.is_some(),
        always_edible: food.is_some_and(|f| f.can_always_eat),
        // The modern destroy progress reads the item itself.
        tool_speed: None,
        modern_item: item.map(|_| id),
        // (the thrown items' SUCCESS: set for a right click, `engine::items::use_equips`)
        swing_on_use: false,
        equips: false,
        equip_swings: false,
        // `Item.canDestroyBlock`: a tool component that cannot destroy blocks in creative
        // (swords, the trident, the mace, spears).
        creative_keeps_blocks: item
            .and_then(super::data::Item::tool)
            .is_some_and(|t| !t.can_destroy_blocks_in_creative),
        use_succeeds: false,
    }
}

/// `BlockBehaviour.getDestroyProgress` of this version (oracle-verified in its `data::dig`).
pub(crate) fn dig_progress(
    m: &crate::hands::ModernDig,
    held: Option<&HeldItem>,
    f: crate::hands::DigFactors,
) -> f32 {
    use super::data::{BlockState, Item, dig};
    let Some(state) = BlockState::from_id(m.state) else {
        return 0.0;
    };
    let item = held.and_then(|h| h.modern_item).and_then(Item::from_id);
    let c = dig::DigConditions {
        mining_efficiency: m.mining_efficiency,
        block_break_speed: m.block_break_speed,
        submerged_mining_speed: m.submerged_mining_speed,
        haste: (f.haste > 0).then(|| i32::from(f.haste) - 1),
        conduit_power: m.conduit_power,
        mining_fatigue: (f.fatigue > 0).then(|| i32::from(f.fatigue) - 1),
        eye_in_water: f.in_water,
        on_ground: f.on_ground,
    };
    dig::destroy_progress_with(state, item, &c)
}

/// `Entity.getScoreboardName`: a player's profile name (from the tab list), else the UUID.
fn scoreboard_name<'a>(
    t: &'a super::entity::Tracker,
    e: &'a ghast_entity::Entity,
    buf: &'a mut [u8; 36],
) -> &'a str {
    match t.scoreboard_name(e) {
        Some(n) => n,
        None => e.uuid().hyphenated().encode_lower(buf),
    }
}

/// The resolved entity ids (the per-version table tests).
#[cfg(test)]
pub(super) fn entity_ids_for_test() -> ([i32; 7], [i32; 2], [i32; 2], i32) {
    EntityIds::get().tuple()
}