Item cooldowns: the sweep on a slot, and no use while one runs
Nothing tracked `ItemCooldowns`: `draw_item_decorations` passed a cooldown of 0.0 with a note that there was none to shade, and ender pearls were held back by an ad-hoc `pearl_cooldown` counter. `horizon_client::cooldowns` keeps the `use_cooldown` component's entries by cooldown group the way `Player.getCooldowns` does (start and end ticks, the percent `getCooldownPercent` returns), `ItemInfo` now carries the item's `use_cooldown`, and the game uses it where vanilla does: `ServerPlayerGameMode.useItem`/useItemOn refuse a stack on cooldown, `ItemStack.applyAfterUseComponentSideEffects` starts the entry when a use finishes (a thrown pearl, a wind charge, an eaten chorus fruit), `GuiGraphicsExtractor.itemCooldown` shades the slot, and a server's guests keep their own and are sent `ClientboundCooldownPacket` (started, and 0 when it ends), which a client applies. Fixes #1763 Co-Authored-By: [CC] <deepseek-v4.1-flash> <noreply@deepseek.com>
This commit is contained in:
@@ -0,0 +1,174 @@
|
|||||||
|
//! `Player.getCooldowns()` (`ItemCooldowns`) as the game keeps it: the
|
||||||
|
//! `use_cooldown` component's entries by cooldown group, counted down once a
|
||||||
|
//! tick, and the percent `GuiGraphicsExtractor.itemCooldown` shades a slot
|
||||||
|
//! by. The world crate's `item_cooldowns` models vanilla's hash map and its
|
||||||
|
//! observers for the parity harness; this is the same data with the lookup a
|
||||||
|
//! slot needs, and no observer (vanilla's own player uses the plain class).
|
||||||
|
use crate::items::ItemStack;
|
||||||
|
use horizon_world::nbt::Tag;
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
/// A stack's `minecraft:use_cooldown` component.
|
||||||
|
#[derive(Clone, Debug, PartialEq)]
|
||||||
|
pub struct UseCooldown {
|
||||||
|
pub seconds: f32,
|
||||||
|
/// `cooldown_group`: the group the entry is filed under, else the item.
|
||||||
|
pub group: Option<Arc<str>>,
|
||||||
|
}
|
||||||
|
impl UseCooldown {
|
||||||
|
/// `UseCooldown.ticks`: the seconds in ticks, truncated.
|
||||||
|
pub fn ticks(&self) -> i32 {
|
||||||
|
(self.seconds * 20.0) as i32
|
||||||
|
}
|
||||||
|
/// The component as `items.json` holds it.
|
||||||
|
pub fn from_json(v: &serde_json::Value) -> Option<Self> {
|
||||||
|
let seconds = v.get("seconds")?.as_f64()? as f32;
|
||||||
|
Some(Self {
|
||||||
|
seconds,
|
||||||
|
group: v
|
||||||
|
.get("cooldown_group")
|
||||||
|
.and_then(|g| g.as_str())
|
||||||
|
.map(Arc::from),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/// The component as a stack's saved `components` holds it.
|
||||||
|
pub fn from_tag(t: &Tag) -> Option<Self> {
|
||||||
|
let Tag::Compound(c) = t else {
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
let text = |k: &str| match c.get(&horizon_world::nbt::JavaString::from(k)) {
|
||||||
|
Some(Tag::String(s)) => Some(s.to_string_lossy()),
|
||||||
|
_ => None,
|
||||||
|
};
|
||||||
|
let seconds = match c.get(&horizon_world::nbt::JavaString::from("seconds")) {
|
||||||
|
Some(Tag::Float(bits)) => f32::from_bits(*bits),
|
||||||
|
Some(Tag::Double(bits)) => f64::from_bits(*bits) as f32,
|
||||||
|
_ => return None,
|
||||||
|
};
|
||||||
|
Some(Self {
|
||||||
|
seconds,
|
||||||
|
group: text("cooldown_group").map(Arc::from),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The component a stack carries: its own patch first (`ItemStack.get`), then
|
||||||
|
/// the item's default from `items.json` (`ItemInfo::use_cooldown`).
|
||||||
|
pub fn component(stack: &ItemStack, default: Option<&UseCooldown>) -> Option<UseCooldown> {
|
||||||
|
stack
|
||||||
|
.data()
|
||||||
|
.and_then(|d| d.other("minecraft:use_cooldown"))
|
||||||
|
.and_then(UseCooldown::from_tag)
|
||||||
|
.or_else(|| default.cloned())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ItemCooldowns.getCooldownGroup`: the component's group, else the item id.
|
||||||
|
pub fn group(stack: &ItemStack, default: Option<&UseCooldown>) -> Arc<str> {
|
||||||
|
component(stack, default)
|
||||||
|
.and_then(|c| c.group)
|
||||||
|
.unwrap_or_else(|| Arc::clone(&stack.item))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `ItemCooldowns`: start and end ticks by group, and the tick counter.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub struct Cooldowns {
|
||||||
|
tick_count: i32,
|
||||||
|
entries: HashMap<Arc<str>, (i32, i32)>,
|
||||||
|
}
|
||||||
|
impl Cooldowns {
|
||||||
|
/// `getCooldownPercent`: what is left of the entry, from 1 to 0.
|
||||||
|
pub fn percent(&self, group: &str, partial_tick: f32) -> f32 {
|
||||||
|
let Some((start, end)) = self.entries.get(group) else {
|
||||||
|
return 0.0;
|
||||||
|
};
|
||||||
|
let duration = end.wrapping_sub(*start) as f32;
|
||||||
|
let remaining = *end as f32 - (self.tick_count as f32 + partial_tick);
|
||||||
|
(remaining / duration).clamp(0.0, 1.0)
|
||||||
|
}
|
||||||
|
/// `isOnCooldown`: whether the group still has time to run.
|
||||||
|
pub fn is_on_cooldown(&self, group: &str) -> bool {
|
||||||
|
self.percent(group, 0.0) > 0.0
|
||||||
|
}
|
||||||
|
/// `addCooldown`.
|
||||||
|
pub fn add(&mut self, group: Arc<str>, ticks: i32) {
|
||||||
|
self.entries.insert(
|
||||||
|
group,
|
||||||
|
(self.tick_count, self.tick_count.wrapping_add(ticks)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
/// `ItemCooldowns.tick`: the counter, then every entry that has run out,
|
||||||
|
/// which it hands back (`onCooldownEnded`).
|
||||||
|
pub fn tick(&mut self) -> Vec<Arc<str>> {
|
||||||
|
self.tick_count = self.tick_count.wrapping_add(1);
|
||||||
|
let done: Vec<Arc<str>> = self
|
||||||
|
.entries
|
||||||
|
.iter()
|
||||||
|
.filter(|(_, (_, end))| *end <= self.tick_count)
|
||||||
|
.map(|(group, _)| Arc::clone(group))
|
||||||
|
.collect();
|
||||||
|
self.entries.retain(|_, (_, end)| *end > self.tick_count);
|
||||||
|
done
|
||||||
|
}
|
||||||
|
/// `removeCooldown`.
|
||||||
|
pub fn remove(&mut self, group: &str) {
|
||||||
|
self.entries.remove(group);
|
||||||
|
}
|
||||||
|
pub fn is_empty(&self) -> bool {
|
||||||
|
self.entries.is_empty()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
fn stack(item: &str) -> ItemStack {
|
||||||
|
ItemStack::new(item, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_percent_falls_from_one_to_zero_over_the_entry() {
|
||||||
|
let mut c = Cooldowns::default();
|
||||||
|
c.add(Arc::from("minecraft:ender_pearl"), 20);
|
||||||
|
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
|
||||||
|
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 1.0);
|
||||||
|
for _ in 0..10 {
|
||||||
|
assert!(c.tick().is_empty());
|
||||||
|
}
|
||||||
|
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.5);
|
||||||
|
// The partial tick moves it within the tick.
|
||||||
|
assert_eq!(c.percent("minecraft:ender_pearl", 0.5), 0.475);
|
||||||
|
for _ in 0..9 {
|
||||||
|
c.tick();
|
||||||
|
}
|
||||||
|
assert!(c.is_on_cooldown("minecraft:ender_pearl"));
|
||||||
|
// ItemCooldowns.tick drops the entry at its end tick, and says so.
|
||||||
|
assert_eq!(c.tick(), [Arc::<str>::from("minecraft:ender_pearl")]);
|
||||||
|
assert!(!c.is_on_cooldown("minecraft:ender_pearl"));
|
||||||
|
assert!(c.is_empty());
|
||||||
|
assert_eq!(c.percent("minecraft:ender_pearl", 0.0), 0.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_group_comes_from_the_stack_then_the_item() {
|
||||||
|
let pearl = stack("minecraft:ender_pearl");
|
||||||
|
let default = UseCooldown::from_json(&json!({"seconds": 1.0})).expect("the component");
|
||||||
|
assert_eq!(&*group(&pearl, Some(&default)), "minecraft:ender_pearl");
|
||||||
|
// A stack's own component overrides the item's, group included.
|
||||||
|
let mut grouped = stack("minecraft:ender_pearl");
|
||||||
|
grouped.data_mut().set_other(
|
||||||
|
"minecraft:use_cooldown",
|
||||||
|
Some(Tag::compound([
|
||||||
|
("seconds", Tag::Float(2.0f32.to_bits())),
|
||||||
|
("cooldown_group", Tag::String("minecraft:pearls".into())),
|
||||||
|
])),
|
||||||
|
);
|
||||||
|
let c = component(&grouped, Some(&default)).expect("the stack's component");
|
||||||
|
assert_eq!(c.ticks(), 40);
|
||||||
|
assert_eq!(&*group(&grouped, Some(&default)), "minecraft:pearls");
|
||||||
|
// An item without the component has no cooldown.
|
||||||
|
assert!(component(&stack("minecraft:dirt"), None).is_none());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1320,6 +1320,10 @@ struct Game<'a> {
|
|||||||
hand: Hand,
|
hand: Hand,
|
||||||
/// The shield's item cooldown after an axe disabled it (ticks).
|
/// The shield's item cooldown after an axe disabled it (ticks).
|
||||||
shield_cooldown: u32,
|
shield_cooldown: u32,
|
||||||
|
/// `Player.getCooldowns()`: the `use_cooldown` component's entries, what
|
||||||
|
/// `itemDecorations` shades a slot by. A server's players have their own
|
||||||
|
/// (`GuestPlay::cooldowns`), swapped in for their turn.
|
||||||
|
cooldowns: horizon_client::cooldowns::Cooldowns,
|
||||||
/// The source of a command run through /execute (the player otherwise).
|
/// The source of a command run through /execute (the player otherwise).
|
||||||
command_source: Option<commands::execute::Source>,
|
command_source: Option<commands::execute::Source>,
|
||||||
titles: titles::Titles,
|
titles: titles::Titles,
|
||||||
@@ -1558,6 +1562,9 @@ struct Game<'a> {
|
|||||||
chat_capture: Option<Vec<horizon_client::text::Text>>,
|
chat_capture: Option<Vec<horizon_client::text::Text>>,
|
||||||
/// Packets for the guest acting now, sent once its action returns.
|
/// Packets for the guest acting now, sent once its action returns.
|
||||||
guest_packets: Vec<horizon_protocol::packets::play::Clientbound>,
|
guest_packets: Vec<horizon_protocol::packets::play::Clientbound>,
|
||||||
|
/// The acting guest's cooldowns, as (item, ticks): their packet needs the
|
||||||
|
/// hub's item registry, which the guest's turn does not hold.
|
||||||
|
guest_cooldowns: Vec<(Arc<str>, i32)>,
|
||||||
/// `broadcastToAdmins` lines a guest's command queued, sent once it
|
/// `broadcastToAdmins` lines a guest's command queued, sent once it
|
||||||
/// returns: the line, whether operators get it and whether the console
|
/// returns: the line, whether operators get it and whether the console
|
||||||
/// logs it.
|
/// logs it.
|
||||||
@@ -3394,6 +3401,25 @@ impl Game<'_> {
|
|||||||
|| self.interact_mob()?
|
|| self.interact_mob()?
|
||||||
|| self.interact_knot())
|
|| self.interact_knot())
|
||||||
}
|
}
|
||||||
|
/// `ItemStack.applyAfterUseComponentSideEffects`: a used stack with a
|
||||||
|
/// `use_cooldown` component starts its entry (`UseCooldown.apply`). A
|
||||||
|
/// server's guest also gets `ClientboundCooldownPacket`
|
||||||
|
/// (`ServerItemCooldowns.onCooldownStarted`), queued for their turn's end.
|
||||||
|
pub(super) fn apply_use_cooldown(&mut self, stack: &ItemStack) {
|
||||||
|
let default = self
|
||||||
|
.res
|
||||||
|
.items()
|
||||||
|
.get(&stack.item)
|
||||||
|
.and_then(|i| i.use_cooldown.clone());
|
||||||
|
let Some(component) = horizon_client::cooldowns::component(stack, default.as_ref()) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let group = horizon_client::cooldowns::group(stack, default.as_ref());
|
||||||
|
self.cooldowns.add(Arc::clone(&group), component.ticks());
|
||||||
|
if self.lan_acting.is_some() {
|
||||||
|
self.guest_cooldowns.push((group, component.ticks()));
|
||||||
|
}
|
||||||
|
}
|
||||||
/// One hand's turn in `startUseItem`: `useItemOn` the block aimed at,
|
/// One hand's turn in `startUseItem`: `useItemOn` the block aimed at,
|
||||||
/// then `useItem`. Whether the click ends here (it acted or failed).
|
/// then `useItem`. Whether the click ends here (it acted or failed).
|
||||||
fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result<bool> {
|
fn use_hand(&mut self, block_hit: Option<&Hit>) -> Result<bool> {
|
||||||
@@ -3478,6 +3504,17 @@ impl Game<'_> {
|
|||||||
let Some(info) = self.res.items().get(&stack.item).cloned() else {
|
let Some(info) = self.res.items().get(&stack.item).cloned() else {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
};
|
};
|
||||||
|
// ServerPlayerGameMode.useItem and useItemOn: an item on cooldown is
|
||||||
|
// not used (PASS, so the other hand may still act).
|
||||||
|
if self
|
||||||
|
.cooldowns
|
||||||
|
.is_on_cooldown(&horizon_client::cooldowns::group(
|
||||||
|
&stack,
|
||||||
|
info.use_cooldown.as_ref(),
|
||||||
|
))
|
||||||
|
{
|
||||||
|
return Ok(false);
|
||||||
|
}
|
||||||
if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) {
|
if block_hit.is_some() && (self.use_bone_meal(&stack)? || self.ignite_tnt(&stack)?) {
|
||||||
return Ok(true);
|
return Ok(true);
|
||||||
}
|
}
|
||||||
@@ -3804,6 +3841,8 @@ impl Game<'_> {
|
|||||||
}
|
}
|
||||||
if ticks >= duration {
|
if ticks >= duration {
|
||||||
self.using = None;
|
self.using = None;
|
||||||
|
// ItemStack.finishUsingItem's applyAfterUseComponentSideEffects.
|
||||||
|
self.apply_use_cooldown(&stack);
|
||||||
self.finish_consuming(&info, consumable, &stack);
|
self.finish_consuming(&info, consumable, &stack);
|
||||||
} else {
|
} else {
|
||||||
self.using = Some((slot, ticks));
|
self.using = Some((slot, ticks));
|
||||||
@@ -4405,6 +4444,7 @@ impl Game<'_> {
|
|||||||
// Player.tick's ItemCooldowns.tick for the window's player (a
|
// Player.tick's ItemCooldowns.tick for the window's player (a
|
||||||
// server's players count theirs down in `tick_guests`).
|
// server's players count theirs down in `tick_guests`).
|
||||||
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
|
self.shield_cooldown = self.shield_cooldown.saturating_sub(1);
|
||||||
|
self.cooldowns.tick();
|
||||||
horizon_client::spans::time("tick_using", || self.tick_using());
|
horizon_client::spans::time("tick_using", || self.tick_using());
|
||||||
horizon_client::spans::time("tick_hud", || self.tick_hud());
|
horizon_client::spans::time("tick_hud", || self.tick_hud());
|
||||||
// The player's digging comes in with its packets, before the level
|
// The player's digging comes in with its packets, before the level
|
||||||
@@ -4786,17 +4826,17 @@ impl Game<'_> {
|
|||||||
count_text: Option<String>,
|
count_text: Option<String>,
|
||||||
) {
|
) {
|
||||||
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
|
// GuiGraphicsExtractor.itemDecorations, laid out at the origin and
|
||||||
// moved to (x, y). Horizon tracks no item cooldowns to shade yet.
|
// moved to (x, y): the damage bar, the cooldown shade and the count.
|
||||||
let max_damage = self
|
let info = self.res.items().get(&stack.item);
|
||||||
.res
|
let max_damage = info.map_or(0, |info| info.max_damage as i32);
|
||||||
.items()
|
let cooldown =
|
||||||
.get(&stack.item)
|
horizon_client::cooldowns::group(stack, info.and_then(|i| i.use_cooldown.as_ref()));
|
||||||
.map_or(0, |info| info.max_damage as i32);
|
let partial = self.clock.fraction() as f32;
|
||||||
let decorations = hud_overlays::ItemDecorations {
|
let decorations = hud_overlays::ItemDecorations {
|
||||||
count: stack.count,
|
count: stack.count,
|
||||||
count_text,
|
count_text,
|
||||||
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
|
bar: hud_overlays::damage_bar(stack.damage as i32, max_damage),
|
||||||
cooldown: 0.0,
|
cooldown: self.cooldowns.percent(&cooldown, partial),
|
||||||
};
|
};
|
||||||
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
|
let mut draws = vec![hud_layout::GuiDraw::Push(vec![
|
||||||
hud_layout::PoseOp::Translate(x, y),
|
hud_layout::PoseOp::Translate(x, y),
|
||||||
@@ -11880,6 +11920,7 @@ impl<'a> Game<'a> {
|
|||||||
offhand: None,
|
offhand: None,
|
||||||
hand: Hand::Main,
|
hand: Hand::Main,
|
||||||
shield_cooldown: 0,
|
shield_cooldown: 0,
|
||||||
|
cooldowns: Default::default(),
|
||||||
command_source: None,
|
command_source: None,
|
||||||
titles: Default::default(),
|
titles: Default::default(),
|
||||||
tool_highlight: Default::default(),
|
tool_highlight: Default::default(),
|
||||||
@@ -12028,6 +12069,7 @@ impl<'a> Game<'a> {
|
|||||||
lid_openers: HashMap::new(),
|
lid_openers: HashMap::new(),
|
||||||
lan_acting: None,
|
lan_acting: None,
|
||||||
guest_packets: Vec::new(),
|
guest_packets: Vec::new(),
|
||||||
|
guest_cooldowns: Vec::new(),
|
||||||
lan_acting_name: None,
|
lan_acting_name: None,
|
||||||
lan_acting_uuid: None,
|
lan_acting_uuid: None,
|
||||||
chat_capture: None,
|
chat_capture: None,
|
||||||
|
|||||||
@@ -44,9 +44,7 @@ fn arrow_damage(arrow: &mut Projectile, fallback: &mut impl RandomSource) -> f32
|
|||||||
pub(super) struct Creatures {
|
pub(super) struct Creatures {
|
||||||
pub projectiles: Vec<Projectile>,
|
pub projectiles: Vec<Projectile>,
|
||||||
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
|
/// Player status effects applied by mobs: (effect, ticks left, amplifier).
|
||||||
pub pearl_cooldown: u32,
|
|
||||||
/// The wind charge's use cooldown (ticks).
|
/// The wind charge's use cooldown (ticks).
|
||||||
pub wind_cooldown: u32,
|
|
||||||
/// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs).
|
/// Wind bursts from a guest's turn, waiting for it to end (game/wind.rs).
|
||||||
pub wind_bursts: Vec<super::wind::Burst>,
|
pub wind_bursts: Vec<super::wind::Burst>,
|
||||||
/// Ticks left of the elder guardian's apparition (MobAppearanceParticle).
|
/// Ticks left of the elder guardian's apparition (MobAppearanceParticle).
|
||||||
@@ -642,7 +640,6 @@ impl Game<'_> {
|
|||||||
self.tick_allays();
|
self.tick_allays();
|
||||||
self.tick_breeze_effects();
|
self.tick_breeze_effects();
|
||||||
self.tick_sniffer_effects();
|
self.tick_sniffer_effects();
|
||||||
self.tick_player_effects();
|
|
||||||
self.piglin_pickups();
|
self.piglin_pickups();
|
||||||
self.sulfur_cube_pickups();
|
self.sulfur_cube_pickups();
|
||||||
// Hurt and death sounds of damage dealt outside the mob ticks.
|
// Hurt and death sounds of damage dealt outside the mob ticks.
|
||||||
@@ -1563,12 +1560,6 @@ impl Game<'_> {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
/// Burning applied to the player by mobs.
|
/// Burning applied to the player by mobs.
|
||||||
fn tick_player_effects(&mut self) {
|
|
||||||
self.creatures.wind_cooldown = self.creatures.wind_cooldown.saturating_sub(1);
|
|
||||||
if self.creatures.pearl_cooldown > 0 {
|
|
||||||
self.creatures.pearl_cooldown -= 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
pub(super) fn hurt_player_by(&mut self, damage_type: &str, amount: f32) {
|
pub(super) fn hurt_player_by(&mut self, damage_type: &str, amount: f32) {
|
||||||
if self.creative {
|
if self.creative {
|
||||||
return;
|
return;
|
||||||
@@ -2869,14 +2860,14 @@ impl Game<'_> {
|
|||||||
let kind = match item {
|
let kind = match item {
|
||||||
"minecraft:snowball" => ProjectileKind::Snowball,
|
"minecraft:snowball" => ProjectileKind::Snowball,
|
||||||
"minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => ProjectileKind::Egg,
|
"minecraft:egg" | "minecraft:blue_egg" | "minecraft:brown_egg" => ProjectileKind::Egg,
|
||||||
"minecraft:ender_pearl" => {
|
"minecraft:ender_pearl" => ProjectileKind::EnderPearl,
|
||||||
if self.creatures.pearl_cooldown > 0 {
|
"minecraft:wind_charge" => {
|
||||||
return Ok(true);
|
let thrown = self.throw_wind_charge()?;
|
||||||
|
if thrown {
|
||||||
|
self.apply_use_cooldown(stack);
|
||||||
}
|
}
|
||||||
self.creatures.pearl_cooldown = 20;
|
return Ok(thrown);
|
||||||
ProjectileKind::EnderPearl
|
|
||||||
}
|
}
|
||||||
"minecraft:wind_charge" => return self.throw_wind_charge(),
|
|
||||||
_ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack),
|
_ if item.ends_with("_spawn_egg") => return self.use_spawn_egg(stack),
|
||||||
_ => return Ok(false),
|
_ => return Ok(false),
|
||||||
};
|
};
|
||||||
@@ -2901,6 +2892,9 @@ impl Game<'_> {
|
|||||||
);
|
);
|
||||||
self.creatures.projectiles.push(proj);
|
self.creatures.projectiles.push(proj);
|
||||||
self.player_projectile_shot();
|
self.player_projectile_shot();
|
||||||
|
// ItemStack.use's applyAfterUseComponentSideEffects: the pearl's
|
||||||
|
// second is the `use_cooldown` component, as for any thrown item.
|
||||||
|
self.apply_use_cooldown(stack);
|
||||||
let sound = match kind {
|
let sound = match kind {
|
||||||
ProjectileKind::Snowball => "minecraft:entity.snowball.throw",
|
ProjectileKind::Snowball => "minecraft:entity.snowball.throw",
|
||||||
ProjectileKind::Egg => "minecraft:entity.egg.throw",
|
ProjectileKind::Egg => "minecraft:entity.egg.throw",
|
||||||
|
|||||||
@@ -38,6 +38,8 @@ pub(super) struct GuestPlay {
|
|||||||
use_delay: u32,
|
use_delay: u32,
|
||||||
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
|
/// The shield's ItemCooldowns entry: an axe disabled it for this many ticks.
|
||||||
pub(super) shield_cooldown: u32,
|
pub(super) shield_cooldown: u32,
|
||||||
|
/// The guest's `Player.getCooldowns()` (`Game::cooldowns` for its turn).
|
||||||
|
pub(super) cooldowns: horizon_client::cooldowns::Cooldowns,
|
||||||
attack_ticks: u32,
|
attack_ticks: u32,
|
||||||
/// The main hand's item at the guest's last tick (`Game::attack_item`).
|
/// The main hand's item at the guest's last tick (`Game::attack_item`).
|
||||||
attack_item: Option<std::sync::Arc<str>>,
|
attack_item: Option<std::sync::Arc<str>>,
|
||||||
@@ -125,6 +127,8 @@ pub(super) struct GuestSwap {
|
|||||||
using: Option<(usize, u32)>,
|
using: Option<(usize, u32)>,
|
||||||
use_delay: u32,
|
use_delay: u32,
|
||||||
pub(super) shield_cooldown: u32,
|
pub(super) shield_cooldown: u32,
|
||||||
|
/// The guest's item cooldowns (`Game::cooldowns` for its turn).
|
||||||
|
cooldowns: horizon_client::cooldowns::Cooldowns,
|
||||||
attack_ticks: u32,
|
attack_ticks: u32,
|
||||||
attack_item: Option<std::sync::Arc<str>>,
|
attack_item: Option<std::sync::Arc<str>>,
|
||||||
swing: horizon_client::first_person::SwingState,
|
swing: horizon_client::first_person::SwingState,
|
||||||
@@ -316,6 +320,7 @@ impl Game<'_> {
|
|||||||
let using = std::mem::replace(&mut self.using, play.using.take());
|
let using = std::mem::replace(&mut self.using, play.using.take());
|
||||||
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
|
let use_delay = std::mem::replace(&mut self.use_delay, play.use_delay);
|
||||||
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
|
let shield_cooldown = std::mem::replace(&mut self.shield_cooldown, play.shield_cooldown);
|
||||||
|
let cooldowns = std::mem::replace(&mut self.cooldowns, std::mem::take(&mut play.cooldowns));
|
||||||
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
|
let attack_ticks = std::mem::replace(&mut self.attack_ticks, play.attack_ticks);
|
||||||
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
|
let attack_item = std::mem::replace(&mut self.attack_item, play.attack_item.take());
|
||||||
let swing = std::mem::replace(&mut self.swing, play.swing);
|
let swing = std::mem::replace(&mut self.swing, play.swing);
|
||||||
@@ -400,6 +405,7 @@ impl Game<'_> {
|
|||||||
using,
|
using,
|
||||||
use_delay,
|
use_delay,
|
||||||
shield_cooldown,
|
shield_cooldown,
|
||||||
|
cooldowns,
|
||||||
attack_ticks,
|
attack_ticks,
|
||||||
attack_item,
|
attack_item,
|
||||||
swing,
|
swing,
|
||||||
@@ -456,6 +462,7 @@ impl Game<'_> {
|
|||||||
using,
|
using,
|
||||||
use_delay,
|
use_delay,
|
||||||
shield_cooldown,
|
shield_cooldown,
|
||||||
|
cooldowns,
|
||||||
attack_ticks,
|
attack_ticks,
|
||||||
attack_item,
|
attack_item,
|
||||||
swing,
|
swing,
|
||||||
@@ -491,6 +498,16 @@ impl Game<'_> {
|
|||||||
for packet in std::mem::replace(&mut self.guest_packets, packets) {
|
for packet in std::mem::replace(&mut self.guest_packets, packets) {
|
||||||
host.hub.send_to(conn, &packet);
|
host.hub.send_to(conn, &packet);
|
||||||
}
|
}
|
||||||
|
// ServerItemCooldowns.onCooldownStarted: the guest's own cooldown.
|
||||||
|
for (group, duration) in std::mem::take(&mut self.guest_cooldowns) {
|
||||||
|
host.hub.send_to(
|
||||||
|
conn,
|
||||||
|
&C::Cooldown(play::Cooldown {
|
||||||
|
group: group.to_string(),
|
||||||
|
duration,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
|
(self.lan_acting, self.lan_acting_name, self.lan_acting_uuid) = acting;
|
||||||
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
|
play.death_cause = std::mem::replace(&mut self.ui.death_cause, death_cause);
|
||||||
// An ender chest the guest opened: the menu shows their inventory
|
// An ender chest the guest opened: the menu shows their inventory
|
||||||
@@ -520,6 +537,7 @@ impl Game<'_> {
|
|||||||
play.using = std::mem::replace(&mut self.using, using);
|
play.using = std::mem::replace(&mut self.using, using);
|
||||||
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
|
play.use_delay = std::mem::replace(&mut self.use_delay, use_delay);
|
||||||
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
|
play.shield_cooldown = std::mem::replace(&mut self.shield_cooldown, shield_cooldown);
|
||||||
|
play.cooldowns = std::mem::replace(&mut self.cooldowns, cooldowns);
|
||||||
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
|
play.attack_ticks = std::mem::replace(&mut self.attack_ticks, attack_ticks);
|
||||||
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
|
play.attack_item = std::mem::replace(&mut self.attack_item, attack_item);
|
||||||
play.swing = std::mem::replace(&mut self.swing, swing);
|
play.swing = std::mem::replace(&mut self.swing, swing);
|
||||||
@@ -1783,8 +1801,19 @@ impl Game<'_> {
|
|||||||
}
|
}
|
||||||
let play = host.play.entry(conn).or_default();
|
let play = host.play.entry(conn).or_default();
|
||||||
// Player.tick's ItemCooldowns.tick, once a tick for each player
|
// Player.tick's ItemCooldowns.tick, once a tick for each player
|
||||||
// (the shield an axe disabled).
|
// (the shield an axe disabled, a thrown pearl).
|
||||||
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
|
play.shield_cooldown = play.shield_cooldown.saturating_sub(1);
|
||||||
|
// ServerItemCooldowns.onCooldownEnded: a finished entry is told to
|
||||||
|
// the guest (a duration of 0 removes it).
|
||||||
|
for group in play.cooldowns.tick() {
|
||||||
|
host.hub.send_to(
|
||||||
|
conn,
|
||||||
|
&C::Cooldown(play::Cooldown {
|
||||||
|
group: group.to_string(),
|
||||||
|
duration: 0,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
let digging = play.digging;
|
let digging = play.digging;
|
||||||
let using = play.using.is_some();
|
let using = play.using.is_some();
|
||||||
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
let delayed = play.destroy_delay > 0 || play.use_delay > 0 || play.attack_ticks < 100;
|
||||||
|
|||||||
@@ -2561,6 +2561,16 @@ impl Game<'_> {
|
|||||||
r.commands = Some(tree);
|
r.commands = Some(tree);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
C::Cooldown(p) => {
|
||||||
|
// ClientPacketListener.handleItemCooldown: the server starts
|
||||||
|
// (or confirms) a group's cooldown; 0 ends it.
|
||||||
|
let group: Arc<str> = Arc::from(p.group.as_str());
|
||||||
|
if p.duration == 0 {
|
||||||
|
self.cooldowns.remove(&group);
|
||||||
|
} else {
|
||||||
|
self.cooldowns.add(group, p.duration);
|
||||||
|
}
|
||||||
|
}
|
||||||
C::SystemChat(p) => {
|
C::SystemChat(p) => {
|
||||||
// The component as sent, translated in the client's own
|
// The component as sent, translated in the client's own
|
||||||
// language. ChatListener.handleOverlay for the action bar.
|
// language. ChatListener.handleOverlay for the action bar.
|
||||||
@@ -4303,8 +4313,12 @@ impl Game<'_> {
|
|||||||
let Some(info) = self.res.items().get(&held.item).cloned() else {
|
let Some(info) = self.res.items().get(&held.item).cloned() else {
|
||||||
return false;
|
return false;
|
||||||
};
|
};
|
||||||
// MultiPlayerGameMode.useItem runs the use here too: food starts
|
// MultiPlayerGameMode.useItem runs the use here too (inside
|
||||||
// being eaten (Consumable.startConsuming), a book and quill opens.
|
// startPrediction): the `use_cooldown` component starts its entry, and
|
||||||
|
// the server's ClientboundCooldownPacket confirms it.
|
||||||
|
self.apply_use_cooldown(&held);
|
||||||
|
// Food starts being eaten (Consumable.startConsuming), a book and
|
||||||
|
// quill opens.
|
||||||
self.with_hand(hand, |g| g.start_eating(&info));
|
self.with_hand(hand, |g| g.start_eating(&info));
|
||||||
if self.with_hand(hand, |g| g.remote_use_book(&held)) {
|
if self.with_hand(hand, |g| g.remote_use_book(&held)) {
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -52,10 +52,6 @@ fn triggers(name: &str) -> bool {
|
|||||||
impl Game<'_> {
|
impl Game<'_> {
|
||||||
/// `WindChargeItem.use`.
|
/// `WindChargeItem.use`.
|
||||||
pub(super) fn throw_wind_charge(&mut self) -> Result<bool> {
|
pub(super) fn throw_wind_charge(&mut self) -> Result<bool> {
|
||||||
if self.creatures.wind_cooldown > 0 {
|
|
||||||
return Ok(true);
|
|
||||||
}
|
|
||||||
self.creatures.wind_cooldown = 10;
|
|
||||||
let (Some(eye), Some(p)) = (self.eye_position(), self.player.as_ref()) else {
|
let (Some(eye), Some(p)) = (self.eye_position(), self.player.as_ref()) else {
|
||||||
return Ok(false);
|
return Ok(false);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -77,6 +77,8 @@ pub struct ItemInfo {
|
|||||||
pub consumable: Option<horizon_world::consumable::Consumable<String, ConsumeEffect>>,
|
pub consumable: Option<horizon_world::consumable::Consumable<String, ConsumeEffect>>,
|
||||||
/// `use_remainder`: what a finished use leaves (`UseRemainder`).
|
/// `use_remainder`: what a finished use leaves (`UseRemainder`).
|
||||||
pub use_remainder: Option<String>,
|
pub use_remainder: Option<String>,
|
||||||
|
/// `use_cooldown`: the cooldown a use starts (`UseCooldown`).
|
||||||
|
pub use_cooldown: Option<crate::cooldowns::UseCooldown>,
|
||||||
pub model: String,
|
pub model: String,
|
||||||
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
|
/// Main-hand `attack_damage` / `attack_speed` modifier amounts.
|
||||||
pub attack_damage: f32,
|
pub attack_damage: f32,
|
||||||
@@ -568,6 +570,9 @@ impl Items {
|
|||||||
use_remainder: c["minecraft:use_remainder"]["id"]
|
use_remainder: c["minecraft:use_remainder"]["id"]
|
||||||
.as_str()
|
.as_str()
|
||||||
.map(str::to_owned),
|
.map(str::to_owned),
|
||||||
|
use_cooldown: c
|
||||||
|
.get("minecraft:use_cooldown")
|
||||||
|
.and_then(crate::cooldowns::UseCooldown::from_json),
|
||||||
model: c["minecraft:item_model"]
|
model: c["minecraft:item_model"]
|
||||||
.as_str()
|
.as_str()
|
||||||
.unwrap_or(name)
|
.unwrap_or(name)
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ pub mod confirm_screen;
|
|||||||
pub mod container_screen;
|
pub mod container_screen;
|
||||||
pub mod containers;
|
pub mod containers;
|
||||||
pub mod control;
|
pub mod control;
|
||||||
|
pub mod cooldowns;
|
||||||
pub mod crafting;
|
pub mod crafting;
|
||||||
pub mod crash;
|
pub mod crash;
|
||||||
pub mod creative;
|
pub mod creative;
|
||||||
|
|||||||
@@ -176,6 +176,9 @@ packet!(
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
packet!(ContainerSetData { container: i32 => VarInt, id: i16 => Short, value: i16 => Short });
|
packet!(ContainerSetData { container: i32 => VarInt, id: i16 => Short, value: i16 => Short });
|
||||||
|
// ClientboundCooldownPacket: the cooldown group (an identifier) and the ticks
|
||||||
|
// its entry lasts (0 ends it).
|
||||||
|
packet!(Cooldown { group: String => Ident, duration: i32 => VarInt });
|
||||||
packet!(ContainerSetSlot { container: i32 => VarInt, state: i32 => VarInt, slot: i16 => Short, item: Option<Stack> => Slot });
|
packet!(ContainerSetSlot { container: i32 => VarInt, state: i32 => VarInt, slot: i16 => Short, item: Option<Stack> => Slot });
|
||||||
/// A holder reference: registry id + 1, or 0 for an inline value (unsupported).
|
/// A holder reference: registry id + 1, or 0 for an inline value (unsupported).
|
||||||
pub struct HolderId;
|
pub struct HolderId;
|
||||||
@@ -1761,6 +1764,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound {
|
|||||||
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
|
ContainerSetData(ContainerSetData) = CONTAINER_SET_DATA,
|
||||||
ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT,
|
ContainerSetSlot(ContainerSetSlot) = CONTAINER_SET_SLOT,
|
||||||
CookieRequest(CookieRequest) = COOKIE_REQUEST,
|
CookieRequest(CookieRequest) = COOKIE_REQUEST,
|
||||||
|
Cooldown(Cooldown) = COOLDOWN,
|
||||||
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
|
CustomPayload(CustomPayload) = CUSTOM_PAYLOAD,
|
||||||
Disconnect(Disconnect) = DISCONNECT,
|
Disconnect(Disconnect) = DISCONNECT,
|
||||||
DisguisedChat(DisguisedChat) = DISGUISED_CHAT,
|
DisguisedChat(DisguisedChat) = DISGUISED_CHAT,
|
||||||
@@ -2894,6 +2898,24 @@ mod tests {
|
|||||||
round_trip(beacon, Serverbound::encode, Serverbound::decode);
|
round_trip(beacon, Serverbound::encode, Serverbound::decode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_cooldown_packet_carries_its_group_and_ticks() {
|
||||||
|
let packet = Clientbound::Cooldown(Cooldown {
|
||||||
|
group: "minecraft:ender_pearl".into(),
|
||||||
|
duration: 20,
|
||||||
|
});
|
||||||
|
round_trip(packet, Clientbound::encode, Clientbound::decode);
|
||||||
|
// The group is an identifier, the ticks a VarInt; a duration of 0
|
||||||
|
// removes the entry.
|
||||||
|
let body = Clientbound::encode(&Clientbound::Cooldown(Cooldown {
|
||||||
|
group: "minecraft:ender_pearl".into(),
|
||||||
|
duration: 0,
|
||||||
|
}));
|
||||||
|
assert_eq!(body[0], crate::ids::play::clientbound::COOLDOWN as u8);
|
||||||
|
assert_eq!(&body[1..3], [21, b'm']);
|
||||||
|
assert_eq!(body[body.len() - 1], 0);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn change_game_mode_uses_the_game_type_varint() {
|
fn change_game_mode_uses_the_game_type_varint() {
|
||||||
for mode in 0..=3 {
|
for mode in 0..=3 {
|
||||||
|
|||||||
Reference in New Issue
Block a user