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
//! 1.8.9 item uses in the air (`ClientPlayerInteractionManager.interactItem` after its
//! block-place packet: the stack's `onStartUse` on the client), oracle-proven
//! (`tests/golden/1.8.9/air_use.jsonl.gz`, `AirUseDump`). Their own ray (5 blocks, still liquids
//! or the blocks with a collision box: buckets, boats, glass bottles, lily pads), the arrows of a
//! bow, drinkable and splash potions, the fishing rod's swing, empty maps (the client world's map
//! id is always 0), the blocks and stacks they change on the client. Food and armor answer
//! [`AirAnswer::Flags`] (the held-item flags: hunger, the armor slot); the thrown items' counts
//! are the engine's (`predict_use_effects`, any `use_item` packet of a thrown item).
//!
//! Not modelled (answered [`AirAnswer::Unknown`]): a boat with other entities near the player
//! (their boxes stop the boat's ray and its room), a carrot on a stick while riding, an
//! adventure-mode stack with NBT (`CanPlaceOn`). The writable book opens the book screen, which
//! ghast does not model as a screen; its edit is [`crate::TickContext::edit_book`].

use ghast_data::v1_8::item_use::{ARROW, UseClass, is_splash, use_class};
use ghast_data::v1_8::{BlockState, MaterialKind};
use ghast_physics::math::Aabb;
use ghast_physics::pick::v1_8 as pick;
use ghast_physics::pick::{BlockHit, Direction};
use ghast_protocol::BlockPos;

use super::predict::{AirAnswer, AirQuery, AirResult, AirUse, HandChange};
use crate::common::GameMode;

/// What the rules read besides the query.
pub(crate) struct Ctx<'a> {
    pub world: &'a ghast_world::v1_8::World,
    /// The player's box.
    pub bb: Aabb,
    /// The dimension boils water (`doesWaterVaporize`: the nether).
    pub vaporizes: bool,
    /// The tracked entities (`None`: no tracker).
    pub entities: Option<&'a ghast_entity::Entities>,
    /// Our own entity id.
    pub own_id: Option<i32>,
    /// The player rides an entity.
    pub riding: bool,
}

const BUCKET: i32 = 325;
const WATER_BUCKET: i32 = 326;
const LAVA_BUCKET: i32 = 327;
const POTION: i32 = 373;
const FILLED_MAP: i32 = 358;
const SNOW_LAYER: u8 = 78;
const LILY_PAD: u16 = 111 << 4;
const FLOWING_WATER: u16 = 8 << 4;
const FLOWING_LAVA: u16 = 10 << 4;

/// An answer that changes nothing but the use and the swing.
fn known(result: AirResult, starts: bool) -> AirAnswer {
    AirAnswer::Known(AirUse {
        result,
        starts,
        blocks: Some(Vec::new()),
        hand: HandChange::Keep,
    })
}

/// Nothing on the client.
fn nothing() -> AirAnswer {
    known(AirResult::Consume, false)
}

fn changed(blocks: Vec<(BlockPos, u32)>, hand: HandChange) -> AirAnswer {
    AirAnswer::Known(AirUse {
        result: AirResult::Consume,
        starts: false,
        blocks: Some(blocks),
        hand,
    })
}

/// One used up outside creative.
fn use_one(creative: bool) -> HandChange {
    if creative {
        HandChange::Keep
    } else {
        HandChange::UseOne
    }
}

/// `World.getBlockState`: air outside the build height; an unloaded position reads as air, as
/// an empty client chunk does.
fn state(w: &ghast_world::v1_8::World, p: [i32; 3]) -> BlockState {
    if !(0..256).contains(&p[1]) {
        return BlockState::AIR;
    }
    w.block_state(p[0], p[1], p[2]).unwrap_or(BlockState::AIR)
}

fn offset(p: [i32; 3], d: Direction) -> [i32; 3] {
    let n = d.normal();
    [p[0] + n[0], p[1] + n[1], p[2] + n[2]]
}

/// A block the client sets (none outside the build height: `setBlockState` refuses).
fn set(p: [i32; 3], raw: u16) -> Vec<(BlockPos, u32)> {
    if (0..256).contains(&p[1]) {
        vec![(BlockPos::new(p[0], p[1], p[2]), u32::from(raw))]
    } else {
        Vec::new()
    }
}

/// `PlayerEntity.canModify(pos, face, stack)` for the block a ray hit: a player who may modify
/// the world (survival, creative); in adventure only with the stack's `CanPlaceOn` (not
/// modelled: `None`).
fn may_modify(q: &AirQuery<'_>) -> Option<bool> {
    match q.game_mode {
        GameMode::Survival | GameMode::Creative => Some(true),
        _ if q.stack.nbt().is_some() => None,
        _ => Some(false),
    }
}

