ghast-physics 0.5.2

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
//! A living mount the local player rides (horses, donkeys, mules, zombie and skeleton horses,
//! pigs), as the 1.8.9 client ticks it.
//!
//! The 1.8 client never moves a living mob: its walk (`LivingEntity.travel`) only runs on the
//! server, so the server's position packets are all that move it. The client's part, per tick:
//!
//! 1. The mount's tick: one step of the living interpolation towards the server's last position
//!    and rotation (every position packet sets 3 steps; a teleport within 1/32, 1/64
//!    vertically, keeps the client's position). A saddled horse then takes its rider's yaw and
//!    half its pitch (body and head turn with it); every mob's body yaw follows its head and its
//!    motion (`BodyControl`). A horse's rearing animation (horse flag 64) rises or falls.
//! 2. The rider's tick (`Entity.tickRiding`): motion zeroed, the whole player tick (a living
//!    mount has no collision box for its rider), then `look` and `steer_vehicle` instead of the
//!    movement packets. On a saddled horse the tick charges the jump bar while the jump key is
//!    held and sends the riding-jump action when it is let go ([`JumpBar`]).
//! 3. The mount places its rider: `height × 0.75 - 0.35` above its position; a rearing horse
//!    lifts the rider and moves it forward along its body yaw. The fall distance is reset.
//!
//! The server's position of the mount is kept in 1/32 blocks (`trackedX`…), as relative moves
//! add to it.

use ghast_data::v1_8::BlockState;

use super::player::{Options, PlayerState};
use crate::input::{Packet, Packets, TickInput};
use crate::math::{self, Aabb};
use crate::rotation::wrap_degrees;
use crate::world::BlockView;

/// Horse box width (`float`; every kind of the 1.8 horse, adult).
pub const HORSE_WIDTH: f32 = 1.4;
/// Horse box height (`float`).
pub const HORSE_HEIGHT: f32 = 1.6;
/// Pig box width (`float`).
pub const PIG_WIDTH: f32 = 0.9;
/// Pig box height (`float`).
pub const PIG_HEIGHT: f32 = 0.9;

/// Horse entity-data flag (index 16): saddled.
pub const HORSE_SADDLED: i32 = 4;
/// Horse entity-data flag (index 16): rearing.
pub const HORSE_REARING: i32 = 64;

/// What kind of living mount it is (the 1.8 horse kinds share one class).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum MountKind {
    /// Horse, donkey, mule, zombie or skeleton horse (spawn-mob type 100), adult.
    Horse,
    /// Pig (spawn-mob type 90), adult.
    Pig,
}

impl MountKind {
    /// The kind of a 1.8 spawn-mob type id (`None`: not modelled).
    #[must_use]
    pub fn of_mob_type(id: u8) -> Option<MountKind> {
        match id {
            100 => Some(MountKind::Horse),
            90 => Some(MountKind::Pig),
            _ => None,
        }
    }

    fn size(self) -> (f32, f32) {
        match self {
            MountKind::Horse => (HORSE_WIDTH, HORSE_HEIGHT),
            MountKind::Pig => (PIG_WIDTH, PIG_HEIGHT),
        }
    }
}

/// The client player's horse jump bar (`ClientPlayerEntity`'s jump counter and strength). It
/// belongs to the player and outlives a ride: keep one per player and pass it to every
/// [`tick_mount`]; call [`JumpBar::idle`] on every other tick (walking, a boat, a minecart).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct JumpBar {
    /// Ticks the jump key has been held (`-10` after a jump, counting back to 0).
    pub counter: i32,
    /// The bar, 0 to 1 (what the riding-jump action sends ×100).
    pub strength: f32,
}

impl JumpBar {
    /// A tick that is not on a saddled horse: the bar is empty (the counter is kept).
    #[inline]
    pub fn idle(&mut self) {
        self.strength = 0.0;
    }

