From 7426aed33c6a6e019f93817f64ee4a5b628c4fbb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 11:46:22 +0200 Subject: [PATCH 1/2] Play the equip sound when the player puts on armour LivingEntity.onEquipItem now runs for the player wherever vanilla calls it: the inventory menu's ArmorSlot and off-hand slot (setByPlayer, in the menu engine, so clicks, shift-clicks, number keys, drags and LAN guests' clicks), right-click equipping (Equippable.swapWithEquipmentSlot), the creative screen (every changed slot, as handleSetCreativeModeSlot sets it), the swap-hands key, dispensers (now also a shield into the off hand) and /item and /loot on armour slots. It plays Equippable.equipSound (the generic armour sound by default) on PLAYERS when the item lands in its own slot, and emits equip/unequip game events for armour; nothing for spectators, on a client, or when the item is unchanged. The menu click harness's oracle now records vanilla's onEquipItem calls. Fixes #986 Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/menu_fixture.rs | 11 +- crates/horizon-client/src/game.rs | 20 ++++ .../horizon-client/src/game/armor_stands.rs | 30 ++--- .../horizon-client/src/game/commands/items.rs | 8 +- crates/horizon-client/src/game/dispenser.rs | 32 +++-- crates/horizon-client/src/game/lan_actions.rs | 22 +++- .../horizon-client/src/game/lan_crafting.rs | 9 ++ .../horizon-client/src/game/player_equip.rs | 94 +++++++++++++++ crates/horizon-client/src/menu.rs | 111 ++++++++++++++++-- .../horizonlab/parity/VanillaMenuOracle.java | 9 +- 10 files changed, 302 insertions(+), 44 deletions(-) create mode 100644 crates/horizon-client/src/game/player_equip.rs diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index df472983e..63a5351a3 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -19,11 +19,17 @@ fn state(menu: &Menu) -> String { .map(|i| canon_stack(menu.slot(i))) .collect(); let data: String = menu.data.iter().map(|d| format!(" {d}")).collect(); + let equipped: Vec = menu + .equipped + .iter() + .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) + .collect(); format!( - "{} | {} |{data} | {}", + "{} | {} |{data} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), - menu.drops.join(";") + menu.drops.join(";"), + equipped.join(";") ) } @@ -82,6 +88,7 @@ fn main() -> horizon_client::Result<()> { speed: 1.0, }); menu.drops.clear(); + menu.equipped.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { let slot = op[0].as_i64().unwrap_or(0) as i32; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 225c1a5e2..e99f42ada 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -106,6 +106,7 @@ mod persist; mod perspective; mod pickups; mod piglins; +mod player_equip; mod postprocess; mod potions; mod powder_snow; @@ -5233,6 +5234,9 @@ impl Game<'_> { .collect(); let carried = self.carried.clone(); let creative = self.creative; + // CreativeModeInventoryScreen clicks the menu itself and sends every + // changed slot, which the server sets by player. + let equipment_before = (self.screen == Screen::Creative).then(|| self.player_equipment()); let station_menu = self.station.as_ref().map(|s| { ( s.loom.selected.map_or(-1, |i| i as i32), @@ -5324,6 +5328,7 @@ impl Game<'_> { let dropped = std::mem::take(&mut menu.dropped); let sounds = std::mem::take(&mut menu.sounds); let crafted = std::mem::take(&mut menu.crafted); + let equipped = std::mem::take(&mut menu.equipped); for (i, stack) in after.into_iter().enumerate() { if let Some(g) = game_of[i] { *self.slot_mut(g) = stack; @@ -5366,6 +5371,14 @@ impl Game<'_> { // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. f.input_clicked(self.res.recipes(), before[0].clone()); } + match equipment_before { + Some(before) => self.player_equipment_changed(&before), + None => { + for (slot, stack) in equipped { + self.player_equipped(slot, stack.as_ref()); + } + } + } self.apply_equipment(); true } @@ -8878,10 +8891,12 @@ impl Game<'_> { if self.creative_inventory_open() { if Self::creative_trash_hovered(&batch, self.cursor) { if self.has_shift_down() { + let before = self.player_equipment(); self.inventory.fill(None); self.armor.fill(None); self.offhand = None; self.craft_grid[..4].fill(None); + self.player_equipment_changed(&before); self.apply_equipment(); } else { self.carried = None; @@ -9593,7 +9608,12 @@ impl Game<'_> { } } KeyCode::KeyF if self.screen == Screen::Playing => { + // handlePlayerAction SWAP_ITEM_WITH_OFFHAND: setItemInHand for + // the off hand, then the main hand. std::mem::swap(&mut self.offhand, &mut self.inventory[self.selected]); + let (offhand, main) = (self.offhand.clone(), self.inventory[self.selected].clone()); + self.player_on_equip("offhand", main.as_ref(), offhand.as_ref()); + self.player_on_equip("mainhand", offhand.as_ref(), main.as_ref()); self.using = None; } KeyCode::KeyQ if self.screen == Screen::Playing => { diff --git a/crates/horizon-client/src/game/armor_stands.rs b/crates/horizon-client/src/game/armor_stands.rs index 58cd27494..9f174c5ef 100644 --- a/crates/horizon-client/src/game/armor_stands.rs +++ b/crates/horizon-client/src/game/armor_stands.rs @@ -581,28 +581,31 @@ impl Game<'_> { let Some(info) = self.res.items().get(&stack.item) else { return false; }; - let index = match info.equip_slot.as_deref() { - Some("head") => 0, - Some("chest") => 1, - Some("legs") => 2, - Some("feet") => 3, + let (index, slot) = match info.equip_slot.as_deref() { + Some("head") => (0, "head"), + Some("chest") => (1, "chest"), + Some("legs") => (2, "legs"), + Some("feet") => (3, "feet"), _ => return false, }; if !info.swappable { return false; } - let sound = info.equip_sound.clone(); let current = self.armor[index].clone(); - // PREVENT_ARMOR_CHANGE (Curse of Binding) outside creative, or the same stack. + // PREVENT_ARMOR_CHANGE (Curse of Binding) outside creative, or the same item. if current.as_ref().is_some_and(|c| { - (c.enchantment_level("minecraft:binding_curse") > 0 && !self.creative) || c == stack + (c.enchantment_level("minecraft:binding_curse") > 0 && !self.creative) + || c.same_item_same_components(stack) }) { return true; } - self.armor[index] = Some(ItemStack { + let equipped = ItemStack { count: 1, ..stack.clone() - }); + }; + self.armor[index] = Some(equipped.clone()); + // Player.setItemSlot: onEquipItem plays the equip sound. + self.player_equipped(slot, Some(&equipped)); if !self.creative { let mut held = stack.clone(); held.count -= 1; @@ -620,13 +623,6 @@ impl Game<'_> { } } self.apply_equipment(); - if let Some(sound) = sound { - let at = self - .player - .as_ref() - .map(|p| [p.position.x, p.position.y, p.position.z]); - self.audio.play(&sound, at, 1.0, 1.0); - } self.swing_arm(); true } diff --git a/crates/horizon-client/src/game/commands/items.rs b/crates/horizon-client/src/game/commands/items.rs index fde97764d..b5c6e63d9 100644 --- a/crates/horizon-client/src/game/commands/items.rs +++ b/crates/horizon-client/src/game/commands/items.rs @@ -208,16 +208,20 @@ impl Game<'_> { } None => false, }, + // LivingEntity's equipment SlotAccess: setItemSlot, so onEquipItem. Slot::Armor(i) => match self.armor.get_mut(*i) { Some(slot) => { - *slot = stack; + let old = std::mem::replace(slot, stack.clone()); + let name = ["head", "chest", "legs", "feet"][*i]; + self.player_on_equip(name, old.as_ref(), stack.as_ref()); self.apply_equipment(); true } None => false, }, Slot::Offhand => { - self.offhand = stack; + let old = std::mem::replace(&mut self.offhand, stack.clone()); + self.player_on_equip("offhand", old.as_ref(), stack.as_ref()); true } Slot::Ender(i) => match self.ender_items.get_mut(*i) { diff --git a/crates/horizon-client/src/game/dispenser.rs b/crates/horizon-client/src/game/dispenser.rs index 0f59e5300..b9aa5004c 100644 --- a/crates/horizon-client/src/game/dispenser.rs +++ b/crates/horizon-client/src/game/dispenser.rs @@ -796,9 +796,15 @@ impl Game<'_> { // LivingEntity.canEquipWithDispenser: alive, the slot usable, the // item's allowed entities, the slot empty and the dispenser rule. let target = self.targets_at(front).into_iter().find(|t| match *t { - Target::Player => slot - .armor_index() - .is_some_and(|i| allows("minecraft:player") && self.armor[i].is_none()), + // Player.canUseSlot: every slot; the armour and the off hand are + // the ones an equippable item can reach. + Target::Player => { + allows("minecraft:player") + && match slot { + Slot::OffHand => self.offhand.is_none(), + _ => slot.armor_index().is_some_and(|i| self.armor[i].is_none()), + } + } Target::Stand(i) => slot.stand_index().is_some_and(|s| { allows("minecraft:armor_stand") && self.armor_stands[i].equipment[s].is_none() }), @@ -818,11 +824,20 @@ impl Game<'_> { // setItemSlot: onEquipItem plays the equip sound and the equip event. let (at, sound) = match target { Target::Player => { - if let Some(i) = slot.armor_index() { - self.armor[i] = Some(one); - } + // Player.setItemSlot: onEquipItem plays the sound and the event. + let name = match slot.armor_index() { + Some(i) => { + self.armor[i] = Some(one.clone()); + ["head", "chest", "legs", "feet"][i] + } + None => { + self.offhand = Some(one.clone()); + "offhand" + } + }; + self.player_equipped(name, Some(&one)); self.apply_equipment(); - (self.player_view().map(|v| v.position), sound) + return true; } Target::Stand(i) => { let stand = &mut self.armor_stands[i]; @@ -849,9 +864,8 @@ impl Game<'_> { self.audio.play(&sound, Some([at.x, at.y, at.z]), 1.0, 1.0); } let who = match target { - Target::Player => Some(horizon_client::mobs::Who::Player), Target::Mob(i) => Some(horizon_client::mobs::Who::Mob(self.mobs[i].id)), - Target::Stand(_) => None, + Target::Player | Target::Stand(_) => None, }; let ctx = self.who_context(who, None); self.post_game_event("minecraft:equip", [at.x, at.y, at.z], ctx); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 6c0fa4abf..5c85098e1 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -746,9 +746,15 @@ impl Game<'_> { let g = &mut host.hub.guests[gi]; let slot = g.selected; std::mem::swap(&mut g.inventory[slot], &mut g.offhand); + let (offhand, main) = (g.offhand.clone(), g.inventory[slot].clone()); if let Some(play) = host.play.get_mut(&conn) { play.using = None; } + // setItemInHand: the off hand, then the main hand. + self.as_guest(host, conn, |g| { + g.player_on_equip("offhand", main.as_ref(), offhand.as_ref()); + g.player_on_equip("mainhand", offhand.as_ref(), main.as_ref()); + }); } _ => {} }, @@ -844,7 +850,21 @@ impl Game<'_> { return; } let item = self.item_from_network(host, &p.item); - host.hub.guests[gi].set_menu_slot(p.slot as usize, item); + let slot = p.slot as usize; + let g = &mut host.hub.guests[gi]; + let old = g.menu_slot(slot); + g.set_menu_slot(slot, item.clone()); + // InventoryMenu's ArmorSlot and off-hand slot: setByPlayer. + let equipment = match slot { + 5..=8 => Some(["head", "chest", "legs", "feet"][slot - 5]), + 45 => Some("offhand"), + _ => None, + }; + if let Some(equipment) = equipment { + self.as_guest(host, conn, |g| { + g.player_on_equip(equipment, old.as_ref(), item.as_ref()); + }); + } } S::ContainerClick(p) if self.lan_merchant_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index de26e84aa..6101ce99e 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -105,9 +105,18 @@ impl Game<'_> { load_player(menu, &host.hub.guests[gi]); let result = op(menu, &env); let dropped = std::mem::take(&mut menu.dropped); + let equipped = std::mem::take(&mut menu.equipped); menu.drops.clear(); menu.crafted.clear(); store_player(menu, &mut host.hub.guests[gi]); + if !equipped.is_empty() { + let conn = host.hub.guests[gi].conn; + self.as_guest(host, conn, |g| { + for (slot, stack) in equipped { + g.player_equipped(slot, stack.as_ref()); + } + }); + } self.drop_guest_items(host, gi, dropped); result } diff --git a/crates/horizon-client/src/game/player_equip.rs b/crates/horizon-client/src/game/player_equip.rs new file mode 100644 index 000000000..a13c6400a --- /dev/null +++ b/crates/horizon-client/src/game/player_equip.rs @@ -0,0 +1,94 @@ +//! `LivingEntity.onEquipItem` for players: the equip sound and the equip +//! game event when an armour or off-hand slot takes a different item, from +//! every path that calls it (use, the inventory menu, the creative screen, +//! the swap-hands key, dispensers), for the host and for LAN guests. +use super::Game; +use horizon_client::items::ItemStack; + +/// The equipment slots `onEquipItem` can act on, as `EquipmentSlot` names: +/// the armour (`Player.doesEmitEquipEvent`: these emit the game event) and +/// the off hand. +const ARMOR: [&str; 4] = ["head", "chest", "legs", "feet"]; +const OFFHAND: &str = "offhand"; + +/// `ItemStack.isSameItemSameComponents` over optional stacks. +fn same(a: Option<&ItemStack>, b: Option<&ItemStack>) -> bool { + match (a, b) { + (None, None) => true, + (Some(a), Some(b)) => a.same_item_same_components(b), + _ => false, + } +} + +impl Game<'_> { + /// The armour (head first) and the off hand, in `EquipmentSlot` order of + /// the inventory menu's slots. + pub(super) fn player_equipment(&self) -> [Option; 5] { + let [head, chest, legs, feet] = self.armor.clone(); + [head, chest, legs, feet, self.offhand.clone()] + } + + /// `onEquipItem` for every slot that changed since `before`: what the + /// server does for the creative screen, which sends each changed slot + /// (`handleSetCreativeModeSlot` sets it by player). + pub(super) fn player_equipment_changed(&mut self, before: &[Option; 5]) { + let after = self.player_equipment(); + for (i, slot) in ARMOR.into_iter().chain([OFFHAND]).enumerate() { + self.player_on_equip(slot, before[i].as_ref(), after[i].as_ref()); + } + } + + /// `LivingEntity.onEquipItem(slot, old, new)` for the player in place + /// (the host, or a guest inside `as_guest`). + pub(super) fn player_on_equip( + &mut self, + slot: &str, + old: Option<&ItemStack>, + new: Option<&ItemStack>, + ) { + if !same(old, new) { + self.player_equipped(slot, new); + } + } + + /// The body of `onEquipItem` once the item changed: the item's + /// `Equippable.equipSound` when it is equipped in its own slot, and the + /// `equip` / `unequip` game event for armour. Nothing on a client (the + /// server plays it) or for a spectator. The player's `firstTick` never + /// sees an equip here: loading a save sets the slots directly. + pub(super) fn player_equipped(&mut self, slot: &str, new: Option<&ItemStack>) { + if self.remote.is_some() || self.spectator() { + return; + } + let Some(at) = self.player.as_ref().map(|p| p.position) else { + return; + }; + let at = [at.x, at.y, at.z]; + let equippable = new + .and_then(|s| self.res.items().get(&s.item)) + .and_then(|info| { + let own = info.equip_slot.as_deref()?; + Some((own == slot, info.equip_sound.clone())) + }); + if let Some((true, sound)) = &equippable { + let sound = sound + .as_deref() + .unwrap_or("minecraft:item.armor.equip_generic"); + // Player.getSoundSource: PLAYERS. + let players = horizon_client::settings::SOUND_SOURCES + .iter() + .position(|s| *s == "player") + .unwrap_or(0); + self.audio.play_on(players, sound, Some(at), 1.0, 1.0); + } + if ARMOR.contains(&slot) { + let event = if equippable.is_some() { + "minecraft:equip" + } else { + "minecraft:unequip" + }; + let ctx = self.player_context(None); + self.post_game_event(event, at, ctx); + } + } +} diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 64286b1fe..f5d8c8480 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -177,6 +177,9 @@ pub struct Menu { pub sounds: Vec<&'static str>, /// Recipes whose result was taken (`awardUsedRecipes`), for the caller. pub crafted: Vec, + /// `LivingEntity.onEquipItem` calls that change the item: the + /// `EquipmentSlot` name and the new stack, in order, for the caller. + pub equipped: Vec<(&'static str, Option)>, /// The merchant a merchant menu trades with. pub merchant: Option>, } @@ -398,6 +401,7 @@ impl Menu { loom_patterns: Vec::new(), sounds: Vec::new(), crafted: Vec::new(), + equipped: Vec::new(), merchant: None, } } @@ -699,6 +703,47 @@ impl Menu { self.slot_changed(env, s); } + /// `Slot.setByPlayer(stack)`: the slot's item is the previous one. + fn set_by_player(&mut self, env: &Env, s: usize, stack: Option) { + let previous = self.slot(s).cloned(); + self.set_by_player_from(env, s, stack, previous.as_ref()); + } + + /// `Slot.setByPlayer(stack, previous)`: `ArmorSlot` and the inventory + /// menu's off-hand slot first call the owner's `onEquipItem`, which acts + /// only when the item changes (`isSameItemSameComponents`). + fn set_by_player_from( + &mut self, + env: &Env, + s: usize, + mut stack: Option, + previous: Option<&ItemStack>, + ) { + tidy(&mut stack); + if let Some(slot) = self.equipment_slot(s) { + let same = match (previous.filter(|p| p.count > 0), stack.as_ref()) { + (None, None) => true, + (Some(a), Some(b)) => a.same_item_same_components(b), + _ => false, + }; + if !same { + self.equipped.push((slot, stack.clone())); + } + } + self.put(env, s, stack); + } + + /// The `EquipmentSlot` of an `ArmorSlot` or of `InventoryMenu`'s off-hand + /// slot (the only menu slot over inventory slot 40). + fn equipment_slot(&self, s: usize) -> Option<&'static str> { + let slot = self.slots[s]; + match slot.role { + Role::Armor(eq) => Some(["feet", "legs", "chest", "head"][eq]), + _ if slot.container == PLAYER && slot.index == OFFHAND => Some("offhand"), + _ => None, + } + } + /// `Slot.remove`: the container's `removeItem`. fn remove(&mut self, env: &Env, s: usize, amount: u32) -> Option { let slot = self.slots[s]; @@ -832,7 +877,7 @@ impl Menu { } let result = self.remove(env, s, amount.min(max_amount))?; if self.slot(s).is_none() { - self.put(env, s, None); + self.set_by_player_from(env, s, None, Some(&result)); } Some(result) } @@ -872,12 +917,12 @@ impl Menu { match self.slot(s).cloned() { None => { let part = split(stack, transferable); - self.put(env, s, Some(part)); + self.set_by_player(env, s, Some(part)); } Some(mut current) if current.same_item_same_components(stack) => { stack.count -= transferable; current.count += transferable; - self.put(env, s, Some(current)); + self.set_by_player(env, s, Some(current)); } Some(_) => {} } @@ -1033,7 +1078,7 @@ impl Menu { if !self.has_item(dest) && self.may_place(env, dest, stack) { let max = self.slot_max(env, dest, stack); let part = split(stack, stack.count.min(max)); - self.put(env, dest, Some(part)); + self.set_by_player(env, dest, Some(part)); changed = true; break; } @@ -1312,7 +1357,8 @@ impl Menu { let slot = self.slots[index]; if stack.count == 0 { self.containers[slot.container][slot.index] = None; - self.put(env, index, None); + // InventoryMenu: setByPlayer(EMPTY, clicked). + self.set_by_player_from(env, index, None, Some(&clicked)); } else { self.containers[slot.container][slot.index] = Some(stack.clone()); self.slot_changed(env, index); @@ -1418,7 +1464,7 @@ impl Menu { remaining -= i64::from(new_count) - i64::from(have); let mut placed = source.clone(); placed.count = new_count; - self.put(env, s, Some(placed)); + self.set_by_player(env, s, Some(placed)); } } source.count = remaining.max(0) as u32; @@ -1578,7 +1624,7 @@ impl Menu { tidy(&mut self.carried); } else if carried.count <= self.slot_max(env, s, &carried) { self.carried = Some(clicked); - self.put(env, s, Some(carried)); + self.set_by_player(env, s, Some(carried)); } else { self.carried = Some(carried); } @@ -1612,7 +1658,7 @@ impl Menu { (None, Some(taken)) => { if self.may_pickup(env, target) { self.containers[PLAYER][inv_slot] = Some(taken.clone()); - self.put(env, target, None); + self.set_by_player(env, target, None); self.on_take(env, target); } } @@ -1622,10 +1668,10 @@ impl Menu { if source.count > max { let part = split(&mut source, max); self.containers[PLAYER][inv_slot] = Some(source); - self.put(env, target, Some(part)); + self.set_by_player(env, target, Some(part)); } else { self.containers[PLAYER][inv_slot] = None; - self.put(env, target, Some(source)); + self.set_by_player(env, target, Some(source)); } } } @@ -1635,14 +1681,14 @@ impl Menu { if source.count > max { let part = split(&mut source, max); self.containers[PLAYER][inv_slot] = Some(source); - self.put(env, target, Some(part)); + self.set_by_player(env, target, Some(part)); self.on_take(env, target); if !self.inventory_add(env, &mut taken) { self.drop_stack(&taken); } } else { self.containers[PLAYER][inv_slot] = Some(taken); - self.put(env, target, Some(source)); + self.set_by_player(env, target, Some(source)); self.on_take(env, target); } } @@ -1988,6 +2034,47 @@ pub(crate) mod tests { test(&env, &mut menu); } + /// `onEquipItem` runs from the armour and off-hand slots' `setByPlayer` + /// when the item changes: never from `Inventory.setItem` (a swap's source). + #[test] + fn armour_and_off_hand_slots_report_what_is_equipped() { + with_menu(Kind::Inventory, |env, menu| { + menu.creative = false; + let name = |e: &[(&str, Option)]| { + e.iter() + .map(|(slot, s)| format!("{slot}:{}", s.as_ref().map_or("-", |s| &*s.item))) + .collect::>() + }; + // A shift-click puts the helmet on (InventoryMenu.quickMoveStack). + menu.set_slot(env, 9, stack("iron_helmet", 1)); + menu.click(env, 9, 0, Input::QuickMove).unwrap(); + assert_eq!(name(&menu.equipped), ["head:minecraft:iron_helmet"]); + // Taking it off; the same helmet back on is a change both ways. + menu.equipped.clear(); + menu.click(env, 5, 0, Input::Pickup).unwrap(); + menu.click(env, 5, 0, Input::Pickup).unwrap(); + assert_eq!( + name(&menu.equipped), + ["head:-", "head:minecraft:iron_helmet"] + ); + // F over a hotbar slot: the shield reaches the off hand by + // Inventory.setItem, so nothing; a number key onto the off-hand + // slot sets it by player. + menu.equipped.clear(); + menu.set_slot(env, 36, stack("shield", 1)); + menu.click(env, 36, 40, Input::Swap).unwrap(); + assert_eq!(menu.slot(45).map(|s| &*s.item), Some("minecraft:shield")); + assert!(menu.equipped.is_empty()); + menu.click(env, 45, 1, Input::Swap).unwrap(); + assert_eq!(name(&menu.equipped), ["offhand:-"]); + // Other menus have no equipment slots. + let mut chest = Menu::new(Kind::Chest(1)); + chest.set_slot(env, 0, stack("iron_helmet", 1)); + chest.click(env, 0, 0, Input::QuickMove).unwrap(); + assert!(chest.equipped.is_empty()); + }); + } + #[test] fn a_quick_craft_drag_previews_each_slot_and_the_rest_in_hand() { with_menu(Kind::Inventory, |env, menu| { diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 58c2eb94f..2a93a32d6 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -35,6 +35,8 @@ public final class VanillaMenuOracle { static java.lang.reflect.Method allocate; static RecipeManager recipes; static final List drops = new ArrayList<>(); + /** onEquipItem calls that change the item (its sound and game event): slot and new stack. */ + static final List equips = new ArrayList<>(); /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; @@ -105,7 +107,9 @@ public final class VanillaMenuOracle { @Override public EntityType getType() { return net.minecraft.world.entity.EntityTypes.PLAYER; } @Override public net.minecraft.core.Holder> typeHolder() { return net.minecraft.world.entity.EntityTypes.PLAYER.builtInRegistryHolder(); } @Override public boolean canUseSlot(EquipmentSlot slot) { return true; } - @Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { } + @Override public void onEquipItem(EquipmentSlot slot, ItemStack old, ItemStack now) { + if (!ItemStack.isSameItemSameComponents(old, now)) equips.add(slot.getName() + ":" + ParityData.canon(now)); + } @Override public boolean hasDisconnected() { return false; } @Override public ItemEntity drop(ItemStack stack, boolean thrown, net.minecraft.util.Prediction p) { if (!stack.isEmpty()) drops.add(ParityData.canon(stack)); @@ -190,6 +194,7 @@ public final class VanillaMenuOracle { out.append(" |"); for (DataSlot d : data) out.append(' ').append(d.get()); out.append(" | ").append(String.join(";", drops)); + out.append(" | ").append(String.join(";", equips)); return out.toString(); } @@ -207,6 +212,7 @@ public final class VanillaMenuOracle { var f = JsonParser.parseString(line).getAsJsonObject(); try { drops.clear(); + equips.clear(); var world = make(World.class); world.server = make(Server.class); var player = make(FakePlayer.class); @@ -228,6 +234,7 @@ public final class VanillaMenuOracle { var dataJson = f.getAsJsonArray("data"); for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); + equips.clear(); out.println("init " + state(menu, inv)); for (var opJson : f.getAsJsonArray("ops")) { var op = opJson.getAsJsonArray(); From 7c06feec74348884460975275c304fcc66ff3d8f Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Mon, 19 Oct 2026 12:48:49 +0200 Subject: [PATCH 2/2] Keep the equip list out of the place_recipe oracle's state line VanillaPlaceRecipeOracle prints VanillaMenuOracle.state, so the equips field the menu_click harness compares broke its lines. Only the menu_click oracle's own lines carry it now. Co-Authored-By: Claude Opus 5.5 --- .../dev/horizonlab/parity/VanillaMenuOracle.java | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java index 2a93a32d6..5c784fdfe 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -194,10 +194,14 @@ public final class VanillaMenuOracle { out.append(" |"); for (DataSlot d : data) out.append(' ').append(d.get()); out.append(" | ").append(String.join(";", drops)); - out.append(" | ").append(String.join(";", equips)); return out.toString(); } + /** {@link #state} and what was equipped: the menu_click harness's line (place_recipe prints {@code state}). */ + static String clickState(AbstractContainerMenu menu, Inventory inv) throws Exception { + return state(menu, inv) + " | " + String.join(";", equips); + } + public static void main(String[] args) throws Exception { ParityData.init(); var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); @@ -235,7 +239,7 @@ public final class VanillaMenuOracle { for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); equips.clear(); - out.println("init " + state(menu, inv)); + out.println("init " + clickState(menu, inv)); for (var opJson : f.getAsJsonArray("ops")) { var op = opJson.getAsJsonArray(); int slot = op.get(0).getAsInt(); @@ -244,13 +248,13 @@ public final class VanillaMenuOracle { if (kind.equals("BUTTON")) { // ServerGamePacketListenerImpl.handleContainerButtonClick if (menu.clickMenuButton(player, slot)) menu.broadcastChanges(); - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); continue; } if (kind.equals("SLOT_STATE")) { // handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1); - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); continue; } if (kind.equals("QUICK_MOVE_ALL")) { @@ -266,7 +270,7 @@ public final class VanillaMenuOracle { } } } - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); continue; } var input = ContainerInput.valueOf(kind); @@ -278,7 +282,7 @@ public final class VanillaMenuOracle { if (System.getenv("MENU_TRACE") != null) cause.printStackTrace(); continue; } - out.println(state(menu, inv)); + out.println(clickState(menu, inv)); } out.println("end"); } catch (Throwable e) {