ghast-client 0.5.4

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 client-side physics of the tracked non-living entities
//! ([`crate::Interests::ENTITY_PHYSICS`]): projectiles, item entities, experience orbs, primed
//! TNT and falling blocks run their own tick on the client every client tick
//! (`World.checkChunk`), with the client's side of the rules
//! (`ghast_physics::v1_8::{projectile, drop}`, oracle-proven per kind).
//!
//! The physics state is the client's copy of the entity. Each packet the tracker applied is
//! handed to the copy the way `ClientPlayNetworkHandler` does it, and the copy is written back
//! to the tracker ([`ghast_entity::v1_8::Tracker::client_simulated`]):
//!
//! * spawn (`onEntitySpawn`): the entity the client constructs at the packet's position (a
//!   hurting projectile's acceleration from the packet's motion), the packet's rotation, then
//!   `setVelocityClient` with the packet's motion when the object data is above 0 after the
//!   client's resets; an item's, orb's and TNT's constructor motion comes from an unseeded
//!   random — here the packet's motion (0 without one), which the velocity packet a server
//!   sends after a spawn replaces;
//! * relative moves, the bare `entity` packet and teleports (`onEntityUpdate`,
//!   `onEntityPosition`; a teleport within 1/32, 1/64 vertically, of the copy keeps the copy's
//!   position): `updateTrackedPositionAndAngles` — thrown items, hurting projectiles, items,
//!   orbs, TNT and falling blocks move there and are pushed up onto the block boxes they run
//!   into, an arrow just moves, a fishing bobber interpolates toward it over 3 ticks; the
//!   ground flag is the packet's;
//! * velocity (`setVelocityClient`): a thrown item or an arrow with a previous rotation of
//!   0 / 0 also turns to the motion; a bobber keeps the motion for its next position packet;
//! * entity data: a dangerous wither skull.
//!
//! A 1.8 client ticks every entity filed in a loaded chunk, and keeps ticking it wherever it
//! goes; one spawned in an unloaded column is filed (and ticks) once a packet moves it into a
//! loaded one. The client discards a TNT whose fuse ran out, a falling block of air and an
//! entity below y −64.
//!
//! Not simulated: entity hits, pickup, merging, an orb following a player within 8 blocks,
//! passengers, other entities' boxes in the position packets' push-up (boats, minecarts), the
//! falling block's removal of its own block from the client world, a hurting projectile
//! spawned without motion (NaN acceleration in vanilla), and the random draws of a client
//! entity (unseeded in vanilla; seeded with the entity id here).

use std::collections::HashMap;

use super::*;
use ghast_entity::EntityType;
use ghast_physics::v1_8::Side;
use ghast_physics::v1_8::drop::{self, Drop, DropKind};
use ghast_physics::v1_8::projectile::{self, Projectile, ProjectileKind};

#[derive(Debug)]
enum State {
    Projectile(Projectile),
    Drop(Drop),
}

/// One simulated entity.
#[derive(Debug)]
struct Entry {
    state: State,
    /// `updateNeeded`: filed in a loaded chunk.
    filed: bool,
}

/// A position / motion / rotation / ground update for the tracker.
type Update = (i32, [f64; 3], [f64; 3], [f32; 2], bool);

/// The simulated entities (a side table: only while [`crate::Interests::ENTITY_PHYSICS`] is on).
#[derive(Debug, Default)]
pub(super) struct NonLiving18 {
    map: HashMap<i32, Entry>,
    updates: Vec<Update>,
    discards: Vec<i32>,
}

impl NonLiving18 {
    /// Forgets every entity (a new world, a new tracker).
    pub(super) fn clear(&mut self) {
        self.map.clear();
    }
}

/// `WitherSkullEntity`'s invulnerable (dangerous) flag: entity data 10, a byte.
const SKULL_DANGEROUS: u8 = 10;

#[derive(Clone, Copy)]
enum Kind {
    Projectile(ProjectileKind),
    Drop(DropKind),
}

/// The kind of a 1.8 object type (`onEntitySpawn`'s type byte).
fn kind_of(t: EntityType) -> Option<Kind> {
    use Kind::{Drop as D, Projectile as P};
    Some(match t {
        EntityType::ExperienceOrb => D(DropKind::ExperienceOrb),
        EntityType::LegacyObject(o) => match o {
            2 => D(DropKind::Item),
            50 => D(DropKind::PrimedTnt),
            70 => D(DropKind::FallingBlock),
            60 => P(ProjectileKind::Arrow),
            61 => P(ProjectileKind::Snowball),
            62 => P(ProjectileKind::Egg),
            65 => P(ProjectileKind::EnderPearl),
            73 => P(ProjectileKind::SplashPotion),
            75 => P(ProjectileKind::ExperienceBottle),
            63 => P(ProjectileKind::LargeFireball),
            64 => P(ProjectileKind::SmallFireball),
            66 => P(ProjectileKind::WitherSkull),
            90 => P(ProjectileKind::FishingBobber),
            _ => return None,
        },
        _ => return None,
    })
}

