ghast-physics 0.5.4

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
//! Living mounts the local player rides, as the 1.12.2 client ticks them: the horse family
//! (horse, donkey, mule, skeleton and zombie horse), the llama and the pig.
//!
//! # Who moves the mount
//!
//! The client moves every living mount whose first passenger is the local player: those mounts
//! name their first passenger as the controlling one (`getPrimaryPassenger`), so
//! `Entity.method_13003` ("the passenger steers") holds on the client. Such a mount skips the
//! interpolation towards the server's position packets, runs its own travel and is reported to
//! the server with `vehicle_move` every tick. Whether the rider's keys reach the travel is a
//! second question (`canBeControlledByRider` and the saddle):
//!
//! * **Horse family** with the saddle bit (4) of its status byte: steered by the rider's
//!   sideways (×0.5) and forward input (backwards ×0.25), turned to the rider's yaw (pitch ×0.5),
//!   with the rider's jump bar. Without a saddle it travels on its own (no input of its own on the
//!   client: it falls, slides and keeps what its last steered tick left in its forward input).
//! * **Llama**: never steered (`canBeControlledByRider` is false), the client still moves it.
//! * **Pig**: steered while the rider holds a carrot on a stick in either hand (the saddle does
//!   not matter for the travel): always forward at the speed attribute × 0.225, faster during a
//!   boost the server starts with the pig's boost-time entity data; step height 1.0 (0.5
//!   unsteered).
//!
//! # A tick while riding, in vanilla order
//!
//! 1. The mount's tick (`LivingEntity.tick`): its base tick (water contact and flow push, lava),
//!    the jump cool-down, its velocity ×0.98 (the client copy of a mob that does not move
//!    voluntarily), the 0.003 cut-off, its own (decaying) input, then the travel of its kind
//!    (above), the body rotation (`BodyControl`) and, for the horse family, the rearing counter
//!    and animation.
//! 2. The passenger's tick (`tickRiding`): the whole player tick as a passenger, with the jump bar
//!    of a saddled horse; a released bar sends `entity_action` `start_riding_jump` (strength =
//!    bar × 100) and sets the horse's jump power (it rears and jumps on its next tick while on
//!    the ground). Then `look`, `steer_vehicle` and `vehicle_move` with the mount's position and
//!    rotation.
//! 3. The seat (`updatePassengerPosition`): `mount y + mounted offset − 0.35` (height × 0.75 for
//!    the horse family and the pig, − 0.1875 more for a skeleton horse, height × 0.67 and 0.3
//!    forward along the body yaw for a llama); a rearing horse moves its rider forward and up by
//!    the previous tick's rearing amount. The rider's fall distance is reset.
//!
//! The 1.12 client never dismounts by itself: sneaking only reaches the server in
//! `steer_vehicle`, whose `set_passengers` then takes the player off.

use ghast_data::v1_12::BlockState;

use super::ext::PlayerExt;
use super::player::{PlayerState, box_at, mount_base_tick, mount_travel, tick_mount_passenger};
use crate::attribute::Modifiers;
use crate::input::{Packet, Packets, TickInput};
use crate::math::{self, Aabb};
use crate::rotation::wrap_degrees;
use crate::world::BlockView;

const DEG_TO_RAD: f32 = (std::f64::consts::PI / 180.0) as f32;

/// Horse status bit: tame.
pub const HORSE_TAME: u8 = 2;
/// Horse status bit: saddled (the rider steers).
pub const HORSE_SADDLED: u8 = 4;
/// Horse status bit: eating (movement blocked).
pub const HORSE_EATING: u8 = 16;
/// Horse status bit: rearing (movement blocked on the ground).
pub const HORSE_REARING: u8 = 32;

/// The kind of a living mount.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum MountKind {
    /// `horse`.
    Horse,
    /// `donkey`.
    Donkey,
    /// `mule`.
    Mule,
    /// `skeleton_horse`.
    SkeletonHorse,
    /// `zombie_horse`.
    ZombieHorse,
    /// `llama` (never steered).
    Llama,
    /// `pig` (steered with a carrot on a stick).
    Pig,
}

impl MountKind {
    /// The kind of a 1.12 entity registry name (`"horse"`, `"llama"`, ...), if it is a mount.
    #[must_use]
    pub fn from_name(name: &str) -> Option<MountKind> {
        Some(match name {
            "horse" => MountKind::Horse,
            "donkey" => MountKind::Donkey,
            "mule" => MountKind::Mule,
            "skeleton_horse" => MountKind::SkeletonHorse,
            "zombie_horse" => MountKind::ZombieHorse,
            "llama" => MountKind::Llama,
            "pig" => MountKind::Pig,
            _ => return None,
        })
    }