    /// The rider's tick on a saddled horse, before its travel: `was` / `now` are the jump key
    /// of the previous and this tick's input.
    pub(super) fn tick(&mut self, was: bool, now: bool, out: &mut Packets) {
        if self.counter < 0 {
            self.counter += 1;
            if self.counter == 0 {
                self.strength = 0.0;
            }
        }
        if was && !now {
            self.counter = -10;
            out.push(Packet::StartRidingJump {
                strength: (self.strength * 100.0) as i32,
            });
        } else if !was && now {
            self.counter = 0;
            self.strength = 0.0;
        } else if was {
            self.counter += 1;
            self.strength = if self.counter < 10 {
                self.counter as f32 * 0.1
            } else {
                0.8 + 2.0 / (self.counter - 9) as f32 * 0.1
            };
        }
    }
}

/// A living mount the player rides. Create it where the client has it ([`Mount::new`] or
/// [`Mount::spawned`]), then feed it the server's packets for it.
#[derive(Clone, Debug, PartialEq)]
pub struct Mount {
    /// Kind.
    pub kind: MountKind,
    /// Position.
    pub pos: [f64; 3],
    /// Yaw.
    pub yaw: f32,
    /// Pitch.
    pub pitch: f32,
    /// Head yaw.
    pub head_yaw: f32,
    /// Body yaw.
    pub body_yaw: f32,
    /// On the ground (the server's last position packet's flag).
    pub on_ground: bool,
    /// Saddled (horse flag 4, the pig's saddle byte).
    pub saddled: bool,
    /// Rearing (horse flag 64; never set for a pig).
    pub rearing: bool,
    /// The server's position of it in 1/32 blocks.
    pub tracked: [i32; 3],
    target: [f64; 3],
    target_yaw: f64,
    target_pitch: f64,
    steps: i32,
    /// `BodyControl`: ticks the head has kept still, the head yaw it compares with.
    body_ticks: i32,
    body_last_head_yaw: f32,
    /// Rearing animation (`angryAnimationProgress` and its last value).
    rear: f32,
    last_rear: f32,
}

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

/// `BodyControl.clampAndWrapAngle`.
fn clamp_towards(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
}

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

impl Mount {
    /// A mount at `pos` with a body and head turned to `yaw`, not interpolating, the body
    /// clock as a freshly spawned mob has it; its server position is `pos` (to 1/32).
    #[must_use]
    pub fn new(kind: MountKind, pos: [f64; 3], yaw: f32, pitch: f32) -> Mount {
        Mount {
            kind,
            pos,
            yaw,
            pitch,
            head_yaw: yaw,
            body_yaw: yaw,
            on_ground: false,
            saddled: false,
            rearing: false,
            tracked: pos.map(|v| (v * 32.0).floor() as i32),
            target: pos,
            target_yaw: f64::from(yaw),
            target_pitch: f64::from(pitch),
            steps: 0,
            body_ticks: 0,
            body_last_head_yaw: 0.0,
            rear: 0.0,
            last_rear: 0.0,
        }
    }

    /// A mount as the spawn-mob packet creates it: at the packet's fixed-point position (`/ 32`),
    /// with its angle bytes (body and head from the head byte).
    #[must_use]
    pub fn spawned(kind: MountKind, fixed: [i32; 3], yaw: i8, pitch: i8, head_yaw: i8) -> Mount {
        let mut m = Mount::new(
            kind,
            fixed.map(|v| f64::from(v) / 32.0),
            angle(yaw),
            angle(pitch),
        );
        m.head_yaw = angle(head_yaw);
        m.body_yaw = m.head_yaw;
        m.tracked = fixed;
        m
    }

    /// Continues the client's interpolation that was under way when the player boarded: the
    /// target position and rotation and the steps left.
    pub fn set_interpolation(&mut self, target: [f64; 3], yaw: f32, pitch: f32, steps: i32) {
        self.target = target;
        self.target_yaw = f64::from(yaw);
        self.target_pitch = f64::from(pitch);
        self.steps = steps;
    }

