ghast-client 0.5.1

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 legacy creative mode actions through the engine (1.8.9): opening window 0 in creative
//! mode sends the achievement command and the creative listener's broadcast, clicks in the
//! creative screen and on an item tab's menu send `creative_inventory_action`s, and the pick
//! block key puts the item into the hotbar, sends that slot and syncs the selected slot on the
//! same tick. The packet rules themselves are oracle-proven in ghast-inventory
//! (`tests/oracle_creative_legacy.rs`); this checks the engine's wiring and the wire bytes.

use super::tests::{Script, engine, join};
use super::*;
use crate::version::ClientVersion;
use ghast_inventory::{Click, CreativeTab, Stack};
use ghast_protocol::frame::{FrameDecoder, FrameEncoder};

/// The tick's inventory packets (creative actions, client commands, held slot changes) as
/// version `V`'s wire layer writes them: (id, body).
fn wire_v<V: ClientVersion>(out: &[Outbound], keep: &[i32]) -> Vec<(i32, Vec<u8>)>
where
    V::Wire: Default,
{
    let mut enc = FrameEncoder::new();
    let mut w = V::Wire::default();
    for o in out {
        V::write_play(&mut enc, o, &mut w).unwrap();
    }
    let bytes = enc.take();
    let mut dec = FrameDecoder::new();
    dec.push(&bytes);
    let mut v = Vec::new();
    while let Some(p) = dec.next_packet().unwrap() {
        if keep.contains(&p.id) {
            v.push((p.id, p.body.to_vec()));
        }
    }
    v
}

fn wire(out: &[Outbound]) -> Vec<(i32, Vec<u8>)> {
    wire_v::<crate::version::V1_8>(out, &[CREATIVE_ACTION, CLIENT_COMMAND, HELD_SLOT])
}

