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 engine's share of the item cooldowns ([`crate::cooldown`]): the server's `set_cooldown`,
//! the hands' view of a cooling stack before a right click, the cooldowns the client's own item
//! uses start, the 26.x finished use, and the count in the player tick. Everything here runs
//! only while a cooldown is kept or a right click happened (nothing on the plain tick).

use super::*;
use crate::cooldown::{
    CooldownEvent, CooldownKey, MAX_EVENTS, instant_use, key_of, use_cooldown_ticks,
};
use crate::version::ItemCooldownRules;

/// Bits of [`Hands::used_ok`](crate::hands::Hands): the hand's `use` ran and succeeded (an
/// instant use on 26.x sets its `use_cooldown`) …
pub(crate) const USED: u8 = 1;
/// … or its `useOn` on a block succeeded (shifted by the hand: off hand `<< 1`).
pub(crate) const USED_ON: u8 = 4;

fn event(c: &mut Core, e: CooldownEvent) {
    let m = c.pending.more();
    if m.cooldowns.len() < MAX_EVENTS {
        m.cooldowns.push(e);
    }
}

/// `onCooldownUpdate` / `handleItemCooldown`: 0 ticks removes the cooldown, else it starts now.
pub(super) fn server_cooldown(c: &mut Core, key: CooldownKey, ticks: i32) {
    if c.opts.caps.item_cooldowns == ItemCooldownRules::None {
        return;
    }
    if ticks == 0 {
        c.cooldowns.remove(&key);
        event(c, CooldownEvent::Removed { key });
    } else {
        c.cooldowns.add(key.clone(), ticks);
        event(
            c,
            CooldownEvent::Started {
                key,
                ticks,
                from_server: true,
            },
        );
    }
}

fn client_cooldown(c: &mut Core, key: CooldownKey, ticks: i32) {
    c.cooldowns.add(key.clone(), ticks);
    event(
        c,
        CooldownEvent::Started {
            key,
            ticks,
            from_server: false,
        },
    );
}

/// The stack of a hand now.
fn hand(c: &Core, off_hand: bool) -> Option<&ghast_inventory::Stack> {
    if off_hand {
        c.inv.offhand()
    } else {
        c.inv.held()
    }
}

/// Before a right click with a cooldown kept: whether each hand's stack (main, off) cools down.
#[cold]
#[inline(never)]
pub(super) fn cooling_hands(c: &Core) -> [bool; 2] {
    let rules = c.opts.caps.item_cooldowns;
    let v = c.inv.version();
    [false, true].map(|off| {
        hand(c, off)
            .and_then(|s| key_of(rules, v, s))
            .is_some_and(|k| c.cooldowns.is_cooling(&k))
    })
}

/// The ender pearl's item id of a legacy data set.
fn ender_pearl(data: crate::version::DataSet) -> Option<i32> {
    match data {
        crate::version::DataSet::V1_12 => Some(368),
        #[cfg(feature = "v1_16_5")]
        crate::version::DataSet::V1_16_5 => {
            ghast_data::v1_16_5::Item::from_name("ender_pearl").map(|i| i32::from(i.id()))
        }
        _ => None,
    }
}

/// After the key handling: the cooldowns this tick's item uses start on the client (`used`:
/// the hands' [`USED`] / [`USED_ON`] bits), read from the stacks before the uses changed them.
/// 1.12.2 / 1.16.5: `EnderPearlItem.use` (20 ticks). 26.x: the stack's `use_cooldown` after an
/// instant use (`getUseDuration` 0) or a use on a block that succeeded.
#[cold]
#[inline(never)]
pub(super) fn use_cooldowns(c: &mut Core, used: u8) {
    let rules = c.opts.caps.item_cooldowns;
    let v = c.inv.version();
    for off in [false, true] {
        let shift = u8::from(off);
        let (instant, on_block) = (used & (USED << shift) != 0, used & (USED_ON << shift) != 0);
        if !instant && !on_block {
            continue;
        }
        let Some(s) = hand(c, off) else { continue };
        match rules {
            ItemCooldownRules::PerItem => {
                if instant && ender_pearl(c.opts.caps.data) == Some(s.id()) {
                    client_cooldown(c, CooldownKey::Item(s.id()), 20);
                }
            }
            ItemCooldownRules::Groups => {
                let Some(ticks) = use_cooldown_ticks(v, s) else {
                    continue;
                };
                let instant = instant && instant_use(v, s);
                if (instant || on_block)
                    && let Some(k) = key_of(rules, v, s)
                {
                    client_cooldown(c, k, ticks);
                }
            }
            _ => {}
        }
    }
}

/// 26.x `finishUsingItem` (the server's entity status 9): the used stack's `use_cooldown`
/// (chorus fruit), when the hand still holds the item.
pub(super) fn finish_cooldown(c: &mut Core) {
    let Some((off, item)) = c.hands.use_item() else {
        return;
    };
    let v = c.inv.version();
    let Some(s) = hand(c, off).filter(|s| u16::try_from(s.id()) == Ok(item)) else {
        return;
    };
    let Some(ticks) = use_cooldown_ticks(v, s) else {
        return;
    };
    if let Some(k) = key_of(c.opts.caps.item_cooldowns, v, s) {
        client_cooldown(c, k, ticks);
    }
}

/// The player tick's `update` / `tick` of the cooldowns (only while one is kept).
pub(super) fn tick_cooldowns(c: &mut Core) {
    let (cooldowns, pending) = (&mut c.cooldowns, &mut c.pending);
    cooldowns.tick(|key| {
        let m = pending.more();
        if m.cooldowns.len() < MAX_EVENTS {
            m.cooldowns.push(CooldownEvent::Ended { key: key.clone() });
        }
    });
}