Merge pull request #1476 from ludovic111/fix/st-held-use

🤖 Agent: merged after verify and CI parity passed, built merged with current main (st-default-1: server-thread gaps checked against vanilla, each with a lan_e2e check that fails on main and passes here, host and guest, both modes; tables in the PR body).
This commit is contained in:
Ludovic Marie
2026-10-24 03:43:11 +02:00
committed by GitHub
7 changed files with 242 additions and 28 deletions
+12 -9
View File
@@ -3681,16 +3681,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 {
@@ -3746,6 +3738,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;
+3
View File
@@ -411,6 +411,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,
+12 -6
View File
@@ -871,14 +871,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
+67 -13
View File
@@ -641,6 +641,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,
@@ -4034,19 +4050,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.
@@ -4065,7 +4117,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) {
@@ -4073,8 +4126,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;
+19
View File
@@ -432,6 +432,13 @@ pub fn stack_to_network(
item_id: impl Fn(&str) -> i32,
enchantment_id: impl Fn(&str) -> Option<i32>,
s: &Option<ItemStack>,
) -> Option<Stack> {
network_stack(&item_id, &enchantment_id, s)
}
fn network_stack(
item_id: &dyn Fn(&str) -> i32,
enchantment_id: &dyn Fn(&str) -> Option<i32>,
s: &Option<ItemStack>,
) -> Option<Stack> {
let s = s.as_ref()?;
let mut stack = Stack::new(item_id(&s.item), s.count as i32);
@@ -488,6 +495,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((
+26
View File
@@ -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<String>),
WrittenBook(WrittenBook),
/// `ChargedProjectiles`: a loaded crossbow's ammunition, as templates.
Stacks(Vec<Stack>),
}
/// `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::<Result<_>>()?)
}
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::<Option<Hashed>, 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 "**".
+103
View File
@@ -203,6 +203,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).
@@ -4723,5 +4727,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()