fn tick(e: &mut Engine<Box<dyn Sim>>, t0: Instant, f: impl FnMut(&mut TickContext<'_>)) {
    e.note_inbound(t0);
    e.tick(&mut Script(f), t0);
}

const CREATIVE_ACTION: i32 = ghast_protocol::v1_8::play::serverbound::id::SET_CREATIVE_SLOT;
const CLIENT_COMMAND: i32 = ghast_protocol::v1_8::play::serverbound::id::CLIENT_COMMAND;
const HELD_SLOT: i32 = ghast_protocol::v1_8::play::serverbound::id::HELD_ITEM_SLOT;

/// `creative_inventory_action` body: slot, then the 1.8 slot (id, count, damage, no NBT).
fn action(slot: i16, item: Option<(i16, u8, i16)>) -> Vec<u8> {
    let mut b = slot.to_be_bytes().to_vec();
    match item {
        None => b.extend((-1i16).to_be_bytes()),
        Some((id, n, d)) => {
            b.extend(id.to_be_bytes());
            b.push(n);
            b.extend(d.to_be_bytes());
            b.push(0);
        }
    }
    b
}

#[test]
fn creative_screen_and_pick_block_on_1_8_9() {
    let t0 = Instant::now();
    let mut e = engine(GameVersion::V1_8_9);
    join(&mut e);
    // creative mode: the abilities packet's flag (the version's inventory filter applies it)
    e.core.inv.set_creative(true);
    e.core.game_mode = GameMode::Creative;
    let mut w0 = vec![None; 45];
    w0[36] = Some(Stack::new(1, 64, 0)); // stone in hotbar slot 0
    w0[9] = Some(Stack::new(4, 10, 0)); // cobblestone in the main inventory
    e.core.inv.on_window_items(0, w0);
    e.core.test_set_slot(0);
    tick(&mut e, t0, |_| {});
    e.outbound().clear();

    // Opening: the achievement command, then the listener's first broadcast (two slots).
    tick(&mut e, t0, |ctx| ctx.open_inventory().unwrap());
    let got = wire(e.outbound());
    e.outbound().clear();
    assert_eq!(
        got,
        vec![
            (CLIENT_COMMAND, vec![2]),
            (CREATIVE_ACTION, action(9, Some((4, 10, 0)))),
            (CREATIVE_ACTION, action(36, Some((1, 64, 0)))),
        ]
    );
    // The first opening shows an item tab; the inventory tab drops one stone on Q.
    assert_eq!(
        e.core.inv.creative_screen_legacy(),
        Some(CreativeTab::Items)
    );
    tick(&mut e, t0, |ctx| {
        ctx.set_creative_tab(CreativeTab::Inventory);
        ctx.click(Click::Drop {
            slot: 36,
            all: false,
        })
        .unwrap();
    });
    let got = wire(e.outbound());
    e.outbound().clear();
    assert_eq!(got, vec![(CREATIVE_ACTION, action(-1, Some((1, 1, 0))))]);
    assert_eq!(e.core.inv.player(0).map(Stack::count), Some(63));
    // An item tab: a number key over a menu stack of glass fills hotbar slot 2, and the
    // broadcast also sends the stone slot the drop changed.
    tick(&mut e, t0, |ctx| {
        ctx.set_creative_tab(CreativeTab::Items);
        ctx.creative_menu_click(
            Some(Stack::new(20, 1, 0)),
            Click::Swap { slot: 0, hotbar: 2 },
        )
        .unwrap();
    });
    let got = wire(e.outbound());
    e.outbound().clear();
    assert_eq!(
        got,
        vec![
            (CREATIVE_ACTION, action(36, Some((1, 63, 0)))),
            (CREATIVE_ACTION, action(38, Some((20, 64, 0)))),
        ]
    );
    tick(&mut e, t0, |ctx| ctx.close_window().unwrap());
    e.outbound().clear();

    // Pick block of cobblestone (in the main inventory, not the hotbar): the first empty
    // hotbar slot (1) is selected and takes the cobblestone stack; that slot is sent now and
    // the selection by the slot sync after the behaviour.
    tick(&mut e, t0, |ctx| {
        ctx.pick_block(&Stack::new(4, 1, 0), false).unwrap()
    });
    let got = wire(e.outbound());
    e.outbound().clear();
    assert_eq!(
        got,
        vec![
            (CREATIVE_ACTION, action(37, Some((4, 10, 0)))),
            (HELD_SLOT, 1i16.to_be_bytes().to_vec()),
        ]
    );
    assert_eq!(e.core.inv.selected(), 1);
    assert_eq!(e.core.inv.player(9), None);
}

#[cfg(feature = "v26_1")]
#[test]
fn pick_block_is_refused_where_not_modelled() {
    let t0 = Instant::now();
    let mut e = engine(GameVersion::V26_1);
    join(&mut e);
    tick(&mut e, t0, |ctx| {
        assert_eq!(
            ctx.pick_block(&Stack::new(1, 1, 0), false),
            Err(ClickRefused::Inventory(
                ghast_inventory::ClickError::Unpredictable
            ))
        );
    });
}

#[test]
fn creative_screen_pick_and_saved_toolbar_on_1_12_2() {
    use ghast_protocol::v1_12_2::play::serverbound::id;
    let keep = [
        id::SET_CREATIVE_SLOT,
        id::CLIENT_COMMAND,
        id::HELD_ITEM_SLOT,
    ];
    let w = |e: &mut Engine<Box<dyn Sim>>| {
        let got = wire_v::<crate::version::V1_12_2>(e.outbound(), &keep);
        e.outbound().clear();
        got
    };
    let t0 = Instant::now();
    let mut e = engine(GameVersion::V1_12_2);
    join(&mut e);
    e.core.inv.set_creative(true);
    e.core.game_mode = GameMode::Creative;
    let mut w0 = vec![None; 46];
    w0[36] = Some(Stack::new(1, 64, 0));
    w0[45] = Some(Stack::new(4, 10, 0)); // the offhand
    e.core.inv.on_window_items(0, w0);
    e.core.test_set_slot(0);
    tick(&mut e, t0, |_| {});
    e.outbound().clear();
    // Opening: no achievement command on 1.12, the broadcast only (window 0 order).
    tick(&mut e, t0, |ctx| ctx.open_inventory().unwrap());
    assert_eq!(
        w(&mut e),
        vec![
            (id::SET_CREATIVE_SLOT, action(36, Some((1, 64, 0)))),
            (id::SET_CREATIVE_SLOT, action(45, Some((4, 10, 0)))),
        ]
    );
    // The inventory tab's Q on the offhand: the drop and, on 1.12, the slot's rest at once.
    tick(&mut e, t0, |ctx| {
        ctx.set_creative_tab(CreativeTab::Inventory);
        ctx.click(Click::Drop {
            slot: 45,
            all: false,
        })
        .unwrap();
    });
    assert_eq!(
        w(&mut e),
        vec![
            (id::SET_CREATIVE_SLOT, action(-1, Some((4, 1, 0)))),
            (id::SET_CREATIVE_SLOT, action(45, Some((4, 9, 0)))),
        ]
    );
    tick(&mut e, t0, |ctx| ctx.close_window().unwrap());
    e.outbound().clear();
    // A saved toolbar: every hotbar slot is sent.
    let mut saved: [Option<Stack>; 9] = Default::default();
    saved[3] = Some(Stack::new(20, 64, 0));
    tick(&mut e, t0, |ctx| ctx.creative_load_hotbar(&saved).unwrap());
    let got = w(&mut e);
    assert_eq!(got.len(), 9);
    assert_eq!(
        got[3],
        (id::SET_CREATIVE_SLOT, action(39, Some((20, 64, 0))))
    );
    assert_eq!(got[0], (id::SET_CREATIVE_SLOT, action(36, None)));
    // Pick block of the glass now in hotbar slot 3: selected, no new stack; the selected
    // slot is sent, then the slot sync.
    tick(&mut e, t0, |ctx| {
        ctx.pick_block(&Stack::new(20, 1, 0), false).unwrap()
    });
    assert_eq!(
        w(&mut e),
        vec![
            (id::SET_CREATIVE_SLOT, action(39, Some((20, 64, 0)))),
            (id::HELD_ITEM_SLOT, 3i16.to_be_bytes().to_vec()),
        ]
    );
}

#[test]
fn creative_screen_swings_and_pick_on_1_16_5() {
    use ghast_protocol::v1_16_5::play::serverbound::id;
    let keep = [id::SET_CREATIVE_SLOT, id::ARM_ANIMATION, id::HELD_ITEM_SLOT];
    let w = |e: &mut Engine<Box<dyn Sim>>| {
        let got = wire_v::<crate::version::V1_16_5>(e.outbound(), &keep);
        e.outbound().clear();
        got
    };
    // 1.16.5 slots: item id varint, count, NBT (0 = none)
    let slot16 = |slot: i16, item: Option<(u8, u8)>| {
        let mut b = slot.to_be_bytes().to_vec();
        match item {
            None => b.push(0),
            Some((id, n)) => b.extend([1, id, n, 0]),
        }
        b
    };
    let t0 = Instant::now();
    let mut e = engine(GameVersion::V1_16_5);
    join(&mut e);
    e.core.inv.set_creative(true);
    e.core.game_mode = GameMode::Creative;
    let mut w0 = vec![None; 46];
    w0[36] = Some(Stack::new(1, 64, 0));
    e.core.inv.on_window_items(0, w0);
    e.core.test_set_slot(0);
    tick(&mut e, t0, |_| {});
    e.outbound().clear();
    tick(&mut e, t0, |ctx| ctx.open_inventory().unwrap());
    assert_eq!(
        w(&mut e),
        vec![(id::SET_CREATIVE_SLOT, slot16(36, Some((1, 64))))]
    );
    // Q on the inventory tab: the client's dropItem swings, then the drop and the slot's rest.
    tick(&mut e, t0, |ctx| {
        ctx.set_creative_tab(CreativeTab::Inventory);
        ctx.click(Click::Drop {
            slot: 36,
            all: false,
        })
        .unwrap();
    });
    assert_eq!(
        w(&mut e),
        vec![
            (id::ARM_ANIMATION, vec![0]),
            (id::SET_CREATIVE_SLOT, slot16(-1, Some((1, 1)))),
            (id::SET_CREATIVE_SLOT, slot16(36, Some((1, 63)))),
        ]
    );
    tick(&mut e, t0, |ctx| ctx.close_window().unwrap());
    e.outbound().clear();
    // Pick block of stone: in the hotbar already, so only the slot is sent.
    tick(&mut e, t0, |ctx| {
        ctx.pick_block(&Stack::new(1, 1, 0), false).unwrap()
    });
    assert_eq!(
        w(&mut e),
        vec![(id::SET_CREATIVE_SLOT, slot16(36, Some((1, 63))))]
    );
}

/// The legacy right clicks on blocks through the engine (`engine_tests_place_legacy.rs`).
#[path = "engine_tests_place_legacy.rs"]
mod place_legacy;