    /// A member of the horse family (`AbstractHorseEntity`: status byte, jump strength, step
    /// height 1.0); the llama is one too.
    #[must_use]
    pub fn horse_family(self) -> bool {
        !matches!(self, MountKind::Pig)
    }

    /// Box width and height (adults).
    #[must_use]
    pub fn size(self) -> (f32, f32) {
        match self {
            MountKind::Llama => (0.9, 1.87),
            MountKind::Pig => (0.9, 0.9),
            _ => (1.396_484_4, 1.6),
        }
    }
}

/// The rider's jump bar (`ClientPlayerEntity.field_6449` / `field_6450`): the 1.12 client keeps
/// the counter between rides (it is only touched while riding a saddled horse); the bar is 0 in
/// every tick that is not.
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RiderJump {
    /// Ticks the key is held (counting up), or the cool-down after a release (−10 up to 0).
    pub ticks: i32,
    /// The bar (0 to 1).
    pub bar: f32,
}

impl RiderJump {
    /// One tick of the bar. `horse`: the rider sits on a saddled horse-family mount. Returns the
    /// released strength (bar × 100, floored) when the key was let go.
    pub(super) fn tick(&mut self, horse: bool, prev: bool, now: bool) -> Option<i32> {
        if !horse {
            self.bar = 0.0;
            return None;
        }
        if self.ticks < 0 {
            self.ticks += 1;
            if self.ticks == 0 {
                self.bar = 0.0;
            }
        }
        if prev && !now {
            self.ticks = -10;
            return Some(floor_f32(self.bar * 100.0));
        }
        if !prev && now {
            self.ticks = 0;
            self.bar = 0.0;
        } else if prev {
            self.ticks += 1;
            self.bar = if self.ticks < 10 {
                self.ticks as f32 * 0.1
            } else {
                0.8 + 2.0 / (self.ticks - 9) as f32 * 0.1
            };
        }
        None
    }
}

/// `EntityTracker.method_12764`: `lfloor(v * 4096)`.
fn fixed(v: f64) -> i64 {
    (v * 4096.0).floor() as i64
}

/// An angle byte as `float` degrees (`byte * 360 / 256.0F`).
fn angle(b: i8) -> f32 {
    (i32::from(b) * 360) as f32 / 256.0
}

/// `MathHelper.wrapDegrees(double)`.
fn wrap_degrees_f64(d: f64) -> f64 {
    let mut e = d % 360.0;
    if e >= 180.0 {
        e -= 360.0;
    }
    if e < -180.0 {
        e += 360.0;
    }
    e
}

/// `MathHelper.floor(float)`.
fn floor_f32(v: f32) -> i32 {
    let i = v as i32;
    if v < i as f32 { i - 1 } else { i }
}

/// A living mount the local player rides (as its first passenger). Create it from the spawn
/// packet ([`Mount::new`]), then give it the server's entity data and attributes.
#[derive(Clone, Debug, PartialEq)]
pub struct Mount {
    kind: MountKind,
    /// The movement body: position, box, velocity, rotation, ground and collision flags, fall
    /// distance, cobweb and water contact, jump cool-down, its own input (`sideways_speed`,
    /// `forward_speed`, `upward_speed`) and air acceleration (`flying_speed`).
    body: PlayerState,
    /// Body yaw.
    pub body_yaw: f32,
    /// Head yaw.
    pub head_yaw: f32,
    body_ticks: i32,
    body_last_head_yaw: f32,
    /// The horse status byte (entity data; bits [`HORSE_SADDLED`], [`HORSE_REARING`], ...).
    pub flags: u8,
    /// The pig's saddle (entity data; informational, the travel does not read it).
    pub saddled: bool,
    /// The rider holds a carrot on a stick in either hand (kept by the caller; steers a pig).
    pub carrot: bool,
    speed_base: f64,
    speed_modifiers: Modifiers,
    jump_base: f64,
    /// The movement speed field (`getMovementSpeed`): set by the steered travel, read as the
    /// ground speed and, one tick late, as the air acceleration.
    movement_speed: f32,
    step_height: f32,
    jump_power: f32,
    horse_jumping: bool,
    stand_sliding: bool,
    rear_ticks: i32,
    rear_amount: f32,
    prev_rear_amount: f32,
    boosting: bool,
    boost_ticks: i32,
    boost_total: i32,
    /// The server's position in 1/4096 blocks (`tracedX`...).
    tracked: [i64; 3],
    /// Interpolation towards the server: target, yaw, pitch, steps left (unsteered mounts).
    lerp: ([f64; 3], f32, f32, i32),
    /// The local player is its first passenger ([`Mount::new`]); `false` for a mount the client
    /// only watches ([`Mount::watched`]) until [`Mount::board`].
    passenger: bool,
}