/// [`super::Sim::air_use`] of 1.8.9.
pub(crate) fn air_use(cx: &Ctx<'_>, q: &AirQuery<'_>) -> AirAnswer {
    let Some(class) = u16::try_from(q.stack.id()).ok().and_then(use_class) else {
        return AirAnswer::Unknown;
    };
    let eye = [q.eyes.x, q.eyes.y, q.eyes.z];
    let look = pick::look_vector(q.yaw, q.pitch);
    let ray = |liquids: bool| pick::item_ray(cx.world, eye, look, liquids, !liquids);
    let creative = q.creative;
    match class {
        // the held-item flags (hunger; the armor slot)
        UseClass::Food | UseClass::Armor => AirAnswer::Flags,
        UseClass::Plain
        | UseClass::EnderEye
        | UseClass::SpawnEgg
        | UseClass::WrittenBook
        | UseClass::WritableBook => nothing(),
        UseClass::Sword | UseClass::MilkBucket => known(AirResult::Consume, true),
        UseClass::Bow => {
            // `containsItem(ARROW)`: the main inventory
            let arrows =
                (0..36).any(|k| q.inv.player(k).is_some_and(|s| s.id() == i32::from(ARROW)));
            known(AirResult::Consume, creative || arrows)
        }
        // thrown: one used up outside creative (creative throws no pearl), the engine's
        // thrown-item count
        UseClass::Potion if is_splash(q.stack.damage()) => nothing(),
        UseClass::Potion => known(AirResult::Consume, true),
        UseClass::Thrown | UseClass::EnderPearl => nothing(),
        // casts or reels in on the server; the client swings
        UseClass::FishingRod => known(AirResult::Success, false),
        UseClass::CarrotOnAStick if cx.riding => AirAnswer::Unknown,
        UseClass::CarrotOnAStick => nothing(),
        // `getIntState("map")` of the client world's `TemporaryStateManager`: 0
        UseClass::EmptyMap => {
            let map = ghast_inventory::Stack::new(FILLED_MAP, 1, 0);
            changed(Vec::new(), HandChange::ExchangeLegacy { output: map })
        }
        UseClass::GlassBottle => {
            let Some(hit) = ray(true) else {
                return nothing();
            };
            match may_modify(q) {
                None => return AirAnswer::Unknown,
                Some(false) => return nothing(),
                Some(true) => {}
            }
            if state(cx.world, hit.pos).block().material().kind != MaterialKind::Water {
                return nothing();
            }
            let water = ghast_inventory::Stack::new(POTION, 1, 0);
            changed(Vec::new(), HandChange::ExchangeLegacy { output: water })
        }
        UseClass::LilyPad => {
            let Some(hit) = ray(true) else {
                return nothing();
            };
            match may_modify(q) {
                None => return AirAnswer::Unknown,
                Some(false) => return nothing(),
                Some(true) => {}
            }
            let at = state(cx.world, hit.pos);
            let up = offset(hit.pos, Direction::Up);
            if at.block().material().kind != MaterialKind::Water
                || at.meta() != 0
                || state(cx.world, up).block().material().kind != MaterialKind::Air
            {
                return nothing();
            }
            changed(set(up, LILY_PAD), use_one(creative))
        }
        UseClass::Boat => boat(cx, q, eye, ray(true)),
        UseClass::Bucket => bucket(cx, q, &ray),
        _ => AirAnswer::Unknown,
    }
}

/// `BoatItem.onStartUse`.
fn boat(cx: &Ctx<'_>, q: &AirQuery<'_>, eye: [f64; 3], hit: Option<BlockHit>) -> AirAnswer {
    let Some(hit) = hit else {
        return nothing();
    };
    // another entity's box around the eyes or near the boat: not modelled
    if let Some(ents) = cx.entities {
        let near = ents.iter().any(|e| {
            Some(e.id()) != cx.own_id
                && e.bounding_box().is_none_or(|b| {
                    b[3] > eye[0] - 8.0
                        && b[0] < eye[0] + 8.0
                        && b[4] > eye[1] - 8.0
                        && b[1] < eye[1] + 8.0
                        && b[5] > eye[2] - 8.0
                        && b[2] < eye[2] + 8.0
                })
        });
        if near {
            return AirAnswer::Unknown;
        }
    }
    let mut p = hit.pos;
    if state(cx.world, p).block().id() == SNOW_LAYER {
        p[1] -= 1;
    }
    // `blockPos.getX() + 0.5F`: float maths
    let pos = [
        f64::from(p[0] as f32 + 0.5),
        f64::from(p[1] as f32 + 1.0),
        f64::from(p[2] as f32 + 0.5),
    ];
    if !ghast_physics::v1_8::boat_item_fits(cx.world, pos, &cx.bb) {
        return nothing();
    }
    changed(Vec::new(), use_one(q.creative))
}

/// `BucketItem.onStartUse`.
fn bucket(cx: &Ctx<'_>, q: &AirQuery<'_>, ray: &dyn Fn(bool) -> Option<BlockHit>) -> AirAnswer {
    let id = q.stack.id();
    let empty = id == BUCKET;
    let Some(hit) = ray(empty) else {
        return nothing();
    };
    match may_modify(q) {
        None => return AirAnswer::Unknown,
        Some(false) => return nothing(),
        Some(true) => {}
    }
    let w = cx.world;
    if empty {
        // a still liquid (level 0) becomes air; outside creative one bucket becomes the full
        let at = state(w, hit.pos);
        let filled = match at.block().material().kind {
            MaterialKind::Water if at.meta() == 0 => WATER_BUCKET,
            MaterialKind::Lava if at.meta() == 0 => LAVA_BUCKET,
            _ => return nothing(),
        };
        let blocks = set(hit.pos, 0);
        return changed(
            blocks,
            if q.creative {
                HandChange::Keep
            } else {
                HandChange::ExchangeLegacy {
                    output: ghast_inventory::Stack::new(filled, 1, 0),
                }
            },
        );
    }
    // `empty(world, pos)` beside the hit: air or a material that is not solid takes the
    // flowing fluid (water vaporizes in the nether); outside creative the bucket is emptied
    let target = offset(hit.pos, hit.face);
    let s = state(w, target);
    if s.block().material().solid {
        return nothing();
    }
    let water = id == WATER_BUCKET;
    let blocks = if cx.vaporizes && water {
        Vec::new()
    } else {
        set(target, if water { FLOWING_WATER } else { FLOWING_LAVA })
    };
    changed(
        blocks,
        if q.creative {
            HandChange::Keep
        } else {
            HandChange::Replace(ghast_inventory::Stack::new(BUCKET, 1, 0))
        },
    )
}