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
//! The behaviour contract: the [`Behavior`] trait (with its boxed form), the do-nothing
//! [`Idle`] behaviour, and a click's ticket and refusal ([`ClickTicket`], [`ClickRefused`]).

use super::*;

/// A bot behaviour: the code that decides what the player does each tick.
///
/// Behaviours never see packets or versions: they read a [`TickContext`] and call its
/// actions. A panic in a behaviour stops that behaviour (its [`Behavior::stop`] is called with
/// `"panic"`) but not the connection: the player keeps standing and answering the server.
pub trait Behavior {
    /// Name for logs.
    fn name(&self) -> &str {
        "behavior"
    }

    /// Optional packet groups this behaviour needs. Read every tick; a change updates the
    /// packet filter. Everything not asked for is dropped before it is decoded.
    fn interests(&self) -> Interests {
        Interests::NONE
    }

    /// Extra clientbound play packet ids (of `version`) to copy undecoded into
    /// [`TickEvents::raw`], including packets the core consumes itself (the core's handling
    /// does not change). Read every tick like [`Behavior::interests`]; a change updates the
    /// packet filter. Decoding is the behaviour's job (`ghast::protocol::v1_8::play::clientbound`
    /// / `v1_16_5`). A behaviour made of modules returns the union of their lists
    /// (`Cow::Owned([a.ids(version), b.ids(version)].concat())`; duplicates are harmless).
    /// Most needs have typed events now: [`TickEvents::effects`], [`TickEvents::hurt`],
    /// [`TickEvents::deaths`], [`TickEvents::item_use`], [`TickEvents::entities`],
    /// [`TickContext::spawn_position`].
    fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
        let _ = version;
        std::borrow::Cow::Borrowed(&[])
    }

    /// Called on the first tick the player is in the world, before that tick's
    /// [`Behavior::tick`] (both see the same events).
    fn start(&mut self, ctx: &mut TickContext<'_>) {
        let _ = ctx;
    }

    /// Called every tick while the player is in the world and the server is answering.
    fn tick(&mut self, ctx: &mut TickContext<'_>);

    /// Whether the behaviour still wants ticks. Once it returns `false` the behaviour is done:
    /// it is not ticked again (the player keeps standing and answering the server) and
    /// [`Behavior::stop`] still runs when the session ends. Read after every start / tick.
    fn running(&self) -> bool {
        true
    }

    /// Called after every tick's movement step (also while the behaviour is on hold or has
    /// finished), with a read-only view of what the server now has: the pose sent this tick,
    /// the world, entities and inventory. For observers (a viewer, a recorder); it cannot act.
    /// Default: nothing.
    ///
    /// ```
    /// use ghast_client::{Behavior, TickContext, TickView};
    ///
    /// /// Logs where the server has the player, once a second.
    /// struct Tracker;
    ///
    /// impl Behavior for Tracker {
    ///     fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
    ///
    ///     fn after_tick(&mut self, view: &TickView<'_>) {
    ///         if view.tick() % 20 == 0 {
    ///             let p = view.sent();
    ///             println!("{} {:?} in {}", view.tick(), p.pos, view.dimension());
    ///         }
    ///     }
    /// }
    /// ```
    fn after_tick(&mut self, view: &TickView<'_>) {
        let _ = view;
    }

    /// Called once when the session ends (or the behaviour panicked).
    fn stop(&mut self, reason: &str) {
        let _ = reason;
    }

    /// 26.1+: a dialog the server shows during the configuration state, before the player is in
    /// the world (behaviours do not tick there). Called only with [`Interests::DIALOGS`]; the
    /// client sends the returned answer at once, as vanilla would for that button (see
    /// [`crate::dialog`]); `None` leaves the dialog open. A dialog the answer opens is offered
    /// next. Play-state dialogs come through [`TickContext::dialog`] instead. Default: `None`.
    fn configuration_dialog(
        &mut self,
        dialog: &crate::dialog::Dialog,
    ) -> Option<crate::dialog::DialogAnswer> {
        let _ = dialog;
        None
    }
}

/// A boxed behaviour is a behaviour (a runner can pick one from its config at run time).
impl<B: Behavior + ?Sized> Behavior for Box<B> {
    fn name(&self) -> &str {
        (**self).name()
    }
    fn interests(&self) -> Interests {
        (**self).interests()
    }
    fn raw_packets(&self, version: GameVersion) -> std::borrow::Cow<'static, [i32]> {
        (**self).raw_packets(version)
    }
    fn start(&mut self, ctx: &mut TickContext<'_>) {
        (**self).start(ctx);
    }
    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        (**self).tick(ctx);
    }
    fn running(&self) -> bool {
        (**self).running()
    }
    fn after_tick(&mut self, view: &TickView<'_>) {
        (**self).after_tick(view);
    }
    fn stop(&mut self, reason: &str) {
        (**self).stop(reason);
    }
    fn configuration_dialog(
        &mut self,
        dialog: &crate::dialog::Dialog,
    ) -> Option<crate::dialog::DialogAnswer> {
        (**self).configuration_dialog(dialog)
    }
}

/// Why [`TickContext::click`] (or opening / closing a window) sent nothing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ClickRefused {
    /// The player is turning: click only while still.
    Turning,
    /// The inventory refused it.
    Inventory(ghast_inventory::ClickError),
    /// The player is dead (vanilla's death screen takes the input until the respawn).
    Dead,
}

impl std::fmt::Display for ClickRefused {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ClickRefused::Turning => f.write_str("the player is turning"),
            ClickRefused::Inventory(e) => write!(f, "{e}"),
            ClickRefused::Dead => f.write_str("the player is dead"),
        }
    }
}

impl std::error::Error for ClickRefused {}

/// A click that was sent: match it with [`TickEvents::inventory`]'s `clicks` on a later tick
/// (window id and action number, as the server's confirm carries them).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ClickTicket {
    /// Window id the click was sent for; -1 when no [`ghast_inventory::ClickResult`] will
    /// follow (the 26.x creative inventory screen, whose packets the server applies as sent).
    pub window_id: i32,
    /// Its action number.
    pub action: i16,
}

impl ClickTicket {
    /// Whether `r` is the result of this click.
    #[must_use]
    pub fn matches(&self, r: &ghast_inventory::ClickResult) -> bool {
        r.window_id == self.window_id && r.action == self.action
    }
}

/// A behaviour that does nothing (the player stands still).
#[derive(Debug, Clone, Copy, Default)]
pub struct Idle;

impl Behavior for Idle {
    fn name(&self) -> &str {
        "idle"
    }

    fn tick(&mut self, _ctx: &mut TickContext<'_>) {}
}