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.12.2: 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 elytra;
mod entities;
mod fishing;
mod hooks;
mod nonliving;
mod piston;
mod records;
mod vehicles;

use entities::{Class12, Kept, Near12};
use vehicles::{tick_watched_mounts, watched_mount_pushed, watched_packet};

// ---- 1.12.2: ghast-physics --------------------------------------------------------------

/// 1.12 blocks whose client `Block.onUse` answers a right click: the 1.8 list plus the 1.9 – 1.12
/// additions (command blocks, shulker boxes, structure block).
fn activates_1_12(id: u8) -> bool {
    ACTIVATED_1_8.contains(&id) || matches!(id, 137 | 210 | 211 | 219..=234 | 255)
}

/// The 1.12 ray box of a block: the oracle's selection bounds for static shapes; for shapes that
/// follow the neighbours the union of the actual collision boxes (an approximation of vanilla's
/// per-state outline, as for 1.16.5).
fn ray_1_12(w: &ghast_world::v1_12::World, x: i32, y: i32, z: i32) -> Option<[f64; 6]> {
    let s = w.block_state(x, y, z)?;
    let sel = s.selection();
    if !sel.can_collide {
        return None;
    }
    if sel.dependency == ghast_data::ShapeDependency::None {
        let b = sel.bounds;
        return Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z]);
    }
    let local: Vec<ghast_data::Aabb> = ghast_physics::v1_12::collision_boxes(w, x, y, z)
        .iter()
        .map(|b| {
            let (fx, fy, fz) = (f64::from(x), f64::from(y), f64::from(z));
            ghast_data::Aabb::new(
                b.min_x - fx,
                b.min_y - fy,
                b.min_z - fz,
                b.max_x - fx,
                b.max_y - fy,
                b.max_z - fz,
            )
        })
        .collect();
    union(&local).or_else(|| {
        let b = sel.bounds;
        Some([b.min_x, b.min_y, b.min_z, b.max_x, b.max_y, b.max_z])
    })
}

/// 1.12.2: the chunk store and the vanilla-exact physics.
pub(crate) struct Sim12 {
    world: ghast_world::v1_12::World,
    player: ghast_physics::v1_12::PlayerState,
    packets: ghast_physics::Packets,
    force_step_position: ForceStepPosition,
    entities: Option<ghast_entity::v1_12::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.
    block_entities: bool,
    /// With entity tracking: the client side of the entities that push the player or are solid
    /// for it, and the teams' collision rules.
    near: Option<Box<Near12>>,
    /// The player's scoreboard name (team rules).
    profile_name: Box<str>,
    /// Entities push the player (`Client::entity_push`).
    entity_push: bool,
    /// Movement state beyond the player: gliding.
    ext: ghast_physics::v1_12::PlayerExt,
    /// Gliding: the server's flag 7 and the firework rockets attached to us.
    glide: Box<Glide12>,
    /// The extension state can act (an elytra, gliding, rockets): the tick takes
    /// [`Sim12::step_ext`] and the rockets tick after it.
    glide_on: bool,
    /// Movement recording ([`crate::Client::record`]).
    rec: Option<crate::record::Recorder>,
    /// The vehicle we ride (`set_passengers` naming us, with entity tracking): a boat or a
    /// living mount the client moves, or a minecart, llama or unsteered pig the server moves.
    ride: Option<Box<Ride12>>,
    /// The boat we left last (see [`LeftBoat12`]).
    left_boat: Option<Box<LeftBoat12>>,
    /// The rider's jump bar of a saddled horse (kept across rides, as the client player does).
    rider_jump: ghast_physics::v1_12::RiderJump,
    /// The movement attributes the server sent for the living mounts around (entity
    /// properties: movement speed, jump strength), read when we board one.
    mount_attrs: Vec<MountAttrs12>,
    /// We hold a carrot on a stick in either hand (a pig we ride follows it).
    carrot: bool,
    /// The answer to a server packet that goes out at once (`vehicle_move`).
    reply: Option<Outbound>,
    /// The flags byte (entity data index 0) the server last sent for our entity.
    server_flags: Option<u8>,
    /// Our living (hand) flags, entity data index 6, when a packet set them (taken per tick).
    living_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,
    /// The client world's map id counter (`getIntState("map")`): empty maps used since the
    /// world was made (join, a respawn into another dimension).
    maps: std::sync::atomic::AtomicI16,
    /// Blocks pistons move (the client runs the piston itself on a block-action packet).
    pistons: ghast_physics::v1_12::Pistons,
    /// World changes of the pistons, applied right away (kept to reuse the allocation).
    piston_edits: ghast_physics::v1_12::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>,
    /// Client ticks so far: the world time pistons compare (it advances by one per tick).
    piston_time: i64,
    /// The per-world-tick piston budget of the entities a piston moved that the near-entity
    /// model does not hold (armor stands, bats).
    piston_carry: Vec<(i32, ghast_physics::v1_12::PistonCarry)>,
    /// 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::NonLiving12>>,
    /// The bot's own fishing bobber ([`crate::fishing`]).
    fishing: crate::fishing::Fishing,
}