impl Mount {
    /// A mount as the spawn-mob packet creates it: at `pos` with the packet's angles (decoded
    /// from the angle bytes: `byte * 360 / 256`) and velocity (raw / 8000). The default entity
    /// data (no flags, no saddle, pig boost time 0) is applied as the packet's entity data
    /// would; call [`Mount::apply_flags`], [`Mount::apply_boost`] for the packet's values.
    #[must_use]
    pub fn new(
        kind: MountKind,
        pos: [f64; 3],
        yaw: f32,
        pitch: f32,
        head_yaw: f32,
        vel: [f64; 3],
    ) -> Mount {
        let (w, h) = kind.size();
        let pitch = pitch.clamp(-90.0, 90.0);
        let mut body = PlayerState::new(pos, yaw % 360.0, pitch % 360.0);
        body.width = w;
        body.height = h;
        body.bb = box_at(pos[0], pos[1], pos[2], w, h);
        body.vel = vel;
        body.flying_speed = 0.02;
        body.movement_speed_base = 0.0;
        body.speed_modifiers = Modifiers::NONE;
        body.food_level = 0;
        let (speed, jump) = match kind {
            MountKind::Pig => (0.25, 0.0),
            MountKind::SkeletonHorse | MountKind::ZombieHorse => (f64::from(0.2f32), 0.7),
            _ => (0.2, 0.7),
        };
        let mut m = Mount {
            kind,
            body,
            body_yaw: head_yaw,
            head_yaw,
            body_ticks: 0,
            body_last_head_yaw: 0.0,
            flags: 0,
            saddled: false,
            carrot: false,
            speed_base: speed,
            speed_modifiers: Modifiers::NONE,
            jump_base: jump,
            movement_speed: 0.0,
            step_height: if kind.horse_family() { 1.0 } else { 0.6 },
            jump_power: 0.0,
            horse_jumping: false,
            stand_sliding: false,
            rear_ticks: 0,
            rear_amount: 0.0,
            prev_rear_amount: 0.0,
            boosting: false,
            boost_ticks: 0,
            boost_total: 0,
            tracked: pos.map(fixed),
            lerp: (pos, yaw, pitch, 0),
            passenger: true,
        };
        if kind == MountKind::Pig {
            // The spawn packet carries every entry; the boost time's handler starts a boost of 0.
            m.apply_boost(0);
        }
        m
    }

    /// A mount the client only watches (no rider), as the spawn-mob packet creates it (see
    /// [`Mount::new`]; `vel` from the packet's velocity: `raw / 8000.0F`, in `float`). Feed it the
    /// server's packets and tick it with [`tick_watched`] every client tick: it then holds what
    /// the real client holds when the player boards it ([`Mount::board`]): the interpolation
    /// towards the server and its steps left, the velocity of the server's velocity packets
    /// (×0.98 on ticks without an interpolation step, cut off below 0.003), the mob's own pushes
    /// on the player, the ground flag of the last packet, body and head yaw, the rearing.
    #[must_use]
    pub fn watched(
        kind: MountKind,
        pos: [f64; 3],
        yaw: f32,
        pitch: f32,
        head_yaw: f32,
        vel: [f64; 3],
    ) -> Mount {
        let mut m = Mount::new(kind, pos, yaw, pitch, head_yaw, vel);
        m.passenger = false;
        m
    }

    /// The local player became its first passenger (`set_passengers`).
    pub fn board(&mut self) {
        self.passenger = true;
    }

    /// The local player is no longer its passenger: from now on it is only watched.
    pub fn leave(&mut self) {
        self.passenger = false;
    }

    /// The local player is its first passenger.
    #[must_use]
    pub fn ridden(&self) -> bool {
        self.passenger
    }

    /// The server's velocity packet (`setVelocityClient`, units of 1/8000).
    pub fn server_velocity(&mut self, x: i16, y: i16, z: i16) {
        self.body.vel = [x, y, z].map(|v| f64::from(v) / 8000.0);
    }

