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
//! [`TickView`]: the read-only view a behaviour's `after_tick` gets after the movement step.

use super::*;

/// The getters [`TickContext`] and [`TickView`] share word for word, docs included: each name
/// expands to that method (both types hold `core: &Core` and `world`, a [`WorldView`]).
macro_rules! shared_getters {
    ($($name:ident),+ $(,)?) => {
        $(shared_getters!(@ $name);)+
    };
    (@ piston_uncertain) => {
        /// Moving pistons ran into a case the physics model does not cover in the last tick (its
        /// packets and its movement step): 1.8 moving stairs, slabs, fences, walls, panes,
        /// trapdoors or iron bars next to the player (their moving box comes from bounds the model
        /// does not track); 1.8 a moving head's push whose outcome depends on the head plate a
        /// crosshair ray may have left on ticks the engine did not trace it (it traces the ray while
        /// blocks move or piston heads are within reach); 1.8 moving heads, slabs, stairs, fences,
        /// panes and trapdoors whose box comes from shared bounds another entity's client-side move
        /// or ray may have changed (items, orbs, projectiles, falling blocks, TNT, boats the player
        /// has boarded: without entity tracking, or with a tracker started after the join, the
        /// engine cannot rule them out, so it always assumes one); 1.8
        /// a push that meets a boat, a minecart,
        /// TNT, an end crystal, a fireball, a falling block, a rider or a ridden entity (with entity
        /// tracking the engine moves its copies of players, mobs and armor stands, which the
        /// crosshair then picks where vanilla draws them); 1.12.2 a piston touching an entity that
        /// rides or carries another or one of those solid objects; 1.16.5 one touching the boat the
        /// player just left; 1.16.5 a client shape update of a kind the model does not cover
        /// (redstone wire, vines, fire, bamboo, bells, note blocks, tripwire, kelp and nether vine
        /// stems, bubble columns next to a piston's writes); 26.1 / 26.2 a client shape update of a
        /// kind the model does not cover (doors, beds, chests, redstone wire, vines, fire, note
        /// blocks, ... next to a piston's writes), a piston next to a rider or a ridden entity or
        /// the boat the player left, moving blocks while the player rides. The
        /// simulation goes on with the model's result, so the pose may differ from vanilla's until
        /// the server corrects it. `false` while nothing moves. Not flagged: on 1.8 the player's own
        /// collision with a moving head whose box comes from a head plate a ray left on a tick the
        /// engine did not trace.
        #[must_use]
        pub fn piston_uncertain(&self) -> bool {
            self.world.piston_uncertain()
        }
    };
    (@ entity_id) => {
        /// Our entity id.
        #[must_use]
        pub fn entity_id(&self) -> i32 {
            self.core.entity_id
        }
    };
    (@ health) => {
        /// Health, food, saturation and absorption.
        #[must_use]
        pub fn health(&self) -> Health {
            self.core.health
        }
    };
    (@ effects) => {
        /// Our active status effects (from `entity_effect` / `remove_entity_effect`, without
        /// entity tracking), with their durations and the tick each arrived; a new player entity
        /// (join, respawn) has none. [`crate::common::ActiveEffect::remaining`] counts down like
        /// the vanilla client. Changes: [`TickEvents::effects`].
        #[must_use]
        pub fn effects(&self) -> &[crate::common::ActiveEffect] {
            &self.core.active_effects
        }
    };
    (@ spawn_position) => {
        /// The world's spawn point from the server's last `spawn_position` (`None` before one).
        #[must_use]
        pub fn spawn_position(&self) -> Option<&crate::common::SpawnPoint> {
            self.core.spawn_point.as_ref()
        }
    };
    (@ teams) => {
        /// The scoreboard teams (only with [`Interests::TEAMS`]; `None` without it).
        #[must_use]
        pub fn teams(&self) -> Option<&crate::teams::Teams> {
            self.core.teams.as_deref()
        }
    };
    (@ hud) => {
        /// What the HUD shows now: boss bars, title, subtitle, action bar, the tab list's header
        /// and footer (only with [`Interests::HUD`]; `None` without it). See [`crate::hud`].
        #[must_use]
        pub fn hud(&self) -> Option<&crate::hud::Hud> {
            self.core.hud.as_deref()
        }
    };
    (@ last_hurt_tick) => {
        /// The tick (as [`TickContext::tick`]) in which the behaviour first saw our last hurt
        /// ([`TickEvents::hurt`]); `None` before one and for a new player entity.
        #[must_use]
        pub fn last_hurt_tick(&self) -> Option<u64> {
            self.core.last_hurt
        }
    };
    (@ world_time) => {
        /// The world's time: game time and the dimension's time of day (`update_time`, counted on
        /// between the server's updates); `None` before the first update.
        #[must_use]
        pub fn world_time(&self) -> Option<crate::common::WorldTime> {
            self.core.clocks.world_time(self.core.day_clock)
        }
    };
    (@ game_mode) => {
        /// Game mode.
        #[must_use]
        pub fn game_mode(&self) -> GameMode {
            self.core.game_mode
        }
    };
    (@ item_cooldowns) => {
        /// The player's item cooldowns now (1.9+; always empty on 1.8.9): the server's and the
        /// ones the client's own item uses started. See [`crate::cooldown`].
        #[must_use]
        pub fn item_cooldowns(&self) -> &crate::cooldown::ItemCooldowns {
            &self.core.cooldowns
        }

        /// The cooldown `stack` is under (its item on 1.12.2 / 1.16.5, its cooldown group on
        /// 26.x), while it cools down: a right click with it does nothing but its packets.
        /// `None` when it does not cool down (always on 1.8.9).
        #[must_use]
        pub fn item_cooldown(
            &self,
            stack: &ghast_inventory::Stack,
        ) -> Option<crate::cooldown::ItemCooldown> {
            if self.core.cooldowns.is_empty() {
                return None;
            }
            let key = crate::cooldown::key_of(
                self.core.opts.caps.item_cooldowns,
                self.core.inv.version(),
                stack,
            )?;
            self.core
                .cooldowns
                .get(&key)
                .filter(|c| c.fraction > 0.0)
        }

        /// [`Self::item_cooldown`] of the main hand's stack.
        #[must_use]
        pub fn held_cooldown(&self) -> Option<crate::cooldown::ItemCooldown> {
            self.core.inv.held().and_then(|s| self.item_cooldown(s))
        }
    };
}
pub(super) use shared_getters;