    /// Steps of interpolation left.
    #[must_use]
    pub fn interpolation_steps(&self) -> i32 {
        self.steps
    }

    /// The rearing animation, 0 to 1 (after the mount's last tick).
    #[must_use]
    pub fn rearing_progress(&self) -> f32 {
        self.rear
    }

    /// The box at the mount's position.
    #[must_use]
    pub fn bounding_box(&self) -> Aabb {
        let (w, h) = self.kind.size();
        let r = f64::from(w / 2.0);
        let [x, y, z] = self.pos;
        Aabb::new(x - r, y, z - r, x + r, y + f64::from(h), z + r)
    }

    /// The server's entity-data value at index 16: horse flags (int), pig saddle (byte).
    pub fn set_flags(&mut self, flags: i32) {
        match self.kind {
            MountKind::Horse => {
                self.saddled = flags & HORSE_SADDLED != 0;
                self.rearing = flags & HORSE_REARING != 0;
            }
            MountKind::Pig => self.saddled = flags as u8 & 1 != 0,
        }
    }

    /// `updateTrackedPositionAndAngles(…, 3)` of a living entity.
    fn retarget(&mut self, target: [f64; 3], yaw: f32, pitch: f32) {
        self.target = target;
        self.target_yaw = f64::from(yaw);
        self.target_pitch = f64::from(pitch);
        self.steps = 3;
    }

    /// The server's entity teleport (`onEntityPosition`): fixed-point position, angle bytes,
    /// ground flag.
    pub fn server_teleport(&mut self, fixed: [i32; 3], yaw: i8, pitch: i8, on_ground: bool) {
        self.tracked = fixed;
        let [x, y, z] = fixed.map(|v| f64::from(v) / 32.0);
        #[allow(clippy::neg_cmp_op_on_partial_ord)]
        let near = !((self.pos[0] - x).abs() >= 0.03125)
            && !((self.pos[1] - y).abs() >= 0.015625)
            && !((self.pos[2] - z).abs() >= 0.03125);
        let target = if near { self.pos } else { [x, y, z] };
        self.retarget(target, angle(yaw), angle(pitch));
        self.on_ground = on_ground;
    }

    /// The server's relative move, look, move-look or bare entity packet (`onEntityUpdate`):
    /// `delta` in 1/32 blocks, `rotation` the angle bytes when the packet has them.
    pub fn server_update(&mut self, delta: [i8; 3], rotation: Option<(i8, i8)>, on_ground: bool) {
        for (t, d) in self.tracked.iter_mut().zip(delta) {
            *t += i32::from(d);
        }
        let target = self.tracked.map(|v| f64::from(v) / 32.0);
        let (yaw, pitch) = rotation.map_or((self.yaw, self.pitch), |(y, p)| (angle(y), angle(p)));
        self.retarget(target, yaw, pitch);
        self.on_ground = on_ground;
    }

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

    /// The mount's client tick with its rider's rotation (`ridden`: the local player rides it).
    pub fn tick(&mut self, ridden: Option<(f32, f32)>) {
        let prev = self.pos;
        if self.steps > 0 {
            let n = f64::from(self.steps);
            let x = self.pos[0] + (self.target[0] - self.pos[0]) / n;
            let y = self.pos[1] + (self.target[1] - self.pos[1]) / n;
            let z = self.pos[2] + (self.target[2] - self.pos[2]) / n;
            let g = wrap_degrees_f64(self.target_yaw - f64::from(self.yaw));
            let yaw = (f64::from(self.yaw) + g / n) as f32;
            let pitch =
                (f64::from(self.pitch) + (self.target_pitch - f64::from(self.pitch)) / n) as f32;
            self.steps -= 1;
            self.pos = [x, y, z];
            self.yaw = yaw % 360.0;
            self.pitch = pitch % 360.0;
        }
        // A saddled horse turns with its rider (`HorseBaseEntity.travel`, client side too).
        if let (MountKind::Horse, true, Some((yaw, pitch))) = (self.kind, self.saddled, ridden) {
            self.yaw = yaw % 360.0;
            self.pitch = (pitch * 0.5) % 360.0;
            self.head_yaw = self.yaw;
            self.body_yaw = self.yaw;
        }
        self.body_control(prev);
        if self.kind == MountKind::Horse {
            self.last_rear = self.rear;
            if self.rearing {
                self.rear += (1.0 - self.rear) * 0.4 + 0.05;
                if self.rear > 1.0 {
                    self.rear = 1.0;
                }
            } else {
                self.rear += (0.8 * self.rear * self.rear * self.rear - self.rear) * 0.6 - 0.05;
                if self.rear < 0.0 {
                    self.rear = 0.0;
                }
            }
        }
    }

