ghast-physics 0.5.5

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3), verified bit for bit against the real game
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
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
//! Living mounts the local player rides, as the 26.x client ticks them: horses, donkeys, mules,
//! skeleton horses and zombie horses. A saddled one is controlled by its rider
//! (`AbstractHorse.getControllingPassenger`) and then client-authoritative: the client moves it with
//! the rider's input and tells the server where it is. An unsaddled one is moved by the server.
//!
//! # A tick while riding, in vanilla order
//!
//! 1. Mouse turning (before the tick): the player's rotation (a horse does not clamp it).
//! 2. The mount's tick (`ClientLevel.tickNonPassenger`): the entity base tick (fluid pushing, the
//!    non-player current), then `LivingEntity.aiStep`: the jump cooldown, the per-axis 0.003 motion
//!    cutoff, and for a controlled mount `travelRidden`: the rider's input of its PREVIOUS tick
//!    (sideways halved, backwards a quarter, nothing while the horse stands on the ground),
//!    the horse turned to the rider's yaw and half its pitch, a pending jump
//!    (`executeRidersJump`) when on the ground, then `LivingEntity.travel` with the movement
//!    speed attribute (air, water, lava; step height at least one block), floating up in water
//!    for the types that float while ridden, block effects. An uncontrolled mount only slows down
//!    (x 0.98). Last, `AbstractHorse.tick`: the standing counter and the standing animation.
//! 3. The passenger's tick (`tickPassenger` -> `rideTick`): its motion is zeroed, then the whole
//!    player tick runs as a passenger; the jump key charges the jump bar (`jumpRidingTicks`) and
//!    its release sends `player_command` `START_RIDING_JUMP` (bar x 100) and makes the horse rear
//!    (20 ticks) with a pending jump. Packets: `player_input` (when the keys changed), a
//!    rotation-only movement packet, `vehicle_move` with the horse's position, rotation and
//!    ground flag (controlled only).
//! 4. The mount places its passenger (`positionRider`): on its passenger attachment point, moved
//!    up and back by the standing animation, minus the player's 0.6 vehicle attachment; the fall
//!    distance is reset.
//!
//! [`tick_mount`] runs all four. Server packets: `set_passengers` naming the player puts it on the
//! mount ([`Mount::board`]); `move_vehicle` is a correction ([`Mount::server_move`]); the saddle
//! comes with the mount's equipment ([`Mount::set_saddled`]), the standing flag with its entity
//! data ([`Mount::set_horse_flags`]), speed / jump strength / step height / gravity with its
//! attributes ([`Mount::apply_attribute`]). Sneaking does not dismount on the client: the shift
//! key goes to the server in `player_input`.

#![allow(clippy::neg_cmp_op_on_partial_ord)]

use super::attr::ModifierId;
use super::collide::Ents;
use super::collide::{Border, MountExt, MountFacts, World};
use super::ext::{MovementAttributes, PlayerExt};
use super::math::{self as m, DEG_TO_RAD, V3, floor};
use super::player::{
    AttributeKind, Attributes, Ctx, Dimensions, Glide, PlayerState, Pose, Ride, tick_core,
};
use super::rules::Rules;
use crate::math::Aabb;
use crate::world::{BlockView, TickCache};
use crate::{Packet, Packets, TickInput};

#[path = "mount_steer.rs"]
mod steer;

#[path = "mount_camel.rs"]
mod camel;

#[path = "mount_fly.rs"]
mod fly;
pub use fly::happy_ghast_collides;

#[path = "mount_swim.rs"]
mod swim;

#[path = "mount_seat.rs"]
mod seat;
pub(crate) use steer::{LIQUID_STABLE, stands_on_lava};

/// The kind of a living mount.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum MountKind {
    /// `horse`.
    Horse,
    /// `donkey`.
    Donkey,
    /// `mule`.
    Mule,
    /// `skeleton_horse`.
    SkeletonHorse,
    /// `zombie_horse`.
    ZombieHorse,
    /// `pig` (steered with a carrot on a stick).
    Pig,
    /// `strider` (steered with a warped fungus on a stick).
    Strider,
    /// `camel` (a horse that dashes, sprints and sits: `mount_camel.rs`).
    Camel,
    /// `camel_husk` (moves like a camel).
    CamelHusk,
    /// `happy_ghast` (adult): steered with a harness, flies (`mount_fly.rs`).
    HappyGhast,
    /// `nautilus`: steered when tame and saddled, swims and dashes (`mount_swim.rs`).
    Nautilus,
    /// `zombie_nautilus` (as the nautilus, faster).
    ZombieNautilus,
}

/// What the client reads of a mount type: box, passenger seat, default attributes.
struct TypeFacts {
    width: f32,
    height: f32,
    eye_height: f32,
    /// `passengerAttachments(y)`.
    seat: f32,
    movement_speed: f32,
    jump_strength: f64,
    water_slow_down: f32,
    /// `#can_float_while_ridden`.
    floats: bool,
    /// The step height attribute's default.
    step_height: f64,
}