/// Object types whose object data the client resets to 0 before it applies the motion.
fn data_reset(t: u8) -> bool {
    matches!(t, 63 | 64 | 66 | 70 | 71 | 73 | 75 | 77 | 90)
}

/// The column at `pos` is loaded.
fn column_loaded(w: &ghast_world::v1_8::World, pos: [f64; 3]) -> bool {
    w.is_column_loaded((pos[0].floor() as i32) >> 4, (pos[2].floor() as i32) >> 4)
}

impl Sim18 {
    /// Switches the client-side physics of the non-living entities on or off.
    pub(super) fn set_nonliving(&mut self, on: bool) {
        if on == self.nonliving.is_some() {
            return;
        }
        // Entities spawned before are known again once the server sends them again.
        self.nonliving = on.then(Box::default);
    }

    /// A packet the simulated entities care about, after the tracker applied it.
    #[cold]
    #[inline(never)]
    pub(super) fn nonliving_packet(&mut self, raw: &RawPacket) -> Result<(), SimError> {
        use ghast_protocol::defs::p47::types::EntityMetadataValue as V;
        use ghast_protocol::v1_8::play::clientbound as cb;
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return Ok(());
        };
        let world = &self.world;
        let mut r = ghast_protocol::Reader::new(&raw.body);
        let id = match raw.id {
            cb::id::LOGIN => {
                n.clear();
                return Ok(());
            }
            cb::id::SPAWN_ENTITY | cb::id::SPAWN_ENTITY_EXPERIENCE_ORB => {
                let id = r.read_varint()?;
                n.map.remove(&id);
                let Some(e) = t.get(id) else {
                    return Ok(());
                };
                let Some(state) = spawned(e) else {
                    return Ok(());
                };
                // addEntityToChunk: filed when its column is loaded.
                let filed = column_loaded(world, e.position());
                n.map.insert(id, Entry { state, filed });
                id
            }
            cb::id::ENTITY_VELOCITY => {
                let id = r.read_varint()?;
                let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
                    return Ok(());
                };
                match &mut en.state {
                    State::Projectile(p) => p.set_velocity_client(e.velocity()),
                    State::Drop(d) => d.set_vel(e.velocity()),
                }
                id
            }
            cb::id::REL_ENTITY_MOVE
            | cb::id::ENTITY_MOVE_LOOK
            | cb::id::ENTITY_LOOK
            | cb::id::ENTITY
            | cb::id::ENTITY_TELEPORT => {
                let id = r.read_varint()?;
                let (Some(en), Some(e)) = (n.map.get_mut(&id), t.get(id)) else {
                    return Ok(());
                };
                let target = e.position();
                // onEntityPosition: a copy within 1/32 (1/64 vertically) of the packet's
                // position stays where it is.
                let to = |at: [f64; 3]| {
                    if raw.id == cb::id::ENTITY_TELEPORT
                        && (at[0] - target[0]).abs() < 0.03125
                        && (at[1] - target[1]).abs() < 0.015625
                        && (at[2] - target[2]).abs() < 0.03125
                    {
                        at
                    } else {
                        target
                    }
                };
                // The rotation: the packet's, or the copy's own (the tracker holds it).
                let (yaw, pitch) = (e.yaw(), e.pitch());
                match &mut en.state {
                    State::Projectile(p) => {
                        p.set_tracked_position(to(p.pos()), yaw, pitch, world);
                        p.set_on_ground(e.on_ground());
                    }
                    State::Drop(d) => {
                        d.set_tracked_position(to(d.pos()), world);
                        d.set_on_ground(e.on_ground());
                    }
                }
                id
            }
            cb::id::ENTITY_METADATA => {
                let id = r.read_varint()?;
                let Some(State::Projectile(p)) = n.map.get_mut(&id).map(|en| &mut en.state) else {
                    return Ok(());
                };
                if p.kind() != ProjectileKind::WitherSkull {
                    return Ok(());
                }
                let m: cb::EntityMetadata = raw.decode_as()?;
                for m in &m.metadata {
                    if let (SKULL_DANGEROUS, V::Byte(b)) = (m.key, &m.value) {
                        p.set_dangerous(*b == 1);
                    }
                }
                return Ok(());
            }
            _ => return Ok(()),
        };
        // The copy as the handler left it.
        if let Some(en) = n.map.get(&id) {
            let (pos, vel, rot, g) = copy_of(&en.state, t.get(id));
            t.client_simulated(id, pos, vel, rot, g);
        }
        Ok(())
    }

    /// One client tick of the simulated entities (`World.checkChunk` of each one that is not
    /// riding).
    #[cold]
    #[inline(never)]
    pub(super) fn tick_nonliving(&mut self) {
        let (Some(n), Some(t)) = (&mut self.nonliving, &mut self.entities) else {
            return;
        };
        if n.map.is_empty() {
            return;
        }
        let world = &self.world;
        let NonLiving18 {
            map,
            updates,
            discards,
        } = &mut **n;
        updates.clear();
        discards.clear();
        map.retain(|&id, en| {
            let Some(e) = t.get(id) else {
                return false;
            };
            if e.vehicle().is_some() {
                return true;
            }
            if !en.filed {
                // Not filed in a chunk: no tick; it is filed once its column is loaded.
                if let State::Projectile(p) = &mut en.state {
                    p.skip_tick();
                }
                en.filed = column_loaded(world, e.position());
                return true;
            }
            match &mut en.state {
                State::Projectile(p) => {
                    projectile::tick_projectile(p, Side::Client, world);
                    if p.removed() {
                        discards.push(id);
                        return false;
                    }
                }
                State::Drop(d) => {
                    drop::tick_drop(d, Side::Client, world);
                    if d.removed() {
                        discards.push(id);
                        return false;
                    }
                }
            }
            let (pos, vel, rot, g) = copy_of(&en.state, Some(e));
            updates.push((id, pos, vel, rot, g));
            true
        });
        for &(id, pos, vel, rot, g) in updates.iter() {
            t.client_simulated(id, pos, vel, rot, g);
        }
        for &id in discards.iter() {
            t.client_discarded(id);
        }
    }
}

