ghast-client 0.5.6

Headless Minecraft Java Edition client for the ghast library: connection, login, fixed 50 ms tick loop and a version-agnostic bot API (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3)
Documentation
//! 1.8.9: the chunk store and the vanilla-exact physics.

use ghast_protocol::{BlockPos, RawPacket};

use super::*;
use crate::common::{Abilities, Controls, Outbound, Pose, Teleport, Vec3};
use crate::hands::{BlockQuery, HeldItem};

mod entities;
mod fishing;
mod hooks;
mod nonliving;
mod piston;
mod vehicles;

/// Block-local `[min, max]` of a physics box.
fn arr(b: &ghast_physics::math::Aabb) -> [f64; 6] {
    [b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]
}

/// The 1.8 ray shape at a position (ghast-physics: vanilla's bounds after
/// `Block.setBoundingBox`, neighbour-dependent shapes and the stairs passes):
/// `(selection, stairs passes)`.
fn ray_1_8(w: &ghast_world::v1_8::World, x: i32, y: i32, z: i32) -> RayBox {
    use ghast_physics::v1_8::RayShape;
    match ghast_physics::v1_8::ray_shape(w, x, y, z, false) {
        RayShape::None => (None, None),
        RayShape::Bounds(b) => (Some(arr(&b)), None),
        RayShape::Stairs(p) => (None, Some(p.boxes().map(|b| b.as_ref().map(arr)))),
    }
}

/// A ray shape as the hands take it.
type RayBox = (Option<[f64; 6]>, Option<[Option<[f64; 6]>; 8]>);

// ---- 1.8.9: ghast-physics ---------------------------------------------------------------

/// 1.8.9: the chunk store and the vanilla-exact physics.
pub(crate) struct Sim18 {
    world: ghast_world::v1_8::World,
    pub(super) player: ghast_physics::v1_8::PlayerState,
    packets: ghast_physics::Packets,
    rec: Option<crate::record::Recorder>,
    force_step_position: ForceStepPosition,
    entities: Option<ghast_entity::v1_8::Tracker>,
    /// Block changes since the last drain (position, version raw state), when collected.
    updates: BlockUpdates,
    /// The session's last join and respawn packets: a tracker started mid-session replays
    /// them to learn our entity id and dimension.
    session: SessionPackets,
    /// The world keeps block entities (signs, tile entity NBT).
    block_entities: bool,
    /// The boat we ride (the 1.8 client simulates it; with entity tracking).
    ride: Option<Box<Ride18>>,
    /// Our entity id (join game).
    own_id: Option<i32>,
    /// Test hook: the dimension's water vaporizes (an oracle case's).
    #[cfg(test)]
    vaporizes: bool,
    /// The flags byte (entity data index 0) the server last sent for our entity.
    server_flags: Option<u8>,
    /// The absorption the server last sent for our entity (player entity data; 0 before any).
    absorption: f32,
    /// `absorption` changed since the engine last took it.
    absorption_dirty: bool,
    /// Asleep in a bed: the box is the sleeping one (`PlayerEntity.inBed`).
    asleep: bool,
    /// Blocks pistons move (the client runs the piston itself on a block-action packet).
    pistons: ghast_physics::v1_8::Pistons,
    /// World changes of the pistons, applied right away (kept to reuse the allocation).
    piston_edits: ghast_physics::v1_8::Edits,
    /// An unmodelled piston condition in the last movement step or the packets since
    /// ([`super::WorldView::piston_uncertain`]): the player's `ticks_alive` when it was raised (it
    /// holds while that counter has not moved on, so the plain tick never touches it).
    piston_uncertain_at: Option<i32>,
    /// The moving blocks' half of this tick is still to run, after the other entities' ticks
    /// ([`Sim18::tick_piston_phase`], from `tick_entities`; with entity tracking).
    piston_phase: bool,
    /// A tick since the last crosshair ray of [`Sim18::step_pistons`] went without the ray
    /// while a piston head may have been within its reach (riding): the heads' shared bounds'
    /// history is not known. Plain ticks never set it: they are only taken while no head is
    /// loaded or none is within reach ([`Sim18::heads_near`]), when the ray cannot change the
    /// bounds.
    ray_missed: bool,
    /// Piston heads may be loaded in the client world (seen in a chunk's palette, a block
    /// change or a piston's write; cleared with the world): the ticks then check the heads'
    /// distance ([`Sim18::heads_near`]).
    head_watch: bool,
    /// The piston heads around [`Sim18::heads_center`] ([`Sim18::update_ray_need`]).
    heads: Vec<[i32; 3]>,
    heads_center: Option<[i32; 3]>,
    /// Boats we boarded (`onEntityAttach` naming us clears vanilla's empty flag): their client
    /// tick runs `Entity.move` from then on, even after we leave, until another entity boards
    /// them ([`Sim18::bounds_movers`]).
    boarded: Vec<i32>,
    /// The horses and pigs the client watches (with entity tracking), from their spawn packets
    /// on: the interpolation, body clock and rearing animation the player boards
    /// ([`watched_packet`](Sim18::watched_packet)).
    watched: Vec<(i32, ghast_physics::v1_8::Mount)>,
    /// The entity tracker started (or restarted) after the join: entities spawned before are
    /// not known until the next join or a respawn into another dimension.
    tracker_late: bool,
    /// Test hook: the JVM's `Math.sin` / `Math.cos` of the next boat tick (argument bits, sine,
    /// cosine), from an oracle record.
    #[cfg(test)]
    trig: Vec<(u64, f64, f64)>,
    /// The player's horse jump bar (it outlives a ride).
    jump_bar: ghast_physics::v1_8::JumpBar,
    /// With entity tracking and [`crate::Interests::ENTITY_PHYSICS`]: the client-side physics
    /// of the tracked non-living entities (`None`: off, nothing runs for them).
    nonliving: Option<Box<nonliving::NonLiving18>>,
    /// The bot's own fishing bobber ([`crate::fishing`]).
    fishing: crate::fishing::Fishing,
    /// The packet filter must change ([`Sim::take_filter_dirty`]: our bobber's splash sound).
    filter_dirty: bool,
}