impl MountKind {
    /// The kind of an entity type name (`horse`, `minecraft:donkey`, ...); `None` for anything
    /// that is not a modelled mount.
    #[must_use]
    pub fn from_entity_name(name: &str) -> Option<MountKind> {
        Some(match name.strip_prefix("minecraft:").unwrap_or(name) {
            "horse" => MountKind::Horse,
            "donkey" => MountKind::Donkey,
            "mule" => MountKind::Mule,
            "skeleton_horse" => MountKind::SkeletonHorse,
            "zombie_horse" => MountKind::ZombieHorse,
            "pig" => MountKind::Pig,
            "strider" => MountKind::Strider,
            "camel" => MountKind::Camel,
            "camel_husk" => MountKind::CamelHusk,
            "happy_ghast" => MountKind::HappyGhast,
            "nautilus" => MountKind::Nautilus,
            "zombie_nautilus" => MountKind::ZombieNautilus,
            _ => return None,
        })
    }

    fn facts(self) -> TypeFacts {
        // EntityTypes sizes; AbstractHorse / AbstractChestedHorse / SkeletonHorse attributes.
        let horse = TypeFacts {
            width: 1.396_484_4,
            height: 1.6,
            eye_height: 1.52,
            seat: 1.443_75,
            movement_speed: 0.225,
            jump_strength: 0.7,
            water_slow_down: 0.8,
            floats: true,
            step_height: 1.0,
        };
        match self {
            MountKind::Horse => horse,
            MountKind::Donkey => TypeFacts {
                height: 1.5,
                eye_height: 1.425,
                seat: 1.1125,
                movement_speed: 0.175,
                jump_strength: 0.5,
                ..horse
            },
            MountKind::Mule => TypeFacts {
                seat: 1.2125,
                movement_speed: 0.175,
                jump_strength: 0.5,
                ..horse
            },
            MountKind::SkeletonHorse => TypeFacts {
                seat: 1.318_75,
                movement_speed: 0.2,
                water_slow_down: 0.96,
                floats: false,
                ..horse
            },
            MountKind::ZombieHorse => TypeFacts {
                seat: 1.318_75,
                ..horse
            },
            // EntityTypes: pig 0.9 x 0.9 (eyes 0.85 of the height), its passenger attachment;
            // strider 0.9 x 1.7, the default attachment (its height). Pig / Strider attributes.
            MountKind::Pig => TypeFacts {
                width: 0.9,
                height: 0.9,
                eye_height: 0.9 * 0.85,
                seat: 0.868_75,
                movement_speed: 0.25,
                jump_strength: f64::from(0.42f32),
                floats: false,
                step_height: 0.6,
                ..horse
            },
            MountKind::Strider => TypeFacts {
                width: 0.9,
                height: 1.7,
                eye_height: 1.7 * 0.85,
                seat: 1.7,
                movement_speed: 0.175,
                jump_strength: f64::from(0.42f32),
                floats: false,
                step_height: 0.6,
                ..horse
            },
            // EntityTypes 1.7 x 2.375, eyes 2.275 (standing; sitting: mount_camel.rs);
            // Camel.createAttributes (the camel husk uses it too). The seat is computed.
            MountKind::Camel | MountKind::CamelHusk => TypeFacts {
                width: 1.7,
                height: 2.375,
                eye_height: 2.275,
                seat: 0.0,
                movement_speed: 0.09,
                jump_strength: f64::from(0.42f32),
                step_height: 1.5,
                ..horse
            },
            // EntityTypes 4 x 4, eyes 2.6; HappyGhast.createAttributes. Its seats: `mount_fly.rs`.
            MountKind::HappyGhast => TypeFacts {
                width: 4.0,
                height: 4.0,
                eye_height: 2.6,
                seat: 4.0,
                movement_speed: 0.05,
                jump_strength: f64::from(0.42f32),
                floats: false,
                step_height: 0.6,
                ..horse
            },
            // EntityTypes 0.875 x 0.95, eyes 0.2751, passenger attachment 1.1375;
            // AbstractNautilus / ZombieNautilus attributes.
            MountKind::Nautilus | MountKind::ZombieNautilus => TypeFacts {
                width: 0.875,
                height: 0.95,
                eye_height: 0.2751,
                seat: 1.1375,
                movement_speed: if self == MountKind::Nautilus {
                    1.0
                } else {
                    1.1
                },
                jump_strength: f64::from(0.42f32),
                floats: false,
                step_height: 0.6,
                ..horse
            },
        }
    }
}

/// `AbstractHorse` flag bits of its entity data.
const FLAG_TAME: u8 = 2;
const FLAG_EATING: u8 = 16;
const FLAG_STANDING: u8 = 32;

/// A living mount the player rides. Create it from the add-entity packet ([`Mount::new`]).
#[derive(Clone, Debug)]
pub struct Mount {
    kind: MountKind,
    /// The generic living-entity state (position, box, motion, ground and collision flags, fall
    /// distance, fluids, attributes).
    e: PlayerState,
    attrs: MovementAttributes,
    s: MountState,
    /// Pig and strider state.
    st: steer::SteerState,
    /// Camel state.
    cm: camel::CamelState,
    /// Happy ghast state.
    fly: fly::FlyState,
    /// Nautilus state.
    sw: swim::SwimState,
}

