ghast-client 0.4.10

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 and 26.2)
Documentation
//! The client-side result of a right click on an entity, per hand (`doUse` / `doItemUse`):
//! whether `interactAt` or `interact` handle it (the item use does not follow) and whether
//! the hand swings. Oracle: the legacy `interact_*` Combat cases.

use crate::hands::{Interact, InteractEffect as Fx};
use ghast_entity::Entities;
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
use ghast_entity::{Entity, EntityType};

/// The outcome for the main hand and the off hand on the version with protocol `protocol`
/// (its family: 1.8, 1.12, 1.16), with what the click does to that hand's stack on the
/// client. `items`: the raw item ids and damage values in the hands. 26.x and unknown
/// entities: not handled. `creative`: the stack effects are left out (vanilla keeps the
/// counts in creative mode; not oracle-checked).
pub(crate) fn outcome(
    ents: &Entities,
    protocol: i32,
    id: i32,
    spectator: bool,
    sneaking: bool,
    creative: bool,
    items: [Option<(u16, i16)>; 2],
) -> [(Interact, Fx); 2] {
    let Some(e) = ents.get(id) else {
        return [(Interact::NotHandled, Fx::None); 2];
    };
    let one = |held: Option<(u16, i16)>| {
        let item = held.map(|h| h.0);
        let (kind, fx) = match protocol {
            #[cfg(feature = "v1_8")]
            47 => mob_1_8(e, spectator, held).unwrap_or((legacy_1_8(ents, e, spectator), Fx::None)),
            #[cfg(feature = "v1_12_2")]
            335..=340 => mob_1_12(e, spectator, held)
                .unwrap_or((legacy_1_12(e, spectator, sneaking, item), Fx::None)),
            #[cfg(feature = "v1_16_5")]
            735..=754 => mob_1_16(e, spectator, item)
                .unwrap_or((v1_16_5(e, spectator, sneaking, item), Fx::None)),
            _ => {
                let _ = (e, spectator, sneaking, item, held);
                (Interact::NotHandled, Fx::None)
            }
        };
        (kind, if creative { Fx::None } else { fx })
    };
    [one(items[0]), one(items[1])]
}

/// 1.8 / 1.12 raw ids of the mobs and items the mob table knows.
#[cfg(any(feature = "v1_8", feature = "v1_12_2"))]
// Each version's table uses its own subset.
#[allow(dead_code)]
mod legacy_ids {
    pub(super) const PIG: u8 = 90;
    pub(super) const SHEEP: u8 = 91;
    pub(super) const COW: u8 = 92;
    pub(super) const WOLF: u8 = 95;
    pub(super) const VILLAGER: u8 = 120;
    pub(super) const LEAD: u16 = 420;
    pub(super) const SADDLE: u16 = 329;
    pub(super) const SHEARS: u16 = 359;
    pub(super) const DYE: u16 = 351;
    pub(super) const WHEAT: u16 = 296;
    pub(super) const BUCKET: u16 = 325;
    pub(super) const NAME_TAG: u16 = 421;
    pub(super) const COOKED_BEEF: u16 = 364;
    pub(super) const BONE: u16 = 352;
    pub(super) const SPAWN_EGG: u16 = 383;
}

/// The mob state the outcome depends on, from the entity data the tracker keeps. Without
/// metadata tracking ([`crate::Interests::ENTITIES`]) nothing is kept and every mob reads as
/// fresh: adult, untamed, unsheared, white, unsaddled
/// ([`crate::TickContext::mob_state_known`]).
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
// Each version's table reads its own subset.
#[allow(dead_code)]
#[derive(Clone, Copy, Default)]
struct MobState {
    baby: bool,
    sheared: bool,
    /// Sheep colour (`DyeColor` id, 0 white).
    color: u8,
    saddled: bool,
    tamed: bool,
}

/// Reads [`MobState`] at the version's indices: `baby` and the mob byte / boolean.
#[cfg(any(feature = "v1_8", feature = "v1_12_2", feature = "v1_16_5"))]
fn mob_state(e: &Entity, baby: u8, baby_is_age: bool, mob: u8) -> MobState {
    use ghast_entity::MetaValue;
    let m = e.metadata();
    let flag = |i: u8| match m.get(i) {
        Some(MetaValue::Bool(b)) => Some(*b),
        Some(MetaValue::Byte(b)) => Some(*b != 0),
        _ => None,
    };
    let byte = m.byte(mob).unwrap_or(0) as u8;
    MobState {
        baby: if baby_is_age {
            m.byte(baby).is_some_and(|a| a < 0)
        } else {
            flag(baby).unwrap_or(false)
        },
        sheared: byte & 0x10 != 0,
        color: byte & 0x0F,
        saddled: flag(mob).unwrap_or(false),
        tamed: byte & 0x04 != 0,
    }
}

