ghast-physics 0.5.6

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
//! Pieces the non-living entity ports of the legacy versions (1.8.9, 1.12.2, 1.16.5) share: the
//! side an entity is ticked on, the entity random (`java.util.Random`), `MathHelper.atan2` and
//! the rotation helpers of projectiles. Everything here is plain functions on plain data, so the
//! per-version modules call it with no indirection.

/// Which game's tick runs: the server's (what really happens) or a client's (what a vanilla
/// client shows between two server updates of the entity).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Side {
    /// The server's tick (`World.isClient` false).
    Server,
    /// A client's tick of an entity the server owns.
    Client,
}

/// The entity a fishing bobber is hooked to, as the bobber's tick reads it (1.12.2 `caughtEntity`,
/// 1.16.5 `hookedEntity`; set from the synced hooked-entity id).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
#[cfg_attr(not(any(feature = "v1_12", feature = "v1_16_5")), allow(dead_code))]
pub struct HookedEntity {
    /// The entity's position (feet; 1.12.2: give the bottom of its box, `minY`, as y).
    pub pos: [f64; 3],
    /// Its height: the bobber sits at 0.8 of it.
    pub height: f32,
    /// It was removed: the bobber lets go and flies again.
    pub removed: bool,
}

#[cfg_attr(not(any(feature = "v1_12", feature = "v1_16_5")), allow(dead_code))]
impl HookedEntity {
    /// An entity at `pos` with height `height`, present.
    #[must_use]
    pub const fn new(pos: [f64; 3], height: f32) -> HookedEntity {
        HookedEntity {
            pos,
            height,
            removed: false,
        }
    }

    /// The entity is gone.
    #[must_use]
    pub const fn removed() -> HookedEntity {
        HookedEntity {
            pos: [0.0; 3],
            height: 0.0,
            removed: true,
        }
    }
}

// ---------------------------------------------------------------------------------------------
// The entity random

/// `java.util.Random`: the 48-bit linear congruential generator an entity is created with, plus
/// the cached second value of `nextGaussian`.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct LegacyRandom {
    seed: i64,
    next_gaussian: Option<f64>,
}

const MULTIPLIER: i64 = 0x5_DEEC_E66D;
const MASK: i64 = (1 << 48) - 1;

impl LegacyRandom {
    /// `new Random(seed)`.
    pub(crate) fn new(seed: i64) -> LegacyRandom {
        LegacyRandom {
            seed: (seed ^ MULTIPLIER) & MASK,
            next_gaussian: None,
        }
    }

    fn next(&mut self, bits: u32) -> i32 {
        self.seed = self.seed.wrapping_mul(MULTIPLIER).wrapping_add(11) & MASK;
        (self.seed >> (48 - bits)) as i32
    }

    /// `nextInt(bound)` for a positive bound.
    #[cfg(test)]
    pub(crate) fn next_int(&mut self, bound: i32) -> i32 {
        if bound & -bound == bound {
            return ((i64::from(bound) * i64::from(self.next(31))) >> 31) as i32;
        }
        loop {
            let bits = self.next(31);
            let val = bits % bound;
            if bits.wrapping_sub(val).wrapping_add(bound - 1) >= 0 {
                return val;
            }
        }
    }

    /// `nextBoolean()`.
    #[cfg_attr(not(feature = "v1_8"), allow(dead_code))]
    pub(crate) fn next_boolean(&mut self) -> bool {
        self.next(1) != 0
    }

    /// `nextFloat()`: 24 bits times `2^-24`.
    pub(crate) fn next_float(&mut self) -> f32 {
        self.next(24) as f32 / (1 << 24) as f32
    }

    /// `nextDouble()`: 53 bits times `2^-53`.
    pub(crate) fn next_double(&mut self) -> f64 {
        let a = i64::from(self.next(26));
        let b = i64::from(self.next(27));
        ((a << 27) + b) as f64 * (1.0 / (1u64 << 53) as f64)
    }

    /// `nextGaussian()` (the polar method; the second value is kept for the next call).
    pub(crate) fn next_gaussian(&mut self) -> f64 {
        if let Some(g) = self.next_gaussian.take() {
            return g;
        }
        loop {
            let v1 = 2.0 * self.next_double() - 1.0;
            let v2 = 2.0 * self.next_double() - 1.0;
            let s = v1 * v1 + v2 * v2;
            if s < 1.0 && s != 0.0 {
                let m = (-2.0 * crate::nonliving::strict_log(s) / s).sqrt();
                self.next_gaussian = Some(v2 * m);
                return v1 * m;
            }
        }
    }

