ghast-client 0.5.5

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
//! Small pieces shared by the per-version simulations (each one is the same code in every
//! version that uses it). The macros expand inside each version's own module, so every copy is
//! compiled against that version's types, exactly as a hand-written copy would be.

/// The `WorldView` methods that only forward to the version's player and world: `$age` is the
/// player's tick counter that `WorldView::piston_uncertain` compares with.
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
macro_rules! world_view_forwards {
    (age: $age:ident) => {
        fn collisions(&self) -> (bool, bool) {
            (
                self.player.horizontal_collision,
                self.player.vertical_collision,
            )
        }

        fn piston_uncertain(&self) -> bool {
            self.piston_uncertain_at == Some(self.player.$age)
        }

        fn is_column_loaded(&self, chunk_x: i32, chunk_z: i32) -> bool {
            self.world.is_column_loaded(chunk_x, chunk_z)
        }

        fn entities(&self) -> Option<&ghast_entity::Entities> {
            self.entities.as_deref()
        }

        fn loaded_columns(&self) -> usize {
            self.world.columns().len()
        }
    };
}

/// The piston bookkeeping methods of a simulation: `prune_pistons` (a moving block whose block
/// is no longer a moving-piston block is gone; `$moving` tells the moving-piston block's
/// state) and, with `wire_id`, `apply_piston_edits` (the pistons' world changes into the chunk
/// store and the block-update buffer, `$wire` being the state's wire id).
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
macro_rules! piston_bookkeeping {
    (moving: $moving:expr) => {
        /// After a packet changed blocks: a moving block whose block is no longer a
        /// moving-piston block is gone (the client drops the block entity of a replaced block).
        #[inline]
        pub(super) fn prune_pistons(&mut self) {
            if !self.pistons.is_empty() {
                self.prune_pistons_slow();
            }
        }

        #[cold]
        #[inline(never)]
        fn prune_pistons_slow(&mut self) {
            let w = &self.world;
            self.pistons.retain(|m| {
                w.block_state(m.pos[0], m.pos[1], m.pos[2])
                    .is_some_and($moving)
            });
        }
    };
    (moving: $moving:expr, wire_id: $wire:ident) => {
        piston_bookkeeping!(moving: $moving);

        /// Writes the pistons' world changes into the chunk store.
        fn apply_piston_edits(&mut self) {
            for &([x, y, z], s) in &self.piston_edits {
                if self.world.set_block_state(x, y, z, s) {
                    self.updates
                        .push(BlockPos::new(x, y, z), u32::from(s.$wire()));
                }
            }
        }
    };
}

/// `fn $name(pose, $p: &$state)`: the player's state into the engine's `Pose`. `$y` is the
/// position's y (1.8 and 1.12 read the box's bottom), `$sneak` the state's sneaking method.
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
macro_rules! sync_pose_fn {
    ($name:ident($p:ident: $state:ty), y: $y:expr, sneaking: $sneak:ident) => {
        fn $name(pose: &mut Pose, $p: &$state) {
            pose.pos = Vec3::new($p.pos[0], $y, $p.pos[2]);
            pose.motion = Vec3::new($p.vel[0], $p.vel[1], $p.vel[2]);
            pose.yaw = $p.yaw;
            pose.pitch = $p.pitch;
            pose.on_ground = $p.on_ground;
            pose.flying = $p.abilities.flying;
            pose.sneaking = $p.$sneak();
            pose.sprinting = $p.sprinting;
        }
    };
}

/// The clientbound packets a ride recording reads (`record_vehicle_packet`), by the ids of the
/// protocol module `$proto` (1.12.2 and 1.16.5 name them alike).
#[cfg(any(feature = "v1_12_2", feature = "v1_16_5"))]
macro_rules! recorded_vehicle_packets {
    ($($proto:ident)::+) => {{
        use $($proto)::+::play::clientbound::id;
        [
            id::SPAWN_ENTITY_LIVING,
            id::ENTITY_METADATA,
            id::ENTITY_UPDATE_ATTRIBUTES,
            id::ENTITY_VELOCITY,
            id::REL_ENTITY_MOVE,
            id::ENTITY_MOVE_LOOK,
            id::ENTITY_LOOK,
            id::ENTITY_TELEPORT,
            id::ENTITY_HEAD_ROTATION,
            id::ENTITY_EQUIPMENT,
            id::ENTITY_DESTROY,
            id::SET_PASSENGERS,
            id::VEHICLE_MOVE,
        ]
    }};
}