/// The mount's own fields (`AbstractHorse`).
#[derive(Clone, Copy, Debug, Default)]
struct MountState {
    saddled: bool,
    /// The `AbstractHorse` flags byte.
    flags: u8,
    /// `playerJumpPendingScale`.
    pending: f32,
    allow_stand_sliding: bool,
    stand_counter: i32,
    stand_anim: f32,
    stand_anim_o: f32,
    /// `LivingEntity.speed`: set to the movement speed each tick the rider controls it.
    speed: f32,
    /// The number of passengers (`set_passengers`; 0 and 1 seat one).
    passengers: u8,
    /// Where the entity tracker's interpolation put the mount this tick (position, yaw, pitch):
    /// applied at the interpolation step of `aiStep` ([`Mount::follow_tracker`]).
    follow: Option<([f64; 3], f32, f32)>,
    /// The mount interpolated before this tick's step and still does after it
    /// (`isInterpolating`: no x 0.98 slowdown; which one counts depends on the version).
    follow_interp: (bool, bool),
    /// A teleport's ground flag, set at the start of the next tick (`setOnGround`, which also
    /// finds the supporting block).
    ground: Option<bool>,
    /// The interpolation target (position, yaw, pitch) while a steered mount still interpolates
    /// after this tick's step: the `vehicle_move` carries it (`ServerboundMoveVehiclePacket.fromEntity`).
    send_target: Option<([f64; 3], f32, f32)>,
}

impl Mount {
    /// A mount as the add-entity packet creates it: at `pos` with the packet's rotation (`yaw`,
    /// `pitch` as decoded from the packet's angle bytes), the type's default attributes, no
    /// saddle.
    #[must_use]
    pub fn new(kind: MountKind, pos: [f64; 3], yaw: f32, pitch: f32) -> Mount {
        let f = kind.facts();
        let mut e = PlayerState::new(pos, yaw % 360.0, pitch.clamp(-90.0, 90.0) % 360.0);
        e.dims = Dimensions {
            width: f.width,
            height: f.height,
            eye_height: f.eye_height,
        };
        let mut a = Attributes::default();
        a.movement_speed.set_base(f64::from(f.movement_speed));
        a.jump_strength.set_base(f.jump_strength);
        a.step_height.set_base(f.step_height);
        a.safe_fall_distance.set_base(6.0);
        e.attributes = a;
        e.set_pos(pos[0], pos[1], pos[2]);
        e.pose = Pose::Standing;
        e.on_ground = false;
        Mount {
            kind,
            e,
            attrs: MovementAttributes::default(),
            s: MountState::default(),
            st: steer::SteerState::default(),
            cm: camel::CamelState::default(),
            fly: fly::FlyState::default(),
            sw: swim::SwimState::default(),
        }
    }

    /// The kind.
    #[must_use]
    pub fn kind(&self) -> MountKind {
        self.kind
    }

    /// Position (feet).
    #[must_use]
    pub fn pos(&self) -> [f64; 3] {
        self.e.pos
    }

    /// Motion.
    #[must_use]
    pub fn vel(&self) -> [f64; 3] {
        self.e.vel
    }

    /// Yaw.
    #[must_use]
    pub fn yaw(&self) -> f32 {
        self.e.yaw
    }

    /// Pitch.
    #[must_use]
    pub fn pitch(&self) -> f32 {
        self.e.pitch
    }

    /// The box.
    #[must_use]
    pub fn bounding_box(&self) -> Aabb {
        self.e.bb
    }

    /// On the ground.
    #[must_use]
    pub fn on_ground(&self) -> bool {
        self.e.on_ground
    }

    /// Horizontal collision of the last move.
    #[must_use]
    pub fn horizontal_collision(&self) -> bool {
        self.e.horizontal_collision
    }

    /// Vertical collision of the last move.
    #[must_use]
    pub fn vertical_collision(&self) -> bool {
        self.e.vertical_collision
    }

    /// Fall distance.
    #[must_use]
    pub fn fall_distance(&self) -> f64 {
        self.e.fall_distance
    }

    /// The generic entity state (fluids, supporting block, attributes, ...).
    #[must_use]
    pub fn entity(&self) -> &PlayerState {
        &self.e
    }

    /// Saddled: the rider controls it.
    #[must_use]
    pub fn saddled(&self) -> bool {
        self.s.saddled
    }

    /// The rider controls the mount (`getControllingPassenger()` is the player): it is saddled
    /// (`isSaddled`; a donkey's or mule's saddle counts only when it is tame,
    /// `AbstractHorse.canUseSlot`).
    #[must_use]
    pub fn controlled(&self) -> bool {
        if self.kind == MountKind::HappyGhast {
            return fly::controlled(self);
        }
        if swim::is_nautilus(self.kind) {
            return swim::controlled(self);
        }
        // getFirstPassenger: only the passenger in front can steer.
        self.fly.seat == 0
            && self.s.saddled
            && match self.kind {
                MountKind::Donkey | MountKind::Mule => self.s.flags & FLAG_TAME != 0,
                MountKind::Pig | MountKind::Strider => self.st.holds(self.kind),
                _ => true,
            }
    }

    /// A pig or strider (`ItemSteerable`).
    fn steered(&self) -> bool {
        matches!(self.kind, MountKind::Pig | MountKind::Strider)
    }

