ghast-physics 0.4.10

Vanilla-exact, pure and deterministic player movement for the ghast Minecraft Java Edition client library (1.8.9 first), verified bit for bit against the real game
Documentation
//! The 1.16.5 crosshair block pick (vanilla `Entity.raycast(reach, 1.0F, false)`, which
//! `GameRenderer.updateTargetedEntity` stores as the crosshair target when no entity is nearer),
//! without entities. The client's reach is 4.5 (survival / adventure) or 5.0 (creative).
//! Verified against the oracle: `tests/golden/1.16.5/raytrace.jsonl.gz`.

use ghast_data::v1_16_5::{Block, BlockState, OffsetType};

use ghast_data::Aabb;

use super::{
    BlockHit, Direction, PickEntity, PlacedShape, Target, entity_hit, length_sqr, search_box,
};
use crate::math::{cos, sin};
use crate::world::BlockView;

/// Survival / adventure block reach.
pub const REACH: f64 = 4.5;
/// Creative block reach.
pub const CREATIVE_REACH: f64 = 5.0;

/// `Entity.getCameraPosVec(1.0F)`: `(x, y + eye height, z)` (no interpolation at 1.0).
#[must_use]
pub fn eye_position(pos: [f64; 3], eye_height: f32) -> [f64; 3] {
    [pos[0], pos[1] + f64::from(eye_height), pos[2]]
}

/// `Entity.getRotationVector(pitch, yaw)`: the unit look vector (float sine table).
#[must_use]
pub fn rotation_vector(yaw: f32, pitch: f32) -> [f64; 3] {
    const DEG: f32 = (std::f64::consts::PI / 180.0) as f32;
    let f = pitch * DEG;
    let g = -yaw * DEG;
    let h = cos(g);
    let i = sin(g);
    let j = cos(f);
    let k = sin(f);
    [f64::from(i * j), f64::from(-k), f64::from(h * j)]
}

/// `AbstractBlockState.getModelOffset` at `(x, z)`.
#[must_use]
pub fn model_offset(offset: OffsetType, x: i32, z: i32) -> [f64; 3] {
    if offset == OffsetType::None {
        return [0.0; 3];
    }
    // MathHelper.hashCode(x, 0, z)
    let mut l = i64::from(x.wrapping_mul(3_129_871)) ^ i64::from(z).wrapping_mul(116_129_781);
    l = l
        .wrapping_mul(l)
        .wrapping_mul(42_317_861)
        .wrapping_add(l.wrapping_mul(11));
    let l = l >> 16;
    let h = |bits: i64| (f64::from((bits & 15) as f32 / 15.0) - 0.5) * 0.5;
    let y = if offset == OffsetType::Xyz {
        (f64::from(((l >> 4) & 15) as f32 / 15.0) - 1.0) * 0.2
    } else {
        0.0
    };
    [h(l), y, h(l >> 8)]
}

/// The shapes the pick tests at a block: the outline (the held-item variant when the player holds
/// this block's own item; moved by the model offset where the block does that) and the raycast
/// shape.
// (inlined into each ray: the crosshair's pick keeps its code with the item ray as a second user)
#[must_use]
#[inline(always)]
pub fn shapes(
    state: BlockState,
    pos: [i32; 3],
    held_block: Option<Block>,
) -> (PlacedShape, PlacedShape) {
    let outline = if held_block == Some(state.block()) {
        state.outline_shape_holding_own_item()
    } else {
        state.outline_shape()
    };
    let shift = state
        .outline_offset()
        .then(|| model_offset(state.block().vanilla().offset, pos[0], pos[2]));
    (
        PlacedShape {
            shape: outline,
            shift,
        },
        PlacedShape::fixed(state.raycast_shape()),
    )
}

/// The block ray `from -> to` (vanilla `World.raycast` with `ShapeType.OUTLINE`,
/// `FluidHandling.NONE` and the player's shape context).
///
/// `held_block` is the block form of the main-hand item (`None` for an empty hand or a non-block
/// item); it only matters for scaffolding, whose outline is a full cube to a player holding it.
pub fn clip<W: BlockView<State = BlockState>>(
    world: &W,
    from: [f64; 3],
    to: [f64; 3],
    held_block: Option<Block>,
) -> BlockHit {
    super::clip(from, to, |pos| {
        // World.getBlockState: void air outside the build height.
        if !(0..256).contains(&pos[1]) {
            return None;
        }
        let (o, i) = shapes(world.block(pos[0], pos[1], pos[2]), pos, held_block);
        (!o.shape.empty).then_some((o, i))
    })
}

/// The crosshair target with no entity in reach: the block ray from `eye` along `look` to `reach`.
pub fn pick<W: BlockView<State = BlockState>>(
    world: &W,
    eye: [f64; 3],
    look: [f64; 3],
    reach: f64,
    held_block: Option<Block>,
) -> BlockHit {
    let to = [
        eye[0] + look[0] * reach,
        eye[1] + look[1] * reach,
        eye[2] + look[2] * reach,
    ];
    clip(world, eye, to, held_block)
}