    /// The draws of 1.16's `Entity.onSwimmingStart` for a box `width` wide (the sound pitch, then the
    /// bubble and splash particles); none of them moves anything.
    #[cfg_attr(not(feature = "v1_16_5"), allow(dead_code))]
    pub(crate) fn splash(&mut self, width: f32) {
        self.next_float();
        self.next_float();
        let n = 1.0f32 + width * 20.0;
        let mut i = 0;
        while (i as f32) < n {
            self.next_double();
            self.next_double();
            self.next_double();
            i += 1;
        }
        let mut i = 0;
        while (i as f32) < n {
            self.next_double();
            self.next_double();
            i += 1;
        }
    }
}

/// `StrictMath.log` (fdlibm `e_log.c`), the logarithm `nextGaussian` uses (the constants as
/// fdlibm publishes them).
#[allow(clippy::excessive_precision)]
pub(crate) fn strict_log(x: f64) -> f64 {
    const LN2_HI: f64 = 6.931_471_803_691_238_164_90e-01;
    const LN2_LO: f64 = 1.908_214_929_270_587_700_02e-10;
    const TWO54: f64 = 1.801_439_850_948_198_400_00e+16;
    const LG1: f64 = 6.666_666_666_666_735_130e-01;
    const LG2: f64 = 3.999_999_999_940_941_908e-01;
    const LG3: f64 = 2.857_142_874_366_239_149e-01;
    const LG4: f64 = 2.222_219_843_214_978_396e-01;
    const LG5: f64 = 1.818_357_216_161_805_012e-01;
    const LG6: f64 = 1.531_383_769_920_937_332e-01;
    const LG7: f64 = 1.479_819_860_511_658_591e-01;
    let mut x = x;
    let bits = x.to_bits();
    let mut hx = (bits >> 32) as i32;
    let lx = bits as u32;
    let mut k = 0i32;
    if hx < 0x0010_0000 {
        if ((hx & 0x7fff_ffff) as u32 | lx) == 0 {
            return f64::NEG_INFINITY;
        }
        if hx < 0 {
            return f64::NAN;
        }
        k -= 54;
        x *= TWO54;
        hx = (x.to_bits() >> 32) as i32;
    }
    if hx >= 0x7ff0_0000 {
        return x + x;
    }
    k += (hx >> 20) - 1023;
    hx &= 0x000f_ffff;
    let i = (hx + 0x95f64) & 0x0010_0000;
    // Normalise x or x / 2 into [sqrt(2)/2, sqrt(2)).
    let hi = hx | (i ^ 0x3ff0_0000);
    x = f64::from_bits((u64::from(hi as u32) << 32) | (x.to_bits() & 0xffff_ffff));
    k += i >> 20;
    let f = x - 1.0;
    let dk = f64::from(k);
    if (0x000f_ffff & (2 + hx)) < 3 {
        if f == 0.0 {
            return if k == 0 {
                0.0
            } else {
                dk * LN2_HI + dk * LN2_LO
            };
        }
        let r = f * f * (0.5 - 0.333_333_333_333_333_33 * f);
        return if k == 0 {
            f - r
        } else {
            dk * LN2_HI - ((r - dk * LN2_LO) - f)
        };
    }
    let s = f / (2.0 + f);
    let z = s * s;
    let mut i = hx - 0x6147a;
    let w = z * z;
    let j = 0x6b851 - hx;
    let t1 = w * (LG2 + w * (LG4 + w * LG6));
    let t2 = z * (LG1 + w * (LG3 + w * (LG5 + w * LG7)));
    i |= j;
    let r = t2 + t1;
    if i > 0 {
        let hfsq = 0.5 * f * f;
        if k == 0 {
            f - (hfsq - s * (hfsq + r))
        } else {
            dk * LN2_HI - ((hfsq - (s * (hfsq + r) + dk * LN2_LO)) - f)
        }
    } else if k == 0 {
        f - s * (f - r)
    } else {
        dk * LN2_HI - ((s * (f - r) - dk * LN2_LO) - f)
    }
}

// ---------------------------------------------------------------------------------------------
// Rotation

/// The two 257-entry tables of `MathHelper.atan2` (the same values since 1.8).
#[path = "v1_8/atan_table.rs"]
#[allow(dead_code, clippy::duplicate_mod)]
mod atan_table;