/// Test hook: `Math.sin` / `Math.cos` from a table, the platform's for other arguments.
#[cfg(test)]
struct TableTrig<'a>(&'a [(u64, f64, f64)]);

#[cfg(test)]
impl ghast_physics::v1_8::JavaTrig for TableTrig<'_> {
    fn sin(&self, x: f64) -> f64 {
        self.0
            .iter()
            .find(|e| e.0 == x.to_bits())
            .map_or_else(|| x.sin(), |e| e.1)
    }
    fn cos(&self, x: f64) -> f64 {
        self.0
            .iter()
            .find(|e| e.0 == x.to_bits())
            .map_or_else(|| x.cos(), |e| e.2)
    }
}

/// The boat the player rides: its entity id and its client-side state.
#[derive(Debug)]
struct Ride18 {
    id: i32,
    seat: Seat18,
}

/// The boat the 1.8 client simulates, or the minecart or living mount the server moves.
#[derive(Debug)]
enum Seat18 {
    Boat(ghast_physics::v1_8::Boat),
    Cart(ghast_physics::v1_8::Minecart),
    Mount(ghast_physics::v1_8::Mount),
}

/// One client tick of every horse and pig the client watches (`Mount::tick` without a rider);
/// one another entity rides is no longer modelled.
#[cold]
#[inline(never)]
fn tick_watched_mounts(
    watched: &mut Vec<(i32, ghast_physics::v1_8::Mount)>,
    t: &ghast_entity::v1_8::Tracker,
    ridden: Option<i32>,
) {
    let me = t.self_id();
    watched.retain(|(id, _)| {
        t.get(*id)
            .is_some_and(|e| e.vehicle().is_none() && e.passengers().iter().all(|&p| Some(p) == me))
    });
    for (id, m) in watched.iter_mut() {
        if ridden != Some(*id) {
            m.tick(None);
        }
    }
}

/// A living mount (horse kinds, pig) as the client has it when we board it: the tracker's
/// drawn position and interpolation, rotation, head yaw, ground flag and entity data index 16
/// (without entity data a horse counts as saddled). The body clock starts as a fresh spawn's.
fn mount_of(e: &ghast_entity::Entity, kind: ghast_physics::v1_8::MountKind) -> Seat18 {
    use ghast_entity::MetaValue;
    let (yaw, pitch) = e.drawn_rotation();
    let mut m = ghast_physics::v1_8::Mount::new(kind, e.drawn_position(), yaw, pitch);
    m.tracked = e.position().map(|v| (v * 32.0).round() as i32);
    if let Some((target, steps)) = e.interpolation() {
        m.set_interpolation(target, e.yaw(), e.pitch(), i32::from(steps));
    }
    m.head_yaw = e.head_yaw();
    m.body_yaw = m.head_yaw;
    m.on_ground = e.drawn_on_ground();
    match e.metadata().get(16) {
        Some(MetaValue::Int(f)) => m.set_flags(*f),
        Some(MetaValue::Byte(b)) => m.set_flags(i32::from(*b)),
        _ => {
            log::warn!(
                "riding {kind:?} {} without its entity data (the metadata store is off): its \
                 saddle / rearing flags are unknown, taken as saddled and not rearing",
                e.id()
            );
            m.set_flags(ghast_physics::v1_8::HORSE_SADDLED | 1);
        }
    }
    Seat18::Mount(m)
}

impl std::fmt::Debug for Sim18 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Sim18")
            .field("world", &self.world)
            .field("pos", &self.player.pos)
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
impl Sim18 {
    /// Test hook: the physics player.
    pub(crate) fn test_player(&self) -> &ghast_physics::v1_8::PlayerState {
        &self.player
    }

