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
//! Launch velocities of player-launched projectiles, aimed fireballs and dropped items in 1.8.9,
//! exactly as the server computes them (the shooting constructors of thrown items, arrows and the
//! fishing bobber, `ExplosiveProjectileEntity`'s aimed constructor, `PlayerEntity.dropItem`),
//! checked against the vanilla oracle (`tests/golden/1.8.9/projectile_launch.jsonl.gz`).
//!
//! 1.8 starts a projectile 0.16 to the side of the shooter's eyes (and 0.1 lower) and adds no
//! shooter motion. The server adds a random spread: per axis of the normalised direction a
//! Gaussian term `nextGaussian() * 0.0075 * uncertainty` (an arrow's also gets a random sign),
//! before the power scales it. A client cannot know the server's random, so [`shoot`] with
//! [`Noise::NONE`] is the expected launch.

use crate::math::{cos, sin, sqrt_f64_as_f32};
use crate::nonliving::{LegacyRandom, atan2, degrees_1_8 as degrees};

/// The spread's standard deviation per unit of uncertainty (`0.0075F`).
pub const SPREAD: f64 = 0.0075f32 as f64;

/// What is launched: the constructors differ in the direction's length (thrown items and the
/// bobber scale it by 0.4 first, which the normalisation then removes up to rounding) and in the
/// arrow's random signs.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Shooter {
    /// Snowballs, eggs, ender pearls, bottles o' enchanting, splash potions.
    Thrown,
    /// An arrow shot from a bow.
    Arrow,
    /// A cast fishing bobber.
    Bobber,
}

/// How an item launches its projectile.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct LaunchSpec {
    /// Speed of the launch.
    pub power: f32,
    /// Added to the shooter's pitch for the vertical direction (potions and bottles: -20).
    pub pitch_offset: f32,
    /// `divergence` (1 for players).
    pub uncertainty: f32,
}

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

    /// Snowballs, eggs and ender pearls (`1.5`).
    pub const THROWN: LaunchSpec = LaunchSpec::new(1.5, 0.0, 1.0);
    /// Splash potions (`0.5`, 20 degrees up).
    pub const POTION: LaunchSpec = LaunchSpec::new(0.5, -20.0, 1.0);
    /// Bottles o' enchanting (`0.7`, 20 degrees up).
    pub const EXPERIENCE_BOTTLE: LaunchSpec = LaunchSpec::new(0.7, -20.0, 1.0);
    /// A cast fishing bobber (`1.5`).
    pub const BOBBER: LaunchSpec = LaunchSpec::new(1.5, 0.0, 1.0);

    /// A bow released after `ticks_held` ticks: power `bow_power(ticks) * 2 * 1.5`; `None` when
    /// the draw is too short to shoot (`bow_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::new(p * 2.0 * 1.5, 0.0, 1.0))
        }
    }
}

/// The bow's pull: `(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 (per axis `nextGaussian() * 0.0075F * uncertainty`,
/// an arrow's with a random sign).
#[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.
    #[must_use]
    pub fn from_seed(seed: i64, shooter: Shooter, uncertainty: f32) -> Noise {
        let mut r = LegacyRandom::new(seed);
        let k = f64::from(0.0075f32);
        let u = f64::from(uncertainty);
        let mut n = [0.0; 3];
        for v in &mut n {
            let g = r.next_gaussian();
            let g = if shooter == Shooter::Arrow {
                g * if r.next_boolean() { -1.0 } else { 1.0 }
            } else {
                g
            };
            *v = g * k * u;
        }
        Noise(n)
    }
}

/// A launched projectile's start, motion and rotation.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Launch {
    /// Where the projectile starts.
    pub pos: [f64; 3],
    /// The projectile's motion.
    pub vel: [f64; 3],
    /// Its yaw (degrees).
    pub yaw: f32,
    /// Its pitch.
    pub pitch: f32,
}

/// `angle / 180.0F * (float)Math.PI`.
#[inline]
fn rad(deg: f32) -> f32 {
    deg / 180.0 * core::f32::consts::PI
}

