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
//! The flying mount: the happy ghast, as the 26.x client ticks it (a child module of `mount`).
//!
//! # Who steers
//!
//! `HappyGhast.getControllingPassenger`: the first passenger when it is a player, the ghast wears
//! a harness (`isWearingBodyArmor`: any item in the body slot, the harness being the only item that
//! fits there) and it is not kept still (`isOnStillTimeout`; on the client that is the
//! `STAYS_STILL` entity data, which the server sets while a player stands on top of the ghast and
//! for ten ticks after a passenger got off). Then the client moves it; otherwise the server does
//! and the client only slows its copy down (x 0.98), like a horse without a saddle.
//!
//! # A tick of a ghast the player steers
//!
//! The order is the horse's ([`tick_mount`](super::tick_mount)); the ghast's own steps:
//!
//! 1. `getRiddenInput` from the rider's previous tick: sideways is the rider's `xxa`; with a
//!    forward or back key the input follows the rider's pitch (`cos` forward, `-sin` up; backwards
//!    half of it reversed); the jump key adds half a unit up. All of it scaled by 3.9 times the
//!    `flying_speed` attribute.
//! 2. `tickRidden`: the ghast turns 8 % of the way to the rider's yaw and takes half its pitch.
//! 3. `travel` (`travelFlying` with one speed, `flying_speed` x 5 / 3): no gravity; in water the
//!    motion keeps 0.8 of itself after the move, in lava 0.5, in the air 0.91. The move has no
//!    fall check (`checkFallDamage` does nothing: no fall distance and no fluid update in a
//!    move); the step height is at least one block.
//! 4. Block effects; no floating.
//!
//! # Seats
//!
//! Up to four passengers, on the four attachment points of the type (front, right, back, left at
//! height 4, 1.7 blocks out), turned with the ghast. The player sits on the one of its index
//! among the passengers ([`Mount::set_seat`]); only the first one steers.

use super::super::attr::{Attribute, ModifierId};
use super::super::collide::MountExt;
use super::super::math::{self as m, DEG_TO_RAD, V3};
use super::super::player::{Ctx, PlayerState};
use super::super::rules::Rules;
use super::{Mount, MountKind};
use crate::world::{BlockView, TickCache};

/// The happy ghast's own client state.
#[derive(Clone, Debug)]
pub(super) struct FlyState {
    /// `flying_speed`.
    flying_speed: Attribute,
    /// The `STAYS_STILL` entity data.
    stays_still: bool,
    /// The player's index among the passengers.
    pub(super) seat: u8,
}

impl Default for FlyState {
    fn default() -> FlyState {
        FlyState {
            // HappyGhast.createAttributes (range of Attributes.FLYING_SPEED).
            flying_speed: Attribute::new(0.05, 0.0, 1024.0),
            stays_still: false,
            seat: 0,
        }
    }
}

impl FlyState {
    /// An attributes packet entry the ghast reads beyond the living ones; `false` for others.
    pub(super) fn apply_attribute(
        &mut self,
        name: &str,
        base: f64,
        modifiers: &[(ModifierId, f64, u8)],
    ) -> bool {
        if name.strip_prefix("minecraft:").unwrap_or(name) == "flying_speed" {
            self.flying_speed.apply_packet(base, modifiers);
            true
        } else {
            false
        }
    }
}

impl Mount {
    /// The server's `STAYS_STILL` entity data of a happy ghast (it then does not let the player
    /// steer).
    pub fn set_stays_still(&mut self, still: bool) {
        self.fly.stays_still = still;
    }

    /// The `STAYS_STILL` entity data of a happy ghast.
    #[must_use]
    pub fn stays_still(&self) -> bool {
        self.fly.stays_still
    }

    /// The player's index among the mount's passengers (`set_passengers` order; 0 = in front,
    /// the one who steers). Only the happy ghast has more than one seat here.
    pub fn set_seat(&mut self, index: usize) {
        self.fly.seat = index.min(u8::MAX as usize) as u8;
    }

    /// The player's index among the passengers.
    #[must_use]
    pub fn seat(&self) -> usize {
        usize::from(self.fly.seat)
    }

    /// The `flying_speed` attribute value (a happy ghast's).
    #[must_use]
    pub fn flying_speed(&self) -> f64 {
        self.fly.flying_speed.value()
    }
}

/// `HappyGhast.getControllingPassenger() == player`.
pub(super) fn controlled(mount: &Mount) -> bool {
    mount.s.saddled && !mount.fly.stays_still && mount.fly.seat == 0
}