    /// Test hook: the JVM's sine / cosine values of the next boat ticks (argument bits, sine,
    /// cosine).
    #[cfg(all(feature = "v1_12_2", feature = "v1_16_5", feature = "v26_1"))]
    pub(crate) fn test_set_trig(&mut self, t: Vec<(u64, f64, f64)>) {
        self.trig = t;
    }

    /// Test hook: replaces the physics player and syncs `pose`.
    pub(crate) fn test_set_player(&mut self, pose: &mut Pose, p: ghast_physics::v1_8::PlayerState) {
        self.player = p;
        self.piston_uncertain_at = None;
        self.pistons.forget_shared_bounds();
        sync_pose(pose, &self.player);
    }

    /// Test hook: sets one block.
    #[cfg(all(test, feature = "v1_12_2", feature = "v1_16_5"))]
    pub(crate) fn test_set_block(
        &mut self,
        x: i32,
        y: i32,
        z: i32,
        s: ghast_data::v1_8::BlockState,
    ) {
        let old = self.world.block_state(x, y, z);
        self.head_change(x, y, z, old, s.block().id() == 34);
        self.world.set_block_state(x, y, z, s);
    }

    /// Test hook: the chunk store.
    pub(crate) fn test_world(&self) -> &ghast_world::v1_8::World {
        &self.world
    }
}

impl Sim18 {
    pub(crate) fn new() -> Self {
        Sim18 {
            world: ghast_world::v1_8::World::new(config()),
            player: ghast_physics::v1_8::PlayerState::new([0.0; 3], 0.0, 0.0),
            packets: ghast_physics::Packets::new(),
            rec: None,
            force_step_position: ForceStepPosition::Off,
            entities: None,
            updates: BlockUpdates::default(),
            session: SessionPackets::default(),
            block_entities: false,
            ride: None,
            own_id: None,
            #[cfg(test)]
            vaporizes: false,
            server_flags: None,
            absorption: 0.0,
            absorption_dirty: false,
            pistons: ghast_physics::v1_8::Pistons::new(),
            piston_edits: ghast_physics::v1_8::Edits::new(),
            piston_uncertain_at: None,
            piston_phase: false,
            ray_missed: false,
            head_watch: false,
            heads: Vec::new(),
            heads_center: None,
            boarded: Vec::new(),
            watched: Vec::new(),
            tracker_late: false,
            #[cfg(test)]
            trig: Vec::new(),
            jump_bar: ghast_physics::v1_8::JumpBar::default(),
            asleep: false,
            nonliving: None,
            fishing: crate::fishing::Fishing::default(),
            filter_dirty: false,
        }
    }

    /// The tick asleep: out of line, so the plain tick stays as it was.
    #[cold]
    #[inline(never)]
    pub(super) fn step_asleep(&mut self, input: &ghast_physics::TickInput) {
        ghast_physics::v1_8::tick_asleep(
            &mut self.player,
            input,
            &self.world,
            &ghast_physics::v1_8::Options::default(),
            &mut self.packets,
        );
    }

    /// Animation 2 for our entity (`PlayerEntity.awaken(false, false, false)` on the client):
    /// `setBounds(0.6F, 1.8F)` grows the box from the sleeping box's minimum corner (the
    /// position stays until the next move derives it from the box). The stand-up position
    /// the client then computes next to a bed (`BedBlock.findSpawnablePos`) is not modelled:
    /// the server's position packet that follows the wake-up replaces it.
    pub(super) fn wake_up_legacy(&mut self) {
        if std::mem::take(&mut self.asleep) {
            let b = self.player.bb;
            let (w, h) = (
                f64::from(ghast_physics::v1_8::WIDTH),
                f64::from(ghast_physics::v1_8::HEIGHT),
            );
            self.player.bb = ghast_physics::math::Aabb {
                max_x: b.min_x + w,
                max_y: b.min_y + h,
                max_z: b.min_z + w,
                ..b
            };
        }
    }

    /// A sim with options (recording, Grim compatibility).
    pub(crate) fn with(opts: &SimOptions) -> Self {
        let mut s = Self::new();
        s.force_step_position = opts.force_step_position;
        s.entities = opts.entities.map(ghast_entity::v1_8::Tracker::new);
        if let Some(c) = opts.world {
            s.world = ghast_world::v1_8::World::new(c);
            s.block_entities = c.block_entities;
        }
        if opts.shared_chunks.is_some() {
            log::debug!("shared chunks are not used on 1.8.9; every section stays owned");
        }
        if let Some(p) = opts.record.as_deref() {
            match crate::record::Recorder::create(p) {
                Ok(r) => s.rec = Some(r),
                Err(e) => log::warn!("cannot record to {}: {e}", p.display()),
            }
        }
        s
    }
}

sync_pose_fn!(sync_pose(p: ghast_physics::v1_8::PlayerState), y: p.bb.min_y, sneaking: sneaking);