/// The shooting constructor of a player at `pos` with `eye_height` looking at `yaw`, `pitch`,
/// then `setVelocity(direction, power, uncertainty)` with the given spread.
#[must_use]
pub fn shoot(
    shooter: Shooter,
    yaw: f32,
    pitch: f32,
    pos: [f64; 3],
    eye_height: f32,
    spec: &LaunchSpec,
    noise: Noise,
) -> Launch {
    let start = [
        pos[0] - f64::from(cos(rad(yaw)) * 0.16),
        pos[1] + f64::from(eye_height) - f64::from(0.1f32),
        pos[2] - f64::from(sin(rad(yaw)) * 0.16),
    ];
    let scale = if shooter == Shooter::Arrow { 1.0 } else { 0.4 };
    let offset = if shooter == Shooter::Thrown {
        spec.pitch_offset
    } else {
        0.0
    };
    let d = if shooter == Shooter::Arrow {
        [
            -sin(rad(yaw)) * cos(rad(pitch)),
            -sin(rad(pitch)),
            cos(rad(yaw)) * cos(rad(pitch)),
        ]
    } else {
        [
            -sin(rad(yaw)) * cos(rad(pitch)) * scale,
            -sin(rad(pitch + offset)) * scale,
            cos(rad(yaw)) * cos(rad(pitch)) * scale,
        ]
    };
    let v = d.map(f64::from);
    let f = f64::from(sqrt_f64_as_f32(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]));
    let mut m = [0.0; 3];
    for a in 0..3 {
        m[a] = (v[a] / f + noise.0[a]) * f64::from(spec.power);
    }
    let g = f64::from(sqrt_f64_as_f32(m[0] * m[0] + m[2] * m[2]));
    Launch {
        pos: start,
        vel: m,
        yaw: degrees(atan2(m[0], m[2])),
        pitch: degrees(atan2(m[1], g)),
    }
}

/// The three Gaussian draws of an aimed fireball whose entity random was created with `seed`.
#[must_use]
pub fn aimed_noise(seed: i64) -> [f64; 3] {
    let mut r = LegacyRandom::new(seed);
    [r.next_gaussian(), r.next_gaussian(), r.next_gaussian()]
}

/// The acceleration of a fireball or wither skull a mob aims along `dir`: the server adds
/// `gaussian * 0.4` per axis (`gaussians`, `[0.0; 3]` for the expected aim), then `dir / |dir| *
/// 0.1` (the length a float square root).
#[must_use]
pub fn aimed_power(dir: [f64; 3], gaussians: [f64; 3]) -> [f64; 3] {
    let d = [
        dir[0] + gaussians[0] * 0.4,
        dir[1] + gaussians[1] * 0.4,
        dir[2] + gaussians[2] * 0.4,
    ];
    let g = f64::from(sqrt_f64_as_f32(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]));
    [d[0] / g * 0.1, d[1] / g * 0.1, d[2] / g * 0.1]
}

/// 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(),
        ])
    }
}

/// `PlayerEntity.dropItem(stack, false, _)`: the motion of an item the player drops from its hand
/// at rotation `yaw`, `pitch` (it starts at [`drop_y`]).
///
/// The random horizontal term reads `Math.cos` / `Math.sin` of the angle, which the JVM computes
/// with its own intrinsic: here the values HotSpot x86-64 (JDK 9 and later) gives for every
/// angle a `nextFloat()` can make, exact on every platform. A server on another JVM (Java 8,
/// another architecture: not checked) may differ by one unit in the last place.
#[must_use]
pub fn drop_velocity(yaw: f32, pitch: f32, noise: DropNoise) -> [f64; 3] {
    let [r1, r2, r3, r4] = noise.0;
    let x = -sin(rad(yaw)) * cos(rad(pitch)) * 0.3;
    let z = cos(rad(yaw)) * cos(rad(pitch)) * 0.3;
    let y = -sin(rad(pitch)) * 0.3 + 0.1;
    // (r1 * PI) * 2: the same float as r1 * 2pi
    let (cos_i, sin_i) = crate::jdk_trig::drop_cos_sin(r1);
    let h = f64::from(0.02f32 * r2);
    [
        f64::from(x) + cos_i * h,
        f64::from(y) + f64::from((r3 - r4) * 0.1),
        f64::from(z) + sin_i * h,
    ]
}

/// The motion of an item dropped in a random direction (`dropItem(stack, true, _)`) for its two
/// random floats.
#[must_use]
pub fn drop_velocity_random(noise: [f32; 2]) -> [f64; 3] {
    let f = noise[0] * 0.5;
    let g = noise[1] * core::f32::consts::PI * 2.0;
    [
        f64::from(-sin(g) * f),
        f64::from(0.2f32),
        f64::from(cos(g) * f),
    ]
}

/// Where a dropped item starts: `y - 0.3F + eye_height` (in that order).
#[must_use]
pub fn drop_y(y: f64, eye_height: f32) -> f64 {
    y - f64::from(0.3f32) + f64::from(eye_height)
}