    /// The mob pushed the local player in its tick (`tickCramming` → `player.pushAwayFrom(mob)`):
    /// `player` is the velocity the player took ([`push_by_with`](super::push_by_with)); the mob
    /// takes the opposite (`addVelocity`).
    pub fn pushed_player(&mut self, player: [f64; 2]) {
        let v = &mut self.body.vel;
        v[0] += -player[0];
        v[1] += 0.0;
        v[2] += -player[1];
        self.body.velocity_dirty = true;
    }

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

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

    /// Box.
    #[must_use]
    pub fn bb(&self) -> Aabb {
        self.body.bb
    }

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

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

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

    /// On the ground after its last move.
    #[must_use]
    pub fn on_ground(&self) -> bool {
        self.body.on_ground
    }

    /// The movement body (position, box, velocity, flags, own input) for inspection.
    #[must_use]
    pub fn body(&self) -> &PlayerState {
        &self.body
    }

    /// Step height of the last travel.
    #[must_use]
    pub fn step_height(&self) -> f32 {
        self.step_height
    }

    /// The movement speed field (see the struct docs).
    #[must_use]
    pub fn movement_speed(&self) -> f32 {
        self.movement_speed
    }

    /// The movement speed attribute value.
    #[must_use]
    pub fn speed_attr(&self) -> f64 {
        self.speed_modifiers.value(self.speed_base)
    }

    /// The jump strength attribute value (horse family; clamped to 0..2).
    #[must_use]
    pub fn jump_strength(&self) -> f64 {
        self.jump_base.clamp(0.0, 2.0)
    }

    /// The pending jump power (`field_15492`), the horse is in a jump (`field_15489`), it may
    /// slide while rearing (`field_15501`).
    #[must_use]
    pub fn jump_state(&self) -> (f32, bool, bool) {
        (self.jump_power, self.horse_jumping, self.stand_sliding)
    }

    /// The rearing counter and the rearing amount after and before the last tick.
    #[must_use]
    pub fn rearing(&self) -> (i32, f32, f32) {
        (self.rear_ticks, self.rear_amount, self.prev_rear_amount)
    }

    /// The pig's boost: running, ticks into it, its length.
    #[must_use]
    pub fn boost(&self) -> (bool, i32, i32) {
        (self.boosting, self.boost_ticks, self.boost_total)
    }

    /// The body rotation state (`BodyControl`): ticks standing still, the head yaw it follows.
    #[must_use]
    pub fn body_control(&self) -> (i32, f32) {
        (self.body_ticks, self.body_last_head_yaw)
    }

    /// The client moves this mount (`MobEntity.method_13003`: `canBeControlledByRider` with the
    /// local player as the first passenger): the horse family but the llama, a pig while the
    /// rider holds a carrot on a stick. Such a mount ignores the server's position packets and is
    /// reported with `vehicle_move`; any other follows the server's packets (interpolated).
    #[must_use]
    pub fn steered(&self) -> bool {
        if !self.passenger {
            return false;
        }
        match self.kind {
            MountKind::Llama => false,
            MountKind::Pig => self.carrot,
            _ => true,
        }
    }

    /// The rider's keys reach the travel: a steered pig, a steered horse with its saddle.
    fn keys_steer(&self) -> bool {
        if !self.passenger {
            return false;
        }
        match self.kind {
            MountKind::Llama => false,
            MountKind::Pig => self.carrot,
            _ => self.flags & HORSE_SADDLED != 0,
        }
    }

    /// The rider's jump bar is active (`isRidingHorse`: a saddled horse-family mount).
    #[must_use]
    pub fn jumping_mount(&self) -> bool {
        self.kind.horse_family() && self.flags & HORSE_SADDLED != 0
    }

    /// Entity data: the horse status byte.
    pub fn apply_flags(&mut self, flags: u8) {
        self.flags = flags;
    }

    /// Entity data: the pig's saddle.
    pub fn apply_saddle(&mut self, saddled: bool) {
        self.saddled = saddled;
    }

    /// Entity data: the pig's boost time (`onTrackedDataSet`: a boost of that length starts).
    pub fn apply_boost(&mut self, time: i32) {
        if self.kind == MountKind::Pig {
            self.boosting = true;
            self.boost_ticks = 0;
            self.boost_total = time;
        }
    }

    /// Entity properties: the movement speed attribute (base and every modifier,
    /// `(uuid, amount, operation)` in packet order).
    pub fn apply_speed_attribute(&mut self, base: f64, modifiers: &[(u128, f64, u8)]) {
        self.speed_base = base;
        self.speed_modifiers.clear();
        for &(uuid, amount, op) in modifiers {
            self.speed_modifiers.insert(uuid, amount, op);
        }
    }