/// A read-only view after the movement step ([`Behavior::after_tick`]).
pub struct TickView<'a> {
    pub(super) core: &'a Core,
    pub(super) world: &'a dyn WorldView,
}

impl std::fmt::Debug for TickView<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TickView")
            .field("tick", &self.core.tick)
            .field("sent", &self.core.sent)
            .finish_non_exhaustive()
    }
}

impl TickView<'_> {
    /// Ticks since the session started.
    #[must_use]
    pub fn tick(&self) -> u64 {
        self.core.tick
    }

    /// The protocol version.
    #[must_use]
    pub fn version(&self) -> GameVersion {
        self.core.opts.caps.version
    }

    /// The client pose after this tick's movement step.
    #[must_use]
    pub fn pose(&self) -> &Pose {
        &self.core.pose
    }

    /// What the server has after this tick's movement packet (position, look, flags).
    #[must_use]
    pub fn sent(&self) -> &Pose {
        &self.core.sent
    }

    /// This tick's movement step hit a wall (see [`TickContext::horizontal_collision`]).
    #[must_use]
    pub fn horizontal_collision(&self) -> bool {
        self.world.collisions().0
    }

    /// This tick's movement step was cut vertically (see
    /// [`TickContext::vertical_collision`]).
    #[must_use]
    pub fn vertical_collision(&self) -> bool {
        self.world.collisions().1
    }

    shared_getters!(piston_uncertain);

    /// The world.
    #[must_use]
    pub fn world(&self) -> &dyn WorldView {
        self.world
    }

    /// The tracked entities (with [`Interests::ENTITIES`]).
    #[must_use]
    pub fn entities(&self) -> Option<&ghast_entity::Entities> {
        self.world.entities()
    }

    /// The inventory and the open window.
    #[must_use]
    pub fn inventory(&self) -> &ghast_inventory::Inventory {
        &self.core.inv
    }

    /// What the behaviour saw this tick (the events of [`TickContext::events`]).
    #[must_use]
    pub fn events(&self) -> &TickEvents {
        &self.core.current
    }

    shared_getters!(
        entity_id,
        health,
        effects,
        spawn_position,
        teams,
        hud,
        last_hurt_tick,
        world_time,
        game_mode,
        item_cooldowns
    );

    /// The selected hotbar slot.
    #[must_use]
    pub fn held_slot(&self) -> u8 {
        self.core.held_slot
    }

    /// The block being broken and its progress 0 … 1.
    #[must_use]
    pub fn mining(&self) -> Option<(ghast_protocol::BlockPos, f32)> {
        self.core.hands.mining()
    }

    /// Arm swings sent so far (see [`TickContext::swings`]).
    #[must_use]
    pub fn swings(&self) -> u64 {
        self.core.swings
    }

    /// Blocks broken so far.
    #[must_use]
    pub fn broken(&self) -> u64 {
        self.core.hands.broken
    }

    /// The current dimension (`"0"` / `"-1"` / `"1"` on 1.8, the world name on 1.16), as
    /// [`TickContext::dimension`].
    #[must_use]
    pub fn dimension(&self) -> &str {
        &self.core.dimension
    }

    /// Using the held item (eating, blocking, drawing a bow): movement input is slowed. As
    /// [`TickContext::using_item`].
    #[must_use]
    pub fn using_item(&self) -> bool {
        self.core.hands.using_item()
    }

    /// The serverbound packets of this tick in write order (its actions, the movement
    /// packet, `tick_end`), plus the answers to packets that arrived just before it; written
    /// to the socket right after [`Behavior::after_tick`]. A dig shows as
    /// [`Outbound::Dig`](crate::common::Outbound::Dig) with its status, block and face. The
    /// wire layer adds per-protocol details when it writes them (sequence numbers:
    /// [`TickView::prediction_sequence`]).
    #[must_use]
    pub fn outbound(&self) -> &[Outbound] {
        &self.core.out
    }

    /// [`TickContext::prediction_sequence`] (before this tick's packets are written).
    #[must_use]
    pub fn prediction_sequence(&self) -> Option<i32> {
        self.core.sequence
    }
}