/// Position, motion, rotation and ground flag of the client copy (a drop keeps the tracker's
/// rotation: its tick never turns it).
fn copy_of(s: &State, e: Option<&ghast_entity::Entity>) -> ([f64; 3], [f64; 3], [f32; 2], bool) {
    match s {
        State::Projectile(p) => (p.pos(), p.vel(), [p.yaw(), p.pitch()], p.on_ground()),
        State::Drop(d) => (
            d.pos(),
            d.vel(),
            e.map_or([0.0; 2], |e| [e.yaw(), e.pitch()]),
            d.on_ground(),
        ),
    }
}

/// The client's copy of a freshly spawned entity (`onEntitySpawn` / `onExperienceOrbSpawn`): the
/// constructor at the packet's position, the packet's rotation, then the packet's motion through
/// `setVelocityClient` when the object data (after the client's resets) is above 0. `None` for
/// other types. Its random is seeded with the entity id.
fn spawned(e: &ghast_entity::Entity) -> Option<State> {
    let ty = e.entity_type();
    let pos = e.position();
    // The packet's motion (the tracker reads it when the data is above 0).
    let packet_vel = e.velocity();
    let seed = i64::from(e.id());
    let applies = match ty {
        EntityType::LegacyObject(o) => !data_reset(o) && e.data() > 0,
        _ => false,
    };
    Some(match kind_of(ty)? {
        Kind::Projectile(k) => {
            // Only a hurting projectile's constructor reads the motion (its acceleration).
            let mut p = Projectile::new(k, pos, packet_vel).with_random_seed(seed);
            p.set_vel([0.0; 3]);
            p.set_rotation(e.yaw(), e.pitch());
            if applies {
                p.set_velocity_client(packet_vel);
            }
            State::Projectile(p)
        }
        Kind::Drop(k) => {
            let mut d = Drop::new(k, pos, [0.0; 3])
                .with_id(e.id())
                .with_random_seed(seed);
            if k == DropKind::FallingBlock {
                // The block from the data (id | meta << 12).
                let raw = e.data() & 0xFFFF;
                d = d.with_block(ghast_data::v1_8::BlockState::from_raw_vanilla(
                    (((raw & 4095) as u16) << 4) | ((raw >> 12) & 15) as u16,
                ));
            } else if k != DropKind::ExperienceOrb {
                d.set_vel(packet_vel);
            }
            State::Drop(d)
        }
    })
}