/// 1.8.9 right clicks on a mob that its `interactMob` / the item's `useOnEntity` handle on the
/// client (oracle `mob_*` cases, fresh and not); `None`: not a case of the table.
#[cfg(feature = "v1_8")]
fn mob_1_8(e: &Entity, spectator: bool, held: Option<(u16, i16)>) -> Option<(Interact, Fx)> {
    use legacy_ids::*;
    let EntityType::LegacyMob(m) = e.entity_type() else {
        return None;
    };
    if spectator {
        return None;
    }
    // Age byte 12, the mob's byte 16.
    let st = mob_state(e, 12, true, 16);
    let (item, damage) = held.unwrap_or((0, 0));
    Some(match (m, item) {
        (PIG, LEAD) if !st.baby => (Interact::Handled, Fx::Take),
        // A saddled pig is ridden instead.
        (PIG, SADDLE) if st.saddled => (Interact::Handled, Fx::None),
        (PIG, SADDLE) if !st.baby => (Interact::Handled, Fx::Take),
        // SheepEntity: shears hurt the shears (an adult, unsheared sheep) and fall through.
        (SHEEP, SHEARS) if !st.sheared && !st.baby => (Interact::NotHandled, Fx::Damage),
        (SHEEP, SHEARS) => (Interact::NotHandled, Fx::None),
        // DyeItem: another colour takes one dye (dye d is colour 15 - d); the same colour is
        // still handled.
        (SHEEP, DYE) if i32::from(st.color) != 15 - i32::from(damage) => {
            (Interact::Handled, Fx::Take)
        }
        (SHEEP, DYE) => (Interact::Handled, Fx::None),
        // AnimalEntity breeding (1.8 judges the love on the client too); a baby grows.
        (COW | SHEEP, WHEAT) | (WOLF, COOKED_BEEF) => (Interact::Handled, Fx::Take),
        (COW, BUCKET) if !st.baby => (Interact::Handled, Fx::IntoMilk),
        (WOLF, BONE) if !st.tamed => (Interact::Handled, Fx::Take),
        (WOLF, BONE) => (Interact::NotHandled, Fx::None),
        (VILLAGER, i) if i != SPAWN_EGG => (Interact::Handled, Fx::None),
        _ => return None,
    })
}

/// 1.12.2: as [`mob_1_8`], but a breeding food on an adult is not handled on the client (its
/// age reads 1), a baby takes it.
#[cfg(feature = "v1_12_2")]
fn mob_1_12(e: &Entity, spectator: bool, held: Option<(u16, i16)>) -> Option<(Interact, Fx)> {
    use legacy_ids::*;
    let EntityType::LegacyMob(m) = e.entity_type() else {
        return None;
    };
    if spectator {
        return None;
    }
    // Baby boolean 12, the mob's byte / boolean 13.
    let st = mob_state(e, 12, false, 13);
    let (item, damage) = held.unwrap_or((0, 0));
    Some(match (m, item) {
        (PIG, LEAD) if !st.baby => (Interact::Handled, Fx::Take),
        (PIG, SADDLE) if st.saddled => (Interact::Handled, Fx::None),
        (PIG, SADDLE) if !st.baby => (Interact::Handled, Fx::Take),
        (PIG, NAME_TAG) => (Interact::Handled, Fx::None),
        (SHEEP, SHEARS) if !st.sheared && !st.baby => (Interact::NotHandled, Fx::Damage),
        (SHEEP, SHEARS) => (Interact::NotHandled, Fx::None),
        (SHEEP, DYE) if i32::from(st.color) != 15 - i32::from(damage) => {
            (Interact::Handled, Fx::Take)
        }
        (SHEEP, DYE) => (Interact::Handled, Fx::None),
        (COW | SHEEP, WHEAT) if st.baby => (Interact::Handled, Fx::Take),
        (COW, BUCKET) if !st.baby => (Interact::Handled, Fx::IntoMilk),
        (WOLF, BONE) if !st.tamed => (Interact::Handled, Fx::Take),
        (VILLAGER, i) if i != SPAWN_EGG => (Interact::Handled, Fx::None),
        _ => return None,
    })
}

/// 1.16.5 (ActionResult: SUCCESS swings, CONSUME does not; the server does most stack
/// changes).
#[cfg(feature = "v1_16_5")]
fn mob_1_16(e: &Entity, spectator: bool, item: Option<u16>) -> Option<(Interact, Fx)> {
    if spectator || e.class() != ghast_entity::EntityClass::Mob {
        return None;
    }
    let mob = ghast_entity::v1_16_5::info(e.entity_type())?.name;
    let name = item
        .and_then(ghast_data::v1_16_5::Item::from_id)
        .map_or("", |i| i.info().name);
    // Baby boolean 15, the mob's byte / boolean 16 (sheep colour, pig saddle, tame flags).
    let st = mob_state(e, 15, false, 16);
    Some(match (mob, name) {
        ("pig", "lead") if !st.baby => (Interact::HandledSwing, Fx::Take),
        ("pig", "saddle") => (Interact::HandledSwing, Fx::None),
        // The same colour: PASS (the dye's use follows).
        ("sheep", "red_dye") if st.color == 14 => return None,
        ("sheep", "red_dye") => (Interact::HandledSwing, Fx::None),
        // A baby grows: SUCCESS, one food less.
        ("cow" | "sheep", "wheat") if st.baby => (Interact::HandledSwing, Fx::Take),
        ("sheep", "shears") | ("cow" | "sheep", "wheat") | ("wolf", "bone") => {
            (Interact::Handled, Fx::None)
        }
        ("cow", "bucket") if !st.baby => (Interact::HandledSwing, Fx::IntoMilk),
        ("villager", n) if !n.ends_with("spawn_egg") => (Interact::HandledSwing, Fx::None),
        _ => return None,
    })
}

