ghast 0.5.6

Headless Minecraft Java Edition client / bot library (1.8.9, 1.12.2, 1.16.5, 26.1, 26.2 and 26.3) with vanilla-exact behaviour: facade crate re-exporting the ghast-* crates
Documentation
//! Landing step-up onto a 1/8-higher edge, on purpose (the Grim corner case behind
//! `Client::force_step_position`): on the lab pad (`lab/reset-field.sh`, soul sand strip
//! x 16..23, z 8..23 at y 3, grass around it) the bot bunny-hops forward over the soul sand into
//! the grass edge at z 24, from slightly different starts. A hop that lands with a step-up
//! moving less than the position threshold makes vanilla send a look-only packet with
//! on-ground true. Every unexpected server teleport is logged as `ALERT setback`; with
//! `--grim-compat` the client sends the position on those ticks instead.
//!
//! The bot must be opped (each run starts with `/tp`).
//!
//! ```text
//! cargo run -p ghast --release --example step_edge -- --host 127.0.0.1 --port 25636 \
//!     --username GhastBot2 --version 26.3 --seed 1 [--grim-compat] [--runs 40]
//! ```

mod support;

use ghast::{Behavior, Controls, Interests, TickContext};

/// Start of the bunny hop (the oracle scenario `landing_step_soul_sand_to_grass`, moved to the
/// lab pad's y): x, z, yaw, pitch.
const START: (f64, f64, f32, f32) = (
    18.235_736_476_016_67,
    21.138_383_760_069_11,
    2.479_122_6,
    10.004_477,
);

struct Edge {
    runs: u32,
    run: u32,
    ticks: u32,
    rng: u64,
    expect_tp: bool,
    setbacks: u32,
    setback_runs: Vec<u32>,
    unsent: u32,
    start: (f64, f64, f32),
}

fn next(s: &mut u64) -> u64 {
    *s ^= *s >> 12;
    *s ^= *s << 25;
    *s ^= *s >> 27;
    s.wrapping_mul(0x2545_f491_4f6c_dd1d)
}

impl Behavior for Edge {
    fn name(&self) -> &str {
        "step_edge"
    }

    fn interests(&self) -> Interests {
        Interests::CHAT
    }

    fn tick(&mut self, ctx: &mut TickContext<'_>) {
        for m in &ctx.events().chat {
            let t = m.plain();
            if t.contains("Grim") || t.contains("failed") {
                log::warn!("ALERT chat: {t}");
            }
        }
        if ctx.events().teleported {
            if self.expect_tp {
                self.expect_tp = false;
            } else {
                self.setbacks += 1;
                if self.setback_runs.last() != Some(&self.run) {
                    self.setback_runs.push(self.run);
                }
                let p = ctx.pose().pos;
                log::warn!(
                    "ALERT setback in run {} (tick {}) to {} {} {}",
                    self.run,
                    self.ticks,
                    p.x,
                    p.y,
                    p.z
                );
            }
        }
        // Feet height changed but the server still has the old one: the last movement packet
        // carried no position (vanilla's sub-threshold move; `--grim-compat` sends it).
        let (now, sent) = (ctx.pose().pos.y, ctx.sent().pos.y);
        if now != sent && ctx.pose().on_ground {
            self.unsent += 1;
            log::info!(
                "STEP CASE run {} tick {}: feet {now}, the server has {sent}",
                self.run,
                self.ticks
            );
        }
        ctx.set_controls(Controls::NONE);
        self.ticks += 1;
        match self.ticks {
            1 => {
                if self.run == self.runs {
                    log::info!(
                        "EDGE done: {} runs, {} unsent feet heights, {} setbacks in runs {:?}",
                        self.runs,
                        self.unsent,
                        self.setbacks,
                        self.setback_runs
                    );
                    ctx.disconnect("done");
                    return;
                }
                // Up to ±0.3 in x, 0..0.6 back in z, ±4° of yaw.
                let r = |s: &mut u64| (next(s) >> 11) as f64 / (1u64 << 53) as f64;
                let dx = (r(&mut self.rng) - 0.5) * 0.6;
                let dz = -r(&mut self.rng) * 0.6;
                let dyaw = ((r(&mut self.rng) - 0.5) * 8.0) as f32;
                self.start = (START.0 + dx, START.1 + dz, START.2 + dyaw);
                self.expect_tp = true;
                ctx.chat(format!(
                    "/tp @s {} 3.875 {} {} {}",
                    self.start.0, self.start.1, self.start.2, START.3
                ));
            }
            // Wait for the teleport and settle.
            2..=30 => {}
            31..=60 => {
                let (_, pitch) = ctx.aim();
                ctx.set_aim(self.start.2, pitch);
                ctx.set_controls(Controls {
                    forward: true,
                    jump: true,
                    ..Controls::NONE
                });
            }
            61..=80 => {}
            _ => {
                let p = ctx.pose().pos;
                log::info!("run {} ended at {} {} {}", self.run, p.x, p.y, p.z);
                self.run += 1;
                self.ticks = 0;
            }
        }
    }
}

fn main() {
    let mut args: Vec<String> = std::env::args().skip(1).collect();
    let mut runs = 40;
    if let Some(i) = args.iter().position(|a| a == "--runs") {
        runs = args[i + 1].parse().expect("--runs <n>");
        args.drain(i..=i + 1);
    }
    let opts = support::Options::parse_from(args);
    support::init_logger(opts.verbose);
    let rt = tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .expect("tokio runtime");
    rt.block_on(async {
        let client = match opts.client() {
            Ok(c) => c,
            Err(e) => {
                log::error!("{e}");
                std::process::exit(2);
            }
        };
        let mut edge = Edge {
            runs,
            run: 0,
            ticks: 0,
            rng: opts.seed.wrapping_mul(0x9e37_79b9_7f4a_7c15) | 1,
            expect_tp: false,
            setbacks: 0,
            setback_runs: Vec::new(),
            unsent: 0,
            start: (START.0, START.1, START.2),
        };
        let end = client
            .run_until(&mut edge, async {
                let _ = tokio::signal::ctrl_c().await;
            })
            .await;
        match &end {
            Ok(e) => log::info!("session ended: {e:?}"),
            Err(e) => log::error!("session failed: {e}"),
        }
    });
}