    /// Entity properties: the jump strength base (`horse.jumpStrength`).
    pub fn apply_jump_strength(&mut self, base: f64) {
        self.jump_base = base;
    }

    /// The server's entity teleport of the mount (`onEntityPosition`): the position and the
    /// angle bytes. A steered mount only keeps the 1/4096 server position; any other is moved
    /// there over 3 ticks (within 1/32, 1/64 vertically, it only turns).
    pub fn server_teleport(&mut self, pos: [f64; 3], yaw: i8, pitch: i8, on_ground: bool) {
        self.tracked = pos.map(fixed);
        if self.steered() {
            return;
        }
        let (yaw, pitch) = (angle(yaw), angle(pitch));
        let b = &self.body;
        #[allow(clippy::neg_cmp_op_on_partial_ord)]
        let near = !((b.pos[0] - pos[0]).abs() >= 0.03125)
            && !((b.pos[1] - pos[1]).abs() >= 0.015625)
            && !((b.pos[2] - pos[2]).abs() >= 0.03125);
        if near {
            self.lerp = (b.pos, yaw, pitch, 0);
        } else {
            self.lerp = (pos, yaw, pitch, 3);
        }
        self.body.on_ground = on_ground;
    }

    /// The server's relative move, look, move-look or bare entity packet of the mount
    /// (`onEntityUpdate`): `delta` in 1/4096 blocks, `rotation` the angle bytes when the packet
    /// has them. A steered mount only keeps the server position.
    pub fn server_update(&mut self, delta: [i16; 3], rotation: Option<(i8, i8)>, on_ground: bool) {
        for (t, d) in self.tracked.iter_mut().zip(delta) {
            *t += i64::from(d);
        }
        if self.steered() {
            return;
        }
        let target = self.tracked.map(|v| v as f64 / 4096.0);
        let (yaw, pitch) = rotation.map_or((self.body.yaw, self.body.pitch), |(y, p)| {
            (angle(y), angle(p))
        });
        self.lerp = (target, yaw, pitch, 3);
        self.body.on_ground = on_ground;
    }

    /// The server's position of the mount in 1/4096 blocks (what relative moves add to).
    #[must_use]
    pub fn tracked(&self) -> [i64; 3] {
        self.tracked
    }

    /// Sets the server's position of the mount in 1/4096 blocks (a mount created where the
    /// client has it, after the server moved it).
    pub fn set_tracked(&mut self, tracked: [i64; 3]) {
        self.tracked = tracked;
    }

    /// The server's head-look packet (`onEntitySetHeadYaw`).
    pub fn server_head_yaw(&mut self, yaw: i8) {
        self.head_yaw = angle(yaw);
    }

    /// Steps of the interpolation towards the server's position left (unsteered mounts).
    #[must_use]
    pub fn interpolation_steps(&self) -> i32 {
        self.lerp.3
    }

    /// Sets the interpolation towards the server (`updateTrackedPositionAndAngles`): what the
    /// client's copy of the mob had pending when the player boarded it. It is kept while the
    /// mount is steered and resumes when it no longer is.
    pub fn set_interpolation(&mut self, target: [f64; 3], yaw: f32, pitch: f32, steps: i32) {
        self.lerp = (target, yaw, pitch, steps);
    }

    /// The position the interpolation towards the server goes to (unsteered mounts; see
    /// [`Mount::interpolation_steps`]).
    #[must_use]
    pub fn interpolation_target(&self) -> [f64; 3] {
        self.lerp.0
    }

    /// The server's `vehicle_move` (`onVehicleMove`: `updatePositionAndAngles` of a steered
    /// mount); returns the `vehicle_move` the client answers with at once, `None` for a mount the
    /// client does not move (the packet is ignored).
    pub fn server_move(&mut self, pos: [f64; 3], yaw: f32, pitch: f32) -> Option<Packet> {
        if !self.steered() {
            return None;
        }
        let b = &mut self.body;
        b.yaw = yaw % 360.0;
        b.pitch = pitch.clamp(-90.0, 90.0) % 360.0;
        b.set_position(
            pos[0].clamp(-3.0e7, 3.0e7),
            pos[1],
            pos[2].clamp(-3.0e7, 3.0e7),
        );
        Some(self.vehicle_move())
    }