/// The boat the player last left, as it was then: a boat the client does not move keeps its
/// turn (`yawVelocity`, never decayed) and paddle flags; boarded again before it ticked, it is
/// exactly this.
#[derive(Debug)]
struct LeftBoat12 {
    id: i32,
    /// The client tick count (the sim's `piston_time`) of the next tick after it left.
    tick: i64,
    boat: ghast_physics::v1_12::Boat,
}

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

/// The boat the client moves, the minecart the server moves, or a living mount (the client
/// moves the horse family but the llama, and a pig while we hold its carrot on a stick).
#[derive(Debug)]
enum Seat12 {
    Boat(ghast_physics::v1_12::Boat),
    Cart(ghast_physics::v1_12::Minecart),
    Mount(Box<ghast_physics::v1_12::Mount>),
}

/// Attribute modifiers `(uuid, amount, operation)` in packet order.
type SpeedModifiers12 = Vec<(u128, f64, u8)>;

/// The movement attributes the server sent for a living mount (`entity_update_attributes`).
#[derive(Debug, Clone, Default)]
struct MountAttrs12 {
    id: i32,
    /// Movement speed: base and modifiers `(uuid, amount, operation)`.
    speed: Option<(f64, SpeedModifiers12)>,
    /// Jump strength base (`horse.jumpStrength`).
    jump: Option<f64>,
}

/// The living mount kind of a tracked 1.12 entity (its mob id), if it is one.
fn mount_kind_12(t: ghast_entity::EntityType) -> Option<ghast_physics::v1_12::MountKind> {
    use ghast_physics::v1_12::MountKind as K;
    let ghast_entity::EntityType::LegacyMob(m) = t else {
        return None;
    };
    Some(match m {
        100 => K::Horse,
        31 => K::Donkey,
        32 => K::Mule,
        28 => K::SkeletonHorse,
        29 => K::ZombieHorse,
        103 => K::Llama,
        90 => K::Pig,
        _ => return None,
    })
}

/// The attributes the server sent, applied to the mount.
fn apply_mount_attrs(m: &mut ghast_physics::v1_12::Mount, a: &MountAttrs12) {
    if let Some((base, mods)) = &a.speed {
        m.apply_speed_attribute(*base, mods);
    }
    if let Some(j) = a.jump {
        m.apply_jump_strength(j);
    }
}

/// 1.12 item id of the carrot on a stick.
const CARROT_ON_A_STICK_12: i32 = 398;
/// Capacity of [`Sim12::mount_attrs`] (the oldest entry goes first).
const MOUNT_ATTRS_CAP: usize = 64;

/// What the 1.12.2 glide reads beyond the physics state, decoded once an elytra was seen in the
/// chest slot: our shared flags (the server starts and ends the glide) and the rockets attached
/// to us.
#[derive(Debug, Default)]
struct Glide12 {
    /// Our entity data, rocket spawns and entity removals are read.
    watch: bool,
    /// The packet filter must change ([`Sim::take_filter_dirty`]).
    filter_dirty: bool,
    /// Our entity id (the tick's).
    own_id: i32,
    /// Firework rockets spawned but not (yet) known as attached to us: id, spawn height.
    pending: Vec<(i32, f64)>,
    /// The rockets attached to us, in the client world's entity list order (they tick after
    /// us): id, height (the spawn height, then ours after each of its ticks).
    rockets: Vec<(i32, f64)>,
}

