From 3e868683bae129f0875b030507d3bc77d809673e Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:13:30 +0200 Subject: [PATCH] Anvil and smithing table on the menu engine; LAN guests use them AnvilMenu and SmithingMenu (ItemCombinerMenu) now run on horizon_client::menu: their slot rules, createResult (the anvil's cost data slot, repair count and rename, the smithing table's hasRecipeError), mayPickup with the player's levels, the results' onTake and quickMoveStack, verified against the vanilla classes by test_menu_click_parity with repairs, merges, renames (a new RENAME op, AnvilMenu.setItemName) and the player's levels. The harness found the anvil treating only enchanted books as books (vanilla: anything with stored enchantments), now fixed, and the grindstone's and anvil's result slots now count for a double click's pick-all as in vanilla. Single player routes both screens' clicks, drags and double clicks through the engine; the anvil's wear and level events 1030/1029, and the smithing table's 1044, play with vanilla's random pitch. The LAN host opens minecraft:anvil and minecraft:smithing for guests, handles ServerboundRenameItemPacket (new in horizon-protocol), charges the guest's levels and wears the anvil; guests send the rename box as AnvilScreen.onNameChanged does and show the server's cost. The control socket's `type` now reaches the anvil's rename box. Part of #868. Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 2 + .../horizon-client/examples/menu_fixture.rs | 9 + .../examples/place_recipe_fixture.rs | 2 + .../examples/trading_fixture.rs | 2 + crates/horizon-client/src/creative.rs | 1 + crates/horizon-client/src/game.rs | 35 ++- crates/horizon-client/src/game/control.rs | 11 +- crates/horizon-client/src/game/lan_actions.rs | 1 + .../horizon-client/src/game/lan_crafting.rs | 2 + .../horizon-client/src/game/lan_stations.rs | 38 +++ crates/horizon-client/src/game/lan_trading.rs | 1 + crates/horizon-client/src/game/recipe_book.rs | 1 + crates/horizon-client/src/game/remote.rs | 2 + .../src/game/remote_stations.rs | 40 ++- crates/horizon-client/src/game/stations.rs | 172 ++++++------ crates/horizon-client/src/menu.rs | 248 +++++++++++++++++- crates/horizon-client/src/stations.rs | 6 +- crates/horizon-protocol/src/packets/play.rs | 11 + .../horizonlab/parity/VanillaMenuOracle.java | 11 + tools/lan_e2e.py | 72 ++++- tools/test_menu_click_parity.py | 71 ++++- 21 files changed, 632 insertions(+), 106 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 8093079cc..9c4d0f8df 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -84,6 +84,7 @@ fn main() -> horizon_client::Result<()> { let banners = horizon_client::banner::Banners::default(); let station_recipes = horizon_client::stations::StationRecipes::default(); let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, @@ -91,6 +92,7 @@ fn main() -> horizon_client::Result<()> { banners: &banners, station_recipes: &station_recipes, enchantments: &enchantments, + names: &names, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index ee5629498..984f024c1 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -46,6 +46,7 @@ fn main() -> horizon_client::Result<()> { let banners = horizon_client::banner::Banners::load(root); let station_recipes = horizon_client::stations::StationRecipes::load(root, &items); let enchantments = horizon_client::enchant::Enchantments::load(root); + let names = horizon_client::creative::Names::load(root); let env = Env { items: &items, recipes: &recipes, @@ -53,6 +54,7 @@ fn main() -> horizon_client::Result<()> { banners: &banners, station_recipes: &station_recipes, enchantments: &enchantments, + names: &names, trade: None, }; let mut out = String::new(); @@ -74,6 +76,7 @@ fn main() -> horizon_client::Result<()> { .ok_or("menu kind")?; let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); + menu.levels = case["levels"].as_i64().unwrap_or(0) as i32; for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); } @@ -104,6 +107,12 @@ fn main() -> horizon_client::Result<()> { out += &format!("{}\n", state(&menu)); continue; } + // ServerboundRenameItemPacket: AnvilMenu.setItemName. + "RENAME" => { + menu.rename(&env, op[3].as_str().unwrap_or_default()); + out += &format!("{}\n", state(&menu)); + continue; + } // ServerboundContainerSlotStateChangedPacket. "SLOT_STATE" => { if (0..9).contains(&slot) { diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index 7d05a4cd3..5d22e28f9 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -40,6 +40,7 @@ fn main() -> horizon_client::Result<()> { let banners = horizon_client::banner::Banners::default(); let station_recipes = horizon_client::stations::StationRecipes::default(); let enchantments = horizon_client::enchant::Enchantments::default(); + let names = horizon_client::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, @@ -47,6 +48,7 @@ fn main() -> horizon_client::Result<()> { banners: &banners, station_recipes: &station_recipes, enchantments: &enchantments, + names: &names, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs index a2dd8f461..0bbfb0775 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -239,6 +239,7 @@ fn main() -> horizon_client::Result<()> { let vanilla = fs::read_to_string(args.get(3).ok_or(usage)?)?; let items = Items::catalog(root)?; let enchantments = Enchantments::load(root); + let names = horizon_client::creative::Names::default(); let trades = Trades::load(root); let recipes = horizon_client::crafting::Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); @@ -381,6 +382,7 @@ fn main() -> horizon_client::Result<()> { banners: &banners, station_recipes: &station_recipes, enchantments: &enchantments, + names: &names, trade: Some(&env_trade), }; trade(&mut out, name, &kv, &mut world, &env, origin)?; diff --git a/crates/horizon-client/src/creative.rs b/crates/horizon-client/src/creative.rs index 80445d541..55e4eb28e 100644 --- a/crates/horizon-client/src/creative.rs +++ b/crates/horizon-client/src/creative.rs @@ -44,6 +44,7 @@ pub struct Creative { search_index: Vec, } /// Display names from the pinned en_us language file. +#[derive(Default)] pub struct Names { map: HashMap, } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index f3593b29c..2056e52ed 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2550,6 +2550,7 @@ impl Game<'_> { 1031 => Some(("minecraft:block.anvil.land", 0.3)), 1505 => Some(("minecraft:item.bone_meal.use", 1.0)), 1042 => Some(("minecraft:block.grindstone.use", 1.0)), + 1044 => Some(("minecraft:block.smithing_table.use", 1.0)), _ => None, }; if let Some((name, volume)) = sound { @@ -2559,7 +2560,7 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } - 1042 => self.world.random.next_float() * 0.1 + 0.9, + 1029 | 1030 | 1042 | 1044 => self.world.random.next_float() * 0.1 + 0.9, _ => 1.0, }; self.audio.play(name, c, volume, pitch); @@ -5433,10 +5434,10 @@ impl Game<'_> { .station .as_ref() .is_some_and(|s| s.kind == stations::Kind::Stonecutter); - let grindstone_open = self - .station - .as_ref() - .is_some_and(|s| s.kind == stations::Kind::Grindstone); + let station_kind = self.station.as_ref().map(|s| s.kind); + let grindstone_open = station_kind == Some(stations::Kind::Grindstone); + let anvil_open = station_kind == Some(stations::Kind::Anvil); + let smithing_open = station_kind == Some(stations::Kind::Smithing); let (kind, game_of): (Kind, Vec>) = if self.creative_tab_open() { // ItemPickerMenu: the display slots (clicked by the screen), then the hotbar. let mut v = vec![None; 45]; @@ -5477,6 +5478,21 @@ impl Game<'_> { ]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Grindstone, v) + } else if anvil_open || smithing_open { + // ItemCombinerMenu: the inputs, the result, then the inventory. + let inputs = if anvil_open { 2 } else { 3 }; + let mut v: Vec> = + (0..inputs).map(|i| Some(stations::INPUT + i)).collect(); + v.push(Some(stations::RESULT)); + v.extend((9..36).chain(0..9).map(Some)); + ( + if anvil_open { + Kind::Anvil + } else { + Kind::Smithing + }, + v, + ) } else { let (kind, map) = if self.container.is_some() { let size = self.container_size(); @@ -5596,10 +5612,16 @@ impl Game<'_> { banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: Some(&trade_env), }; menu.creative = creative; menu.selected = self.selected; + menu.levels = self.experience.level; + if anvil_open { + // The rename box as AnvilScreen.onNameChanged gives it to the menu. + menu.anvil.name = self.station.as_ref().map(|s| self.anvil_item_name(s)); + } for (i, stack) in before.iter().enumerate() { menu.set_slot(&env, i, stack.clone()); } @@ -5699,6 +5721,9 @@ impl Game<'_> { { self.grindstone_taken(pos, amount); } + if kind == Kind::Anvil || kind == Kind::Smithing { + self.combiner_session_end(&menu, predicting); + } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self .container diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index d79f69d3c..0032d44b7 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -523,13 +523,22 @@ impl Game<'_> { Screen::Inventory if self.recipe_search_focused() => { self.recipe_text(Some(text), false) } + // The anvil's rename box. + Screen::Inventory + if self + .station + .as_ref() + .is_some_and(|s| s.kind == super::stations::Kind::Anvil) => + { + self.station_text(Some(text), false) + } Screen::Creative if self.creative_screen.tab().search => { // As typed: replaces a selected query, keeps the length limit. self.creative_search_edit(Some(text), false) } _ => { return Err( - "type needs the chat screen (key t tap), the language search, the creative search or World Options".into(), + "type needs the chat screen (key t tap), the language search, the creative search, the anvil or World Options".into(), ); } } diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 95f2dc49b..655a11cbd 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -920,6 +920,7 @@ impl Game<'_> { S::ContainerButtonClick(p) => { self.lan_station_button(host, conn, p.container, p.button); } + S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { let g = &mut host.hub.guests[gi]; diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 54bf872ae..9c0cce1fe 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -55,6 +55,7 @@ fn load_player(menu: &mut Menu, g: &Guest) { menu.set_player_item(OFFHAND, g.offhand.clone()); menu.selected = g.selected; menu.creative = g.creative(); + menu.levels = g.xp_level; menu.carried = g.carried.clone(); } @@ -91,6 +92,7 @@ impl Game<'_> { banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: None, } } diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 5cae6d6e9..8d31ba05e 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -36,6 +36,8 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:loom", Kind::Loom, 0..3), StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1), StationKind::Grindstone => ("minecraft:grindstone", Kind::Grindstone, 0..2), + StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2), + StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), _ => return None, }) } @@ -98,12 +100,48 @@ impl Game<'_> { if let Some(amount) = gs.menu.ground.take() { self.grindstone_taken(gs.pos, amount); } + self.lan_station_combined(host, conn, &mut gs); } host.play.entry(conn).or_default().station = Some(gs); self.lan_send_station(host, conn); true } + /// The rest of a taken anvil or smithing result's `onTake`: the guest + /// pays the levels, the anvil wears (level event 1030 or 1029), the + /// smithing table sounds (1044). + fn lan_station_combined(&mut self, host: &mut LanHost, conn: u32, gs: &mut GuestStation) { + let change = std::mem::take(&mut gs.menu.level_change); + if change != 0 { + self.as_guest(host, conn, |g| g.give_levels(change)); + } + if !std::mem::take(&mut gs.menu.combined) { + return; + } + if gs.kind == StationKind::Smithing { + self.level_event_at(1044, gs.pos, 0); + } else { + let creative = gs.menu.creative; + // A broken anvil closes the menu on the next stillValid check. + self.anvil_used(gs.pos, creative); + } + } + + /// `ServerGamePacketListenerImpl.handleRenameItem`: the guest's anvil + /// takes the name (`AnvilMenu.setItemName`). + pub(super) fn lan_station_rename(&mut self, host: &mut LanHost, conn: u32, name: &str) { + let anvil = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .is_some_and(|s| s.kind == StationKind::Anvil); + if anvil { + self.lan_station_op(host, conn, None, |menu, env| { + menu.rename(env, name); + }); + } + } + /// The sounds the menu played, at the station (heard by everyone around, /// as `level.playSound(null, pos, ...)`), once per tick. fn lan_station_sounds(&mut self, gs: &mut GuestStation) { diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index a3a33c019..587e67fa8 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -257,6 +257,7 @@ impl Game<'_> { banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: Some(&trade_env), }; let mut menu = Menu::new(Kind::Merchant); diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 4000fa64c..ec19c0caf 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -281,6 +281,7 @@ impl Game<'_> { banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, enchantments: &self.res.stations().enchantments, + names: &self.pack.names, trade: None, }; for i in 0..36 { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5c6ebb86f..ebd1e2e58 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1266,6 +1266,8 @@ impl Game<'_> { "minecraft:loom" => Kind::Loom, "minecraft:stonecutter" => Kind::Stonecutter, "minecraft:grindstone" => Kind::Grindstone, + "minecraft:anvil" => Kind::Anvil, + "minecraft:smithing" => Kind::Smithing, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index 643df30db..fd5dc42aa 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -48,11 +48,12 @@ impl Game<'_> { /// `Slot.set` runs its container's `setChanged`, so the loom lists the /// patterns its inputs allow and the stonecutter the recipes of its input. pub(super) fn remote_station_slot_changed(&mut self, internal: usize) { - if !self - .station - .as_ref() - .is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter | Kind::Grindstone)) - { + if !self.station.as_ref().is_some_and(|s| { + matches!( + s.kind, + Kind::Loom | Kind::Stonecutter | Kind::Grindstone | Kind::Anvil | Kind::Smithing + ) + }) { return; } self.menu_session(|menu, env, to_menu| { @@ -61,6 +62,9 @@ impl Game<'_> { menu.set_slot(env, i, stack); Some(true) }); + // AnvilScreen.slotChanged: the box shows the new input's name, which + // its responder sends. + self.remote_anvil_rename(); } /// `AbstractContainerMenu.setData` from the server. @@ -73,10 +77,36 @@ impl Game<'_> { (Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(), // StonecutterMenu.selectedRecipeIndex. (Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(), + // AnvilMenu.cost. + (Kind::Anvil, 0) => s.anvil.cost = i32::from(value), _ => {} } } + /// `AnvilScreen.onNameChanged` on a server: the rename box's text (blank + /// when it is the input's own name) goes to the server when the menu's + /// `setItemName` takes it. + pub(super) fn remote_anvil_rename(&mut self) { + if self.remote.is_none() { + return; + } + let Some(s) = self + .station + .as_ref() + .filter(|s| s.kind == Kind::Anvil && s.inputs[0].is_some()) + else { + return; + }; + let name = self.anvil_item_name(s); + if s.anvil_sent.as_deref() == Some(&name) { + return; + } + if let Some(s) = self.station.as_mut() { + s.anvil_sent = Some(name.clone()); + } + self.send(S::RenameItem(play::RenameItem { name })); + } + /// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already /// ran `clickMenuButton` on its own menu. pub(super) fn remote_station_button(&self, button: i32) { diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 04104c9b3..ed114419e 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -133,7 +133,7 @@ pub(super) struct Station { pub(super) result: Option, offers: EnchantOffers, bookcases: i32, - anvil: AnvilResult, + pub(super) anvil: AnvilResult, /// Anvil rename box text. pub(super) name: String, /// Stonecutter: the menu's recipe list (horizon_client::menu), its @@ -143,6 +143,8 @@ pub(super) struct Station { start: usize, /// Anvil: the input the rename box was last filled from. anvil_last: Option, + /// Anvil on a server: the name last sent (the client menu's `itemName`). + pub(super) anvil_sent: Option, /// When the screen opened: the rename box has the focus from then. opened: std::time::Instant, pub(super) last_sound: u64, @@ -168,6 +170,7 @@ impl Station { selected: None, start: 0, anvil_last: None, + anvil_sent: None, opened: std::time::Instant::now(), last_sound: 0, merchant: None, @@ -412,7 +415,7 @@ impl Game<'_> { .count() as i32 } /// The anvil name the menu works with (`AnvilScreen.onNameChanged`). - fn anvil_item_name(&self, s: &Station) -> String { + pub(super) fn anvil_item_name(&self, s: &Station) -> String { match &s.inputs[0] { Some(input) if input.custom_name().is_none() && s.name == self.pack.names.item(&input.item) => @@ -494,7 +497,6 @@ impl Game<'_> { } /// `Slot.mayPlace` and `getMaxStackSize` for station slots. fn slot_rules(&self, slot: usize, stack: &ItemStack) -> (bool, u32) { - let data = self.data(); if slot >= super::mount_menu::SADDLE { return self.mount_slot_rules(slot, stack); } @@ -531,7 +533,6 @@ impl Game<'_> { 64, ), Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), _ => (true, 64), } } @@ -703,20 +704,13 @@ impl Game<'_> { self.move_to(&mut stack, &halves, false); } } - Kind::Anvil | Kind::Smithing => { - let inputs: Vec = (0..kind.inputs()).map(|i| INPUT + i).collect(); - // ItemCombinerMenu.canMoveIntoInputSlots: always for the - // anvil; the smithing table needs an empty slot whose - // ingredient test takes the stack. - let into_inputs = kind == Kind::Anvil - || (0..3).any(|i| { - empty(self, i) && self.data().recipes.smithing_accepts(i, &stack) - }); - let targets = if into_inputs { &inputs } else { &halves }; - self.move_to(&mut stack, targets, false); - } // Their clicks run on the menu engine. - Kind::Merchant | Kind::Loom | Kind::Stonecutter | Kind::Grindstone => {} + Kind::Merchant + | Kind::Loom + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing => {} } } let moved = stack.count != start; @@ -725,6 +719,70 @@ impl Game<'_> { } moved } + /// After an anvil or smithing click on the menu engine: the anvil's cost + /// and state back into the station and the rename box following the + /// input (`AnvilScreen.slotChanged`), then the rest of a taken result's + /// `onTake` (the levels, the anvil's wear, the use sound) unless a + /// server does it. + pub(super) fn combiner_session_end( + &mut self, + menu: &horizon_client::menu::Menu, + predicting: bool, + ) { + let Some(s) = self.station.as_mut() else { + return; + }; + let (pos, kind) = (s.pos, s.kind); + if kind == Kind::Anvil { + s.anvil.cost = menu.data[0]; + s.anvil.repair_item_count_cost = menu.anvil.repair_count; + s.anvil.only_renaming = menu.anvil.only_renaming; + s.anvil.result = s.result.clone(); + } + self.station_after_input(); + if !menu.combined || predicting { + return; + } + if kind == Kind::Smithing { + self.level_event_at(1044, pos, 0); + return; + } + self.give_levels(menu.level_change); + if self.anvil_used(pos, self.creative) { + self.close_station(); + self.screen = Screen::Playing; + self.capture(true); + } + } + /// `AnvilMenu.onTake`'s level part: out of creative a 12% chance + /// (`AnvilBlock.damage`) to wear the anvil a stage, or break a damaged one + /// (level event 1029); otherwise level event 1030. True when it broke. + pub(super) fn anvil_used(&mut self, pos: [i32; 3], creative: bool) -> bool { + let state = self.world.block(pos[0], pos[1], pos[2]); + let name = self.res.facts().get(state).name.clone(); + let anvil = matches!( + &*name, + "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" + ); + if !creative && anvil && self.world.random.next_float() < 0.12 { + match &*name { + "minecraft:anvil" => { + let _ = self.set_state_named(pos, "minecraft:chipped_anvil", &["facing"]); + } + "minecraft:chipped_anvil" => { + let _ = self.set_state_named(pos, "minecraft:damaged_anvil", &["facing"]); + } + _ => { + let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + self.level_event_at(1029, pos, 0); + return true; + } + } + } + self.level_event_at(1030, pos, 0); + false + } /// The grindstone result's `onTake` with a level (`amount`: the menu's /// `getExperienceAmount` sum): the orbs at the block's centre /// (`ExperienceOrb.award`), then level event 1042, the grindstone's sound @@ -780,68 +838,12 @@ impl Game<'_> { }; let pos = s.pos; match s.kind { - Kind::Anvil => { - let cost = s.anvil.cost; - let repair = s.anvil.repair_item_count_cost; - if repair > 0 { - if let Some(a) = s.inputs[1].as_mut() - && a.count > repair - { - a.count -= repair; - } else { - s.inputs[1] = None; - } - } else if !s.anvil.only_renaming { - s.inputs[1] = None; - } - s.inputs[0] = None; - s.name.clear(); - if !self.creative { - self.give_levels(-cost); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - if !self.creative && self.world.random.next_float() < 0.12 { - // AnvilBlock.damage - let state = self.world.block(pos[0], pos[1], pos[2]); - let name = self.res.facts().get(state).name.clone(); - let next = match &*name { - "minecraft:anvil" => Some("minecraft:chipped_anvil"), - "minecraft:chipped_anvil" => Some("minecraft:damaged_anvil"), - _ => None, - }; - match next { - Some(next) => { - let _ = self.set_state_named(pos, next, &["facing"]); - self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); - } - None => { - let _ = self.world.set(pos[0], pos[1], pos[2], self.world.air); - self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); - self.play_at("minecraft:block.anvil.destroy", pos, 1.0, pitch); - self.station = Some(s); - self.close_station(); - self.screen = Screen::Playing; - self.capture(true); - return; - } - } - } else { - self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); - } - } - Kind::Smithing => { - for slot in s.inputs.iter_mut() { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch); - } - Kind::Merchant | Kind::Stonecutter | Kind::Grindstone => {} + // Their clicks run on the menu engine. + Kind::Merchant + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing => {} Kind::Beacon => {} Kind::Cartography => { for slot in &mut s.inputs { @@ -1050,10 +1052,16 @@ impl Game<'_> { if self.station.as_ref().is_none_or(|s| { matches!( s.kind, - Kind::Loom | Kind::Merchant | Kind::Stonecutter | Kind::Grindstone + Kind::Loom + | Kind::Merchant + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing ) }) { - // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu and the brewing stand's + // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu, AnvilMenu, + // SmithingMenu and the brewing stand's // BrewingStandMenu clicks run on the verified menu engine. let input = if shift { horizon_client::menu::Input::QuickMove @@ -1171,6 +1179,7 @@ impl Game<'_> { } } self.station_changed(); + self.remote_anvil_rename(); } /// Ctrl+A/C/V/X in the anvil's rename box (an `EditBox` of 50) or the /// recipe book's search box. @@ -1191,6 +1200,7 @@ impl Game<'_> { ANVIL_NAME_CHARS, ) { self.station_changed(); + self.remote_anvil_rename(); } } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 0e85d92dd..510a7c7aa 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -26,8 +26,11 @@ pub struct Env<'a> { pub banners: &'a Banners, /// The stonecutter's recipes. pub station_recipes: &'a crate::stations::StationRecipes, - /// The grindstone's curse and cost rules. + /// The grindstone's and the anvil's enchantment rules. pub enchantments: &'a crate::enchant::Enchantments, + /// Item display names: the anvil compares the rename box with the + /// input's hover name. + pub names: &'a crate::creative::Names, /// What a merchant menu needs for offers made while it is open (level-ups). pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, } @@ -79,6 +82,10 @@ pub enum Kind { Stonecutter, /// `GrindstoneMenu`: two inputs, the result, then the inventory. Grindstone, + /// `AnvilMenu`: two inputs, the result, then the inventory. + Anvil, + /// `SmithingMenu`: template, base, addition, the result, then the inventory. + Smithing, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -106,6 +113,8 @@ impl Kind { "loom" => Self::Loom, "stonecutter" => Self::Stonecutter, "grindstone" => Self::Grindstone, + "anvil" => Self::Anvil, + "smithing" => Self::Smithing, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -149,6 +158,10 @@ enum Role { GrindInput, /// The grindstone's result slot (`onTake` clears both inputs). GrindResult, + /// A smithing table input: its recipe property set (template, base, addition). + SmithInput(usize), + /// `ItemCombinerMenu`'s result slot (the anvil's and the smithing table's). + CombineResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -204,6 +217,27 @@ pub struct Menu { /// set when the result was taken: the caller (with a level) awards the /// orbs and plays level event 1042. pub ground: Option, + /// `Player.experienceLevel`, which the anvil's result needs. + pub levels: i32, + /// The levels the menu gave the player (`giveExperienceLevels`), for the caller. + pub level_change: i32, + /// `AnvilMenu`'s state besides its slots and its cost data slot. + pub anvil: Anvil, + /// The anvil's or the smithing table's result was taken: the caller (with + /// a level) runs the rest of its `onTake` (the anvil's wear and level + /// event 1030 or 1029, the smithing table's 1044). + pub combined: bool, +} + +/// `AnvilMenu`'s state besides its slots and `cost`. +#[derive(Clone, Default, Debug, PartialEq)] +pub struct Anvil { + /// `itemName`: the rename box's text (`ServerboundRenameItemPacket`). + pub name: Option, + /// `repairItemCountCost`. + pub repair_count: u32, + /// `onlyRenaming`. + pub only_renaming: bool, } /// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`. @@ -373,6 +407,34 @@ impl Menu { }); player(&mut slots); } + Kind::Anvil => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CombineResult, + }); + player(&mut slots); + // cost: DataSlot.standalone() starts at 0. + data = 1; + } + Kind::Smithing => { + containers[MAIN] = vec![None; 3]; + slots.extend((0..3).map(|index| Slot { + container: MAIN, + index, + role: Role::SmithInput(index), + })); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CombineResult, + }); + player(&mut slots); + // hasRecipeError. + data = 1; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -460,6 +522,10 @@ impl Menu { merchant: None, stone: Stonecutter::default(), ground: None, + levels: 0, + level_change: 0, + anvil: Anvil::default(), + combined: false, } } @@ -621,6 +687,11 @@ impl Menu { self.merchant_update(env); return; } + // SmithingMenu.slotsChanged runs for its result container too. + if self.kind == Kind::Smithing && self.slots[s].container == RESULT { + self.smith_error(); + return; + } if self.slots[s].container != MAIN { return; } @@ -637,10 +708,77 @@ impl Menu { ); } Kind::CrafterBlock => self.crafter_result(env), + Kind::Anvil => self.anvil_result(env), + Kind::Smithing => { + self.smith_result(env); + self.smith_error(); + } _ => {} } } + /// `AnvilMenu.createResult`. + fn anvil_result(&mut self, env: &Env) { + let hover = self.containers[MAIN][0] + .as_ref() + .map(|i| crate::stations::hover_name(&|id| env.names.item(id), i)) + .unwrap_or_default(); + let out = crate::stations::anvil_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + self.anvil.name.as_deref(), + &hover, + self.creative, + ); + // onlyRenaming is reset, repairItemCountCost only where an input is. + self.anvil.only_renaming = out.only_renaming; + if self.containers[MAIN][0].is_some() { + self.anvil.repair_count = out.repair_item_count_cost; + } + self.data[0] = out.cost; + self.containers[RESULT][0] = out.result; + } + + /// `AnvilMenu.setItemName` (`ServerboundRenameItemPacket`): false when + /// the name is refused or unchanged. + pub fn rename(&mut self, env: &Env, name: &str) -> bool { + // StringUtil.filterText, then validateName's length limit. + let name: String = name + .chars() + .filter(|&c| c != '\u{a7}' && c >= ' ' && c != '\u{7f}') + .collect(); + if self.kind != Kind::Anvil + || name.encode_utf16().count() > 50 + || self.anvil.name.as_deref() == Some(&name) + { + return false; + } + if let Some(result) = self.containers[RESULT][0].as_mut() { + result.data_mut().custom_name = (!name.trim().is_empty()).then(|| name.clone()); + result.tidy(); + } + self.anvil.name = Some(name); + self.anvil_result(env); + true + } + + /// `SmithingMenu.createResult`. + fn smith_result(&mut self, env: &Env) { + let [a, b, c] = [0, 1, 2].map(|i| self.containers[MAIN][i].as_ref()); + self.containers[RESULT][0] = env + .station_recipes + .smithing_result(env.enchantments, a, b, c); + } + + /// `SmithingMenu.slotsChanged`'s `hasRecipeError`: every input filled and no result. + fn smith_error(&mut self) { + let error = self.containers[MAIN].iter().all(Option::is_some) + && self.containers[RESULT][0].is_none(); + self.data[0] = i32::from(error); + } + pub fn slot_count(&self) -> usize { self.slots.len() } @@ -748,9 +886,12 @@ impl Menu { Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), - Role::LoomResult | Role::MerchantResult | Role::StoneResult | Role::GrindResult => { - false - } + Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), + Role::LoomResult + | Role::MerchantResult + | Role::StoneResult + | Role::GrindResult + | Role::CombineResult => false, } } @@ -762,6 +903,10 @@ impl Menu { fn may_pickup(&self, env: &Env, s: usize) -> bool { match self.slots[s].role { Role::Inert => false, + // AnvilMenu.mayPickup: the levels to pay, and a price. + Role::CombineResult if self.kind == Kind::Anvil => { + (self.creative || self.levels >= self.data[0]) && self.data[0] > 0 + } Role::MerchantResult => self .merchant .as_ref() @@ -882,7 +1027,12 @@ impl Menu { if out.is_some() && matches!( self.kind, - Kind::Loom | Kind::Merchant | Kind::Stonecutter | Kind::Grindstone + Kind::Loom + | Kind::Merchant + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing ) { self.slot_changed(env, s); @@ -890,6 +1040,36 @@ impl Menu { out } + /// `AnvilMenu.onTake`: the levels, the material used up, then the input. + fn anvil_take(&mut self, env: &Env) { + let cost = self.data[0]; + if !self.creative { + // Player.giveExperienceLevels(-cost). + self.level_change -= cost; + self.drops.push(format!( + "levels{}{}", + if cost <= 0 { "+" } else { "" }, + -cost + )); + } + let repair = self.anvil.repair_count; + if repair > 0 { + let addition = self.containers[MAIN][1] + .clone() + .filter(|a| a.count > repair) + .map(|mut a| { + a.count -= repair; + a + }); + self.put(env, 1, addition); + } else if !self.anvil.only_renaming { + self.put(env, 1, None); + } + self.data[0] = 0; + self.put(env, 0, None); + self.combined = true; + } + /// `CraftingMenu.slotChangedCraftingGrid`. fn recompute(&mut self, env: &Env) { if self.grid_size == 0 { @@ -933,6 +1113,21 @@ impl Menu { self.put(env, 1, None); return; } + if self.slots[s].role == Role::CombineResult && self.kind == Kind::Anvil { + self.anvil_take(env); + return; + } + if self.slots[s].role == Role::CombineResult { + // SmithingMenu.onTake: awardUsedRecipes, then one of each input. + for i in 0..3 { + if let Some(mut stack) = self.containers[MAIN][i].clone() { + stack.count -= 1; + self.put(env, i, Some(stack)); + } + } + self.combined = true; + return; + } if self.slots[s].role == Role::LoomResult { // LoomMenu's result onTake: one banner and one dye are used up. self.remove(env, 0, 1); @@ -1430,6 +1625,39 @@ impl Menu { return None; } } + Kind::Anvil | Kind::Smithing => { + // ItemCombinerMenu.quickMoveStack. + after_take = true; + let result = if self.kind == Kind::Anvil { 2 } else { 3 }; + let (start, use_row) = (result + 1, result + 28); + let end = result + 37; + let into_inputs = self.kind == Kind::Anvil + || (0..3).any(|i| { + self.containers[MAIN][i].is_none() + && env.station_recipes.smithing_accepts(i, &stack) + }); + if index == result { + if !self.move_to(env, &mut stack, start, end, true) { + return None; + } + } else if index < result { + if !self.move_to(env, &mut stack, start, end, false) { + return None; + } + } else if into_inputs && (start..end).contains(&index) { + if !self.move_to(env, &mut stack, 0, result, false) { + return None; + } + } else if (start..use_row).contains(&index) { + if !self.move_to(env, &mut stack, use_row, end, false) { + return None; + } + } else if (use_row..end).contains(&index) + && !self.move_to(env, &mut stack, start, use_row, false) + { + return None; + } + } Kind::Merchant => { after_take = true; if index == 2 { @@ -1900,12 +2128,14 @@ impl Menu { } /// The PICKUP_ALL branch (double click). - /// `canTakeItemForPickAll`: never the result slots (the loom's is a - /// plain slot), MerchantMenu's or an item tab's display slots. + /// `canTakeItemForPickAll`: never the result slots of the menus that + /// override it (crafting, smithing, stonecutter, cartography), MerchantMenu's + /// or an item tab's display slots. fn can_take_for_pick_all(&self, t: usize) -> bool { self.kind != Kind::Merchant && self.slots[t].role != Role::CreativeDisplay - && (self.slots[t].container != RESULT || self.kind == Kind::Loom) + && (self.slots[t].container != RESULT + || matches!(self.kind, Kind::Loom | Kind::Grindstone | Kind::Anvil)) } /// `AbstractContainerScreen.mouseReleased` on a Shift double click: @@ -2227,6 +2457,7 @@ pub(crate) mod tests { let banners = Banners::load(&root); let station_recipes = crate::stations::StationRecipes::load(&root, &items); let enchantments = crate::enchant::Enchantments::default(); + let names = crate::creative::Names::default(); let env = Env { items: &items, recipes: &recipes, @@ -2234,6 +2465,7 @@ pub(crate) mod tests { banners: &banners, station_recipes: &station_recipes, enchantments: &enchantments, + names: &names, trade: None, }; let mut menu = Menu::new(kind); diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index eb0a20a02..715c2663e 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -198,8 +198,10 @@ pub fn anvil_result( let mut repair_item_count_cost = 0; let mut naming_cost = 0; if let Some(addition) = addition { - // addition.has(STORED_ENCHANTMENTS): only enchanted books carry that component. - let using_book = &*addition.item == "minecraft:enchanted_book"; + // addition.has(STORED_ENCHANTMENTS): an enchanted book (its default + // component), or any item given stored enchantments. + let using_book = &*addition.item == "minecraft:enchanted_book" + || !addition.stored_enchantments().is_empty(); if is_damageable(items, &result) && is_valid_repair_item(e, items, input, addition) { let max = max_damage(items, &result); let mut repair = (result.damage as i32).min(max / 4); diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 3c3d24f44..11166408a 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1715,6 +1715,10 @@ packet!( /// (the loom's patterns, the stonecutter's recipes, the enchanting table's offers). ContainerButtonClick { container: i32 => VarInt, button: i32 => VarInt } ); +packet!( + /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. + RenameItem { name: String => Str } +); packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); packet!( /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. @@ -1797,6 +1801,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { PlayerInput(PlayerInput) = PLAYER_INPUT, PlayerLoaded(Empty) = PLAYER_LOADED, Pong(Ping) = PONG, + RenameItem(RenameItem) = RENAME_ITEM, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, SelectTrade(SelectTrade) = SELECT_TRADE, @@ -2373,6 +2378,12 @@ mod tests { }); assert_eq!(&button.encode()[1..], &[3, 0xC8, 1]); round_trip(button, Serverbound::encode, Serverbound::decode); + // The name, a UTF-8 string with its VarInt length. + let rename = Serverbound::RenameItem(RenameItem { + name: "Blade".into(), + }); + assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']); + round_trip(rename, Serverbound::encode, Serverbound::decode); } #[test] 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 c05f92322..d55417e7c 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -180,6 +180,8 @@ public final class VanillaMenuOracle { case "loom" -> new LoomMenu(0, inv); case "stonecutter" -> new StonecutterMenu(0, inv); case "grindstone" -> new GrindstoneMenu(0, inv); + case "anvil" -> new AnvilMenu(0, inv); + case "smithing" -> new SmithingMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } @@ -227,6 +229,9 @@ public final class VanillaMenuOracle { player.advancements = make(net.minecraft.server.PlayerAdvancements.class); set(player.advancements, net.minecraft.server.PlayerAdvancements.class, "activeTriggers", new java.util.IdentityHashMap<>()); set(player, ServerPlayer.class, "connection", make(Connection.class)); + // AnvilMenu.onTake filters a new name; the anvil's result needs the levels. + set(player, ServerPlayer.class, "textFilter", net.minecraft.server.network.TextFilter.DUMMY); + player.experienceLevel = f.has("levels") ? f.get("levels").getAsInt() : 0; var inv = new Inventory(player, new EntityEquipment()); player.inv = inv; AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv); @@ -253,6 +258,12 @@ public final class VanillaMenuOracle { out.println(clickState(menu, inv)); continue; } + if (kind.equals("RENAME")) { + // ServerGamePacketListenerImpl.handleRenameItem: AnvilMenu.setItemName + if (menu instanceof AnvilMenu anvil) anvil.setItemName(op.get(3).getAsString()); + out.println(clickState(menu, inv)); + continue; + } if (kind.equals("SLOT_STATE")) { // handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index fd899e6c6..10b654adb 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -45,6 +45,11 @@ address. The script then checks, from both sides, what a guest's game used to ge - grindstone: a grindstone opens on the guest's screen; the enchanted sword the guest shift-clicks in shows the server's result, and the guest takes it with only its curse left and the experience orbs the server awards (#868); +- anvil: an anvil opens on the guest's screen; the guest repairs a sword with iron ingots and + renames it (ServerboundRenameItemPacket), takes it for the server's level cost, and the + server has the repaired, renamed sword (#868); +- smithing: a smithing table opens on the guest's screen; the guest upgrades a diamond sword to + netherite and the server has it (#868); - feedback: the guest's command feedback names the guest and shows the numbers; - chat: a line the host sends reaches the guest's event log (`wait-for chat`), and on the server thread the host window's too; @@ -139,7 +144,7 @@ ROOT = Path(__file__).resolve().parents[1] GUEST_NAME = 'Guest' # The host plays single player on its server thread (--server-thread). SERVER_THREAD = False -CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] +CHECKS = ['tab', 'self', 'armour', 'nametags', 'walls', 'chest', 'crafting', 'sign', 'damage', 'mobs', 'hazards', 'pvp', 'arrows', 'kills', 'hurt', 'respawn', 'containers', 'feedback', 'titles', 'chat', 'commands', 'recipes', 'machines', 'brewing', 'loom', 'stonecutter', 'grindstone', 'anvil', 'smithing', 'trials', 'clicks', 'sleep', 'predict', 'push', 'eat', 'eating', 'xp', 'objects', 'projectiles', 'worn', 'blast', 'barter', 'deflect', 'fireball', 'light', 'time', 'swings', 'cracks', 'plates', 'effects', 'portals', 'distance', 'growth'] class Game: @@ -1041,6 +1046,69 @@ def check_grindstone(host, guest, out): return seen +def check_anvil(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='xp set @s 5 levels') + guest('command', command='give @s minecraft:iron_sword[minecraft:damage=200]') + guest('command', command='give @s minecraft:iron_ingot 3') + at = open_station(guest, 'anvil', out, 'anvil') + # ItemCombinerMenu.quickMoveStack: into the first input that takes it. + for item in ('iron_sword', 'iron_ingot'): + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + # The box shows "Iron Sword": erase it and type the new name. + for _ in range(len('Iron Sword')): + guest.raw('type-back') + guest.raw('type', 'Blade') + guest.wait(10) + menu = guest.raw('menu') + offered = (menu['info']['anvil_cost'], station_slots(guest).get(650)) + guest.shot(out, 'anvil-rename') + guest.raw('click-slot', 650, 'shift') + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components', + 'minecraft:damage') + levels = server_reply(guest, 'xp query @s levels', 'experience levels') + seen = {'offered': offered, 'left': left, 'name': 'Blade' in sword, + 'damage': re.search(r'minecraft:damage"?: 14\b', sword) is not None, + 'levels': int(re.search(r'has (\d+) experience', levels).group(1)), + 'ingots': server_count(guest, 'iron_ingot')} + # Three ingots repair 62 each (a quarter of 250), plus the name: four levels. + want = {'offered': (4, ('minecraft:iron_sword', 1)), 'left': {}, 'name': True, 'damage': True, + 'levels': 1, 'ingots': 0} + assert seen == want, f'the anvil on the guest: {seen} ({sword!r})' + return seen + + +def check_smithing(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + for item in ('netherite_upgrade_smithing_template', 'diamond_sword', 'netherite_ingot'): + guest('command', command=f'give @s minecraft:{item}') + at = open_station(guest, 'smithing_table', out, 'smithing') + # SmithingMenu.canMoveIntoInputSlots: each to the slot whose recipe test takes it. + for item in ('netherite_upgrade_smithing_template', 'diamond_sword', 'netherite_ingot'): + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + guest.wait(5) + loaded = station_slots(guest) + guest.shot(out, 'smithing-result') + guest.raw('click-slot', 650, 'shift') + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + seen = {'loaded': loaded, 'left': left, + 'server': {item: server_count(guest, item) for item in ('netherite_sword', 'diamond_sword', 'netherite_ingot')}} + want = {'loaded': {600: ('minecraft:netherite_upgrade_smithing_template', 1), 601: ('minecraft:diamond_sword', 1), + 602: ('minecraft:netherite_ingot', 1), 650: ('minecraft:netherite_sword', 1)}, + 'left': {}, 'server': {'netherite_sword': 1, 'diamond_sword': 0, 'netherite_ingot': 0}} + assert seen == want, f'the smithing table on the guest: {seen}' + return seen + + def slot_point(game, slot): """The GUI point in the middle of slot `slot` of the open screen (`ui`'s slot-N).""" for w in game.raw('ui')['widgets']: @@ -2235,6 +2303,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'loom': check_loom, 'stonecutter': check_stonecutter, 'grindstone': check_grindstone, + 'anvil': check_anvil, + 'smithing': check_smithing, 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 357ad94da..06ba00dd9 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -12,7 +12,8 @@ crafting table, chests, hopper, dispenser, shulker box, the furnaces, the brewing stand, the crafter (the client's menu, and the server's over the block entity with slot state packets), the loom (with its pattern buttons), the stonecutter (with its recipe buttons), the grindstone (enchanted, damaged and -cursed tools and books) and the +cursed tools and books), the anvil (repairs, enchantment merges and renames, +with the player's levels) and the smithing table (upgrades and trims) and the server's furnace menus over their block entities (`*_be`: a new input restarts cooking, other clicks keep its progress). After every click the slots, carried stack, data slots and drops are compared. @@ -28,7 +29,7 @@ except ImportError: MENUS = {'inventory': 46, 'crafting': 46, 'chest1': 45, 'chest2': 54, 'chest3': 63, 'chest4': 72, 'chest5': 81, 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, - 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, 'stonecutter': 1, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} @@ -52,6 +53,17 @@ ENCHANTS = ['sharpness', 'unbreaking', 'mending', 'efficiency', 'protection', 'p 'binding_curse', 'vanishing_curse'] +# Anvil renames (ServerboundRenameItemPacket): blank, too long, a section sign, an item's own name. +NAMES = ['', ' ', 'Blade', 'Iron Sword', 'Diamond Pickaxe', 'Enchanted Book', '\u00a7cRed', 'x' * 50, 'x' * 51] +# Smithing inputs: templates, bases and additions (trim materials and netherite). +TEMPLATES = ['netherite_upgrade_smithing_template', 'coast_armor_trim_smithing_template', + 'sentry_armor_trim_smithing_template', 'bolt_armor_trim_smithing_template'] +BASES = ['diamond_sword', 'diamond_chestplate', 'diamond_pickaxe', 'iron_helmet', 'iron_chestplate', 'netherite_boots', + 'leather_leggings', 'golden_helmet', 'turtle_helmet', 'diamond_hoe'] +ADDITIONS = ['netherite_ingot', 'iron_ingot', 'gold_ingot', 'emerald', 'redstone', 'quartz', 'amethyst_shard', + 'lapis_lazuli', 'copper_ingot', 'diamond'] + + def quote(text): return '"' + text + '"' @@ -141,6 +153,36 @@ class Gen: body = ',components:{%s}' % ','.join(comps) if comps else '' return '{id:%s,count:%d%s}' % (quote(item), count, body) + def anvil_stack(self): + """A tool to repair or enchant, an enchanted book, a repair material, a named item or anything.""" + rng = self.rng + roll = rng.random() + if roll < 0.45: + stack = self.grind_stack() + elif roll < 0.65: + item = rng.choice(['iron_ingot', 'diamond', 'leather', 'oak_planks', 'phantom_membrane', 'string']) + stack = snbt('minecraft:' + item, rng.choice([1, 1, 2, 3, 5, 64])) + else: + stack = self.stack() + if rng.random() < 0.15: + name = '"minecraft:custom_name":"%s"' % rng.choice(['Blade', 'Iron Sword', 'Old']) + stack = stack.replace(',components:{', ',components:{%s,' % name) if ',components:{' in stack \ + else stack[:-1] + ',components:{%s}}' % name + return stack + + def smith_stack(self, slot=None): + """A template, a base or an addition (for `slot`, else any), sometimes anything.""" + rng = self.rng + if rng.random() < 0.15: + return self.stack() + slot = rng.randrange(3) if slot is None else slot + pool = [TEMPLATES, BASES, ADDITIONS][slot] + item = 'minecraft:' + rng.choice(pool) + count = 1 if slot == 1 else rng.choice([1, 1, 2, 5, 64]) + if slot == 1 and rng.random() < 0.3: + return '{id:%s,count:1,components:{"minecraft:enchantments":{"minecraft:unbreaking":2}}}' % quote(item) + return snbt(item, count) + def recipe(self, slots, width, start=1): """Fills the crafting grid (slots `start`..) with a small known recipe.""" rng = self.rng @@ -174,6 +216,13 @@ class Gen: if menu == 'stonecutter' and rng.random() < 0.2: out.append([1, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) continue + if menu == 'anvil' and rng.random() < 0.15: + out.append([0, 0, 'RENAME', rng.choice(NAMES)]) + continue + if menu in ('anvil', 'smithing') and rng.random() < 0.2: + result = 2 if menu == 'anvil' else 3 + out.append([result, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) + continue if menu == 'grindstone' and rng.random() < 0.2: out.append([2, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) continue @@ -253,6 +302,20 @@ def main(): slots[1] = slots[0] if rng.random() < 0.4 else g.grind_stack() # The result follows the inputs; a fixture stack there is rare. slots[2] = '-' if rng.random() < 0.9 else g.grind_stack() + if menu == 'anvil': + for i in rng.sample(range(3, size), 10): + slots[i] = g.anvil_stack() + slots[0] = g.anvil_stack() if rng.random() < 0.8 else '-' + slots[1] = g.anvil_stack() if rng.random() < 0.6 else '-' + if slots[0] != '-' and rng.random() < 0.25: + slots[1] = slots[0] + slots[2] = '-' if rng.random() < 0.9 else g.anvil_stack() + if menu == 'smithing': + for i in rng.sample(range(4, size), 12): + slots[i] = g.smith_stack() + for i in range(3): + slots[i] = g.smith_stack(i) if rng.random() < 0.75 else '-' + slots[3] = '-' if rng.random() < 0.9 else g.smith_stack() if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -281,10 +344,12 @@ def main(): if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) return 0 - carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack, 'grindstone': g.grind_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' + carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack, 'grindstone': g.grind_stack, + 'anvil': g.anvil_stack, 'smithing': g.smith_stack}.get(menu, g.stack)() if rng.random() < 0.5 else '-' if carried_food is not None: carried = carried_food cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, + 'levels': rng.choice([0, 1, 3, 8, 30, 39, 40]), 'carried': carried, 'data': [datum(i) for i in range(DATA.get(menu, 0))], 'ops': g.ops(size, menu, slots)}) (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))