From ad76f911bdeff02d524acc0cad0916fc59b23167 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Fri, 23 Oct 2026 19:50:41 +0200 Subject: [PATCH] Shields, tridents, crossbows and spyglasses end their use on a server: the client starts it too Item.use runs on the client as well (MultiPlayerGameMode.useItem), and only a use the client started sends RELEASE_USE_ITEM when the button lets go. A server's client started one for bows and food only, so a shield kept blocking after release, a charged trident never left the hand, a loaded crossbow stayed "in use" on the server and never fired, and a spyglass never scoped. The client now starts what the window's own Item.use does: a bow or crossbow with ammunition, a trident, a spyglass, a shield off cooldown, and keeps it until the button lets go. The server's RELEASE_USE_ITEM let go of a main-hand bow only. It now runs ServerPlayer.releaseUsingItem with the used item's hand, through the release the window's own tick shares (bow, trident, spyglass). A loaded crossbow reached its client without its ammunition: the network stack gets minecraft:charged_projectiles (registry id 51, ItemStackTemplate list), and a server's client decodes it. lan_e2e gets a helduse check, for the host and the guest, both modes. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 21 ++-- crates/horizon-client/src/game/lan.rs | 3 + crates/horizon-client/src/game/lan_actions.rs | 18 ++- crates/horizon-client/src/game/remote.rs | 80 +++++++++++--- crates/horizon-client/src/lan/guest.rs | 19 ++++ crates/horizon-protocol/src/item.rs | 26 +++++ tools/lan_e2e.py | 103 ++++++++++++++++++ 7 files changed, 242 insertions(+), 28 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c62994dec..11f5dded2 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3653,16 +3653,8 @@ impl Game<'_> { // Switching hotbar slots only ends a main-hand use. let hand_changed = slot != self.selected && slot != shield::OFFHAND_SLOT; if !self.right || hand_changed || self.screen != Screen::Playing { - if &*stack.item == "minecraft:bow" && !hand_changed { - self.release_bow(ticks); - } - if &*stack.item == "minecraft:spyglass" { - self.stop_spyglass(); - } - if &*stack.item == "minecraft:trident" && !hand_changed { - self.release_trident(ticks); - } self.using = None; + self.release_used_item(&stack, ticks, hand_changed); return; } let Some(info) = self.res.items().get(&stack.item).cloned() else { @@ -3718,6 +3710,17 @@ impl Game<'_> { self.using = Some((slot, ticks)); } } + /// `LivingEntity.releaseUsingItem` (`Item.releaseUsing`) for `stack`, + /// used for `ticks`, its hand acting: a bow or a trident lets go (not + /// when its hand changed), a spyglass stops scoping. + pub(super) fn release_used_item(&mut self, stack: &ItemStack, ticks: u32, hand_changed: bool) { + match &*stack.item { + "minecraft:bow" if !hand_changed => self.release_bow(ticks), + "minecraft:trident" if !hand_changed => self.release_trident(ticks), + "minecraft:spyglass" => self.stop_spyglass(), + _ => {} + } + } fn tick_mining(&mut self) -> Result<()> { if self.destroy_delay > 0 { self.destroy_delay -= 1; diff --git a/crates/horizon-client/src/game/lan.rs b/crates/horizon-client/src/game/lan.rs index 9db544421..e0db6d725 100644 --- a/crates/horizon-client/src/game/lan.rs +++ b/crates/horizon-client/src/game/lan.rs @@ -409,6 +409,9 @@ impl Game<'_> { "game_mode": g.game_mode, // ItemCooldowns: the ticks the shield an axe disabled stays down. "shield_cooldown": h.play.get(&g.conn).map_or(0, |p| p.shield_cooldown), + // The item the server has this guest using: its slot and ticks. + "using": h.play.get(&g.conn).and_then(|p| p.using()) + .map(|(slot, ticks)| json!({ "slot": slot, "ticks": ticks })), "sneaking": g.sneaking, // The server's Elytra glide (shared flag 7). "fall_flying": g.fall_flying, diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 81ee2860b..91e4e15e5 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -868,14 +868,20 @@ impl Game<'_> { self.as_guest(host, conn, |g| g.drop_held(a.action == 4)); } } + // RELEASE_USE_ITEM: ServerPlayer.releaseUsingItem, with the + // hand of the item in use acting. 6 => { self.as_guest(host, conn, |g| { - if let Some((slot, ticks)) = g.using.take() - && g.stack_in(slot) - .is_some_and(|s| &*s.item == "minecraft:bow") - { - g.release_bow(ticks); - } + let Some(hand) = g.used_hand() else { + return; + }; + g.with_hand(hand, |g| { + if let Some((slot, ticks)) = g.using.take() + && let Some(stack) = g.stack_in(slot).cloned() + { + g.release_used_item(&stack, ticks, false); + } + }); }); } // SWAP_ITEM_WITH_OFFHAND: the hands swap and the item in use stops diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 362dc3cf2..21c3ff963 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -638,6 +638,22 @@ impl Game<'_> { ("mob_factor", Tag::Float(v[5].to_bits())), ]), Component::Profile(p) => profile_tag(p), + // ItemStackTemplate.CODEC: id, count and components. + Component::Stacks(stacks) => Tag::List( + stacks + .iter() + .map(|t| { + let mut entries = vec![ + ("id", Tag::String(self.item_name(t.item).as_ref().into())), + ("count", Tag::Int(t.count)), + ]; + if let Some(c) = self.protocol_components(t) { + entries.push(("components", c)); + } + Tag::compound(entries) + }) + .collect(), + ), Component::CustomModelData { floats, flags, @@ -4001,19 +4017,55 @@ impl Game<'_> { if self.with_hand(hand, |g| g.remote_use_book(&held)) { return true; } - // BowItem.use: startUsingItem here too (with an arrow, or in creative), so that letting - // go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and the server shoots. - if &*held.item == "minecraft:bow" { - self.with_hand(hand, |g| { - if g.using.is_none() && (g.creative || g.projectile_slot("minecraft:bow").is_some()) - { - g.using = Some((g.held_slot(), 0)); - } - }); - } + self.with_hand(hand, |g| g.remote_start_held_use(&held)); item_has_use(&info) } + /// `Item.use` runs on the client too (MultiPlayerGameMode.useItem): an + /// item held in use until the button lets go starts being used here, so + /// that letting go sends RELEASE_USE_ITEM (Minecraft.handleKeybinds) and + /// the server ends the use: a bow or a trident is let go, a crossbow's + /// charge ends, a shield is lowered, a spyglass stops scoping. Their + /// sounds, loaded arrows and thrown tridents come from the server. + fn remote_start_held_use(&mut self, held: &ItemStack) { + if self.using.is_some() { + return; + } + let start = match &*held.item { + // BowItem.use: with an arrow, or in creative. + "minecraft:bow" => self.creative || self.projectile_slot("minecraft:bow").is_some(), + // CrossbowItem.use: charging when not charged and with ammunition; + // a charged one shoots on the server. + "minecraft:crossbow" => { + held.data().is_none_or(|d| d.charged.is_empty()) + && (self.creative || self.projectile_slot("minecraft:crossbow").is_some()) + } + // TridentItem.use: not about to break, Riptide only in water or rain. + "minecraft:trident" => { + self.use_trident(held); + return; + } + // SpyglassItem.use (its sound is the server's). + "minecraft:spyglass" => true, + // ShieldItem.use: anything that blocks attacks, off cooldown. + _ => { + self.raise_shield(self.held_slot()); + return; + } + }; + if start { + self.using = Some((self.held_slot(), 0)); + } + } + /// Whether `stack` stays in use until the button lets go (bows, + /// crossbows, tridents, spyglasses, shields): its use only counts ticks here. + fn held_until_released(&self, stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:bow" | "minecraft:crossbow" | "minecraft:trident" | "minecraft:spyglass" + ) || self.blocks_attacks(stack).is_some() + } + /// The rest of Minecraft.startUseItem once the main hand's target passed: /// the main hand's item, then the off hand's turn (its block, its item). /// The server does each packet's part with that packet's hand only. @@ -4026,7 +4078,8 @@ impl Game<'_> { } self.remote_use_item(Hand::Off); } - /// `LivingEntity.updatingUsingItem` on a server client: a drawn bow, and a + /// `LivingEntity.updatingUsingItem` on a server client: an item held in + /// use (`held_until_released`), and a /// consumable's eating animation and its crumbs. The server eats it and /// sends the stack, the hunger and the sounds. fn remote_tick_using(&mut self) { @@ -4034,8 +4087,9 @@ impl Game<'_> { return; }; let stack = self.stack_in(slot).cloned(); - // A drawn bow: held until the button lets go (or another slot is picked). - if stack.as_ref().is_some_and(|s| &*s.item == "minecraft:bow") { + // A drawn bow, a charging crossbow, a raised shield...: held until + // the button lets go (or another slot is picked). + if stack.as_ref().is_some_and(|s| self.held_until_released(s)) { self.using = (slot == self.selected || slot == super::shield::OFFHAND_SLOT) .then_some((slot, ticks + 1)); return; diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 6ed7a2925..fd2b197e0 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -430,6 +430,13 @@ pub fn stack_to_network( item_id: impl Fn(&str) -> i32, enchantment_id: impl Fn(&str) -> Option, s: &Option, +) -> Option { + network_stack(&item_id, &enchantment_id, s) +} +fn network_stack( + item_id: &dyn Fn(&str) -> i32, + enchantment_id: &dyn Fn(&str) -> Option, + s: &Option, ) -> Option { let s = s.as_ref()?; let mut stack = Stack::new(item_id(&s.item), s.count as i32); @@ -486,6 +493,18 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(i32::from(mode)), )); } + // A loaded crossbow's ammunition. + if !d.charged.is_empty() { + let charged = d + .charged + .iter() + .filter_map(|c| network_stack(item_id, enchantment_id, &Some(c.clone()))) + .collect(); + stack.added.push(( + horizon_protocol::item::component::CHARGED_PROJECTILES, + horizon_protocol::item::Component::Stacks(charged), + )); + } // The books a lectern shows and a guest reads. if !d.writable_pages.is_empty() { stack.added.push(( diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 6f59228b5..650fa4baa 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -32,6 +32,7 @@ pub mod component { pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; pub const MAP_POST_PROCESSING: i32 = 50; + pub const CHARGED_PROJECTILES: i32 = 51; pub const WRITABLE_BOOK_CONTENT: i32 = 56; pub const WRITTEN_BOOK_CONTENT: i32 = 57; } @@ -75,6 +76,8 @@ pub enum Component { /// `WritableBookContent`: the pages (raw text). WritableBook(Vec), WrittenBook(WrittenBook), + /// `ChargedProjectiles`: a loaded crossbow's ammunition, as templates. + Stacks(Vec), } /// `Filterable.streamCodec`: the raw value, then an optional filtered one @@ -125,6 +128,10 @@ impl Component { resolved: r.bool()?, }) } + CHARGED_PROJECTILES => { + let n = r.count(1024)?; + Self::Stacks((0..n).map(|_| Template::read(r)).collect::>()?) + } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, ENCHANTMENT_GLINT_OVERRIDE => Self::Bool(r.bool()?), @@ -283,6 +290,10 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::Stacks(stacks) => { + w.varint(stacks.len() as i32); + stacks.iter().for_each(|s| Template::write(s, w)); + } Self::WritableBook(pages) => { w.varint(pages.len() as i32); for page in pages { @@ -533,6 +544,21 @@ mod tests { round::, HashedSlot>(None); } + #[test] + fn charged_projectiles_are_item_stack_templates() { + // A crossbow (id 7) loaded with one arrow (id 9): ChargedProjectiles + // is a list of ItemStackTemplate, the item before the count. + let bytes = [1, 7, 1, 0, 51, 1, 9, 1, 0, 0]; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::CHARGED_PROJECTILES), + Some(&Component::Stacks(vec![Stack::new(9, 1)])) + ); + let mut w = Writer::new(); + Slot::write(&Some(stack), &mut w); + assert_eq!(w.data, bytes); + } + #[test] fn filtered_book_pages_are_read_and_dropped() { // A writable book with one page "hi" and its filtered "**". diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index d93a142f1..b13c3cade 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -190,6 +190,10 @@ address. The script then checks, from both sides, what a guest's game used to ge (ServerboundPlayerCommandPacket START_FALL_FLYING): both their client and the server have them gliding, they go forward far more than down, and the glide ends on both once they land (#1288). +- helduse: the host and the guest raise a shield, charge and fire a crossbow, throw a trident + and scope with a spyglass: each use starts on their own client and on the server, and + letting go ends it on both (RELEASE_USE_ITEM), so the shield lowers, the trident flies + and the loaded crossbow fires on the next use (#1300, #1281, #1282, #1301). Each check is reported on its own (a failing one doesn't stop the others) and the screenshots of both sides go to --out (host-*.png, guest-*.png). @@ -4274,5 +4278,104 @@ CHECKS += ['elytra'] CHECK_FNS.update(elytra=check_elytra) +def server_using(host, game): + """The item the server has the player using ({slot, ticks}), or None.""" + if game is host and not SERVER_THREAD: + return host('state').get('using') + return server_player(host, game).get('using') + + +def flying(game, kind): + """How many of the projectiles this side draws are of `kind` (a trident, an arrow).""" + return sum(kind in q['kind'].lower() for q in game('status')['projectiles']) + + +def check_held_use(host, guest, out): + """Items used until the button lets go, for each player: the client starts the use too + (Item.use runs on both sides), so letting go sends RELEASE_USE_ITEM and the server ends it.""" + hx, hy, hz = (int(v // 1) for v in pos_of(host)) + seen = {} + try: + for game, dz in ((host, -3), (guest, 3)): + x, z = hx, hz + dz + host('command', command=f'fill {x - 1} {hy - 1} {z - 1} {x + 12} {hy - 1} {z + 1} minecraft:stone') + host('command', command=f'fill {x - 1} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:air') + host('command', command=f'fill {x + 12} {hy} {z - 1} {x + 12} {hy + 3} {z + 1} minecraft:stone') + game('command', command='gamemode survival') + game('command', command='clear @s') + game('command', command=f'tp @s {x + 0.5} {hy} {z + 0.5} -90 0') + game.wait(10) + s = {} + # ShieldItem: raised while held, lowered once let go. + game('command', command='item replace entity @s weapon.offhand with minecraft:shield') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['shield'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['shield']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + game('command', command='item replace entity @s weapon.offhand with minecraft:air') + # SpyglassItem: scoping while held. + game('command', command='item replace entity @s weapon.mainhand with minecraft:spyglass') + game.wait(5) + game.raw('mouse', 'right', 'down') + game.wait(10) + s['spyglass'] = {'held': (bool(game('state').get('using')), bool(server_using(host, game)))} + game.raw('mouse', 'right', 'up') + game.wait(10) + s['spyglass']['let_go'] = (bool(game('state').get('using')), bool(server_using(host, game))) + # TridentItem.releaseUsing after 10 ticks: thrown. + host('command', command='kill @e[type=minecraft:trident]') + game('command', command='item replace entity @s weapon.mainhand with minecraft:trident') + game.wait(5) + # /kill finds no thrown trident (Horizon's selectors miss them): count what's new. + before = flying(game, 'trident') + game.raw('use-item', '--hold', 1.2) + game.wait(10) + s['trident'] = {'kept': server_count(game, 'trident'), + 'thrown': flying(game, 'trident') - before} + host('command', command='kill @e[type=minecraft:trident]') + # CrossbowItem: charged by holding (25 ticks), fired by the next use. + host('command', command='kill @e[type=minecraft:arrow]') + game('command', command='clear @s') + game('command', command='item replace entity @s weapon.mainhand with minecraft:crossbow') + game('command', command='give @s minecraft:arrow 16') + game.wait(5) + before = flying(game, 'arrow') + game.raw('use-item', '--hold', 1.6) + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'] = {'loaded': 'charged_projectiles' in str(held.get('components', '')), + 'arrows': server_count(game, 'arrow')} + game.raw('use-item') + game.wait(10) + held = game('state').get('held') or {} + s['crossbow'].update( + fired=flying(game, 'arrow') - before, + emptied='charged_projectiles' not in str(held.get('components', ''))) + game.shot(out, 'helduse') + seen[game.name] = s + finally: + host('command', command='kill @e[type=minecraft:arrow]') + host('command', command='kill @e[type=minecraft:trident]') + for game in (host, guest): + back_to_game(game) + game.raw('mouse', 'right', 'up') + game('command', command='clear @s') + face_each_other(host, guest) + for name, s in seen.items(): + for item in ('shield', 'spyglass'): + assert s[item] == {'held': (True, True), 'let_go': (False, False)}, f'{name} {item}: {seen}' + assert s['trident'] == {'kept': 0, 'thrown': 1}, f'{name} trident: {seen}' + assert s['crossbow'] == {'loaded': True, 'arrows': 15, 'fired': 1, 'emptied': True}, \ + f'{name} crossbow: {seen}' + return seen + + +CHECKS += ['helduse'] +CHECK_FNS.update(helduse=check_held_use) + + if __name__ == '__main__': main()