/// `MathHelper.atan2` (table-driven, not `Math.atan2`).
pub(crate) fn atan2(mut y: f64, mut x: f64) -> f64 {
    let d = x * x + y * y;
    if d.is_nan() {
        return f64::NAN;
    }
    let neg_y = y < 0.0;
    if neg_y {
        y = -y;
    }
    let neg_x = x < 0.0;
    if neg_x {
        x = -x;
    }
    let steep = y > x;
    if steep {
        core::mem::swap(&mut x, &mut y);
    }
    // MathHelper.fastInverseSqrt
    let half = 0.5 * d;
    let r = f64::from_bits((6_910_469_410_427_058_090_i64 - ((d.to_bits() as i64) >> 1)) as u64);
    let r = r * (1.5 - half * r * r);
    x *= r;
    y *= r;
    let bias = f64::from_bits(4_805_340_802_404_319_232);
    let yp = bias + y;
    let i = yp.to_bits() as i32 as usize;
    let phi = f64::from_bits(atan_table::ARCSINE[i]);
    let c = f64::from_bits(atan_table::COSINE[i]);
    let s = yp - bias;
    let sd = y * c - x * s;
    let dd = (6.0 + sd * sd) * sd * 0.166_666_666_666_666_66;
    let mut t = phi + dd;
    if steep {
        t = core::f64::consts::FRAC_PI_2 - t;
    }
    if neg_x {
        t = core::f64::consts::PI - t;
    }
    if neg_y {
        t = -t;
    }
    t
}

/// `(float)(radians * 180.0F / (float)Math.PI)`: the two float constants fold into one
/// (`57.295776F`) in the class files (1.12 and later).
#[cfg_attr(not(any(feature = "v1_12", feature = "v1_16_5")), allow(dead_code))]
#[inline]
pub(crate) fn degrees(radians: f64) -> f32 {
    (radians * f64::from(180.0f32 / core::f32::consts::PI)) as f32
}

/// 1.8's `(float)(radians * 180.0 / (double)(float)Math.PI)`: a multiply, then a divide (two
/// roundings).
#[cfg_attr(not(feature = "v1_8"), allow(dead_code))]
#[inline]
pub(crate) fn degrees_1_8(radians: f64) -> f32 {
    (radians * 180.0 / f64::from(core::f32::consts::PI)) as f32
}

/// `ProjectileEntity.updateRotation(prev, new)`: the old angle brought within 180 of the new
/// one, then `prev + 0.2F * (new - prev)`.
pub(crate) fn lerp_rotation(mut o: f32, r: f32) -> f32 {
    while r - o < -180.0 {
        o -= 360.0;
    }
    while r - o >= 180.0 {
        o += 360.0;
    }
    o + 0.2 * (r - o)
}

/// `Math.signum(double)` (zero and NaN unchanged).
#[cfg_attr(not(any(feature = "v1_12", feature = "v1_16_5")), allow(dead_code))]
#[inline]
pub(crate) fn signum(x: f64) -> f64 {
    if x > 0.0 {
        1.0
    } else if x < 0.0 {
        -1.0
    } else {
        x
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn strict_log_matches_known_values() {
        assert_eq!(strict_log(1.0), 0.0);
        assert_eq!(strict_log(core::f64::consts::E).to_bits(), 1.0f64.to_bits());
        for x in [0.5, 0.25, 0.75, 1e-300, 3.0, 0.999, 0.123_456] {
            assert!((strict_log(x) - x.ln()).abs() <= x.ln().abs() * 4.0 * f64::EPSILON);
        }
    }

    #[test]
    fn java_random_sequence() {
        // new Random(42): nextInt(), nextFloat(), nextGaussian() of the JDK.
        let mut r = LegacyRandom::new(42);
        assert_eq!(r.next(32), -1_170_105_035);
        let mut r = LegacyRandom::new(42);
        assert_eq!(r.next_int(10), 0);
        assert_eq!(r.next_int(10), 3);
        let mut r = LegacyRandom::new(42);
        assert_eq!(
            r.next_gaussian().to_bits(),
            1.141_905_315_473_054_7f64.to_bits()
        );
        // StrictMath.log bits from the JDK.
        assert_eq!(
            strict_log(0.123_456).to_bits() as i64,
            -4_611_479_144_538_851_204
        );
        assert_eq!(strict_log(0.7).to_bits() as i64, -4_623_275_132_358_410_416);
    }
}