    /// What the rider holds, in either hand (`Player.isHolding`): a carrot on a stick (a pig
    /// follows it) and a warped fungus on a stick (a strider follows it). Call it before each
    /// tick with the player's current hands.
    pub fn set_rider_sticks(&mut self, carrot_on_a_stick: bool, warped_fungus_on_a_stick: bool) {
        self.st.carrot = carrot_on_a_stick;
        self.st.fungus = warped_fungus_on_a_stick;
    }

    /// The server's boost time of a pig or strider (entity data `DATA_BOOST_TIME`, sent after the
    /// rider used the stick): a boost of that many ticks starts (`ItemBasedSteering.onSynced`).
    pub fn set_boost_time(&mut self, total: i32) {
        self.st.boost(total);
    }

    /// A pig or strider is boosted, and the ticks of its boost so far.
    #[must_use]
    pub fn boost(&self) -> (bool, i32) {
        (self.st.boosting, self.st.boost_time)
    }

    /// A strider is cold (`isSuffocating`, out of lava: slower).
    #[must_use]
    pub fn suffocating(&self) -> bool {
        self.st.suffocating
    }

    /// The walk animation's speed and position (kept for a strider: it moves its rider).
    #[must_use]
    pub fn walk_animation(&self) -> (f32, f32) {
        (self.st.walk_speed, self.st.walk_pos)
    }

    /// A camel or camel husk.
    fn is_camel(&self) -> bool {
        matches!(self.kind, MountKind::Camel | MountKind::CamelHusk)
    }

    /// The level's game time (`ClientLevel.getGameTime`: the server's time, then one more per
    /// client tick); a camel's sitting reads it. Set it before each tick.
    pub fn set_game_time(&mut self, time: i64) {
        self.cm.game_time = time;
    }

    /// The server's entity data of a camel's pose (`DATA_POSE`): sitting or not (its box).
    pub fn set_camel_sitting(&mut self, sitting: bool) {
        if self.is_camel() {
            self.cm.set_pose(sitting, &mut self.e);
        }
    }

    /// The server's `LAST_POSE_CHANGE_TICK` of a camel (negative: sitting since then).
    pub fn set_last_pose_change_tick(&mut self, tick: i64) {
        self.cm.last_pose_tick = tick;
    }

    /// The server's `DASH` entity data of a camel (a dash cooldown starts if none runs).
    pub fn set_dashing(&mut self, dashing: bool) {
        let first = self.e.first_tick;
        self.cm.set_dashing(dashing, true, first);
    }

    /// A camel's dash cooldown, `DASH` flag, sitting pose, `LAST_POSE_CHANGE_TICK`, game time and
    /// whether it refuses to move (sitting or changing pose).
    #[must_use]
    pub fn camel(&self) -> (i32, bool, bool, i64, i64, bool) {
        let c = &self.cm;
        (
            c.dash_cooldown,
            c.dashing,
            c.sitting_pose,
            c.last_pose_tick,
            c.game_time,
            c.refuse_to_move(),
        )
    }

    /// The `AbstractHorse` flags byte (2 tame, 8 bred, 16 eating, 32 standing, 64 open mouth).
    #[must_use]
    pub fn horse_flags(&self) -> u8 {
        self.s.flags
    }

    /// The jump the horse makes the next time it ticks on the ground (`playerJumpPendingScale`).
    #[must_use]
    pub fn jump_pending(&self) -> f32 {
        self.s.pending
    }

    /// `allowStandSliding`.
    #[must_use]
    pub fn allow_stand_sliding(&self) -> bool {
        self.s.allow_stand_sliding
    }

    /// Ticks the client-side rearing lasts (`standCounter`).
    #[must_use]
    pub fn stand_counter(&self) -> i32 {
        self.s.stand_counter
    }

    /// The standing animation (`standAnim`) and its previous value (`standAnimO`, which moves the
    /// rider).
    #[must_use]
    pub fn stand_anim(&self) -> (f32, f32) {
        (self.s.stand_anim, self.s.stand_anim_o)
    }

    /// `getSpeed()`: the movement speed of the last tick the rider controlled it.
    #[must_use]
    pub fn speed(&self) -> f32 {
        self.s.speed
    }

    /// The client tick of the mount while the player does not ride it (the server moves it): it
    /// only slows down, is pushed off the local player when their boxes overlap
    /// (`LivingEntity.pushEntities` -> `Entity.push`: both are pushed apart; the player's half
    /// is [`push_by`](super::push_by)), and animates. Call it once per client tick, after the
    /// player's tick, for each mount the player is not on (only needed to keep its motion exact
    /// for a later boarding).
    pub fn tick_alone<R: Rules, W: BlockView<State = R::State>>(
        &mut self,
        world: &W,
        p: &PlayerState,
        x: &PlayerExt,
    ) {
        mount_tick::<R, W>(self, None, &[], world);
        if self.s.passengers > 0 {
            // Entity.push: a vehicle (someone else rides it) is not pushed.
            return;
        }
        let (o, b) = (&self.e.bb, &p.bb);
        if !super::math::intersects(b, o.min_x, o.min_y, o.min_z, o.max_x, o.max_y, o.max_z) {
            return;
        }
        // EntitySelector.pushableBy (the player pushable: no spectator, not on a climbable),
        // then Entity.push(mount) of the player: the mount gets `mount - player`.
        if p.spectator || p.no_physics || super::player::on_climbable_ext::<R, W>(p, x, world) {
            return;
        }
        let (mut xa, mut za) = (self.e.pos[0] - p.pos[0], self.e.pos[2] - p.pos[2]);
        let mut dd = xa.abs().max(za.abs());
        if !(dd >= f64::from(0.01f32)) {
            return;
        }
        dd = dd.sqrt();
        xa /= dd;
        za /= dd;
        let pow = (1.0 / dd).min(1.0);
        xa *= pow;
        za *= pow;
        xa *= f64::from(0.05f32);
        za *= f64::from(0.05f32);
        if xa.is_finite() && za.is_finite() {
            let v = V3::of(self.e.vel).add(V3::new(xa, 0.0, za));
            if v.is_finite() {
                self.e.vel = v.arr();
            }
        }
    }

