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
//! The swimming mounts: the nautilus and the zombie nautilus, as the 26.x client ticks them (a
//! child module of `mount`).
//!
//! # Who steers
//!
//! `AbstractNautilus.getControllingPassenger`: the player on it when it is saddled
//! (`isSaddled`: something in the saddle slot, and `canUseSlot(SADDLE)`: tame, the
//! `TamableAnimal` flags bit 4). Otherwise the server moves it and the client only slows its copy
//! down (x 0.98). It takes one passenger.
//!
//! # A tick of a nautilus the player steers
//!
//! The order is the horse's ([`tick_mount`](super::tick_mount)); the nautilus' 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). No jump key part.
//! 2. `tickRidden`: the nautilus turns half the way to the rider's yaw and takes half its pitch;
//!    a pending dash (`playerJumpPendingScale`) pushes it along the rider's look vector by
//!    1.2 (in water) or 0.5 (out of it) x the pending scale x its movement speed x the block
//!    speed factor, starts a 40-tick cooldown and sets the `DASH` flag.
//! 3. The ridden speed (`getRiddenSpeed`): the movement speed x 0.0325 in water, x 0.02 out of
//!    it. In water it travels its own way (`travelInWater`: the speed relative to its yaw, the
//!    move, then 0.9 of the motion is kept: no gravity, no water slowdown, no climbing out); in
//!    lava and on land as a living entity (`LivingEntity.travel`). Water and lava do not push it
//!    (`isPushedByFluid` is false).
//! 4. Block effects; then `AbstractNautilus.tick`: the `DASH` flag clears below 35 ticks of
//!    cooldown, the cooldown counts down.
//!
//! # The dash bar
//!
//! The nautilus is `PlayerRideableJumping` with the cooldown as its jump cooldown: the rider's
//! jump key charges the bar only while the cooldown is 0; the release sends
//! `START_RIDING_JUMP` and sets the pending dash (`onPlayerJump`, saddled and no cooldown). A
//! `DASH` entity data from the server (after its own dash) starts a 40-tick cooldown when none
//! runs ([`Mount::set_dash`]).

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};

/// `TamableAnimal` flags bit: tame.
const FLAG_TAME: u8 = 4;
/// `AbstractNautilus.DASH_COOLDOWN_TICKS`.
pub(super) const DASH_COOLDOWN: i32 = 40;

/// The nautilus' own client state.
#[derive(Clone, Copy, Debug, Default)]
pub(super) struct SwimState {
    /// The `DASH` entity data.
    dash: bool,
    /// `dashCooldown`.
    cooldown: i32,
}

impl SwimState {
    /// The dash cooldown and `DASH` flag, set at a boarding.
    pub(super) fn set_state(&mut self, cooldown: i32, dash: bool) {
        self.cooldown = cooldown;
        self.dash = dash;
    }
}

impl Mount {
    /// The server's `DASH` entity data of a nautilus (`onSyncedDataUpdated`: a 40-tick cooldown
    /// starts unless one runs; not on the entity's first tick).
    pub fn set_dash(&mut self, dash: bool) {
        self.sw.dash = dash;
        if !self.e.first_tick && self.sw.cooldown == 0 {
            self.sw.cooldown = DASH_COOLDOWN;
        }
    }

    /// A nautilus' `DASH` flag and dash cooldown (`getJumpCooldown`).
    #[must_use]
    pub fn dash(&self) -> (bool, i32) {
        (self.sw.dash, self.sw.cooldown)
    }

    /// `isSaddled` of a nautilus: a saddle, and tame (`canUseSlot(SADDLE)`).
    #[must_use]
    pub fn nautilus_saddled(&self) -> bool {
        self.s.saddled && self.s.flags & FLAG_TAME != 0
    }
}

/// A nautilus or zombie nautilus.
pub(super) fn is_nautilus(kind: MountKind) -> bool {
    matches!(kind, MountKind::Nautilus | MountKind::ZombieNautilus)
}

/// `getControllingPassenger() == player`.
pub(super) fn controlled(mount: &Mount) -> bool {
    mount.nautilus_saddled()
}

/// `LocalPlayer.jumpableVehicle()` with no jump cooldown: the dash bar charges.
pub(super) fn jumpable(mount: &Mount) -> bool {
    controlled(mount) && mount.sw.cooldown == 0
}