/// The crosshair target (vanilla `GameRenderer.updateTargetedEntity(1.0F)`): the block pick at
/// the game mode's reach (5.0 creative, else 4.5), unless an entity of `entities` is hit nearer
/// along the ray to 6.0 (creative) or the reach; outside creative an entity farther than 3 blocks
/// gives a miss at its hit point instead. `player_bb` is the player's bounding box.
pub fn pick_target<W: BlockView<State = BlockState>>(
    world: &W,
    player_bb: &Aabb,
    eye: [f64; 3],
    look: [f64; 3],
    creative: bool,
    held_block: Option<Block>,
    entities: &[PickEntity],
) -> Target {
    let reach = if creative { CREATIVE_REACH } else { REACH };
    let block = pick(world, eye, look, reach, held_block);
    let (d, limited) = if creative {
        (6.0, false)
    } else {
        (reach, reach > 3.0)
    };
    let block_sq = length_sqr(block.location, eye);
    let delta = [look[0] * d, look[1] * d, look[2] * d];
    let to = [eye[0] + delta[0], eye[1] + delta[1], eye[2] + delta[2]];
    if let Some(e) = entity_hit(eye, to, &search_box(player_bb, delta), entities, block_sq) {
        let g = length_sqr(e.location, eye);
        if limited && g > 9.0 {
            let face = Direction::approximate_nearest(look[0], look[1], look[2]);
            return Target::Block(BlockHit::miss(e.location, face));
        }
        if g < block_sq {
            return Target::Entity(e);
        }
    }
    Target::Block(block)
}

/// Which fluids an item's own ray stops at (vanilla `RaycastContext.FluidHandling`).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Fluids {
    /// None (the ray passes every fluid).
    None,
    /// Still fluids: sources, waterlogged blocks, kelp, seagrass, bubble columns.
    SourceOnly,
    /// Any fluid.
    Any,
}

/// An item's own ray length (`Item.raycast`: 5 blocks in every game mode).
pub const ITEM_REACH: f64 = 5.0;

/// The ray shapes of a fluid of height `amount / 9` (`VoxelShapes.cuboid(0, 0, 0, 1, h, 1)`:
/// an array shape, since `h` is never a binary fraction), for amounts 1..=8.
static FLUID_SHAPES: [ghast_data::SelectionShape; 8] = {
    const fn shape(ys: &'static [f64; 2], boxes: &'static [Aabb; 1]) -> ghast_data::SelectionShape {
        ghast_data::SelectionShape {
            cube: false,
            sizes: [1, 1, 1],
            xs: &[0.0, 1.0],
            ys,
            zs: &[0.0, 1.0],
            cells: &[1],
            empty: false,
            boxes,
        }
    }
    macro_rules! h {
        ($n:literal) => {
            shape(
                &[0.0, ($n as f32 / 9.0) as f64],
                &[Aabb {
                    min_x: 0.0,
                    min_y: 0.0,
                    min_z: 0.0,
                    max_x: 1.0,
                    max_y: ($n as f32 / 9.0) as f64,
                    max_z: 1.0,
                }],
            )
        };
    }
    [h!(1), h!(2), h!(3), h!(4), h!(5), h!(6), h!(7), h!(8)]
};

/// The ray shape of the fluid in `state` for `fluids` (`RaycastContext.getFluidShape`), if any.
///
/// Vanilla's `FlowableFluid.getShape` keeps the first shape computed for each fluid state (a full
/// block when that position had the same fluid above it); this is the shape with nothing above,
/// which a client that first sees a fluid from its surface keeps.
#[must_use]
pub fn fluid_shape(
    state: BlockState,
    fluids: Fluids,
) -> Option<&'static ghast_data::SelectionShape> {
    let f = state.fluid()?;
    let handled = match fluids {
        Fluids::None => false,
        Fluids::SourceOnly => f.still(),
        Fluids::Any => true,
    };
    handled.then(|| &FLUID_SHAPES[usize::from(f.amount().clamp(1, 8)) - 1])
}

/// The ray of an item's own use (vanilla `Item.raycast(world, player, fluids)`): from the eyes
/// along the look given by `yaw` / `pitch` (its own float steps, not the crosshair's look vector)
/// for [`ITEM_REACH`], with the outline shapes and, per `fluids`, the fluids' shapes; at each block
/// the nearer of the block's and the fluid's hit wins (the block's on a tie). `held_block`: the
/// block form of the main-hand item (scaffolding outlines).
pub fn item_ray<W: BlockView<State = BlockState>>(
    world: &W,
    eye: [f64; 3],
    yaw: f32,
    pitch: f32,
    fluids: Fluids,
    held_block: Option<Block>,
) -> BlockHit {
    const DEG: f32 = (std::f64::consts::PI / 180.0) as f32;
    const PI: f32 = std::f32::consts::PI;
    let h = cos(-yaw * DEG - PI);
    let i = sin(-yaw * DEG - PI);
    let j = -cos(-pitch * DEG);
    let k = sin(-pitch * DEG);
    let (l, n) = (i * j, h * j);
    let to = [
        eye[0] + f64::from(l) * ITEM_REACH,
        eye[1] + f64::from(k) * ITEM_REACH,
        eye[2] + f64::from(n) * ITEM_REACH,
    ];
    super::traverse(eye, to, |pos| {
        // World.getBlockState: void air outside the build height.
        if !(0..256).contains(&pos[1]) {
            return None;
        }
        let state = world.block(pos[0], pos[1], pos[2]);
        let (o, s) = shapes(state, pos, held_block);
        let block = if o.shape.empty {
            None
        } else {
            super::clip_block(&o, &s, eye, to, pos)
        };
        let fluid = fluid_shape(state, fluids)
            .and_then(|f| super::clip_shape(&PlacedShape::fixed(f), eye, to, pos));
        let d = block.map_or(f64::MAX, |b| length_sqr(b.location, eye));
        let e = fluid.map_or(f64::MAX, |b| length_sqr(b.location, eye));
        if d <= e { block } else { fluid }
    })
    .unwrap_or_else(|| {
        BlockHit::miss(
            to,
            Direction::approximate_nearest(eye[0] - to[0], eye[1] - to[1], eye[2] - to[2]),
        )
    })
}