    /// Where the client's copy of a mount the server moves is this tick (the entity tracker's
    /// interpolated position, after the mount's own tick): ignored while the rider controls it.
    pub fn follow_server(&mut self, pos: [f64; 3]) {
        if !self.controlled() {
            self.e.set_pos(pos[0], pos[1], pos[2]);
        }
    }

    /// The saddle slot of the mount's equipment changed (equipment packet): `true` for a saddle.
    pub fn set_saddled(&mut self, saddled: bool) {
        self.s.saddled = saddled;
    }

    /// The server's entity data for the `AbstractHorse` flags byte.
    pub fn set_horse_flags(&mut self, flags: u8) {
        self.s.flags = flags;
    }

    /// The attributes packet entry for one attribute of the mount: base and modifiers `(id,
    /// amount, operation)` in packet order. Attributes movement does not read are ignored.
    /// `scale` is not modelled (the mount keeps its size).
    pub fn apply_attribute(&mut self, name: &str, base: f64, modifiers: &[(ModifierId, f64, u8)]) {
        if self.kind == MountKind::HappyGhast && self.fly.apply_attribute(name, base, modifiers) {
            return;
        }
        if let Some(k) = AttributeKind::from_name(name) {
            if k != AttributeKind::Scale {
                self.e.attributes.get_mut(k).apply_packet(base, modifiers);
            }
        } else if let Some(a) = self.attrs.get_mut(name) {
            a.apply_packet(base, modifiers);
        }
    }

    /// The server's `set_passengers` put the player on this mount (`startRiding`): the standing
    /// pose. The player's rotation is kept: the horse's turn of its rider (`doPlayerRide`) runs on
    /// the server only, and the client turns to the vehicle's yaw only for a boat
    /// (`mounts_board_yaw.jsonl.gz`, replayed through the engine).
    pub fn board(&self, p: &mut PlayerState) {
        if p.pose != Pose::Standing {
            p.pose = Pose::Standing;
            p.dims = Pose::Standing.scaled(p.scale());
            let [x, y, z] = p.pos;
            p.set_pos(x, y, z);
        }
    }

    /// The player got off (`set_passengers` without it): its jump bar is no longer charged.
    pub fn dismount(x: &mut PlayerExt) {
        x.jump_riding_scale = 0.0;
    }

    /// A `move_vehicle` packet from the server (`handleMoveVehicle`): a controlled mount snaps to
    /// it unless it is within 1e-5 and answers at once with a `vehicle_move`; `None` for a mount
    /// the server moves.
    pub fn server_move(&mut self, pos: [f64; 3], yaw: f32, pitch: f32) -> Option<Packet> {
        if !self.controlled() {
            return None;
        }
        let d = V3::of(pos).sub(V3::of(self.e.pos));
        if d.length() > f64::from(1.0e-5f32) {
            self.e.set_pos(pos[0], pos[1], pos[2]);
            if yaw.is_finite() {
                self.e.yaw = yaw % 360.0;
            }
            if pitch.is_finite() {
                self.e.pitch = (pitch.clamp(-90.0, 90.0) % 360.0).clamp(-90.0, 90.0);
            }
        }
        Some(Packet::MoveVehicle {
            pos: self.e.pos,
            yaw: self.e.yaw,
            pitch: self.e.pitch,
            on_ground: self.e.on_ground,
        })
    }

    /// `AbstractHorse.onPlayerJump`: the released jump bar (x 100) as a pending jump; a horse rears.
    fn on_player_jump(&mut self, amount: i32) {
        if swim::is_nautilus(self.kind) {
            swim::on_player_jump(self, amount);
            return;
        }
        if !self.controlled() {
            return;
        }
        let camel = self.is_camel();
        if camel && !(self.cm.dash_cooldown <= 0 && self.e.on_ground) {
            // Camel.onPlayerJump: no dash while one cools down or off the ground.
            return;
        }
        let amount = if amount < 0 {
            0
        } else {
            self.s.allow_stand_sliding = true;
            // standIfPossible: the client simulates the horse (isEffectiveAi); a camel does not
            // rear.
            if !camel {
                self.s.flags &= !FLAG_EATING;
                self.s.flags |= FLAG_STANDING;
                self.s.stand_counter = 20;
            }
            amount
        };
        // PlayerRideableJumping.getPlayerJumpPendingScale
        self.s.pending = if amount >= 90 {
            1.0
        } else {
            0.4 + 0.4 * amount as f32 / 90.0
        };
    }

    fn standing(&self) -> bool {
        self.s.flags & FLAG_STANDING != 0
    }
}