/// A `[min x, min y, min z, max x, max y, max z]` box as the physics' box.
#[cfg(any(feature = "v1_16_5", ghast_modern))]
pub(super) fn aabb(b: [f64; 6]) -> ghast_physics::math::Aabb {
    ghast_physics::math::Aabb::new(b[0], b[1], b[2], b[3], b[4], b[5])
}

/// The identity of each player object for the orbs that follow players
/// (`ghast_physics::orb::OrbPlayer::id`): an orb keeps following the player object it picked,
/// and a player spawned again under the same entity id is a new object. The entity id until a
/// spawn packet for that id arrives, then a fresh number per spawn.
///
/// An orb may follow a player that left the level: that copy still answers `isSpectator()` from
/// the tab list, by its profile's UUID (26.x: through the tab-list object it cached, see
/// [`PlayerIdents::seen`]), so the last facts of each followed identity are kept.
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
#[derive(Debug, Default)]
pub(super) struct PlayerIdents {
    map: std::collections::HashMap<i32, i32>,
    next: i32,
    /// The last facts of each identity.
    known: std::collections::HashMap<i32, PlayerFacts>,
}

/// What a removed player object still answers ([`PlayerIdents`]).
#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
#[derive(Debug, Clone, Copy)]
pub(super) struct PlayerFacts {
    /// Profile UUID (its tab-list entry).
    pub(super) uuid: uuid::Uuid,
    /// 26.x: the generation of the tab-list object it cached (0: none yet).
    #[cfg(ghast_modern)]
    pub(super) generation: u32,
    /// `isSpectator()` when last asked.
    pub(super) spectator: bool,
    /// Where its last tick left it, and its eye height then.
    pub(super) pos: [f64; 3],
    pub(super) eye_height: f32,
}

#[cfg(any(
    feature = "v1_8",
    feature = "v1_12_2",
    feature = "v1_16_5",
    ghast_modern
))]
impl PlayerIdents {
    /// Player entity `id` was spawned (again).
    pub(super) fn spawned(&mut self, id: i32) {
        // Bit 30 set: above every entity id a server hands out in practice.
        self.next = self.next.wrapping_add(1) | 0x4000_0000;
        self.map.insert(id, self.next);
    }

    /// The identity of player entity `id`.
    pub(super) fn of(&self, id: i32) -> i32 {
        self.map.get(&id).copied().unwrap_or(id)
    }

    /// Player identity `ident` is (or was last) like this.
    pub(super) fn seen(&mut self, ident: i32, facts: PlayerFacts) {
        self.known.insert(ident, facts);
    }

    /// Player entity `id`'s eye height changed between ticks (entity data): an orb that keeps
    /// following it after it leaves the world reads the new one.
    pub(super) fn eye_changed(&mut self, id: i32, eye_height: f32) {
        let ident = self.of(id);
        if let Some(f) = self.known.get_mut(&ident) {
            f.eye_height = eye_height;
        }
    }

    /// The last facts of identity `ident` ([`PlayerIdents::seen`]).
    pub(super) fn facts(&self, ident: i32) -> Option<PlayerFacts> {
        self.known.get(&ident).copied()
    }

    /// Keeps the facts of the identities `keep` says yes to.
    pub(super) fn retain(&mut self, mut keep: impl FnMut(i32) -> bool) {
        self.known.retain(|&k, _| keep(k));
    }

    /// Forgets every player (a new level).
    pub(super) fn clear(&mut self) {
        self.map.clear();
        self.known.clear();
    }
}