    /// `BodyControl.tick`: the body turns to the yaw while moving, else follows the head
    /// (within 75 degrees, narrowing after 10 still ticks).
    fn body_control(&mut self, prev: [f64; 3]) {
        let d = self.pos[0] - prev[0];
        let e = self.pos[2] - prev[2];
        if d * d + e * e > f64::from(2.500_000_3e-7_f32) {
            self.body_yaw = self.yaw;
            self.head_yaw = clamp_towards(self.body_yaw, self.head_yaw, 75.0);
            self.body_last_head_yaw = self.head_yaw;
            self.body_ticks = 0;
        } else {
            let mut f = 75.0;
            if (self.head_yaw - self.body_last_head_yaw).abs() > 15.0 {
                self.body_ticks = 0;
                self.body_last_head_yaw = self.head_yaw;
            } else {
                self.body_ticks += 1;
                if self.body_ticks > 10 {
                    f = (1.0 - (self.body_ticks - 10) as f32 / 10.0).max(0.0) * 75.0;
                }
            }
            self.body_yaw = clamp_towards(self.head_yaw, self.body_yaw, f);
        }
    }

    /// The rider's position after the mount's tick (`updatePassengerPosition`).
    #[must_use]
    pub fn passenger_pos(&self) -> [f64; 3] {
        let (_, h) = self.kind.size();
        let base = self.pos[1] + f64::from(h) * 0.75 + -0.35;
        if self.kind == MountKind::Horse && self.last_rear > 0.0 {
            let a = self.body_yaw * std::f32::consts::PI / 180.0;
            let (f, g) = (math::sin(a), math::cos(a));
            let h = 0.7 * self.last_rear;
            let i = 0.15 * self.last_rear;
            return [
                self.pos[0] + f64::from(h * f),
                base + f64::from(i),
                self.pos[2] - f64::from(h * g),
            ];
        }
        [self.pos[0], base, self.pos[2]]
    }

    /// The rider gets the horse jump bar (a saddled horse).
    #[must_use]
    pub fn charges_jumps(&self) -> bool {
        self.kind == MountKind::Horse && self.saddled
    }
}

/// One client tick on a living mount (the module docs list the steps). Packets: the riding
/// jump (a saddled horse, when the jump key is let go), `look`, `steer_vehicle`.
pub fn tick_mount<W: BlockView<State = BlockState>>(
    p: &mut PlayerState,
    mount: &mut Mount,
    bar: &mut JumpBar,
    input: &TickInput,
    world: &W,
    options: &Options,
    out: &mut Packets,
) {
    // The mouse turned the rider before the tick; a saddled horse reads its rotation.
    mount.tick(Some((input.yaw, input.pitch)));
    if mount.charges_jumps() {
        super::player::tick_rider_with_bar(p, input, world, options, &[], Some(bar), out);
    } else {
        bar.idle();
        super::player::tick_rider(p, input, world, options, &[], out);
    }
    let [x, y, z] = mount.passenger_pos();
    p.set_position(x, y, z);
    p.fall_distance = 0.0;
}