ghast-physics 0.5.3

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
//! Launch velocities of player-launched projectiles and dropped items in the modern versions,
//! exactly as the server computes them (`Projectile.shootFromRotation`,
//! `LivingEntity.createItemStackToDrop`), checked against the vanilla oracle
//! (`tests/golden/<v>/projectile_launch.jsonl.gz`).
//!
//! The server adds a random spread: per axis of the normalised direction a triangular term
//! `spread * (a - b)` with `a`, `b` uniform in `[0, 1)` and `spread = 0.0172275 * uncertainty`
//! (so within `±spread`, most likely 0), before the power scales it. A client cannot know the
//! server's random, so [`shoot`] with [`Noise::NONE`] is the expected launch and [`max_spread`]
//! bounds the difference. An item drop adds a random horizontal offset of length below `0.02`
//! and a vertical one within `±0.1`.
//!
//! Item constants (power, pitch offset, uncertainty) are on [`LaunchSpec`]; the projectile starts
//! at the shooter's `x, eye_y - 0.1, z` (a wind charge at the eye height itself, see
//! [`LaunchSpec::eye_offset`]), a dropped item at `eye_y - 0.3`.

use super::body::{LegacyRandom, atan2, degrees};
use super::math::{DEG_TO_RAD, V3, cos, sin};

/// The spread factor per unit of uncertainty (`0.0172275`).
pub const SPREAD: f64 = 0.017_227_5;

/// How an item launches its projectile.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct LaunchSpec {
    /// Speed of the launch (`pow`).
    pub power: f32,
    /// Added to the shooter's pitch for the vertical direction (`yOffset`: potions and bottles
    /// are thrown 20 degrees higher).
    pub pitch_offset: f32,
    /// `uncertainty` (1 for players).
    pub uncertainty: f32,
    /// The projectile starts this far below the shooter's eyes (0.1; a wind charge 0).
    pub eye_offset: f32,
}

impl LaunchSpec {
    /// A launch of `power` with the vertical direction `pitch_offset` degrees off the shooter's
    /// pitch and the given uncertainty, starting `eye_offset` below the shooter's eyes.
    #[must_use]
    pub const fn new(
        power: f32,
        pitch_offset: f32,
        uncertainty: f32,
        eye_offset: f32,
    ) -> LaunchSpec {
        LaunchSpec {
            power,
            pitch_offset,
            uncertainty,
            eye_offset,
        }
    }

    const fn of(power: f32, pitch_offset: f32, eye_offset: f32) -> LaunchSpec {
        LaunchSpec {
            power,
            pitch_offset,
            uncertainty: 1.0,
            eye_offset,
        }
    }

    /// Snowballs, eggs and ender pearls (`1.5`).
    pub const THROWN: LaunchSpec = LaunchSpec::of(1.5, 0.0, 0.1);
    /// Splash and lingering potions (`0.5`, 20 degrees up).
    pub const POTION: LaunchSpec = LaunchSpec::of(0.5, -20.0, 0.1);
    /// Bottles o' enchanting (`0.7`, 20 degrees up).
    pub const EXPERIENCE_BOTTLE: LaunchSpec = LaunchSpec::of(0.7, -20.0, 0.1);
    /// Wind charges (`1.5`, from the eye height).
    pub const WIND_CHARGE: LaunchSpec = LaunchSpec::of(1.5, 0.0, 0.0);
    /// Tridents (`2.5`).
    pub const TRIDENT: LaunchSpec = LaunchSpec::of(2.5, 0.0, 0.1);
    /// Crossbow arrows (`3.15`).
    pub const CROSSBOW_ARROW: LaunchSpec = LaunchSpec::of(3.15, 0.0, 0.1);

    /// A bow released after `ticks_held` ticks (power `3 * bow_power(ticks)`); `None` when the
    /// draw is too short to shoot (power below 0.1).
    #[must_use]
    pub fn bow(ticks_held: i32) -> Option<LaunchSpec> {
        let p = bow_power(ticks_held);
        if f64::from(p) < 0.1 {
            None
        } else {
            Some(LaunchSpec::of(p * 3.0, 0.0, 0.1))
        }
    }
}

/// `BowItem.getPowerForTime(ticks)`: `(t^2 + 2t) / 3` with `t = ticks / 20`, at most 1.
#[must_use]
pub fn bow_power(ticks_held: i32) -> f32 {
    let t = ticks_held as f32 / 20.0;
    let p = (t * t + t * 2.0) / 3.0;
    if p > 1.0 { 1.0 } else { p }
}

/// The three random spread terms of a launch (`random.triangle(0, 0.0172275 * uncertainty)`
/// for x, y, z, in that order).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Noise(pub [f64; 3]);

impl Noise {
    /// No spread: the expected launch.
    pub const NONE: Noise = Noise([0.0; 3]);