/// 1.8.9: `interactAt`, then `PlayerEntity.interact` (`openInventory`).
#[cfg(feature = "v1_8")]
fn legacy_1_8(ents: &Entities, e: &Entity, spectator: bool) -> Interact {
    let EntityType::LegacyObject(t) = e.entity_type() else {
        // Players and mobs: openInventory false (mob-specific interactions and items used on
        // entities are not modelled).
        return Interact::NotHandled;
    };
    match t {
        // ArmorStandEntity.interactAt: true on the client unless a marker (whose empty box the
        // pick never hits).
        78 => Interact::AtHandled,
        // PlayerEntity.interact: a spectator opens no entity.
        _ if spectator => Interact::NotHandled,
        // Boats, item frames, leash knots: openInventory true.
        1 | 71 | 77 => Interact::Handled,
        // Minecarts by kind: rideable (unless another entity, not a player, rides it), chest,
        // furnace, hopper handle it; TNT, spawner and command block do not.
        10 => match e.data() {
            0 => {
                let other = e
                    .passengers()
                    .first()
                    .copied()
                    .filter(|r| Some(*r) != ents.self_id());
                if other.is_some_and(|r| !ents.get(r).is_some_and(Entity::is_player)) {
                    Interact::NotHandled
                } else {
                    Interact::Handled
                }
            }
            1 | 2 | 5 => Interact::Handled,
            _ => Interact::NotHandled,
        },
        _ => Interact::NotHandled,
    }
}

/// 1.12.2 name tag item id.
#[cfg(feature = "v1_12_2")]
const NAME_TAG_1_12: u16 = 421;

/// 1.12.2: `interactAt` (SUCCESS ends the click), then `interact` (true: SUCCESS); no swing.
/// A spectator's manager answers PASS to both.
#[cfg(feature = "v1_12_2")]
fn legacy_1_12(e: &Entity, spectator: bool, sneaking: bool, item: Option<u16>) -> Interact {
    let EntityType::LegacyObject(t) = e.entity_type() else {
        return Interact::NotHandled;
    };
    if spectator {
        return Interact::NotHandled;
    }
    match t {
        // ArmorStandEntity.interactAt: PASS with a name tag (or a marker), else SUCCESS.
        78 if item == Some(NAME_TAG_1_12) => Interact::NotHandled,
        78 => Interact::AtHandled,
        // Boats and rideable minecarts: false while sneaking.
        1 => handled_unless(sneaking),
        10 => match e.data() {
            0 => handled_unless(sneaking),
            1 | 2 | 5 => Interact::Handled,
            _ => Interact::NotHandled,
        },
        71 | 77 => Interact::Handled,
        _ => Interact::NotHandled,
    }
}

#[cfg(feature = "v1_12_2")]
fn handled_unless(sneaking: bool) -> Interact {
    if sneaking {
        Interact::NotHandled
    } else {
        Interact::Handled
    }
}

/// 1.16.5: `interactAt`, then `interact` (`ActionResult`: accepted ends the click, SUCCESS
/// swings, CONSUME does not). A spectator's manager answers PASS to both.
#[cfg(feature = "v1_16_5")]
fn v1_16_5(e: &Entity, spectator: bool, sneaking: bool, item: Option<u16>) -> Interact {
    if spectator || !matches!(e.entity_type(), EntityType::Registry(_)) {
        return Interact::NotHandled;
    }
    let Some(info) = ghast_entity::v1_16_5::info(e.entity_type()) else {
        return Interact::NotHandled;
    };
    let name_of = |id: u16| ghast_data::v1_16_5::Item::from_id(id).map(|i| i.info().name);
    match info.name {
        // ArmorStandEntity.interactAt: PASS with a name tag (or a marker), CONSUME on the
        // client.
        "armor_stand" if item.and_then(name_of) == Some("name_tag") => Interact::NotHandled,
        "armor_stand" => Interact::AtHandled,
        // Boats: PASS while sneaking, else SUCCESS (the time under water is not modelled).
        "boat" if sneaking => Interact::NotHandled,
        "boat" => Interact::HandledSwing,
        // A rideable minecart: PASS while sneaking or ridden.
        "minecart" if sneaking || !e.passengers().is_empty() => Interact::NotHandled,
        "minecart" | "chest_minecart" | "hopper_minecart" | "furnace_minecart" | "leash_knot" => {
            Interact::HandledSwing
        }
        // ItemFrameEntity.interact on the client: PASS with an empty hand (the frame's item
        // is not tracked: taken as empty), else SUCCESS.
        "item_frame" if item.is_none() => Interact::NotHandled,
        "item_frame" => Interact::HandledSwing,
        // Command block minecarts need an operator; TNT / spawner minecarts, players, mobs.
        _ => Interact::NotHandled,
    }
}