/// One client tick of a player riding a living mount: mouse turning, the mount's tick, the
/// passenger's tick and its placing on the mount, in vanilla order (see the module docs).
/// `mount_colliders` are the boxes of the entities the mount collides with (boats, shulkers; not
/// its passenger); `around` is what the player's own tick collides with.
#[allow(clippy::too_many_arguments)]
pub fn tick_mount<R: Rules, W: BlockView<State = R::State>>(
    mount: &mut Mount,
    p: &mut PlayerState,
    x: &mut PlayerExt,
    around: &super::Surroundings<'_>,
    mount_colliders: &[Aabb],
    input: &TickInput,
    world: &W,
    out: &mut Packets,
) {
    if input.yaw.is_finite() {
        p.yaw = input.yaw;
    }
    if input.pitch.is_finite() {
        p.pitch = (input.pitch % 360.0).clamp(-90.0, 90.0);
    }
    mount.e.level = p.level;
    mount_tick::<R, W>(mount, Some(p), mount_colliders, world);
    // tickPassenger -> rideTick: motion zeroed, the player's tick, positionRider.
    p.vel = [0.0; 3];
    if x.jump_bar_age != p.age {
        // The tick before was not on a jumpable mount: vanilla zeroed the bar then.
        x.jump_riding_scale = 0.0;
    }
    // LocalPlayer.jumpableVehicle: a PlayerRideableJumping mount (not the happy ghast).
    let jumpable = if swim::is_nautilus(mount.kind) {
        swim::jumpable(mount)
    } else {
        mount.controlled()
            && mount.kind != MountKind::HappyGhast
            && !mount.steered()
            && (!mount.is_camel() || !mount.cm.refuse_to_move() && mount.cm.dash_cooldown == 0)
    };
    let mut g = Glide {
        fall_flying: x.fall_flying,
        glider: x.glider,
        spin_attack: x.spin_attack,
        auto_spin_ticks: x.auto_spin_ticks,
        riding: Some(Ride {
            pos: mount.e.pos,
            yaw: mount.e.yaw,
            pitch: mount.e.pitch,
            on_ground: mount.e.on_ground,
            jumpable,
            jump_ticks: x.jump_riding_ticks,
            jump_scale: x.jump_riding_scale,
            // vehicleCanSprint: a camel the client moves.
            can_sprint: mount.is_camel() && mount.controlled(),
            ..Ride::vehicle(false, mount.controlled(), mount.e.pos)
        }),
        last_yd: 0.0,
        ..Glide::with_attributes(x)
    };
    if let Some((pos, yaw, pitch)) = mount.s.send_target.take()
        && let Some(r) = g.riding.as_mut()
    {
        // Still interpolating: the packet carries the interpolation's target.
        r.pos = pos;
        r.yaw = yaw;
        r.pitch = pitch;
    }
    let pending = x.pending_move.take();
    let keep = TickInput {
        yaw: f32::NAN,
        pitch: f32::NAN,
        ..*input
    };
    tick_core::<R, W, Ents<'_>>(p, &mut g, pending, Ents(around.entities), &keep, world, out);
    x.fall_flying = g.fall_flying;
    x.auto_spin_ticks = g.auto_spin_ticks;
    if let Some(r) = g.riding {
        x.jump_riding_ticks = r.jump_ticks;
        x.jump_riding_scale = r.jump_scale;
        if jumpable {
            x.jump_bar_age = p.age;
        }
        if let Some(amount) = r.jump_out {
            mount.on_player_jump(amount);
        }
    }
    position_rider(mount, p);
    // LivingEntity.rideTick
    p.fall_distance = 0.0;
}

/// `positionRider`: the passenger on the mount's passenger attachment (turned with the mount),
/// moved by the standing animation, minus its own vehicle attachment (0.6 blocks scaled).
fn position_rider(mount: &Mount, p: &mut PlayerState) {
    let f = mount.kind.facts();
    let a = -mount.e.yaw * DEG_TO_RAD;
    let (c, s) = (
        f64::from(m::cos(f64::from(a))),
        f64::from(m::sin(f64::from(a))),
    );
    let yrot = |v: V3| V3::new(v.x * c + v.z * s, v.y, v.z * c - v.x * s);
    // getDefaultPassengerAttachmentPoint, then AbstractHorse's standing offset (scale 1).
    let seat = yrot(if mount.kind == MountKind::HappyGhast {
        fly::seat(mount.kind, mount.fly.seat)
    } else {
        V3::new(0.0, f64::from(f.seat), 0.0)
    });
    let anim = f64::from(mount.s.stand_anim_o);
    let stand = if mount.kind == MountKind::Strider {
        // Strider.getPassengerAttachmentPoint on the client: the walk animation's bob.
        V3::new(0.0, steer::strider_seat_offset(&mount.st), 0.0)
    } else {
        yrot(V3::new(0.0, 0.15 * anim * 1.0, -0.7 * anim * 1.0))
    };
    let (seat, stand) = if mount.is_camel() {
        // Camel.getPassengerAttachmentPoint (no rearing offset).
        let (index, count) = (mount.fly.seat, mount.s.passengers);
        (
            camel::seat(&mount.cm, mount.e.dims, mount.e.yaw, index, count),
            V3::ZERO,
        )
    } else {
        (seat, stand)
    };
    let pos = V3::of(mount.e.pos).add(seat.add(stand));
    let attach = 0.6 * f64::from(p.scale());
    p.set_pos(pos.x, pos.y - attach, pos.z);
}