    /// The spread a projectile whose entity random was created with `seed` draws (the server's
    /// projectile; for tests and replays with a known seed).
    #[must_use]
    pub fn from_seed(seed: i64, uncertainty: f32) -> Noise {
        let mut r = LegacyRandom::new(seed);
        let s = SPREAD * f64::from(uncertainty);
        let x = r.triangle(0.0, s);
        let y = r.triangle(0.0, s);
        let z = r.triangle(0.0, s);
        Noise([x, y, z])
    }
}

/// The largest difference a launch's spread can make per axis: `power * 0.0172275 * uncertainty`.
#[must_use]
pub fn max_spread(spec: &LaunchSpec) -> f64 {
    f64::from(spec.power) * SPREAD * f64::from(spec.uncertainty)
}

/// A launched projectile's motion and rotation.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Launch {
    /// The projectile's motion (`getDeltaMovement` after the launch).
    pub vel: [f64; 3],
    /// Its yaw (degrees, from the motion before the shooter's own motion is added).
    pub yaw: f32,
    /// Its pitch.
    pub pitch: f32,
}

/// `Projectile.shootFromRotation(shooter, pitch, yaw, pitch_offset, power, uncertainty)` with the
/// given spread: the direction from the rotation, normalised, plus the noise, times the power,
/// plus the shooter's known motion (its vertical part only when it is not on the ground).
#[must_use]
pub fn shoot(
    yaw: f32,
    pitch: f32,
    spec: &LaunchSpec,
    noise: Noise,
    shooter_motion: [f64; 3],
    shooter_on_ground: bool,
) -> Launch {
    let ry = f64::from(yaw * DEG_TO_RAD);
    let rx = f64::from(pitch * DEG_TO_RAD);
    let xd = -sin(ry) * cos(rx);
    let yd = -sin(f64::from((pitch + spec.pitch_offset) * DEG_TO_RAD));
    let zd = cos(ry) * cos(rx);
    let m = V3::new(f64::from(xd), f64::from(yd), f64::from(zd))
        .normalize()
        .add(V3::of(noise.0))
        .scale(f64::from(spec.power));
    let launch_yaw = degrees(atan2(m.x, m.z));
    let launch_pitch = degrees(atan2(m.y, m.horizontal_sqr().sqrt()));
    let s = shooter_motion;
    let v = m.add(V3::new(
        s[0],
        if shooter_on_ground { 0.0 } else { s[1] },
        s[2],
    ));
    Launch {
        vel: v.arr(),
        yaw: launch_yaw,
        pitch: launch_pitch,
    }
}

/// The four random floats of a held-item drop, in draw order (angle, radius, then two for the
/// vertical term); all zero for the expected drop.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DropNoise(pub [f32; 4]);

impl DropNoise {
    /// No spread: the expected drop.
    pub const NONE: DropNoise = DropNoise([0.0; 4]);

    /// The draws of a player whose entity random was created with `seed`.
    #[must_use]
    pub fn from_seed(seed: i64) -> DropNoise {
        let mut r = LegacyRandom::new(seed);
        DropNoise([
            r.next_float(),
            r.next_float(),
            r.next_float(),
            r.next_float(),
        ])
    }
}

/// `LivingEntity.createItemStackToDrop(stack, false, _)`: the motion of an item the player drops
/// from its hand at rotation `yaw`, `pitch` (it starts at `x, eye_y - 0.3, z`).
#[must_use]
pub fn drop_velocity(yaw: f32, pitch: f32, noise: DropNoise) -> [f64; 3] {
    let [r1, r2, r3, r4] = noise.0;
    let sin_x = sin(f64::from(pitch * DEG_TO_RAD));
    let cos_x = cos(f64::from(pitch * DEG_TO_RAD));
    let sin_y = sin(f64::from(yaw * DEG_TO_RAD));
    let cos_y = cos(f64::from(yaw * DEG_TO_RAD));
    let dir = f64::from(r1 * core::f32::consts::TAU);
    let pow2 = f64::from(0.02f32 * r2);
    [
        f64::from(-sin_y * cos_x * 0.3) + dir.cos() * pow2,
        f64::from(-sin_x * 0.3 + 0.1 + (r3 - r4) * 0.1),
        f64::from(cos_y * cos_x * 0.3) + dir.sin() * pow2,
    ]
}

/// The motion of an item dropped in a random direction (`createItemStackToDrop(stack, true, _)`:
/// a death drop or an inventory spill) for its two random floats.
#[must_use]
pub fn drop_velocity_random(noise: [f32; 2]) -> [f64; 3] {
    let pow = noise[0] * 0.5;
    let dir = f64::from(noise[1] * core::f32::consts::TAU);
    [
        f64::from(-sin(dir) * pow),
        f64::from(0.2f32),
        f64::from(cos(dir) * pow),
    ]
}

/// Where a dropped item starts: below the eyes by 0.3 (`getEyeY() - 0.3F`).
#[must_use]
pub fn drop_y(eye_y: f64) -> f64 {
    eye_y - f64::from(0.3f32)
}