/// `getRiddenInput`, `tickRidden` and `travel` of a happy ghast the player steers.
pub(super) fn travel_ridden<R: Rules, W: BlockView<State = R::State>>(
    t: &mut Ctx<'_, '_, R, TickCache<'_, W>, MountExt<'_>>,
    fly: &FlyState,
    rider: &PlayerState,
) {
    // getRiddenInput
    let strafe = rider.xxa;
    let (mut forward, mut up) = (0.0f32, 0.0f32);
    if rider.zza != 0.0 {
        let r = f64::from(rider.pitch * DEG_TO_RAD);
        let mut forward_look = m::cos(r);
        let mut up_look = -m::sin(r);
        if rider.zza < 0.0 {
            forward_look *= -0.5;
            up_look *= -0.5;
        }
        up = up_look;
        forward = forward_look;
    }
    if rider.jumping {
        up += 0.5;
    }
    let k = f64::from(3.9f32) * fly.flying_speed.value();
    let input = V3::new(f64::from(strafe), f64::from(up), f64::from(forward)).scale(k);
    // tickRidden: 8 % of the way to the rider's yaw, half its pitch (setRot, then setXRot's clamp).
    let y = t.p.yaw;
    let y = y + wrap_degrees(rider.yaw - y) * 0.08;
    t.p.yaw = y % 360.0;
    t.p.pitch = ((rider.pitch * 0.5) % 360.0 % 360.0).clamp(-90.0, 90.0);
    // travel -> travelFlying(input, speed, speed, speed)
    let speed = fly.flying_speed.value() as f32 * 5.0 / 3.0;
    move_relative(t, speed, input);
    let v = V3::of(t.p.vel);
    let k = if t.p.touching_water {
        f64::from(0.8f32)
    } else if t.p.in_lava() {
        0.5
    } else {
        f64::from(0.91f32)
    };
    t.entity_move(v);
    t.p.vel = V3::of(t.p.vel).scale(k).arr();
}

/// `moveRelative(speed, input)` with the ghast's yaw.
pub(super) fn move_relative<R: Rules, W: BlockView<State = R::State>>(
    t: &mut Ctx<'_, '_, R, TickCache<'_, W>, MountExt<'_>>,
    speed: f32,
    input: V3,
) {
    let v = V3::of(t.p.vel);
    let len = input.length_sqr();
    if len < 1.0e-7 {
        // Adding Vec3.ZERO turns a signed zero into +0.0.
        t.p.vel = [v.x + 0.0, v.y + 0.0, v.z + 0.0];
        return;
    }
    let i = if len > 1.0 { input.normalize() } else { input }.scale(f64::from(speed));
    let r = f64::from(t.p.yaw * DEG_TO_RAD);
    let (s, c) = (f64::from(m::sin(r)), f64::from(m::cos(r)));
    let add = V3::new(i.x * c - i.z * s, i.y, i.z * c + i.x * s);
    t.p.vel = v.add(add).arr();
}

/// `Mth.wrapDegrees(float)`.
pub(super) fn wrap_degrees(v: f32) -> f32 {
    let mut f = v % 360.0;
    if f >= 180.0 {
        f -= 360.0;
    }
    if f < -180.0 {
        f += 360.0;
    }
    f
}

/// The passenger attachment point of seat `index` (`EntityAttachments.getClamped`: past the last
/// one, the last), before turning with the ghast.
pub(super) fn seat(kind: MountKind, index: u8) -> V3 {
    debug_assert_eq!(kind, MountKind::HappyGhast);
    const SEATS: [[f64; 3]; 4] = [
        [0.0, 4.0, 1.7],
        [-1.7, 4.0, 0.0],
        [0.0, 4.0, -1.7],
        [1.7, 4.0, 0.0],
    ];
    let [x, y, z] = SEATS[usize::from(index).min(3)];
    V3::new(x, y, z)
}

/// `HappyGhast.canBeCollidedWith(player)` on the client for an adult, living happy ghast the
/// player does not ride (a passenger of the same vehicle never collides): while the server keeps
/// it still (`STAYS_STILL`), or when the player's feet are at or above the top of its box. Pass
/// the boxes it is true for in [`Surroundings::entities`](super::super::Surroundings) (the
/// test is made with the player's position at the start of its tick: a player that crosses the
/// top within one tick is not modelled).
#[must_use]
pub fn happy_ghast_collides(stays_still: bool, ghast_box: &crate::math::Aabb, feet_y: f64) -> bool {
    stays_still || feet_y >= ghast_box.max_y
}