/// The mount's client tick (`ClientLevel.tickNonPassenger` -> `AbstractHorse.tick`).
fn mount_tick<R: Rules, W: BlockView<State = R::State>>(
    mount: &mut Mount,
    rider: Option<&PlayerState>,
    colliders: &[Aabb],
    world: &W,
) {
    let f = mount.kind.facts();
    let kind = mount.kind;
    let steered = mount.steered();
    let rider = rider.filter(|_| mount.controlled());
    let controlled = rider.is_some();
    let standing = mount.standing();
    let camel = mount.is_camel();
    let (e, s, st, cm) = (&mut mount.e, &mut mount.s, &mut mount.st, &mut mount.cm);
    let cache = TickCache::new(world, floor(e.pos[0]), floor(e.pos[1]), floor(e.pos[2]));
    let border = Border::new(&world.world_border());
    let w = World::<R, TickCache<'_, W>, MountExt<'_>> {
        w: &cache,
        border: &border,
        min_y: e.level.min_y,
        max_y: e.level.min_y + e.level.height - 1,
        ext: MountExt {
            colliders,
            facts: MountFacts {
                water_slow_down: f.water_slow_down,
                climbs: false,
                lava_walker: kind == MountKind::Strider,
                no_fall_check: kind == MountKind::HappyGhast,
                not_pushed_by_fluid: swim::is_nautilus(kind),
            },
        },
        _r: core::marker::PhantomData,
    };
    if let Some(g) = s.ground.take() {
        // A teleport's setOnGround, at the box the mount had then (nothing moved it since).
        let here = V3::of(e.pos);
        let mut t = Ctx {
            p: &mut *e,
            x: Glide::default(),
            w: &w,
            old_pos: here,
            moves: [None; 4],
            using_item: false,
        };
        t.set_on_ground(g, None);
    }
    // commonTick: old position, tick count.
    if R::INTERPOLATE_IN_COMMON_TICK
        && let Some((pos, yaw, pitch)) = s.follow.take()
    {
        // 26.3 commonTick: the interpolation step before the entity's tick.
        seat::follow(e, pos, yaw, pitch);
    }
    let old_pos = V3::of(e.pos);
    if kind == MountKind::Strider {
        // Strider.tick before the living tick: cold or warm (a speed modifier).
        let mut a = e.attributes;
        {
            let t = Ctx {
                p: &mut *e,
                x: Glide::default(),
                w: &w,
                old_pos,
                moves: [None; 4],
                using_item: false,
            };
            steer::strider_cold(&t, st, &mut a);
        }
        e.attributes = a;
    }
    e.age += 1;
    let a = &mount.attrs;
    let mut t = Ctx {
        p: e,
        x: Glide {
            bounciness: a.bounciness.value(),
            air_drag_modifier: a.air_drag_modifier.value() as f32,
            friction_modifier: a.friction_modifier.value() as f32,
            ..Glide::default()
        },
        w: &w,
        old_pos,
        moves: [None; 4],
        using_item: false,
    };
    // Entity.baseTick
    t.p.was_in_powder_snow = t.p.in_powder_snow;
    t.p.in_powder_snow = false;
    t.update_fluid_interaction();
    if t.p.in_lava() {
        t.p.fall_distance *= 0.5;
    }
    t.p.first_tick = false;
    // LivingEntity.aiStep
    if t.p.no_jump_delay > 0 {
        t.p.no_jump_delay -= 1;
    }
    // The interpolation step (the entity tracker's position of a mount the server moves).
    let (was, still) = core::mem::take(&mut s.follow_interp);
    let interp = if R::INTERPOLATE_IN_COMMON_TICK {
        still
    } else {
        was
    };
    if let Some((pos, yaw, pitch)) = s.follow.take() {
        seat::follow(t.p, pos, yaw, pitch);
    }
    if !controlled && !interp {
        // Not simulated here (and not interpolating): it only slows down.
        let v = V3::of(t.p.vel).scale(0.98);
        t.p.vel = v.arr();
    }
    let mut v = t.p.vel;
    for i in [0, 2] {
        if v[i].abs() < 0.003 {
            v[i] = 0.0;
        }
    }
    if v[1].abs() < 0.003 {
        v[1] = 0.0;
    }
    t.p.vel = v;
    // The mount's own jump input is never set on the client.
    t.p.no_jump_delay = 0;
    if let Some(rider) = rider.filter(|_| kind == MountKind::HappyGhast) {
        fly::travel_ridden(&mut t, &mount.fly, rider);
        t.apply_effects_from_blocks();
    } else if let Some(rider) = rider.filter(|_| swim::is_nautilus(kind)) {
        s.speed = swim::travel_ridden(&mut t, &mut mount.sw, &mut s.pending, rider);
        t.apply_effects_from_blocks();
    } else if let Some(rider) = rider.filter(|_| steered) {
        s.speed = steer::travel_ridden(&mut t, st, kind, rider);
        t.apply_effects_from_blocks();
    } else if let Some(rider) = rider {
        // travelRidden: getRiddenInput, tickRidden, travel.
        let refuse = camel && cm.refuse_to_move();
        // (A camel that refuses to move gets none.)
        let input =
            if refuse || t.p.on_ground && s.pending == 0.0 && standing && !s.allow_stand_sliding {
                V3::ZERO
            } else {
                let sideways = rider.xxa * 0.5;
                let mut forward = rider.zza;
                if forward <= 0.0 {
                    forward *= 0.25;
                }
                V3::new(f64::from(sideways), 0.0, f64::from(forward))
            };
        // tickRidden: the rider's yaw and half its pitch (setRot, then setXRot's clamp).
        if refuse {
            // Camel.getRiddenRotation: its own.
            t.p.yaw %= 360.0;
            t.p.pitch = (t.p.pitch % 360.0 % 360.0).clamp(-90.0, 90.0);
        } else {
            t.p.yaw = rider.yaw % 360.0;
            t.p.pitch = ((rider.pitch * 0.5) % 360.0 % 360.0).clamp(-90.0, 90.0);
        }
        if t.p.on_ground {
            if s.pending > 0.0 {
                if camel {
                    camel::dash(&mut t, cm, s.pending);
                } else {
                    execute_riders_jump(&mut t, s.pending, input);
                }
            }
            s.pending = 0.0;
        }
        let mut input = input;
        if camel {
            // Camel.tickRidden: forward stands a sitting camel up.
            if rider.zza > 0.0 && cm.sitting() && !cm.in_transition() {
                cm.stand_up(t.p);
            }
            s.speed = camel::ridden_speed(cm, t.p.movement_speed(), rider.sprinting);
            // Camel.travel: no horizontal move on the ground while it refuses to.
            if cm.refuse_to_move() && t.p.on_ground {
                let v = t.p.vel;
                t.p.vel = [v[0] * 0.0, v[1], v[2] * 0.0];
                input = V3::new(input.x * 0.0, input.y, input.z * 0.0);
            }
        } else {
            s.speed = t.p.speed();
        }
        let in_fluid = t.p.touching_water || t.p.in_lava();
        let in_water = t.p.touching_water;
        if camel {
            // `travel` reads `getSpeed()`: the ridden speed (the sprint bonus).
            let saved = t.p.attributes.movement_speed;
            t.p.attributes.movement_speed =
                super::attr::Attribute::new(f64::from(s.speed), f64::MIN, f64::MAX);
            t.travel(input);
            t.p.attributes.movement_speed = saved;
        } else {
            t.travel(input);
        }
        // floatInWaterWhileRidden (26.3: floatInLiquidWhileRidden after either fluid).
        let thr = if t.p.dims.eye_height < 0.4 { 0.0 } else { 0.4 };
        if in_fluid
            && (in_water || R::RIDDEN_FLOAT_AFTER_LAVA)
            && f.floats
            && t.p.water_height > thr
        {
            let v = V3::of(t.p.vel).add(V3::new(0.0, f64::from(0.04f32), 0.0));
            t.p.vel = v.arr();
        }
        t.apply_effects_from_blocks();
    }
    if swim::is_nautilus(kind) {
        swim::after_tick(&mut mount.sw);
        return;
    }
    if steered {
        if kind == MountKind::Strider {
            // calculateEntityAnimation (the rider's seat follows it), then floatStrider.
            steer::walk_animation(st, t.p.pos, old_pos);
            steer::float_strider(&mut t);
        }
        return;
    }
    // AbstractHorse.tick: the standing counter, then the standing animation.
    if s.stand_counter > 0 {
        s.stand_counter -= 1;
        if s.stand_counter <= 0 {
            s.flags &= !FLAG_STANDING;
            s.stand_counter = 0;
        }
    }
    s.stand_anim_o = s.stand_anim;
    if s.flags & FLAG_STANDING != 0 {
        s.stand_anim += (1.0 - s.stand_anim) * 0.4 + 0.05;
        if s.stand_anim > 1.0 {
            s.stand_anim = 1.0;
        }
    } else {
        s.allow_stand_sliding = false;
        s.stand_anim +=
            (0.8 * s.stand_anim * s.stand_anim * s.stand_anim - s.stand_anim) * 0.6 - 0.05;
        if s.stand_anim < 0.0 {
            s.stand_anim = 0.0;
        }
    }
    if camel {
        camel::after_tick(cm, t.p);
    }
}

/// `AbstractHorse.executeRidersJump(amount, input)`.
fn execute_riders_jump<R: Rules, W: BlockView<State = R::State>>(
    t: &mut Ctx<'_, '_, R, TickCache<'_, W>, MountExt<'_>>,
    amount: f32,
    input: V3,
) {
    // getJumpPower(amount): no jump boost on a mount.
    let impulse = t.p.attributes.jump_strength.value() as f32 * amount * t.block_jump_factor();
    let v = t.p.vel;
    t.p.vel = [v[0], f64::from(impulse), v[2]];
    if input.z > 0.0 {
        let r = t.p.yaw * DEG_TO_RAD;
        let sin = m::sin(f64::from(r));
        let cos = m::cos(f64::from(r));
        let add = V3::new(
            f64::from(-0.4f32 * sin * amount),
            0.0,
            f64::from(0.4f32 * cos * amount),
        );
        t.p.vel = V3::of(t.p.vel).add(add).arr();
    }
}