/// `onPlayerJump(amount)`: saddled and no cooldown, the pending dash.
pub(super) fn on_player_jump(mount: &mut Mount, amount: i32) {
    if mount.nautilus_saddled() && mount.sw.cooldown <= 0 {
        // PlayerRideableJumping.getPlayerJumpPendingScale
        mount.s.pending = if amount >= 90 {
            1.0
        } else {
            0.4 + 0.4 * amount as f32 / 90.0
        };
    }
}

/// `getRiddenInput`, `tickRidden`, the ridden speed and `travel` of a nautilus the player
/// steers. Returns the ridden speed (`getSpeed()` afterwards).
pub(super) fn travel_ridden<R: Rules, W: BlockView<State = R::State>>(
    t: &mut Ctx<'_, '_, R, TickCache<'_, W>, MountExt<'_>>,
    sw: &mut SwimState,
    pending: &mut f32,
    rider: &PlayerState,
) -> f32 {
    // 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;
    }
    let input = V3::new(f64::from(strafe), f64::from(up), f64::from(forward));
    // tickRidden: half the way to the rider's yaw, half its pitch (setRot, then setXRot's clamp).
    let y = t.p.yaw;
    let y = y + super::fly::wrap_degrees(rider.yaw - y) * 0.5;
    t.p.yaw = y % 360.0;
    t.p.pitch = ((rider.pitch * 0.5) % 360.0 % 360.0).clamp(-90.0, 90.0);
    if *pending > 0.0 {
        // executeRidersJump: along the rider's look (its own `jumping` is never set here).
        let k = if t.p.touching_water { 1.2f32 } else { 0.5f32 } * *pending;
        let k = f64::from(k)
            * t.p.attributes.movement_speed.value()
            * f64::from(t.block_speed_factor());
        let look = view_vector(rider.pitch, rider.yaw).scale(k);
        t.p.vel = V3::of(t.p.vel).add(look).arr();
        sw.cooldown = DASH_COOLDOWN;
        // setDashing(true): a change made here does not restart the cooldown.
        sw.dash = true;
    }
    *pending = 0.0;
    // getRiddenSpeed
    let attr = t.p.attributes.movement_speed.value() as f32;
    let speed = if t.p.touching_water {
        0.0325f32 * attr
    } else {
        0.02f32 * attr
    };
    if t.p.touching_water && !t.p.abilities.flying {
        // travelInFluid -> AbstractNautilus.travelInWater
        super::fly::move_relative(t, speed, input);
        let v = V3::of(t.p.vel);
        t.entity_move(v);
        t.p.vel = V3::of(t.p.vel).scale(0.9).arr();
    } else {
        // `travel` reads `getSpeed()`: the ridden speed is the movement speed for this travel.
        let saved = t.p.attributes.movement_speed;
        t.p.attributes.movement_speed =
            super::super::attr::Attribute::new(f64::from(speed), f64::MIN, f64::MAX);
        t.travel(input);
        t.p.attributes.movement_speed = saved;
    }
    speed
}

/// The end of `AbstractNautilus.tick`: the `DASH` flag clears below 35 ticks of cooldown, the
/// cooldown counts down.
pub(super) fn after_tick(sw: &mut SwimState) {
    if sw.dash && sw.cooldown < 35 {
        sw.dash = false;
        // setDashing -> onSyncedDataUpdated: a cooldown starts when none runs (a `DASH` that
        // arrived before the entity's first tick started none).
        if sw.cooldown == 0 {
            sw.cooldown = DASH_COOLDOWN;
        }
    }
    if sw.cooldown > 0 {
        sw.cooldown -= 1;
    }
}

/// `Entity.calculateViewVector(xRot, yRot)`.
fn view_vector(x_rot: f32, y_rot: f32) -> V3 {
    let rx = x_rot * DEG_TO_RAD;
    let ry = -y_rot * DEG_TO_RAD;
    let (yc, ys) = (m::cos(f64::from(ry)), m::sin(f64::from(ry)));
    let (xc, xs) = (m::cos(f64::from(rx)), m::sin(f64::from(rx)));
    V3::new(f64::from(ys * xc), f64::from(-xs), f64::from(yc * xc))
}