    /// The client's `vehicle_move` packet for this mount.
    #[must_use]
    pub fn vehicle_move(&self) -> Packet {
        Packet::MoveVehicle {
            pos: self.body.pos,
            yaw: self.body.yaw,
            pitch: self.body.pitch,
            on_ground: self.body.on_ground,
        }
    }

    /// `AbstractHorseEntity.setJumpPower`: the released jump bar of the rider (×100).
    fn set_jump_power(&mut self, strength: i32) {
        if self.flags & HORSE_SADDLED == 0 {
            return;
        }
        let mut i = strength;
        if i < 0 {
            i = 0;
        } else {
            self.stand_sliding = true;
            // A mount the client moves rears (eating stops); a llama does not.
            if self.steered() {
                self.rear_ticks = 1;
                self.flags = (self.flags & !HORSE_EATING) | HORSE_REARING;
            }
        }
        self.jump_power = if i >= 90 {
            1.0
        } else {
            0.4 + 0.4 * i as f32 / 90.0
        };
    }

    /// `isMovementBlocked` (the mount's own input is dropped). Health is taken as positive.
    fn movement_blocked(&self) -> bool {
        match self.kind {
            MountKind::Pig => false,
            MountKind::Llama => self.flags & HORSE_EATING != 0,
            _ => self.flags & (HORSE_EATING | HORSE_REARING) != 0,
        }
    }

    /// The passenger's position after the mount's tick (`updatePassengerPosition`).
    #[must_use]
    pub fn passenger_pos(&self) -> [f64; 3] {
        let [x, y, z] = self.body.pos;
        let h = self.body.height;
        let rider = -0.35;
        match self.kind {
            MountKind::Llama => {
                let f = math::cos(self.body_yaw * DEG_TO_RAD);
                let g = math::sin(self.body_yaw * DEG_TO_RAD);
                let off = f64::from(h) * 0.67;
                [
                    x + f64::from(0.3 * g),
                    y + off + rider,
                    z - f64::from(0.3 * f),
                ]
            }
            MountKind::Pig => [x, y + f64::from(h) * 0.75 + rider, z],
            _ => {
                let mut off = f64::from(h) * 0.75;
                match self.kind {
                    MountKind::SkeletonHorse => off -= 0.1875,
                    // The chested horses (`class_3135`).
                    MountKind::Donkey | MountKind::Mule => off -= 0.25,
                    _ => {}
                }
                let prev = self.prev_rear_amount;
                if prev > 0.0 {
                    let f = math::sin(self.body_yaw * DEG_TO_RAD);
                    let g = math::cos(self.body_yaw * DEG_TO_RAD);
                    let hh = 0.7 * prev;
                    let ii = 0.15 * prev;
                    [
                        x + f64::from(hh * f),
                        y + off + rider + f64::from(ii),
                        z - f64::from(hh * g),
                    ]
                } else {
                    [x, y + off + rider, z]
                }
            }
        }
    }
}

/// One client tick while riding `mount` (the module docs list the steps): the mount's tick (with
/// `mount_entities`: the boxes it collides with, i.e. boats and live shulkers near it), the
/// player's passenger tick (with `entities`: the boxes the player collides with) including the
/// jump bar, `vehicle_move`, the seat. `bar` is the rider's jump bar (kept by the caller across
/// rides). Packets in vanilla order: `start_riding_jump` (on a release), `look`,
/// `steer_vehicle`, `vehicle_move`.
#[allow(clippy::too_many_arguments)]
pub fn tick_mount<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    x: &mut PlayerExt,
    bar: &mut RiderJump,
    mount: &mut Mount,
    entities: &[Aabb],
    mount_entities: &[Aabb],
    input: &TickInput,
    world: &W,
    out: &mut Packets,
) {
    // The mount ticks first, with the rider's rotation of this tick (the mouse turned it before
    // the world tick) and its input of the last tick.
    mount_tick(
        mount,
        input.yaw,
        input.pitch,
        p.sideways_speed,
        p.forward_speed,
        world,
        mount_entities,
    );
    let horse = mount.jumping_mount();
    let release = tick_mount_passenger(p, x, bar, horse, entities, input, world, out);
    if let Some(strength) = release {
        mount.set_jump_power(strength);
    }
    if mount.steered() {
        out.push(mount.vehicle_move());
    }
    let [sx, sy, sz] = mount.passenger_pos();
    p.set_position(sx, sy, sz);
    p.fall_distance = 0.0;
}