/// The 1.12.2 spawn-object type of a firework rocket.
const FIREWORK_ROCKET_12: i8 = 76;

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

/// The dimension a 1.12.2 login (`login_id`) or respawn packet names.
fn dimension_of(raw: Option<&RawPacket>, login_id: i32) -> Option<i32> {
    let raw = raw?;
    // login: entity id (int), game mode (byte), dimension (int); respawn: dimension first
    let at = if raw.id == login_id { 5 } else { 0 };
    let b = raw.body.get(at..at + 4)?;
    Some(i32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}

impl Sim12 {
    /// 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.ext.sleeping) {
            self.update_glide();
            let p = &mut self.player;
            let b = p.bb;
            p.width = ghast_physics::v1_12::WIDTH;
            p.height = ghast_physics::v1_12::HEIGHT;
            p.bb = ghast_physics::math::Aabb {
                max_x: b.min_x + f64::from(p.width),
                max_y: b.min_y + f64::from(p.height),
                max_z: b.min_z + f64::from(p.width),
                ..b
            };
        }
    }

    /// The dimension of the session's last join or respawn (`None`: none seen).
    fn dimension(&self) -> Option<i32> {
        dimension_of(
            self.session
                .respawn
                .as_ref()
                .or(self.session.login.as_ref()),
            ghast_protocol::v1_12_2::play::clientbound::id::LOGIN,
        )
    }

    pub(crate) fn new() -> Self {
        Sim12 {
            world: ghast_world::v1_12::World::new(config()),
            player: fresh_player_1_12(),
            packets: ghast_physics::Packets::new(),
            force_step_position: ForceStepPosition::Off,
            entities: None,
            updates: BlockUpdates::default(),
            session: SessionPackets::default(),
            block_entities: false,
            near: None,
            profile_name: "".into(),
            entity_push: true,
            ext: ghast_physics::v1_12::PlayerExt::new(),
            glide: Box::default(),
            glide_on: false,
            rec: None,
            ride: None,
            left_boat: None,
            rider_jump: ghast_physics::v1_12::RiderJump::default(),
            mount_attrs: Vec::new(),
            carrot: false,
            reply: None,
            server_flags: None,
            living_flags: None,
            absorption: 0.0,
            absorption_dirty: false,
            maps: std::sync::atomic::AtomicI16::new(0),
            pistons: ghast_physics::v1_12::Pistons::new(),
            piston_edits: ghast_physics::v1_12::Edits::new(),
            piston_uncertain_at: None,
            piston_time: 0,
            piston_carry: Vec::new(),
            nonliving: None,
            fishing: crate::fishing::Fishing::default(),
        }
    }

    /// A sim with options (Grim compatibility, entities, world contents, movement recording).
    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_12::Tracker::new);
        s.near = s.entities.is_some().then(Box::default);
        if let Some(n) = &opts.profile_name {
            s.profile_name = n.as_str().into();
        }
        if let Some(c) = opts.world {
            s.world = ghast_world::v1_12::World::new(c);
            s.block_entities = c.block_entities;
        }
        if opts.shared_chunks.is_some() {
            log::debug!("shared chunks are not used on 1.12.2; 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
    }
}

/// A fresh 1.12 client player: not yet in a chunk (the first tick with its column loaded adds
/// it, the next one moves it), as vanilla.
fn fresh_player_1_12() -> ghast_physics::v1_12::PlayerState {
    let mut p = ghast_physics::v1_12::PlayerState::new([0.0; 3], 0.0, 0.0);
    p.added_to_chunk = false;
    p
}

sync_pose_fn!(
    sync_pose_12(p: ghast_physics::v1_12::PlayerState),
    y: p.bb.min_y,
    sneaking: sneaking
);