/// One client tick of a mount the client only watches ([`Mount::watched`]): the same mob tick
/// as under a rider that does not steer it (interpolation step or velocity decay, the cut-off,
/// fluid contact, body turn, rearing). Then call [`Mount::pushed_player`] if the mob pushed the
/// player in this tick (`tickCramming`, at the end of its movement tick).
pub fn tick_watched<W: BlockView<State = BlockState>>(m: &mut Mount, world: &W) {
    mount_tick(m, 0.0, 0.0, 0.0, 0.0, world, &[]);
}

/// The mount's own tick (`LivingEntity.tick` with the local player as its first passenger).
fn mount_tick<W: BlockView<State = BlockState>>(
    m: &mut Mount,
    rider_yaw: f32,
    rider_pitch: f32,
    rider_sideways: f32,
    rider_forward: f32,
    world: &W,
    entities: &[Aabb],
) {
    let start = m.body.pos;
    mount_base_tick(&mut m.body, world);
    let blocked = m.movement_blocked();
    let steered = m.steered();
    let b = &mut m.body;
    if b.jump_cooldown > 0 {
        b.jump_cooldown -= 1;
    }
    let (target, tyaw, tpitch, steps) = m.lerp;
    if steps > 0 && !steered {
        // One interpolation step towards the server's position.
        let n = f64::from(steps);
        let x = b.pos[0] + (target[0] - b.pos[0]) / n;
        let y = b.pos[1] + (target[1] - b.pos[1]) / n;
        let z = b.pos[2] + (target[2] - b.pos[2]) / n;
        let g = wrap_degrees_f64(f64::from(tyaw) - f64::from(b.yaw));
        b.yaw = (f64::from(b.yaw) + g / n) as f32;
        b.pitch = (f64::from(b.pitch) + (f64::from(tpitch) - f64::from(b.pitch)) / n) as f32;
        m.lerp.3 = steps - 1;
        b.set_position(x, y, z);
        b.yaw %= 360.0;
        b.pitch %= 360.0;
    } else {
        // The client copy of a mob that does not move voluntarily decays its velocity.
        for v in &mut b.vel {
            *v *= 0.98;
        }
    }
    for v in &mut b.vel {
        if v.abs() < 0.003 {
            *v = 0.0;
        }
    }
    if blocked {
        b.sideways_speed = 0.0;
        b.forward_speed = 0.0;
    }
    // Its own jump key is never pressed on the client.
    b.jump_cooldown = 0;
    b.sideways_speed *= 0.98;
    b.forward_speed *= 0.98;
    travel(
        m,
        rider_yaw,
        rider_pitch,
        rider_sideways,
        rider_forward,
        world,
        entities,
    );
    let [x, _, z] = m.body.pos;
    body_control(m, x - start[0], z - start[2]);
    if m.kind.horse_family() {
        rear_tick(m, steered);
    }
}

/// The travel of the mount's kind (`AbstractHorseEntity.method_2657`, `PigEntity.method_2657`).
fn travel<W: BlockView<State = BlockState>>(
    m: &mut Mount,
    rider_yaw: f32,
    rider_pitch: f32,
    rider_sideways: f32,
    rider_forward: f32,
    world: &W,
    entities: &[Aabb],
) {
    if !m.keys_steer() {
        if m.kind == MountKind::Pig {
            m.step_height = 0.5;
        }
        m.body.flying_speed = 0.02;
        // `LivingEntity.travel` moves only a mount the client moves.
        if m.steered() {
            own_travel(m, world, entities);
        }
        return;
    }
    {
        let b = &mut m.body;
        b.yaw = rider_yaw % 360.0;
        b.pitch = (rider_pitch * 0.5) % 360.0;
        m.body_yaw = b.yaw;
        m.head_yaw = b.yaw;
    }
    if m.kind == MountKind::Pig {
        m.step_height = 1.0;
        m.body.flying_speed = m.movement_speed * 0.1;
        if m.boosting {
            let t = m.boost_ticks;
            m.boost_ticks += 1;
            if t > m.boost_total {
                m.boosting = false;
            }
        }
        let mut speed = m.speed_attr() as f32 * 0.225;
        if m.boosting {
            let a = m.boost_ticks as f32 / m.boost_total as f32 * std::f32::consts::PI;
            speed += speed * 1.15 * math::sin(a);
        }
        set_speed(m, speed);
        let step = m.step_height;
        mount_travel(&mut m.body, 0.0, 0.0, 1.0, step, true, entities, world);
        return;
    }
    let mut strafe = rider_sideways * 0.5;
    let mut forward = rider_forward;
    if forward <= 0.0 {
        forward *= 0.25;
    }
    let b = &mut m.body;
    if b.on_ground && m.jump_power == 0.0 && m.flags & HORSE_REARING != 0 && !m.stand_sliding {
        strafe = 0.0;
        forward = 0.0;
    }
    if m.jump_power > 0.0 && !m.horse_jumping && b.on_ground {
        b.vel[1] = m.jump_base.clamp(0.0, 2.0) * f64::from(m.jump_power);
        b.velocity_dirty = true;
        m.horse_jumping = true;
        if forward > 0.0 {
            let s = math::sin(b.yaw * DEG_TO_RAD);
            let c = math::cos(b.yaw * DEG_TO_RAD);
            b.vel[0] += f64::from(-0.4 * s * m.jump_power);
            b.vel[2] += f64::from(0.4 * c * m.jump_power);
        }
        m.jump_power = 0.0;
    }
    m.body.flying_speed = m.movement_speed * 0.1;
    let speed = m.speed_attr() as f32;
    set_speed(m, speed);
    let up = m.body.upward_speed;
    mount_travel(
        &mut m.body,
        strafe,
        up,
        forward,
        1.0,
        false,
        entities,
        world,
    );
    if m.body.on_ground {
        m.jump_power = 0.0;
        m.horse_jumping = false;
    }
}

/// `MobEntity.setMovementSpeed`: the speed field and the mob's own forward input.
fn set_speed(m: &mut Mount, speed: f32) {
    m.movement_speed = speed;
    m.body.forward_speed = speed;
    m.body.movement_speed_base = f64::from(speed);
}

/// The plain living travel with the mount's own input (unsteered).
fn own_travel<W: BlockView<State = BlockState>>(m: &mut Mount, world: &W, entities: &[Aabb]) {
    m.body.movement_speed_base = f64::from(m.movement_speed);
    let b = &mut m.body;
    let (s, u, f) = (b.sideways_speed, b.upward_speed, b.forward_speed);
    let climb = m.kind == MountKind::Pig;
    let step = if m.kind.horse_family() {
        1.0
    } else {
        m.step_height
    };
    mount_travel(b, s, u, f, step, climb, entities, world);
}

/// `BodyControl.tick` after the travel (`dx`, `dz`: this tick's horizontal move).
fn body_control(m: &mut Mount, dx: f64, dz: f64) {
    if dx * dx + dz * dz > f64::from(2.500_000_3e-7f32) {
        m.body_yaw = m.body.yaw;
        m.head_yaw = clamp_and_wrap(m.body_yaw, m.head_yaw, 75.0);
        m.body_last_head_yaw = m.head_yaw;
        m.body_ticks = 0;
        return;
    }
    // The passenger is a player, not a mob.
    let mut limit = 75.0f32;
    if (m.head_yaw - m.body_last_head_yaw).abs() > 15.0 {
        m.body_ticks = 0;
        m.body_last_head_yaw = m.head_yaw;
    } else {
        m.body_ticks += 1;
        if m.body_ticks > 10 {
            limit = (1.0 - (m.body_ticks - 10) as f32 / 10.0).max(0.0) * 75.0;
        }
    }
    m.body_yaw = clamp_and_wrap(m.head_yaw, m.body_yaw, limit);
}

/// `BodyControl.clampAndWrapAngle`.
fn clamp_and_wrap(from: f32, to: f32, max: f32) -> f32 {
    let mut f = wrap_degrees(from - to);
    if f < -max {
        f = -max;
    }
    if f >= max {
        f = max;
    }
    from - f
}

/// The rearing counter and animation of `AbstractHorseEntity.tick`.
fn rear_tick(m: &mut Mount, steered: bool) {
    if steered && m.rear_ticks > 0 {
        m.rear_ticks += 1;
        if m.rear_ticks > 20 {
            m.rear_ticks = 0;
            m.flags &= !HORSE_REARING;
        }
    }
    m.prev_rear_amount = m.rear_amount;
    if m.flags & HORSE_REARING != 0 {
        m.rear_amount += (1.0 - m.rear_amount) * 0.4 + 0.05;
        if m.rear_amount > 1.0 {
            m.rear_amount = 1.0;
        }
    } else {
        m.stand_sliding = false;
        let a = m.rear_amount;
        m.rear_amount = a + ((0.8 * a * a * a - a) * 0.6 - 0.05);
        if m.rear_amount < 0.0 {
            m.rear_amount = 0.0;
        }
    }
}