From cd37ea98a0e85d93263b58bc18e231f39198b146 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 04:06:14 +0200 Subject: [PATCH 1/8] LAN guests use looms: workstation menus on the host's menu engine A guest's use of a loom opens LoomMenu (minecraft:loom) for the guest. The host runs the guest's menu on the shared menu engine (horizon_client::menu, Kind::Loom, as single player does): clicks, the pattern buttons (ServerboundContainerButtonClickPacket), the content and data slot sync after each, the take-result sound at the loom, stillValid (the block gone or out of reach) and clearContainer when it closes or the guest leaves. The guest opens the loom screen for the server's menu, predicts its clicks and buttons on the engine and sends them, runs the menu's client-side slotsChanged on the server's slots and reads the selected pattern from the data slot. The framework (game/lan_stations.rs, game/remote_stations.rs) takes the other workstations one by one (#868). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 5 +- crates/horizon-client/src/game/lan_actions.rs | 13 +- .../horizon-client/src/game/lan_crafting.rs | 32 ++- .../horizon-client/src/game/lan_stations.rs | 260 ++++++++++++++++++ crates/horizon-client/src/game/lan_trading.rs | 9 +- crates/horizon-client/src/game/loom.rs | 1 + crates/horizon-client/src/game/remote.rs | 54 +++- .../src/game/remote_stations.rs | 85 ++++++ crates/horizon-client/src/game/stations.rs | 14 +- crates/horizon-protocol/src/packets/play.rs | 13 + tools/lan_e2e.py | 64 ++++- 11 files changed, 522 insertions(+), 28 deletions(-) create mode 100644 crates/horizon-client/src/game/lan_stations.rs create mode 100644 crates/horizon-client/src/game/remote_stations.rs diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2df6aa9b0..7dd4c9f5d 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -73,6 +73,7 @@ mod lan_entities; mod lan_mobs; mod lan_pvp; mod lan_screen; +mod lan_stations; mod lan_trading; mod lan_waypoints; mod leads; @@ -118,6 +119,7 @@ mod recipe_book; mod remote; mod remote_objects; mod remote_projectiles; +mod remote_stations; mod render_control; mod render_tick; mod respawn_anchor; @@ -5637,7 +5639,8 @@ impl Game<'_> { s.loom.selected = usize::try_from(menu.data[0]).ok(); s.loom.patterns = std::mem::take(&mut menu.loom_patterns); } - for sound in sounds { + // A server's loom plays its own sounds (the client's menu has no level). + for sound in sounds.into_iter().filter(|_| !predicting) { self.loom_sound(sound); } self.loom_screen_changed(); diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index b261e8ad2..95f2dc49b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -53,6 +53,8 @@ pub(super) struct GuestPlay { pub(super) merchant: Option, /// The inventory menu and the crafting table the guest crafts in. pub(super) crafting: super::lan_crafting::GuestCrafting, + /// The workstation menu the guest has open (game/lan_stations.rs). + pub(super) station: Option, /// What the guest's body was given for its effects and enchantments. potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. @@ -679,6 +681,7 @@ impl Game<'_> { }; // ServerPlayer.openMenu closes the menu that was open. self.guest_container_closed(host, conn); + self.lan_station_closed(host, conn, None); host.hub.open_container( conn, menu, @@ -913,6 +916,10 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_inventory_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {} + S::ContainerButtonClick(p) => { + self.lan_station_button(host, conn, p.container, p.button); + } 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]; @@ -920,7 +927,10 @@ impl Game<'_> { self.drop_guest_items(host, gi, vec![c]); } } - S::ContainerClose(p) if self.lan_crafting_closed(host, conn, Some(p.container)) => { + S::ContainerClose(p) + if self.lan_crafting_closed(host, conn, Some(p.container)) + || self.lan_station_closed(host, conn, Some(p.container)) => + { let g = &mut host.hub.guests[gi]; if let Some(c) = g.carried.take() { self.drop_guest_items(host, gi, vec![c]); @@ -1438,6 +1448,7 @@ impl Game<'_> { /// Per tick, for every guest: dig, use items, pick up drops, die. pub(super) fn tick_guests(&mut self, host: &mut LanHost) { self.lan_merchant_tick(host); + self.lan_stations_tick(host); self.announce_guest_advancements(host); let conns: Vec = host .hub diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 6101ce99e..3bf24b262 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -94,7 +94,7 @@ impl Game<'_> { } /// Runs `op` on the guest's menu with their inventory copied in and back. - fn guest_menu_op( + pub(super) fn guest_menu_op( &mut self, host: &mut LanHost, gi: usize, @@ -331,6 +331,7 @@ impl Game<'_> { /// The guest opened a crafting table (`CraftingTableBlock.getMenuProvider`). pub(super) fn lan_open_crafting(&mut self, host: &mut LanHost, conn: u32) { self.lan_crafting_closed(host, conn, None); + self.lan_station_closed(host, conn, None); // The container it replaces loses its opener. self.guest_container_closed(host, conn); let title = horizon_protocol::text::translatable("container.crafting", &[]); @@ -430,22 +431,35 @@ impl Game<'_> { None => return false, } }; - if grid.is_empty() { - return true; + if !grid.is_empty() { + self.lan_place_back(host, gi, grid); } - let mut menu = Menu::new(Kind::Inventory); - self.guest_menu_op(host, gi, &mut menu, |menu, env| place_back(menu, env, grid)); true } - /// A guest left: what their crafting grids held goes back into their + /// `Inventory.placeItemBackInInventory` of `stacks` for guest `gi`, what + /// doesn't fit dropped (`clearContainer`). + pub(super) fn lan_place_back(&mut self, host: &mut LanHost, gi: usize, stacks: Vec) { + let mut menu = Menu::new(Kind::Inventory); + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + place_back(menu, env, stacks) + }); + } + + /// A guest left: what their crafting grids and workstation held goes back into their /// inventory before it is saved (dropped where they stood if full). pub(super) fn lan_crafting_left(&mut self, host: &mut LanHost, g: &mut Guest) { - let table = host.play.remove(&g.conn).and_then(|p| p.crafting.table); + let play = host.play.remove(&g.conn); let mut grid: Vec = g.craft_grid.iter_mut().filter_map(Option::take).collect(); g.craft_result = None; - if let Some((_, _, menu)) = table { - grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + if let Some(play) = play { + if let Some((_, _, menu)) = play.crafting.table { + grid.extend((1..10).filter_map(|s| menu.slot(s).cloned())); + } + // A workstation's inputs too. + if let Some(station) = &play.station { + grid.extend(super::lan_stations::station_inputs(station)); + } } if grid.is_empty() { return; diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs new file mode 100644 index 000000000..e6c1e5289 --- /dev/null +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -0,0 +1,260 @@ +//! Workstation menus for LAN guests: the screen a guest's use opens runs on +//! the host's menu engine (`horizon_client::menu`), the one single player +//! uses, with vanilla's packets: OpenScreen with the station's `MenuType`, +//! container clicks, `ServerboundContainerButtonClickPacket`, the content and +//! data slot sync after each (`broadcastChanges`), and the inputs back into +//! the inventory when the menu closes (`AbstractContainerMenu.clearContainer`). +use super::{ + Game, + lan::LanHost, + lan_crafting::input, + stations::{Kind as StationKind, Station}, +}; +use horizon_client::{ + items::ItemStack, + menu::{Kind, Menu}, +}; +use horizon_protocol::packets::play::{self, Clientbound as C}; + +/// A guest's open workstation menu. +pub(super) struct GuestStation { + window: i32, + state: i32, + kind: StationKind, + pos: [i32; 3], + menu: Box, + /// The data slots the client was last sent. + sent_data: Vec, + /// The game time of the menu's last sound (`lastSoundTime`). + last_sound: u64, +} + +/// The `MenuType`, the engine's menu and the input slots +/// (`clearContainer`'s container) of a station a guest can use. +fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range)> { + Some(match kind { + StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3), + _ => return None, + }) +} + +impl Game<'_> { + /// A workstation a guest's use opened (`ServerPlayer.openMenu`); false + /// when guests can't use that one yet. + pub(super) fn lan_open_station( + &mut self, + host: &mut LanHost, + conn: u32, + station: &Station, + ) -> bool { + let Some((menu_type, kind, _)) = menu_of(station.kind) else { + return false; + }; + self.lan_station_closed(host, conn, None); + self.lan_crafting_closed(host, conn, None); + // The container it replaces loses its opener. + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable(station.kind.title_key(), &[]); + let Some(window) = host.hub.open_window(conn, menu_type, title) else { + return true; + }; + host.play.entry(conn).or_default().station = Some(GuestStation { + window, + state: 0, + kind: station.kind, + pos: station.pos, + menu: Box::new(Menu::new(kind)), + sent_data: Vec::new(), + last_sound: 0, + }); + self.lan_send_station(host, conn); + true + } + + /// Runs `op` on the guest's open station (window `window`, any when + /// None) with their inventory in it, then sends what changed. False when + /// no such window is open. + fn lan_station_op( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + op: impl FnOnce(&mut Menu, &horizon_client::menu::Env), + ) -> bool { + let Some(mut gs) = host + .play + .get_mut(&conn) + .and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w))) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + { + self.guest_menu_op(host, gi, &mut gs.menu, op); + self.lan_station_sounds(&mut gs); + } + host.play.entry(conn).or_default().station = Some(gs); + self.lan_send_station(host, conn); + true + } + + /// 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) { + let sounds = std::mem::take(&mut gs.menu.sounds); + if sounds.is_empty() || gs.last_sound == self.ticks { + return; + } + gs.last_sound = self.ticks; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + for sound in sounds { + self.audio.play(sound, Some(at), 1.0, 1.0); + } + } + + /// A click on the guest's station window; false for other windows. + pub(super) fn lan_station_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + self.lan_station_op(host, conn, Some(p.container), |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }) + } + + /// `ServerGamePacketListenerImpl.handleContainerButtonClick`: + /// `clickMenuButton`, then `broadcastChanges` when the menu took it. + pub(super) fn lan_station_button( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + id: i32, + ) { + self.lan_station_op(host, conn, Some(window), |menu, env| { + menu.button(env, id); + }); + } + + /// The whole station menu and its changed data slots for the client + /// (`sendAllDataToRemote` / `broadcastChanges`). + fn lan_send_station(&mut self, host: &mut LanHost, conn: u32) { + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return; + }; + let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) else { + return; + }; + gs.state = (gs.state + 1) & 0x7FFF; + let own = gs.menu.slot_count() - 36; + let mut items: Vec> = + (0..own).map(|s| gs.menu.slot(s).cloned()).collect(); + let g = &host.hub.guests[gi]; + items.extend((9..36).chain(0..9).map(|i| g.inventory[i].clone())); + let carried = g.carried.clone(); + let packet = C::ContainerSetContent(play::ContainerSetContent { + container: gs.window, + state: gs.state, + items: items.iter().map(|s| host.hub.stack(s)).collect(), + carried: host.hub.stack(&carried), + }); + gs.sent_data.resize(gs.menu.data.len(), i32::MIN); + let mut data = Vec::new(); + for (k, &v) in gs.menu.data.iter().enumerate() { + if gs.sent_data[k] != v { + gs.sent_data[k] = v; + data.push(C::ContainerSetData(play::ContainerSetData { + container: gs.window, + id: k as i16, + value: v as i16, + })); + } + } + host.hub.send_to(conn, &packet); + for packet in data { + host.hub.send_to(conn, &packet); + } + } + + /// `AbstractContainerMenu.removed` of the guest's station (`window`; + /// None closes it whichever it is): the carried stack and the inputs go + /// back to the inventory, what doesn't fit is dropped. False when no such + /// window is open. + pub(super) fn lan_station_closed( + &mut self, + host: &mut LanHost, + conn: u32, + window: Option, + ) -> bool { + let Some(gs) = host + .play + .get_mut(&conn) + .and_then(|p| p.station.take_if(|s| window.is_none_or(|w| s.window == w))) + else { + return false; + }; + let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) else { + return true; + }; + // AbstractContainerMenu.removed: the carried stack first, then the inputs. + let mut back: Vec = host.hub.guests[gi].carried.take().into_iter().collect(); + back.extend(station_inputs(&gs)); + if !back.is_empty() { + self.lan_place_back(host, gi, back); + } + true + } + + /// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its + /// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`). + pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) { + let conns: Vec = host + .play + .iter() + .filter(|(_, p)| p.station.is_some()) + .map(|(c, _)| *c) + .collect(); + for conn in conns { + let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { + continue; + }; + if !host.hub.here(g) { + continue; + } + let Some(gs) = host.play.get(&conn).and_then(|p| p.station.as_ref()) else { + continue; + }; + let [x, y, z] = gs.pos; + let name = &self.res.facts().get(self.world.block(x, y, z)).name; + let block = StationKind::from_block(name) == Some(gs.kind); + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + // The block interaction range (4.5, creative 5) and the buffer. + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + let near = (0..3) + .map(|k| { + let lo = f64::from(gs.pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach; + if !(block && near) { + let window = gs.window; + self.lan_station_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + } + } + } +} + +/// What `clearContainer` gives back from a station's menu. +pub(super) fn station_inputs(gs: &GuestStation) -> Vec { + menu_of(gs.kind) + .map(|(_, _, inputs)| inputs.filter_map(|s| gs.menu.slot(s).cloned()).collect()) + .unwrap_or_default() +} diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index c7f8a94a6..380030274 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -55,8 +55,9 @@ impl Game<'_> { state.session.update_special_prices(); } let title = self.merchant_display_name(&state); - // The container the trading screen replaces loses its opener. + // The container or workstation the trading screen replaces is closed. self.guest_container_closed(host, conn); + self.lan_station_closed(host, conn, None); let Some(window) = host.hub.open_merchant_window(conn, title) else { self.merchant_closed(&mut state); return; @@ -393,8 +394,8 @@ impl Game<'_> { }); } } - /// Takes a station a guest's action opened: a trading screen goes to the - /// guest; other stations are not shown to guests yet. + /// Takes a station a guest's action opened: a trading screen or a + /// workstation menu goes to the guest (game/lan_stations.rs). pub(super) fn lan_station_opened( &mut self, host: &mut LanHost, @@ -406,6 +407,8 @@ impl Game<'_> { && let Some(m) = station.merchant.take() { self.lan_open_merchant(host, conn, *m); + return; } + self.lan_open_station(host, conn, &station); } } diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index f1ff1a300..a903cf779 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -98,6 +98,7 @@ impl Game<'_> { if taken { self.audio .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); + self.remote_station_button(index as i32); } taken } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 5b8072d7f..8445a11c6 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -108,9 +108,9 @@ pub(super) struct Remote { /// only replace the remembered state; then the block takes it. predictions: HashMap<[i32; 3], (i32, i32)>, /// Open container: (window id, menu name). - menu: Option<(i32, String)>, + pub(super) menu: Option<(i32, String)>, /// The open menu's title as the server named it. - menu_title: Option, + pub(super) menu_title: Option, state_id: i32, use_target: Option<[i32; 3]>, entities: HashMap, @@ -1216,9 +1216,29 @@ impl Game<'_> { "minecraft:hopper" => slots(5), "minecraft:generic_3x3" => slots(9), "minecraft:brewing_stand" => slots(5), - _ => None, + // A workstation: its inputs, its result, then the inventory. + m => { + let kind = Self::remote_station_kind(m)?; + let inputs = kind.inputs(); + let own = inputs + usize::from(kind.has_result()); + match s { + _ if s < inputs => Some(super::stations::INPUT + s), + _ if s < own => Some(super::stations::RESULT), + _ if s < own + 27 => Some(9 + s - own), + _ if s < own + 36 => Some(s - own - 27), + _ => None, + } + } } } + /// The workstation screen of a menu type a server opens. + pub(super) fn remote_station_kind(menu: &str) -> Option { + use super::stations::Kind; + Some(match menu { + "minecraft:loom" => Kind::Loom, + _ => return None, + }) + } fn open_menu_name(&self, container: i32) -> String { match self.remote.as_ref().and_then(|r| r.menu.as_ref()) { Some((id, name)) if *id == container && container != 0 => name.clone(), @@ -1237,6 +1257,9 @@ impl Game<'_> { return; // the result slot is recomputed from the grid } *self.slot_mut(internal) = item; + if internal >= super::stations::INPUT && self.station.is_some() { + self.remote_station_slot_changed(internal); + } } fn handle_packet(&mut self, packet: C) -> Result<()> { @@ -1881,6 +1904,9 @@ impl Game<'_> { } self.remote_synced(); } + C::ContainerSetData(p) if self.remote_station_open(p.container) => { + self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value); + } C::ContainerSetData(p) => { let v = i32::from(p.value); match self @@ -3884,13 +3910,8 @@ impl Game<'_> { r.menu = None; r.menu_title = None; } - if self - .station - .as_ref() - .is_some_and(|s| s.kind == super::stations::Kind::Merchant) - { - self.station = None; - } + // The client's menu has no level access: what it holds is the server's. + self.station = None; self.craft_size = 2; if let Some(key) = self.container.take() { // Server containers stay renderable but lose their copied slots. @@ -3964,6 +3985,19 @@ impl Game<'_> { .as_ref() .and_then(|r| r.use_target) .map(|t| (t[0], t[1], t[2])); + if let Some(kind) = Self::remote_station_kind(&menu) { + let title = plain( + &p.title, + &self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(), + ); + let pos = target.map_or([0, 0, 0], |t| [t.0, t.1, t.2]); + self.remote_open_station(p.container, menu, kind, title, pos); + return; + } if menu == "minecraft:merchant" { // A trading window: its offers follow in a MerchantOffers packet. let title = plain( diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs new file mode 100644 index 000000000..b6a3382b2 --- /dev/null +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -0,0 +1,85 @@ +//! A server's workstation menus on this client: the server opens the menu +//! (`ClientboundOpenScreenPacket` with the station's `MenuType`), the +//! station screen draws it, and its clicks and buttons are predicted on the +//! menu engine (`Game::menu_session`) and sent, as +//! `MultiPlayerGameMode.handleContainerInput` and `handleInventoryButtonClick` +//! do. The menu's client-side `slotsChanged` follows the server's slots, and +//! its data slots come in `ClientboundContainerSetDataPacket`. +use super::{ + Game, Screen, + stations::{Kind, Station}, +}; +use horizon_protocol::packets::play::{self, Serverbound as S}; + +impl Game<'_> { + /// The server opened workstation menu `menu` in window `container`. + pub(super) fn remote_open_station( + &mut self, + container: i32, + menu: String, + kind: Kind, + title: String, + pos: [i32; 3], + ) { + if let Some(r) = self.remote.as_mut() { + r.menu = Some((container, menu)); + r.menu_title = Some(title); + } + self.craft_size = 2; + self.container = None; + self.station = Some(Station::new_kind(kind, pos)); + self.screen = Screen::Inventory; + self.capture(false); + } + + /// Window `container` is the server's workstation menu, open here. + pub(super) fn remote_station_open(&self, container: i32) -> bool { + self.station.is_some() + && self + .remote + .as_ref() + .and_then(|r| r.menu.as_ref()) + .is_some_and(|(id, name)| { + *id == container && Self::remote_station_kind(name).is_some() + }) + } + + /// The server set station slot `internal`: the client menu's + /// `Slot.set` runs its container's `setChanged`, so the loom lists the + /// patterns its inputs allow. + pub(super) fn remote_station_slot_changed(&mut self, internal: usize) { + if !self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom) { + return; + } + self.menu_session(|menu, env, to_menu| { + let i = to_menu(internal)?; + let stack = menu.slot(i).cloned(); + menu.set_slot(env, i, stack); + Some(true) + }); + } + + /// `AbstractContainerMenu.setData` from the server. + pub(super) fn remote_station_data(&mut self, id: usize, value: i16) { + let Some(s) = self.station.as_mut() else { + return; + }; + // LoomMenu.selectedBannerPatternIndex. + if (s.kind, id) == (Kind::Loom, 0) { + s.loom.selected = usize::try_from(value).ok(); + } + } + + /// `MultiPlayerGameMode.handleInventoryButtonClick`: the screen already + /// ran `clickMenuButton` on its own menu. + pub(super) fn remote_station_button(&self, button: i32) { + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) + && self.remote_station_open(*container) + { + self.send(S::ContainerButtonClick(play::ContainerButtonClick { + container: *container, + button, + })); + } + } +} diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index c19f6165c..d1c918c1d 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -36,7 +36,7 @@ pub(super) enum Kind { Loom, } impl Kind { - fn from_block(name: &str) -> Option { + pub(super) fn from_block(name: &str) -> Option { Some(match name { "minecraft:enchanting_table" => Self::Enchanting, "minecraft:anvil" | "minecraft:chipped_anvil" | "minecraft:damaged_anvil" => { @@ -51,7 +51,7 @@ impl Kind { _ => return None, }) } - fn inputs(self) -> usize { + pub(super) fn inputs(self) -> usize { match self { Self::Smithing | Self::Loom => 3, Self::Stonecutter | Self::Beacon => 1, @@ -71,7 +71,7 @@ impl Kind { Self::Loom => "gui/container/loom", } } - fn title_key(self) -> &'static str { + pub(super) fn title_key(self) -> &'static str { match self { Self::Enchanting => "container.enchant", Self::Anvil => "container.repair", @@ -108,6 +108,10 @@ impl Kind { }; table[i.min(table.len() - 1)] } + /// Whether the menu has a result slot after its inputs. + pub(super) fn has_result(self) -> bool { + self.result_pos().is_some() + } fn result_pos(self) -> Option<(f32, f32)> { match self { Self::Enchanting => None, @@ -323,6 +327,10 @@ impl Game<'_> { let Some(mut station) = self.station.take() else { return; }; + if self.remote.is_some() && station.kind != Kind::Merchant { + // A server's workstation: its removed() gives the inputs back. + return; + } if let Some(m) = station.merchant.as_mut() { self.merchant_closed(m); } diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 95a68d1ef..3c3d24f44 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1710,6 +1710,11 @@ packet!( } ); packet!(SelectTrade { item: i32 => VarInt }); +packet!( + /// ServerboundContainerButtonClickPacket: `AbstractContainerMenu.clickMenuButton` + /// (the loom's patterns, the stonecutter's recipes, the enchanting table's offers). + ContainerButtonClick { container: i32 => VarInt, button: i32 => VarInt } +); packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); packet!( /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. @@ -1775,6 +1780,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { ClientInformation(ClientInformation) = CLIENT_INFORMATION, ClientTickEnd(Empty) = CLIENT_TICK_END, ConfigurationAcknowledged(Empty) = CONFIGURATION_ACKNOWLEDGED, + ContainerButtonClick(ContainerButtonClick) = CONTAINER_BUTTON_CLICK, ContainerClick(ContainerClick) = CONTAINER_CLICK, ContainerClose(ContainerClose) = CONTAINER_CLOSE, CustomPayload(CustomPayload) = CUSTOM_PAYLOAD, @@ -2360,6 +2366,13 @@ mod tests { Serverbound::encode, Serverbound::decode, ); + // CONTAINER_ID and the button, both VarInts. + let button = Serverbound::ContainerButtonClick(ContainerButtonClick { + container: 3, + button: 200, + }); + assert_eq!(&button.encode()[1..], &[3, 0xC8, 1]); + round_trip(button, Serverbound::encode, Serverbound::decode); } #[test] diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 4a149ba03..3bb858c4d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -36,6 +36,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - brewing: a brewing stand opens on the guest's screen; blaze powder, nether wart and a bottle the guest shift-clicks go to the fuel, ingredient and bottle slots, and the stand's fuel shows (#848); +- loom: a loom opens on the guest's screen; the banner and dye the guest shift-clicks go to their + slots, a pattern button the guest clicks makes the server's result, and the guest takes the + patterned banner (#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; @@ -130,7 +133,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', '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', '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: @@ -887,6 +890,64 @@ def check_brewing(host, guest, out): return seen +def open_station(guest, block, out, label): + """Place `block` two blocks south of the guest and open it: the station's position.""" + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:{block}') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'station', '--timeout', 10) + guest.wait(10) + guest.shot(out, label) + return at + + +def station_slots(guest): + """The open station's stacks: input slots 600 and up, the result at 650.""" + menu = guest.raw('menu') + return {s['slot']: (s['stack']['item'], s['stack']['count']) for s in menu['slots'] if s['slot'] >= 600} + + +def close_station(guest, at): + guest.raw('key', 'esc', 'tap') + guest.wait(10) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + + +def check_loom(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + for item in ('white_banner', 'red_dye'): + guest('command', command=f'give @s minecraft:{item}') + at = open_station(guest, 'loom', out, 'loom') + # LoomMenu.quickMoveStack: a banner to the banner slot, a dye to the dye slot. + for item in ('white_banner', 'red_dye'): + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + loaded = station_slots(guest) + # LoomScreen's first pattern button (clickMenuButton 0): the server makes the result. + guest.raw('click-gui', 67, 20) + guest.wait(10) + made = station_slots(guest).get(650) + guest.shot(out, 'loom-pattern') + guest.raw('click-slot', 650, 'shift') + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + # The server's copy of the banner the guest took has the red layer. + since = guest.raw('events')['last'] + guest('command', command='data get entity @s Inventory[{id:"minecraft:white_banner"}].components') + layer = guest.raw('wait-for', 'chat', 'color: "red"', '--timeout', 10, '--since', since).get('ok') + counts = guest('inventory')['counts'] + seen = {'loaded': loaded, 'made': made, 'left': left, 'layer': layer, 'counts': counts} + want = {'loaded': {600: ('minecraft:white_banner', 1), 601: ('minecraft:red_dye', 1)}, + 'made': ('minecraft:white_banner', 1), 'left': {}, 'layer': True, + 'counts': {'minecraft:white_banner': 1}} + assert seen == want, f'the loom 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']: @@ -2078,6 +2139,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'containers': check_containers, 'feedback': check_feedback, 'titles': check_titles, 'chat': check_chat, 'machines': check_machines, 'brewing': check_brewing, + 'loom': check_loom, 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, From c8f02d91b782c407266e60beb3eb5f4b6664f0fb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 04:40:04 +0200 Subject: [PATCH 2/8] Stonecutter on the menu engine; LAN guests use stonecutters StonecutterMenu joins horizon_client::menu (Kind::Stonecutter): the input's recipe list (slotsChanged / setupRecipeList), selectedRecipeIndex as its data slot, clickMenuButton (an invalid index is taken too), the result's onTake (one input used up, awardUsedRecipes, the take sound) and quickMoveStack with the leftover of a result move dropped. test_menu_click_parity compares it with vanilla's StonecutterMenu, recipe buttons included. Single player's stonecutter screen now clicks through the engine (drags and double clicks included), and its recipe grid calls clickMenuButton as StonecutterScreen does. A LAN guest's stonecutter opens minecraft:stonecutter on the host's engine, as the loom does (#868). Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 2 + .../horizon-client/examples/menu_fixture.rs | 2 + .../examples/place_recipe_fixture.rs | 2 + .../examples/trading_fixture.rs | 2 + crates/horizon-client/src/game.rs | 33 +++- .../horizon-client/src/game/lan_crafting.rs | 1 + .../horizon-client/src/game/lan_stations.rs | 1 + crates/horizon-client/src/game/lan_trading.rs | 1 + crates/horizon-client/src/game/loom.rs | 5 +- crates/horizon-client/src/game/recipe_book.rs | 1 + crates/horizon-client/src/game/remote.rs | 1 + .../src/game/remote_stations.rs | 17 +- crates/horizon-client/src/game/stations.rs | 153 ++++++++---------- crates/horizon-client/src/menu.rs | 140 +++++++++++++++- crates/horizon-client/src/stations.rs | 1 + .../horizonlab/parity/VanillaMenuOracle.java | 1 + tools/lan_e2e.py | 48 +++++- tools/test_menu_click_parity.py | 33 +++- 18 files changed, 335 insertions(+), 109 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 584425ced..c25badfd2 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -82,11 +82,13 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); // The inventory menu never reads banner patterns. let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, 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 63a5351a3..bc43a59f1 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -44,11 +44,13 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::load(root, &items); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index 45d763980..b1a49e688 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -38,11 +38,13 @@ fn main() -> horizon_client::Result<()> { let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::default(); + let station_recipes = horizon_client::stations::StationRecipes::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, 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 a560b1c06..b7eeb442c 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -243,6 +243,7 @@ fn main() -> horizon_client::Result<()> { let recipes = horizon_client::crafting::Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::load(root); + let station_recipes = horizon_client::stations::StationRecipes::default(); let types: HashMap<_, _> = horizon_client::mobs::MobTypes::load(root)? .types .into_iter() @@ -378,6 +379,7 @@ fn main() -> horizon_client::Result<()> { recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, trade: Some(&env_trade), }; trade(&mut out, name, &kv, &mut world, &env, origin)?; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 7dd4c9f5d..2aaf231f4 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5425,6 +5425,10 @@ impl Game<'_> { .station .as_ref() .is_some_and(|s| s.kind == stations::Kind::Merchant); + let stonecutter_open = self + .station + .as_ref() + .is_some_and(|s| s.kind == stations::Kind::Stonecutter); 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]; @@ -5451,6 +5455,11 @@ impl Game<'_> { v.push(Some(stations::RESULT)); v.extend((9..36).chain(0..9).map(Some)); (Kind::Loom, v) + } else if stonecutter_open { + // StonecutterMenu: the input, the result, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Stonecutter, v) } else { let (kind, map) = if self.container.is_some() { let size = self.container_size(); @@ -5533,6 +5542,10 @@ impl Game<'_> { s.loom.patterns.clone(), ) }); + let stone = self + .station + .as_ref() + .map(|s| (s.selected.map_or(-1, |i| i as i32), s.stone.clone())); let crafter_data = match self.container_kind() { Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), _ => None, @@ -5564,6 +5577,7 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, trade: Some(&trade_env), }; menu.creative = creative; @@ -5585,6 +5599,14 @@ impl Game<'_> { menu.loom_patterns = patterns; menu.set_slot(&env, 3, before[3].clone()); } + if kind == Kind::Stonecutter + && let Some((selected, state)) = stone + { + // The same: the list and selection between clicks, then the result. + menu.data[0] = selected; + menu.stone = state; + menu.set_slot(&env, 1, before[1].clone()); + } if let Some((disabled, triggered)) = crafter_data { for (i, d) in disabled.iter().enumerate() { menu.data[i] = i32::from(*d); @@ -5641,9 +5663,18 @@ impl Game<'_> { } // A server's loom plays its own sounds (the client's menu has no level). for sound in sounds.into_iter().filter(|_| !predicting) { - self.loom_sound(sound); + self.station_sound(sound); } self.loom_screen_changed(); + } else if kind == Kind::Stonecutter { + if let Some(s) = self.station.as_mut() { + s.selected = usize::try_from(menu.data[0]).ok(); + s.stone = std::mem::take(&mut menu.stone); + s.stonecutter_changed(); + } + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); + } } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 3bf24b262..bf71af641 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -89,6 +89,7 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, trade: None, } } diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index e6c1e5289..b2b0c21aa 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -34,6 +34,7 @@ pub(super) struct GuestStation { fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range)> { Some(match kind { StationKind::Loom => ("minecraft:loom", Kind::Loom, 0..3), + StationKind::Stonecutter => ("minecraft:stonecutter", Kind::Stonecutter, 0..1), _ => return None, }) } diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 380030274..7036b60eb 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -255,6 +255,7 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, trade: Some(&trade_env), }; let mut menu = Menu::new(Kind::Merchant); diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index a903cf779..ef49c8cf1 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -68,8 +68,9 @@ impl Game<'_> { } l.last_inputs = inputs; } - /// A sound the loom menu played: the result's once per tick. - pub(super) fn loom_sound(&mut self, sound: &str) { + /// A sound the loom or stonecutter menu played: the result's once per + /// tick (`lastSoundTime`). + pub(super) fn station_sound(&mut self, sound: &str) { let ticks = self.ticks; let Some(s) = self.station.as_mut() else { return; diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 843c01476..f7c00c998 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -279,6 +279,7 @@ impl Game<'_> { recipes: self.res.recipes(), brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, + station_recipes: &self.res.stations().recipes, 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 8445a11c6..686e59430 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1236,6 +1236,7 @@ impl Game<'_> { use super::stations::Kind; Some(match menu { "minecraft:loom" => Kind::Loom, + "minecraft:stonecutter" => Kind::Stonecutter, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index b6a3382b2..62a0238dd 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -46,9 +46,13 @@ impl Game<'_> { /// The server set station slot `internal`: the client menu's /// `Slot.set` runs its container's `setChanged`, so the loom lists the - /// patterns its inputs allow. + /// 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| s.kind == Kind::Loom) { + if !self + .station + .as_ref() + .is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter)) + { return; } self.menu_session(|menu, env, to_menu| { @@ -64,9 +68,12 @@ impl Game<'_> { let Some(s) = self.station.as_mut() else { return; }; - // LoomMenu.selectedBannerPatternIndex. - if (s.kind, id) == (Kind::Loom, 0) { - s.loom.selected = usize::try_from(value).ok(); + match (s.kind, id) { + // LoomMenu.selectedBannerPatternIndex. + (Kind::Loom, 0) => s.loom.selected = usize::try_from(value).ok(), + // StonecutterMenu.selectedRecipeIndex. + (Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(), + _ => {} } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index d1c918c1d..30280d034 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -13,7 +13,6 @@ use horizon_client::{ stations::{self, AnvilResult, EnchantOffers}, }; use horizon_core::random::{LegacyRandom, RandomSource}; -use std::sync::Arc; /// Slot ids of the open station: inputs from 600, the result at 650. pub(super) const INPUT: usize = 600; @@ -137,11 +136,11 @@ pub(super) struct Station { anvil: AnvilResult, /// Anvil rename box text. pub(super) name: String, - /// Stonecutter: recipe indices for the input, selection and first shown index. - recipes: Vec, - selected: Option, + /// Stonecutter: the menu's recipe list (horizon_client::menu), its + /// `selectedRecipeIndex` and the screen's first shown index. + pub(super) stone: horizon_client::menu::Stonecutter, + pub(super) selected: Option, start: usize, - input_item: Option>, /// Anvil: the input the rename box was last filled from. anvil_last: Option, /// When the screen opened: the rename box has the focus from then. @@ -165,10 +164,9 @@ impl Station { bookcases: 0, anvil: AnvilResult::default(), name: String::new(), - recipes: Vec::new(), + stone: Default::default(), selected: None, start: 0, - input_item: None, anvil_last: None, opened: std::time::Instant::now(), last_sound: 0, @@ -180,6 +178,13 @@ impl Station { pub(super) fn new_kind(kind: Kind, pos: [i32; 3]) -> Self { Self::new(kind, pos) } + /// `StonecutterScreen.containerChanged`: without recipes to show, the + /// list scrolls back to the top. + pub(super) fn stonecutter_changed(&mut self) { + if self.inputs[0].is_none() || self.stone.recipes.is_empty() { + self.start = 0; + } + } } /// The 108x19 enchantment button `i` (relative to the GUI origin). @@ -476,32 +481,8 @@ impl Game<'_> { Kind::Cartography => s.result = self.cartography_result(&s), // The menu engine keeps the loom's state (Game::menu_session). Kind::Loom => {} - Kind::Stonecutter => { - let item = s.inputs[0].as_ref().map(|i| i.item.clone()); - if item != s.input_item { - s.input_item = item; - s.selected = None; - s.start = 0; - s.recipes = match &s.inputs[0] { - Some(input) => data - .recipes - .stonecutting - .iter() - .enumerate() - .filter(|(_, r)| r.input.test(input)) - .map(|(i, _)| i) - .collect(), - None => Vec::new(), - }; - } - s.result = match (s.selected, &s.inputs[0]) { - (Some(i), Some(_)) => s - .recipes - .get(i) - .map(|&r| data.recipes.stonecutting[r].result.clone()), - _ => None, - }; - } + // The menu engine keeps the stonecutter's state (Game::menu_session). + Kind::Stonecutter => {} } self.station = Some(s); } @@ -718,13 +699,6 @@ impl Game<'_> { self.move_to(&mut stack, &halves, false); } } - Kind::Stonecutter => { - if self.data().recipes.stonecutter(&stack).is_empty() { - self.move_to(&mut stack, &halves, false); - } else { - self.move_to(&mut stack, &[INPUT], false); - } - } Kind::Cartography => { if super::maps::map_id(&stack).is_some() { self.move_to(&mut stack, &[INPUT], false); @@ -750,7 +724,7 @@ impl Game<'_> { self.move_to(&mut stack, targets, false); } // Their clicks run on the menu engine. - Kind::Merchant | Kind::Loom => {} + Kind::Merchant | Kind::Loom | Kind::Stonecutter => {} } } let moved = stack.count != start; @@ -886,19 +860,7 @@ impl Game<'_> { let pitch = self.world.random.next_float() * 0.1 + 0.9; self.play_at("minecraft:block.smithing_table.use", pos, 1.0, pitch); } - Kind::Stonecutter => { - if let Some(x) = s.inputs[0].as_mut() { - x.count -= 1; - if x.count == 0 { - s.inputs[0] = None; - } - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - self.play_at("minecraft:ui.stonecutter.take_result", pos, 1.0, 1.0); - } - } - Kind::Merchant => {} + Kind::Merchant | Kind::Stonecutter => {} Kind::Beacon => {} Kind::Cartography => { for slot in &mut s.inputs { @@ -1044,7 +1006,7 @@ impl Game<'_> { }) .collect(), Kind::Stonecutter if s.inputs[0].is_some() => (s.start - ..(s.start + 12).min(s.recipes.len())) + ..(s.start + 12).min(s.stone.recipes.len())) .map(|index| { let p = index - s.start; [ @@ -1097,29 +1059,8 @@ impl Game<'_> { } } } - if kind == Kind::Stonecutter - && let Some(s) = self.station.as_ref() - && s.inputs[0].is_some() - { - for index in s.start..(s.start + 12).min(s.recipes.len()) { - let p = index - s.start; - let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); - if inside(local, x, y, 16.0, 18.0) { - if s.selected != Some(index) { - if let Some(st) = self.station.as_mut() { - st.selected = Some(index); - } - self.audio.play( - "minecraft:ui.stonecutter.select_recipe", - None, - 1.0, - 1.0, - ); - self.station_changed(); - } - return true; - } - } + if kind == Kind::Stonecutter && self.stonecutter_click(local) { + return true; } } let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { @@ -1128,10 +1069,10 @@ impl Game<'_> { if self .station .as_ref() - .is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant)) + .is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter)) { - // LoomMenu, MerchantMenu and the brewing stand's BrewingStandMenu - // clicks run on the verified menu engine. + // LoomMenu, MerchantMenu, StonecutterMenu and the brewing stand's + // BrewingStandMenu clicks run on the verified menu engine. let input = if shift { horizon_client::menu::Input::QuickMove } else { @@ -1172,16 +1113,49 @@ impl Game<'_> { } self.station_changed(); } + /// `StonecutterScreen.mouseClicked` on its recipe grid: `clickMenuButton` + /// with the cell's index (an empty cell's too), and the select sound when + /// the menu took it. + fn stonecutter_click(&mut self, local: (f32, f32)) -> bool { + let Some(start) = self + .station + .as_ref() + .filter(|s| s.inputs[0].is_some() && !s.stone.recipes.is_empty()) + .map(|s| s.start) + else { + return false; + }; + for index in start..start + 12 { + let p = index - start; + let (x, y) = (52.0 + (p % 4) as f32 * 16.0, 14.0 + (p / 4) as f32 * 18.0); + if !inside(local, x, y, 16.0, 18.0) { + continue; + } + let mut taken = false; + let flag = &mut taken; + self.menu_session(|menu, env, _| { + *flag = menu.button(env, index as i32); + Some(*flag) + }); + if taken { + self.audio + .play("minecraft:ui.stonecutter.select_recipe", None, 1.0, 1.0); + self.remote_station_button(index as i32); + return true; + } + } + false + } pub(super) fn station_scroll(&mut self, d: f32) { self.merchant_scroll(d); self.loom_scroll(d); let Some(s) = self.station.as_mut() else { return; }; - if s.kind != Kind::Stonecutter || s.recipes.len() <= 12 { + if s.kind != Kind::Stonecutter || s.stone.recipes.len() <= 12 { return; } - let rows = s.recipes.len().div_ceil(4) - 3; + let rows = s.stone.recipes.len().div_ceil(4) - 3; let first_row = (s.start / 4) as i32 - d.signum() as i32; s.start = first_row.clamp(0, rows as i32) as usize * 4; } @@ -1748,9 +1722,9 @@ impl Game<'_> { } Kind::Merchant | Kind::Beacon | Kind::Cartography | Kind::Loom => {} Kind::Stonecutter => { - let display = s.inputs[0].is_some() && !s.recipes.is_empty(); - let active = display && s.recipes.len() > 12; - let rows = s.recipes.len().div_ceil(4).saturating_sub(3).max(1); + let display = s.inputs[0].is_some() && !s.stone.recipes.is_empty(); + let active = display && s.stone.recipes.len() > 12; + let rows = s.stone.recipes.len().div_ceil(4).saturating_sub(3).max(1); let offs = if active { (s.start / 4) as f32 / rows as f32 } else { @@ -1771,13 +1745,14 @@ impl Game<'_> { let (start, selected) = (s.start, s.selected); // graphics.item: the icon only, without the count. let shown: Vec<(usize, ItemStack)> = (start - ..(start + 12).min(s.recipes.len())) + ..(start + 12).min(s.stone.recipes.len())) .map(|i| { ( i, ItemStack { count: 1, - ..self.res.stations().recipes.stonecutting[s.recipes[i]] + ..self.res.stations().recipes.stonecutting + [s.stone.recipes[i]] .result .clone() }, @@ -2090,7 +2065,7 @@ impl Game<'_> { "bookcases": s.bookcases, "anvil_cost": s.anvil.cost, "result": s.result.as_ref().map(|r| format!("{} x{}", r.item, r.count)), - "recipes": s.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), + "recipes": s.stone.recipes.iter().map(|&i| recipes[i].id.clone()).collect::>(), "selected": s.selected, }) } diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 6dc8d7b7f..6c2250f0b 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -3,8 +3,8 @@ //! craft drags, pickup all) for the player inventory, the crafting table, the //! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing //! stand, the crafter (its client menu and the block entity's server menu with -//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`) and the -//! merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the +//! `setSlotState`), the loom (`clickMenuButton`, `slotsChanged`), the +//! stonecutter (its recipe buttons and result) and the merchant (`MerchantMenu` over a `merchant::Session`: payment slots, the //! result slot's trade, `tryMoveItems`). //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. @@ -24,6 +24,8 @@ pub struct Env<'a> { pub recipes: &'a Recipes, pub brewing: &'a Brewing, pub banners: &'a Banners, + /// The stonecutter's recipes. + pub station_recipes: &'a crate::stations::StationRecipes, /// What a merchant menu needs for offers made while it is open (level-ups). pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, } @@ -71,6 +73,8 @@ pub enum Kind { /// result follows the grid, and filling a disabled slot enables it. CrafterBlock, Loom, + /// `StonecutterMenu`: the input, the result, then the inventory. + Stonecutter, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -96,6 +100,7 @@ impl Kind { "crafter" => Self::Crafter, "crafter_be" => Self::CrafterBlock, "loom" => Self::Loom, + "stonecutter" => Self::Stonecutter, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -133,6 +138,8 @@ enum Role { LoomResult, /// `MerchantResultSlot`. MerchantResult, + /// The stonecutter's result slot (`onTake` uses up one input). + StoneResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -182,6 +189,19 @@ pub struct Menu { pub equipped: Vec<(&'static str, Option)>, /// The merchant a merchant menu trades with. pub merchant: Option>, + /// The stonecutter's recipe list (`recipesForInput`). + pub stone: Stonecutter, +} + +/// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`. +#[derive(Clone, Default, Debug, PartialEq)] +pub struct Stonecutter { + /// `recipesForInput`: indices into `StationRecipes.stonecutting`. + pub recipes: Vec, + /// The item the list was made for (`input`; None for nothing). + pub input: Option>, + /// `ResultContainer.recipeUsed`. + pub used: Option, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -318,6 +338,18 @@ impl Menu { player(&mut slots); data = 1; } + Kind::Stonecutter => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::Plain)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::StoneResult, + }); + player(&mut slots); + // selectedRecipeIndex: DataSlot.standalone() starts at 0. + data = 1; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -403,6 +435,7 @@ impl Menu { crafted: Vec::new(), equipped: Vec::new(), merchant: None, + stone: Stonecutter::default(), } } @@ -410,8 +443,20 @@ impl Menu { self.kind } - /// `clickMenuButton`: the loom's pattern buttons. False when refused. + /// `clickMenuButton`: the loom's pattern buttons and the stonecutter's + /// recipes. False when refused. pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind == Kind::Stonecutter { + // StonecutterMenu.clickMenuButton: an invalid index is taken too. + if self.data[0] == id { + return false; + } + if id >= 0 && (id as usize) < self.stone.recipes.len() { + self.data[0] = id; + self.stone_setup_result(env, id); + } + return true; + } if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() { return false; } @@ -510,8 +555,42 @@ impl Menu { } } + /// `StonecutterMenu.slotsChanged`: a new input item lists its recipes + /// (`setupRecipeList`), with none selected and no result. + fn stone_changed(&mut self, env: &Env) { + let input = self.containers[MAIN][0].as_ref().map(|s| s.item.clone()); + if input == self.stone.input { + return; + } + self.stone.input = input; + self.data[0] = -1; + self.containers[RESULT][0] = None; + self.stone.recipes = match &self.containers[MAIN][0] { + Some(stack) => env + .station_recipes + .stonecutting + .iter() + .enumerate() + .filter(|(_, r)| r.input.test(stack)) + .map(|(i, _)| i) + .collect(), + None => Vec::new(), + }; + } + + /// `StonecutterMenu.setupResultSlot`. + fn stone_setup_result(&mut self, env: &Env, index: i32) { + let recipe = usize::try_from(index) + .ok() + .and_then(|i| self.stone.recipes.get(i).copied()); + self.stone.used = recipe; + self.containers[RESULT][0] = + recipe.map(|r| env.station_recipes.stonecutting[r].result.clone()); + } + /// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs, - /// the block crafter refreshes its result. + /// the stonecutter lists its recipes, the block crafter refreshes its + /// result. fn slot_changed(&mut self, env: &Env, s: usize) { // MerchantContainer.setChanged: every slot of it, the result too. if self.kind == Kind::Merchant && self.slots[s].container != PLAYER { @@ -523,6 +602,7 @@ impl Menu { } match self.kind { Kind::Loom => self.loom_changed(env), + Kind::Stonecutter => self.stone_changed(env), Kind::CrafterBlock => self.crafter_result(env), _ => {} } @@ -634,7 +714,7 @@ impl Menu { Role::LoomBanner => Self::is_banner(stack), Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), - Role::LoomResult | Role::MerchantResult => false, + Role::LoomResult | Role::MerchantResult | Role::StoneResult => false, } } @@ -763,7 +843,7 @@ impl Menu { } // SimpleContainer.removeItem calls setChanged when it took something; // MerchantContainer.removeItem updates the result after a payment slot. - if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant) { + if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter) { self.slot_changed(env, s); } out @@ -787,6 +867,19 @@ impl Menu { self.merchant_take(env); return; } + if self.slots[s].role == Role::StoneResult { + // StonecutterMenu's result onTake: awardUsedRecipes, one input + // used up, the result again for the selected recipe. + if let Some(r) = self.stone.used { + self.crafted + .push(env.station_recipes.stonecutting[r].id.clone()); + } + if self.remove(env, 0, 1).is_some() { + self.stone_setup_result(env, self.data[0]); + } + self.sounds.push("minecraft:ui.stonecutter.take_result"); + 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); @@ -1231,6 +1324,34 @@ impl Menu { return None; } } + Kind::Stonecutter => { + after_take = true; + if index == 1 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if index == 0 { + if !self.move_to(env, &mut stack, 2, 38, false) { + return None; + } + } else if env + .station_recipes + .stonecutting + .iter() + .any(|r| r.input.test(&stack)) + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (2..29).contains(&index) { + if !self.move_to(env, &mut stack, 29, 38, false) { + return None; + } + } else if (29..38).contains(&index) && !self.move_to(env, &mut stack, 2, 29, false) + { + return None; + } + } Kind::Merchant => { after_take = true; if index == 2 { @@ -1369,7 +1490,10 @@ impl Menu { if after_take || matches!(self.kind, Kind::Inventory | Kind::Crafting) { self.on_take(env, index); } - if index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting) { + // What the result slot's move left over is dropped. + if (index == 0 && matches!(self.kind, Kind::Inventory | Kind::Crafting)) + || (index == 1 && self.kind == Kind::Stonecutter) + { self.drop_stack(&stack); } Some(clicked) @@ -2023,11 +2147,13 @@ pub(crate) mod tests { let recipes = Recipes::load(&root, &items).unwrap(); let brewing = Brewing::load(&root, &items); let banners = Banners::load(&root); + let station_recipes = crate::stations::StationRecipes::load(&root, &items); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, + station_recipes: &station_recipes, 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 20750d6fe..2fdeeb860 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -450,6 +450,7 @@ pub struct Stonecutting { pub input: Ingredient, pub result: ItemStack, } +#[derive(Default)] pub struct StationRecipes { pub smithing: Vec, /// Sorted by recipe id, the registry order vanilla lists them in. 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 5c784fdfe..aaa6a0677 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -178,6 +178,7 @@ public final class VanillaMenuOracle { } } case "loom" -> new LoomMenu(0, inv); + case "stonecutter" -> new StonecutterMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 3bb858c4d..20e5062bb 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -39,6 +39,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - loom: a loom opens on the guest's screen; the banner and dye the guest shift-clicks go to their slots, a pattern button the guest clicks makes the server's result, and the guest takes the patterned banner (#868); +- stonecutter: a stonecutter opens on the guest's screen with the recipes of the stone the guest puts + in; the guest picks the slab and shift-clicks the result, and the server has cut every + stone into slabs (#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; @@ -133,7 +136,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', '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', '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: @@ -948,6 +951,48 @@ def check_loom(host, guest, out): return seen +def server_count(guest, item): + """How many of `item` the server says the guest has (`clear` with a count of 0 only counts).""" + since = guest.raw('events')['last'] + guest('command', command=f'clear @s minecraft:{item} 0') + for n in range(0, 65): + reply = guest.raw('events', '--since', since) + lines = [e.get('text', '') for e in reply['events'] if e.get('event') == 'chat'] + for line in lines: + if 'matching item' in line or 'No items were found' in line: + return 0 if 'No items' in line else int(line.split('Found ')[1].split(' ')[0]) + guest.wait(2) + raise Failed(f'no answer to clear for {item}') + + +def check_stonecutter(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='give @s minecraft:stone 3') + at = open_station(guest, 'stonecutter', out, 'stonecutter') + # StonecutterMenu.quickMoveStack: stone has recipes, so it goes to the input. + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:stone'), 'shift') + guest.wait(10) + recipes = guest.raw('menu')['info']['recipes'] + index = recipes.index('minecraft:stone_slab_from_stone_stonecutting') + # StonecutterScreen's recipe grid: four columns of 16x18 cells from (52, 14). + guest.raw('click-gui', 52 + index % 4 * 16 + 8, 14 + index // 4 * 18 + 9) + guest.wait(10) + picked = (guest.raw('menu')['info']['selected'], station_slots(guest).get(650)) + guest.shot(out, 'stonecutter-recipe') + # A shift-click on the result cuts while there is stone (doClick repeats quickMoveStack). + guest.raw('click-slot', 650, 'shift') + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + seen = {'picked': picked, 'left': left, + 'server': {item: server_count(guest, item) for item in ('stone_slab', 'stone')}} + want = {'picked': (index, ('minecraft:stone_slab', 2)), 'left': {}, + 'server': {'stone_slab': 6, 'stone': 0}} + assert seen == want, f'the stonecutter 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']: @@ -2140,6 +2185,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'machines': check_machines, 'brewing': check_brewing, 'loom': check_loom, + 'stonecutter': check_stonecutter, '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 d0253866f..d4b7e86be 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -10,7 +10,8 @@ click: QUICK_MOVE on every slot of the clicked slot's container holding the item the first click moved) over the player inventory, 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) and the +entity with slot state packets), the loom (with its pattern buttons), the +stonecutter (with its recipe buttons) 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. @@ -26,8 +27,9 @@ 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, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, '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} DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] @@ -40,6 +42,9 @@ COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_i 'raw_iron', 'potato', 'beef', 'chicken', 'sticky_piston', 'blaze_rod', 'lava_bucket', 'oak_sapling', 'white_dye', 'red_dye', 'torch', 'crafting_table', 'furnace', 'chest', 'glass_bottle', 'nether_wart', 'blaze_powder', 'redstone', 'gunpowder', 'sugar', 'potion', 'splash_potion', 'lingering_potion', 'fermented_spider_eye', 'dragon_breath'] +# Stonecutter inputs (several recipes each), and a block it doesn't cut. +CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sandstone', 'quartz_block', 'deepslate', + 'stone_bricks', 'oak_planks'] def quote(text): @@ -97,6 +102,13 @@ class Gen: return snbt(rng.choice(pool), 1) return self.stack() + def cut_stack(self): + """Mostly something the stonecutter cuts, sometimes anything.""" + rng = self.rng + if rng.random() < 0.75: + return snbt('minecraft:' + rng.choice(CUTTABLE), rng.choice([1, 1, 2, 3, 10, 63, 64])) + return self.stack() + def recipe(self, slots, width, start=1): """Fills the crafting grid (slots `start`..) with a small known recipe.""" rng = self.rng @@ -123,6 +135,13 @@ class Gen: # The result: take it, shift it out, throw it. out.append([3, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'THROW', 'SWAP'])]) continue + if menu == 'stonecutter' and rng.random() < 0.25: + # A recipe button (clickMenuButton), sometimes out of range or the selected one. + out.append([rng.choice([0, 0, 1, 2, 3, 5, 10, 30, -1]), 0, 'BUTTON']) + continue + 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 == 'crafter_be' and rng.random() < 0.2: out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE']) continue @@ -183,6 +202,12 @@ def main(): slots[2] = g.loom_stack(0.6) if rng.random() < 0.4 else rng.choice(['-', '-', g.loom_stack()]) # The result slot follows the inputs; a fixture stack there is rare. slots[3] = '-' if rng.random() < 0.9 else g.loom_stack() + if menu == 'stonecutter': + for i in rng.sample(range(2, size), 8): + slots[i] = g.cut_stack() + slots[0] = g.cut_stack() if rng.random() < 0.8 else '-' + # The result follows the input and the selected recipe; a fixture stack there is rare. + slots[1] = '-' if rng.random() < 0.9 else g.cut_stack() if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -208,10 +233,10 @@ def main(): return [rng.choice([0, 37, 1600]), 1600, rng.choice([0, 1, 57, 199]), rng.choice([200, 100])][i] if menu in ('crafter', 'crafter_be'): return rng.choice([0, 0, 1]) - if menu == 'loom': + if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) return 0 - carried = (g.loom_stack() if menu == 'loom' else g.stack()) if rng.random() < 0.5 else '-' + carried = {'loom': g.loom_stack, 'stonecutter': g.cut_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, From 4fecf43d28c4ff4a85699db7cee93af00c7fdd39 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 05:31:00 +0200 Subject: [PATCH 3/8] Grindstone on the menu engine; LAN guests use grindstones GrindstoneMenu now runs on horizon_client::menu (Kind::Grindstone): its input filter, computeResult, the result's onTake (both inputs cleared, the experience sum handed to the caller) and quickMoveStack, verified against the vanilla class by test_menu_click_parity with enchanted, damaged and cursed tools and books. Single player routes the grindstone's clicks, drags and double clicks through the engine and rolls the orbs and level event 1042 (now playing block.grindstone.use) where the result is taken. The LAN host opens minecraft:grindstone for guests on the same engine and awards the orbs at the block; guests read enchantments, stored enchantments, repair cost and custom names from the server's stacks, and the host now sends repair cost. Part of #868. Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 2 + .../horizon-client/examples/menu_fixture.rs | 2 + .../examples/place_recipe_fixture.rs | 2 + .../examples/trading_fixture.rs | 1 + crates/horizon-client/src/enchant.rs | 1 + crates/horizon-client/src/game.rs | 33 ++++++-- .../horizon-client/src/game/lan_crafting.rs | 1 + .../horizon-client/src/game/lan_stations.rs | 4 + 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 | 29 +++++++ .../src/game/remote_stations.rs | 2 +- crates/horizon-client/src/game/stations.rs | 58 +++++-------- crates/horizon-client/src/lan/guest.rs | 6 ++ crates/horizon-client/src/menu.rs | 84 ++++++++++++++++++- crates/horizon-client/src/stations.rs | 22 +++-- .../horizonlab/parity/VanillaMenuOracle.java | 1 + tools/lan_e2e.py | 51 ++++++++++- tools/test_menu_click_parity.py | 51 ++++++++++- 19 files changed, 297 insertions(+), 55 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index c25badfd2..8093079cc 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -83,12 +83,14 @@ fn main() -> horizon_client::Result<()> { // The inventory menu never reads banner patterns. let banners = horizon_client::banner::Banners::default(); let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, 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 bc43a59f1..ee5629498 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -45,12 +45,14 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); 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 env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: None, }; let mut out = String::new(); diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index b1a49e688..7d05a4cd3 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -39,12 +39,14 @@ fn main() -> horizon_client::Result<()> { let brewing = horizon_client::brewing::Brewing::load(root, &items); let banners = horizon_client::banner::Banners::default(); let station_recipes = horizon_client::stations::StationRecipes::default(); + let enchantments = horizon_client::enchant::Enchantments::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, 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 b7eeb442c..a2dd8f461 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -380,6 +380,7 @@ fn main() -> horizon_client::Result<()> { brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, trade: Some(&env_trade), }; trade(&mut out, name, &kv, &mut world, &env, origin)?; diff --git a/crates/horizon-client/src/enchant.rs b/crates/horizon-client/src/enchant.rs index a988eeb55..039ea658f 100644 --- a/crates/horizon-client/src/enchant.rs +++ b/crates/horizon-client/src/enchant.rs @@ -60,6 +60,7 @@ pub struct ItemProps { /// `minecraft:brewing_fuel` present. pub brewing_fuel: bool, } +#[derive(Default)] pub struct Enchantments { pub list: Vec, index: HashMap, usize>, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2aaf231f4..f3593b29c 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2549,14 +2549,18 @@ impl Game<'_> { 1029 => Some(("minecraft:block.anvil.destroy", 1.0)), 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)), _ => None, }; if let Some((name, volume)) = sound { - let pitch = if id == 1009 { - 2.6 + (self.world.random.next_float() - self.world.random.next_float()) - * 0.8 - } else { - 1.0 + let pitch = match id { + 1009 => { + 2.6 + (self.world.random.next_float() + - self.world.random.next_float()) + * 0.8 + } + 1042 => self.world.random.next_float() * 0.1 + 0.9, + _ => 1.0, }; self.audio.play(name, c, volume, pitch); } @@ -5429,6 +5433,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 (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]; @@ -5460,6 +5468,15 @@ impl Game<'_> { let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Stonecutter, v) + } else if grindstone_open { + // GrindstoneMenu: the two inputs, the result, then the inventory. + let mut v = vec![ + Some(stations::INPUT), + Some(stations::INPUT + 1), + Some(stations::RESULT), + ]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Grindstone, v) } else { let (kind, map) = if self.container.is_some() { let size = self.container_size(); @@ -5578,6 +5595,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, trade: Some(&trade_env), }; menu.creative = creative; @@ -5676,6 +5694,11 @@ impl Game<'_> { self.station_sound(sound); } } + if let Some(amount) = menu.ground.take().filter(|_| !predicting) + && let Some(pos) = self.station.as_ref().map(|s| s.pos) + { + self.grindstone_taken(pos, amount); + } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self .container diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index bf71af641..54bf872ae 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -90,6 +90,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, trade: None, } } diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index b2b0c21aa..5cae6d6e9 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -35,6 +35,7 @@ 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), _ => return None, }) } @@ -94,6 +95,9 @@ impl Game<'_> { { self.guest_menu_op(host, gi, &mut gs.menu, op); self.lan_station_sounds(&mut gs); + if let Some(amount) = gs.menu.ground.take() { + self.grindstone_taken(gs.pos, amount); + } } host.play.entry(conn).or_default().station = Some(gs); self.lan_send_station(host, conn); diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 7036b60eb..a3a33c019 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -256,6 +256,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, 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 f7c00c998..4000fa64c 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -280,6 +280,7 @@ impl Game<'_> { brewing: &self.res.stations().brewing, banners: &self.res.stations().banners, station_recipes: &self.res.stations().recipes, + enchantments: &self.res.stations().enchantments, 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 686e59430..5c6ebb86f 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -493,6 +493,34 @@ impl Game<'_> { if let Some(Component::Int(id)) = s.component(component::MAP_ID) { out.data_mut().map_id = Some(*id); } + if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) { + out.data_mut().repair_cost = (*cost).max(0) as u32; + } + if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + out.data_mut().custom_name = Some(plain(name, &lang)); + } + // The enchantments by the server's registry ids. + let levels = |list: &[(i32, i32)]| -> Vec<(Arc, u32)> { + let names = self.remote.as_ref().map(|r| &r.registries); + list.iter() + .filter_map(|(id, level)| { + let name = names?.name("minecraft:enchantment", *id)?; + Some((Arc::from(name), (*level).max(0) as u32)) + }) + .collect() + }; + if let Some(Component::Enchantments(list)) = s.component(component::ENCHANTMENTS) { + out.data_mut().enchantments = levels(list); + } + if let Some(Component::Enchantments(list)) = s.component(component::STORED_ENCHANTMENTS) { + out.data_mut().stored_enchantments = levels(list); + } + out.tidy(); Some(out) } fn to_network(&self, s: &Option) -> Option { @@ -1237,6 +1265,7 @@ impl Game<'_> { Some(match menu { "minecraft:loom" => Kind::Loom, "minecraft:stonecutter" => Kind::Stonecutter, + "minecraft:grindstone" => Kind::Grindstone, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index 62a0238dd..643df30db 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -51,7 +51,7 @@ impl Game<'_> { if !self .station .as_ref() - .is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter)) + .is_some_and(|s| matches!(s.kind, Kind::Loom | Kind::Stonecutter | Kind::Grindstone)) { return; } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 30280d034..04104c9b3 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -531,7 +531,6 @@ impl Game<'_> { 64, ), Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), - Kind::Grindstone => (stations::grindstone_accepts(self.res.items(), stack), 64), Kind::Smithing => (data.recipes.smithing_accepts(i, stack), 64), _ => (true, 64), } @@ -692,13 +691,6 @@ impl Game<'_> { self.move_to(&mut stack, &halves, false); } } - Kind::Grindstone => { - if empty(self, 0) || empty(self, 1) { - self.move_to(&mut stack, &[INPUT, INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } - } Kind::Cartography => { if super::maps::map_id(&stack).is_some() { self.move_to(&mut stack, &[INPUT], false); @@ -724,7 +716,7 @@ impl Game<'_> { self.move_to(&mut stack, targets, false); } // Their clicks run on the menu engine. - Kind::Merchant | Kind::Loom | Kind::Stonecutter => {} + Kind::Merchant | Kind::Loom | Kind::Stonecutter | Kind::Grindstone => {} } } let moved = stack.count != start; @@ -733,6 +725,17 @@ impl Game<'_> { } moved } + /// 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 + /// for everyone around. + pub(super) fn grindstone_taken(&mut self, pos: [i32; 3], amount: i32) { + let xp = stations::grindstone_xp_roll(amount, &mut self.world.random); + if xp > 0 { + self.spawn_orbs(pos.map(|v| f64::from(v) + 0.5), xp); + } + self.level_event_at(1042, pos, 0); + } fn play_at(&mut self, sound: &str, pos: [i32; 3], volume: f32, pitch: f32) { let at = [ f64::from(pos[0]) + 0.5, @@ -826,28 +829,6 @@ impl Game<'_> { self.play_at("minecraft:block.anvil.use", pos, 1.0, pitch); } } - Kind::Grindstone => { - let (a, b) = (s.inputs[0].take(), s.inputs[1].take()); - let mut random = LegacyRandom::new(self.world.random.next_long()); - let xp = stations::grindstone_experience( - &self.res.stations().enchantments, - &mut random, - a.as_ref(), - b.as_ref(), - ); - if xp > 0 { - self.spawn_orbs( - [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ], - xp, - ); - } - let pitch = self.world.random.next_float() * 0.1 + 0.9; - self.play_at("minecraft:block.grindstone.use", pos, 1.0, pitch); - } Kind::Smithing => { for slot in s.inputs.iter_mut() { if let Some(x) = slot.as_mut() { @@ -860,7 +841,7 @@ impl Game<'_> { 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::Merchant | Kind::Stonecutter | Kind::Grindstone => {} Kind::Beacon => {} Kind::Cartography => { for slot in &mut s.inputs { @@ -1066,12 +1047,13 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; - if self - .station - .as_ref() - .is_none_or(|s| matches!(s.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter)) - { - // LoomMenu, MerchantMenu, StonecutterMenu and the brewing stand's + if self.station.as_ref().is_none_or(|s| { + matches!( + s.kind, + Kind::Loom | Kind::Merchant | Kind::Stonecutter | Kind::Grindstone + ) + }) { + // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu and the brewing stand's // BrewingStandMenu clicks run on the verified menu engine. let input = if shift { horizon_client::menu::Input::QuickMove diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index f46e37abc..814c7a15d 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -418,6 +418,12 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(id), )); } + if d.repair_cost > 0 { + stack.added.push(( + horizon_protocol::item::component::REPAIR_COST, + horizon_protocol::item::Component::Int(d.repair_cost as i32), + )); + } } if let Some(name) = s.custom_name() { stack.added.push(( diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 6c2250f0b..0e85d92dd 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -26,6 +26,8 @@ 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. + pub enchantments: &'a crate::enchant::Enchantments, /// What a merchant menu needs for offers made while it is open (level-ups). pub trade: Option<&'a crate::merchant::TradeEnv<'a>>, } @@ -75,6 +77,8 @@ pub enum Kind { Loom, /// `StonecutterMenu`: the input, the result, then the inventory. Stonecutter, + /// `GrindstoneMenu`: two inputs, the result, then the inventory. + Grindstone, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -101,6 +105,7 @@ impl Kind { "crafter_be" => Self::CrafterBlock, "loom" => Self::Loom, "stonecutter" => Self::Stonecutter, + "grindstone" => Self::Grindstone, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -140,6 +145,10 @@ enum Role { MerchantResult, /// The stonecutter's result slot (`onTake` uses up one input). StoneResult, + /// The grindstone's inputs: damageable or enchanted items. + GrindInput, + /// The grindstone's result slot (`onTake` clears both inputs). + GrindResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -191,6 +200,10 @@ pub struct Menu { pub merchant: Option>, /// The stonecutter's recipe list (`recipesForInput`). pub stone: Stonecutter, + /// The grindstone result's `getExperienceAmount` sum before its roll, + /// set when the result was taken: the caller (with a level) awards the + /// orbs and plays level event 1042. + pub ground: Option, } /// `StonecutterMenu`'s state besides its slots and `selectedRecipeIndex`. @@ -350,6 +363,16 @@ impl Menu { // selectedRecipeIndex: DataSlot.standalone() starts at 0. data = 1; } + Kind::Grindstone => { + containers[MAIN] = vec![None; 2]; + slots.extend(main(2, Role::GrindInput)); + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::GrindResult, + }); + player(&mut slots); + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -436,6 +459,7 @@ impl Menu { equipped: Vec::new(), merchant: None, stone: Stonecutter::default(), + ground: None, } } @@ -603,6 +627,15 @@ impl Menu { match self.kind { Kind::Loom => self.loom_changed(env), Kind::Stonecutter => self.stone_changed(env), + // GrindstoneMenu.createResult. + Kind::Grindstone => { + self.containers[RESULT][0] = crate::stations::grindstone_result( + env.enchantments, + env.items, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ); + } Kind::CrafterBlock => self.crafter_result(env), _ => {} } @@ -714,7 +747,10 @@ impl Menu { Role::LoomBanner => Self::is_banner(stack), Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), - Role::LoomResult | Role::MerchantResult | Role::StoneResult => false, + Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), + Role::LoomResult | Role::MerchantResult | Role::StoneResult | Role::GrindResult => { + false + } } } @@ -843,7 +879,12 @@ impl Menu { } // SimpleContainer.removeItem calls setChanged when it took something; // MerchantContainer.removeItem updates the result after a payment slot. - if out.is_some() && matches!(self.kind, Kind::Loom | Kind::Merchant | Kind::Stonecutter) { + if out.is_some() + && matches!( + self.kind, + Kind::Loom | Kind::Merchant | Kind::Stonecutter | Kind::Grindstone + ) + { self.slot_changed(env, s); } out @@ -880,6 +921,18 @@ impl Menu { self.sounds.push("minecraft:ui.stonecutter.take_result"); return; } + if self.slots[s].role == Role::GrindResult { + // GrindstoneMenu's result onTake: the experience (from the inputs + // before they go), then both inputs cleared. + self.ground = Some(crate::stations::grindstone_xp_base( + env.enchantments, + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + )); + self.put(env, 0, None); + self.put(env, 1, None); + 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); @@ -1352,6 +1405,31 @@ impl Menu { return None; } } + Kind::Grindstone => { + after_take = true; + let full = self.containers[MAIN].iter().all(Option::is_some); + if index == 2 { + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if full { + if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) + && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } else if !self.move_to(env, &mut stack, 0, 2, false) { + return None; + } + } Kind::Merchant => { after_take = true; if index == 2 { @@ -2148,12 +2226,14 @@ pub(crate) mod tests { let brewing = Brewing::load(&root, &items); let banners = Banners::load(&root); let station_recipes = crate::stations::StationRecipes::load(&root, &items); + let enchantments = crate::enchant::Enchantments::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, banners: &banners, station_recipes: &station_recipes, + enchantments: &enchantments, 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 2fdeeb860..eb0a20a02 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -401,13 +401,13 @@ pub fn grindstone_result( (None, None) => None, } } -/// Experience from the grindstone result slot's `getExperienceAmount`. -pub fn grindstone_experience( +/// The grindstone result slot's `getExperienceAmount` before its roll: the +/// minimum costs of the inputs' non-curse enchantments. +pub fn grindstone_xp_base( e: &Enchantments, - random: &mut LegacyRandom, input: Option<&ItemStack>, additional: Option<&ItemStack>, -) -> u32 { +) -> i32 { let from = |s: Option<&ItemStack>| -> i32 { s.map_or(0, |s| { s.crafting_enchantments() @@ -417,7 +417,10 @@ pub fn grindstone_experience( .sum() }) }; - let amount = from(input) + from(additional); + from(input) + from(additional) +} +/// `getExperienceAmount`'s roll of the sum: `half + nextInt(half)`. +pub fn grindstone_xp_roll(amount: i32, random: &mut LegacyRandom) -> u32 { if amount > 0 { let half = (f64::from(amount) / 2.0).ceil() as i32; (half + random.next_int_bound(half).unwrap_or(0)) as u32 @@ -425,6 +428,15 @@ pub fn grindstone_experience( 0 } } +/// Experience from the grindstone result slot's `getExperienceAmount`. +pub fn grindstone_experience( + e: &Enchantments, + random: &mut LegacyRandom, + input: Option<&ItemStack>, + additional: Option<&ItemStack>, +) -> u32 { + grindstone_xp_roll(grindstone_xp_base(e, input, additional), random) +} // ---------------------------------------------------------------- smithing & stonecutting 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 aaa6a0677..c05f92322 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -179,6 +179,7 @@ public final class VanillaMenuOracle { } case "loom" -> new LoomMenu(0, inv); case "stonecutter" -> new StonecutterMenu(0, inv); + case "grindstone" -> new GrindstoneMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 20e5062bb..fd899e6c6 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -42,6 +42,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - stonecutter: a stonecutter opens on the guest's screen with the recipes of the stone the guest puts in; the guest picks the slab and shift-clicks the result, and the server has cut every stone into slabs (#868); +- 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); - 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; @@ -136,7 +139,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', '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', '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: @@ -993,6 +996,51 @@ def check_stonecutter(host, guest, out): return seen +def server_reply(guest, command, *needles): + """The first chat line holding every needle after the guest runs `command`.""" + since = guest.raw('events')['last'] + guest('command', command=command) + for _ in range(0, 65): + reply = guest.raw('events', '--since', since) + for e in reply['events']: + line = e.get('text', '') + if e.get('event') == 'chat' and all(n in line for n in needles): + return line + guest.wait(2) + raise Failed(f'no answer to {command}') + + +def check_grindstone(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='xp set @s 0 levels') + guest('command', command='xp set @s 0 points') + guest('command', command='give @s minecraft:iron_sword[minecraft:enchantments={"minecraft:sharpness":3,' + '"minecraft:vanishing_curse":1},minecraft:damage=100]') + at = open_station(guest, 'grindstone', out, 'grindstone') + # GrindstoneMenu.quickMoveStack: with both inputs empty, into the first. + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:iron_sword'), 'shift') + guest.wait(10) + loaded = station_slots(guest) + guest.shot(out, 'grindstone-result') + guest.raw('click-slot', 650, 'shift') + # The orbs (sharpness III: 12 to 23 points) fly to the guest. + guest.wait(60) + left = station_slots(guest) + close_station(guest, at) + sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components', + 'minecraft:damage') + xp = server_reply(guest, 'xp query @s points', 'experience points') + seen = {'loaded': loaded, 'left': left, 'curse kept': 'vanishing_curse' in sword, + 'sharpness gone': 'sharpness' not in sword, + 'damage': re.search(r'minecraft:damage"?: 100\b', sword) is not None, + 'xp': int(re.search(r'has (\d+) experience', xp).group(1)) > 0} + want = {'loaded': {600: ('minecraft:iron_sword', 1), 650: ('minecraft:iron_sword', 1)}, 'left': {}, + 'curse kept': True, 'sharpness gone': True, 'damage': True, 'xp': True} + assert seen == want, f'the grindstone on the guest: {seen} ({sword!r}, {xp!r})' + 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']: @@ -2186,6 +2234,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'brewing': check_brewing, 'loom': check_loom, 'stonecutter': check_stonecutter, + 'grindstone': check_grindstone, '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 d4b7e86be..357ad94da 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -11,7 +11,8 @@ item the first click moved) over the player inventory, 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) and the +stonecutter (with its recipe buttons), the grindstone (enchanted, damaged and +cursed tools and books) 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. @@ -27,7 +28,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, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, '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} @@ -45,6 +46,10 @@ COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_i # Stonecutter inputs (several recipes each), and a block it doesn't cut. CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sandstone', 'quartz_block', 'deepslate', 'stone_bricks', 'oak_planks'] +# Grindstone inputs: tools and armor, books, and their enchantments (curses too). +GRINDABLE = ['iron_sword', 'diamond_pickaxe', 'bow', 'iron_helmet', 'elytra', 'shield', 'fishing_rod', 'trident'] +ENCHANTS = ['sharpness', 'unbreaking', 'mending', 'efficiency', 'protection', 'power', 'looting', 'fortune', + 'binding_curse', 'vanishing_curse'] def quote(text): @@ -109,6 +114,33 @@ class Gen: return snbt('minecraft:' + rng.choice(CUTTABLE), rng.choice([1, 1, 2, 3, 10, 63, 64])) return self.stack() + def grind_stack(self): + """Mostly an enchanted or damaged tool or an enchanted book, sometimes anything.""" + rng = self.rng + roll = rng.random() + if roll > 0.8: + return self.stack() + levels = ','.join('"minecraft:%s":%d' % (e, rng.randrange(1, 4)) + for e in rng.sample(ENCHANTS, rng.choice([0, 1, 1, 2, 3]))) + comps = [] + if roll < 0.25: + item = 'minecraft:' + rng.choice(['enchanted_book', 'enchanted_book', 'book']) + if levels: + comps.append('"minecraft:stored_enchantments":{%s}' % levels) + count = 1 if rng.random() < 0.85 else 2 + else: + item = 'minecraft:' + rng.choice(GRINDABLE) + info = self.items.get(item, {}) + if levels: + comps.append('"minecraft:enchantments":{%s}' % levels) + if info.get('minecraft:max_damage') and rng.random() < 0.6: + comps.append('"minecraft:damage":%d' % rng.randrange(0, info['minecraft:max_damage'])) + count = 1 + if rng.random() < 0.2: + comps.append('"minecraft:repair_cost":%d' % rng.choice([1, 3, 7])) + body = ',components:{%s}' % ','.join(comps) if comps else '' + return '{id:%s,count:%d%s}' % (quote(item), count, body) + def recipe(self, slots, width, start=1): """Fills the crafting grid (slots `start`..) with a small known recipe.""" rng = self.rng @@ -142,6 +174,9 @@ 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 == 'grindstone' and rng.random() < 0.2: + out.append([2, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP'])]) + continue if menu == 'crafter_be' and rng.random() < 0.2: out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE']) continue @@ -208,6 +243,16 @@ def main(): slots[0] = g.cut_stack() if rng.random() < 0.8 else '-' # The result follows the input and the selected recipe; a fixture stack there is rare. slots[1] = '-' if rng.random() < 0.9 else g.cut_stack() + if menu == 'grindstone': + for i in rng.sample(range(3, size), 10): + slots[i] = g.grind_stack() + slots[0] = g.grind_stack() if rng.random() < 0.7 else '-' + slots[1] = g.grind_stack() if rng.random() < 0.6 else '-' + # Two of the same tool, so mergeItems runs. + if slots[0] != '-' and rng.random() < 0.3: + 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 == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -236,7 +281,7 @@ 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}.get(menu, g.stack)() if rng.random() < 0.5 else '-' + carried = {'loom': g.loom_stack, 'stonecutter': g.cut_stack, 'grindstone': g.grind_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, 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 4/8] 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)) From b5a92262c8cc69bb5e5d783694ad327878a30f5b Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 06:42:47 +0200 Subject: [PATCH 5/8] Enchanting table on the menu engine; LAN guests enchant EnchantmentMenu now runs on horizon_client::menu: the item slot (one item) and the lapis slot, its quickMoveStack, slotsChanged clearing the offers without an enchantable item, and clickMenuButton's checks against the costs, lapis and levels, verified against the vanilla class by test_menu_click_parity (with its ten data slots and the offer buttons; the oracle's player now has a profile for the invalid-button log line). The offers and the enchanting itself, which need a level, stay with the caller. Single player routes the table's clicks, drags and double clicks through the engine. The LAN host opens minecraft:enchantment for guests with their own enchantment seed (saved with their player data), sends the costs, seed and clues as data slots, and on ContainerButtonClick enchants the item, takes the guest's level and lapis and gives a new seed. Guests show the server's offers and send the button the client menu accepts. Part of #868. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 22 ++++ .../horizon-client/src/game/lan_crafting.rs | 2 +- .../horizon-client/src/game/lan_stations.rs | 87 ++++++++++++- crates/horizon-client/src/game/remote.rs | 1 + .../src/game/remote_stations.rs | 18 +++ crates/horizon-client/src/game/stations.rs | 38 +++--- crates/horizon-client/src/lan/guest.rs | 3 + crates/horizon-client/src/lan/playerdata.rs | 2 + crates/horizon-client/src/menu.rs | 116 +++++++++++++++++- .../horizonlab/parity/VanillaMenuOracle.java | 3 + tools/lan_e2e.py | 35 +++++- tools/test_menu_click_parity.py | 23 +++- 12 files changed, 326 insertions(+), 24 deletions(-) diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 2056e52ed..dec8588eb 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5438,6 +5438,7 @@ impl Game<'_> { 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 enchanting_open = station_kind == Some(stations::Kind::Enchanting); 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]; @@ -5478,6 +5479,11 @@ impl Game<'_> { ]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Grindstone, v) + } else if enchanting_open { + // EnchantmentMenu: the item, the lapis, then the inventory. + let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Enchanting, v) } else if anvil_open || smithing_open { // ItemCombinerMenu: the inputs, the result, then the inventory. let inputs = if anvil_open { 2 } else { 3 }; @@ -5647,6 +5653,17 @@ impl Game<'_> { menu.stone = state; menu.set_slot(&env, 1, before[1].clone()); } + if kind == Kind::Enchanting + && let Some(s) = self.station.as_ref() + { + // The offers between clicks (what copying the slots in flagged is not a change). + menu.enchant_changed = false; + for i in 0..3 { + menu.data[i] = s.offers.costs[i]; + menu.data[7 + i] = s.offers.clues[i].as_ref().map_or(-1, |(_, l)| *l as i32); + } + menu.data[3] = self.level.xp_seed; + } if let Some((disabled, triggered)) = crafter_data { for (i, d) in disabled.iter().enumerate() { menu.data[i] = i32::from(*d); @@ -5724,6 +5741,11 @@ impl Game<'_> { if kind == Kind::Anvil || kind == Kind::Smithing { self.combiner_session_end(&menu, predicting); } + if kind == Kind::Enchanting && (menu.enchant_changed || before[0] != menu.slot(0).cloned()) + { + // EnchantmentMenu.slotsChanged: new offers for the item. + self.station_changed(); + } if kind == Kind::CrafterBlock && let Some(BlockEntity::Crafter(c)) = self .container diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 9c0cce1fe..96dc99c14 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -84,7 +84,7 @@ fn place_back(menu: &mut Menu, env: &Env, stacks: Vec) { } impl Game<'_> { - fn menu_env(&self) -> Env<'_> { + pub(super) fn menu_env(&self) -> Env<'_> { Env { items: self.res.items(), recipes: self.res.recipes(), diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 8d31ba05e..5dfb79752 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -14,6 +14,7 @@ use horizon_client::{ items::ItemStack, menu::{Kind, Menu}, }; +use horizon_core::random::RandomSource; use horizon_protocol::packets::play::{self, Clientbound as C}; /// A guest's open workstation menu. @@ -38,6 +39,7 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:grindstone", Kind::Grindstone, 0..2), StationKind::Anvil => ("minecraft:anvil", Kind::Anvil, 0..2), StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), + StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), _ => return None, }) } @@ -62,12 +64,22 @@ impl Game<'_> { let Some(window) = host.hub.open_window(conn, menu_type, title) else { return true; }; + let mut menu = Box::new(Menu::new(kind)); + if let Some(g) = host.hub.guests.iter_mut().find(|g| g.conn == conn) + && kind == Kind::Enchanting + { + // Player.enchantmentSeed, made when first needed. + if g.xp_seed == 0 { + g.xp_seed = self.world.random.next_int(); + } + menu.data[3] = g.xp_seed; + } host.play.entry(conn).or_default().station = Some(GuestStation { window, state: 0, kind: station.kind, pos: station.pos, - menu: Box::new(Menu::new(kind)), + menu, sent_data: Vec::new(), last_sound: 0, }); @@ -101,6 +113,12 @@ impl Game<'_> { self.grindstone_taken(gs.pos, amount); } self.lan_station_combined(host, conn, &mut gs); + if let Some(button) = gs.menu.enchant_button.take() { + self.lan_enchant(host, gi, &mut gs, button); + } + if std::mem::take(&mut gs.menu.enchant_changed) { + self.lan_enchant_offers(host, gi, &mut gs); + } } host.play.entry(conn).or_default().station = Some(gs); self.lan_send_station(host, conn); @@ -127,6 +145,73 @@ impl Game<'_> { } } + /// `EnchantmentMenu.slotsChanged` with a level: the costs and clues for + /// the guest's seed and the bookshelves around the table. + fn lan_enchant_offers(&mut self, host: &LanHost, gi: usize, gs: &mut GuestStation) { + let seed = host.hub.guests[gi].xp_seed; + let bookcases = self.count_bookshelves(gs.pos); + let offers = horizon_client::stations::enchant_offers( + &self.res.stations().enchantments, + self.res.items(), + seed, + bookcases, + gs.menu.slot(0), + ); + for i in 0..3 { + gs.menu.data[i] = offers.costs[i]; + let clue = offers.clues[i].as_ref(); + gs.menu.data[4 + i] = clue + .and_then(|(e, _)| host.hub.registry_id("minecraft:enchantment", e)) + .unwrap_or(-1); + gs.menu.data[7 + i] = clue.map_or(-1, |(_, l)| *l as i32); + } + gs.menu.data[3] = seed; + } + + /// `EnchantmentMenu.clickMenuButton`'s `access.execute`: the item gets + /// the offer's enchantments, the guest pays its levels and lapis and + /// gets a new seed, the table sounds, and the offers are made again. + fn lan_enchant(&mut self, host: &mut LanHost, gi: usize, gs: &mut GuestStation, button: usize) { + let Some(item) = gs.menu.slot(0).cloned() else { + return; + }; + let g = &host.hub.guests[gi]; + let (seed, creative, conn) = (g.xp_seed, g.creative(), g.conn); + let Some(enchanted) = horizon_client::stations::apply_enchantment( + &self.res.stations().enchantments, + self.res.items(), + seed, + button, + gs.menu.data[button], + &item, + ) else { + return; + }; + let need = button as i32 + 1; + // Player.onEnchantmentPerformed. + self.as_guest(host, conn, |game| game.give_levels(-need)); + host.hub.guests[gi].xp_seed = self.world.random.next_int(); + let env = self.menu_env(); + let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| { + l.count = l.count.saturating_sub(need as u32); + l + }); + gs.menu.set_slot(&env, 0, Some(enchanted)); + if !creative { + gs.menu.set_slot(&env, 1, lapis.filter(|l| l.count > 0)); + } + gs.menu.enchant_changed = false; + self.lan_enchant_offers(host, gi, gs); + let pitch = self.world.random.next_float() * 0.1 + 0.9; + let at = gs.pos.map(|v| f64::from(v) + 0.5); + self.audio.play( + "minecraft:block.enchantment_table.use", + Some(at), + 1.0, + pitch, + ); + } + /// `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) { diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ebd1e2e58..ed900ebf9 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1268,6 +1268,7 @@ impl Game<'_> { "minecraft:grindstone" => Kind::Grindstone, "minecraft:anvil" => Kind::Anvil, "minecraft:smithing" => Kind::Smithing, + "minecraft:enchantment" => Kind::Enchanting, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index fd5dc42aa..52e60ed76 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -79,6 +79,24 @@ impl Game<'_> { (Kind::Stonecutter, 0) => s.selected = usize::try_from(value).ok(), // AnvilMenu.cost. (Kind::Anvil, 0) => s.anvil.cost = i32::from(value), + // EnchantmentMenu: costs, the seed (the screen's glyph names), + // the clues' enchantments and levels. + (Kind::Enchanting, 0..3) => s.offers.costs[id] = i32::from(value), + (Kind::Enchanting, 3) => self.level.xp_seed = i32::from(value), + (Kind::Enchanting, 4..7) => { + let name = self.remote.as_ref().and_then(|r| { + r.registries + .name("minecraft:enchantment", i32::from(value)) + .map(std::sync::Arc::::from) + }); + let level = s.offers.clues[id - 4].as_ref().map_or(1, |(_, l)| *l); + s.offers.clues[id - 4] = name.map(|n| (n, level)); + } + (Kind::Enchanting, 7..10) => { + if let Some((_, level)) = s.offers.clues[id - 7].as_mut() { + *level = value.max(0) as u32; + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index ed114419e..7820bd88b 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -131,7 +131,7 @@ pub(super) struct Station { pub(super) pos: [i32; 3], pub(super) inputs: Vec>, pub(super) result: Option, - offers: EnchantOffers, + pub(super) offers: EnchantOffers, bookcases: i32, pub(super) anvil: AnvilResult, /// Anvil rename box text. @@ -391,7 +391,7 @@ impl Game<'_> { _ => &mut self.scratch_slot, } } - fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { + pub(super) fn count_bookshelves(&self, pos: [i32; 3]) -> i32 { let tags = &self.res.items().block_tags; let is = |p: [i32; 3], tag: &str| { let name = &self @@ -435,6 +435,16 @@ impl Game<'_> { let data = self.res.stations(); let items = self.res.items(); match s.kind { + // A server's table: its data slots carry the offers, and its + // client menu only clears them without an enchantable item. + Kind::Enchanting if self.remote.is_some() => { + let enchantable = s.inputs[0].as_ref().is_some_and(|i| { + data.enchantments.enchantable(&i.item) > 0 && i.enchantments().is_empty() + }); + if !enchantable { + s.offers = Default::default(); + } + } Kind::Enchanting => { s.bookcases = self.count_bookshelves(s.pos); s.offers = stations::enchant_offers( @@ -521,7 +531,6 @@ impl Game<'_> { } let i = slot - INPUT; match s.kind { - Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), Kind::Loom => (false, 64), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), @@ -532,7 +541,6 @@ impl Game<'_> { ), 64, ), - Kind::Enchanting => (&*stack.item == "minecraft:lapis_lazuli", 64), _ => (true, 64), } } @@ -669,21 +677,10 @@ impl Game<'_> { if slot >= INPUT { // An input slot: into the inventory, the hotbar's last slot first // where vanilla moves in reverse. - let reverse = matches!(kind, Kind::Enchanting | Kind::Beacon); + let reverse = kind == Kind::Beacon; self.move_to(&mut stack, &Self::player_slots(), reverse); } else { match kind { - Kind::Enchanting => { - if &*stack.item == "minecraft:lapis_lazuli" { - self.move_to(&mut stack, &[INPUT + 1], true); - } else if empty(self, 0) { - *self.station_slot_mut(INPUT) = Some(ItemStack { - count: 1, - ..stack.clone() - }); - stack.count -= 1; - } - } Kind::Beacon => { if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1 { @@ -710,7 +707,8 @@ impl Game<'_> { | Kind::Stonecutter | Kind::Grindstone | Kind::Anvil - | Kind::Smithing => {} + | Kind::Smithing + | Kind::Enchanting => {} } } let moved = stack.count != start; @@ -940,6 +938,11 @@ impl Game<'_> { { return; } + if self.remote.is_some() { + // EnchantmentScreen.mouseClicked: the client menu took it, the server enchants. + self.remote_station_button(button as i32); + return; + } let Some(enchanted) = stations::apply_enchantment( &self.res.stations().enchantments, self.res.items(), @@ -1058,6 +1061,7 @@ impl Game<'_> { | Kind::Grindstone | Kind::Anvil | Kind::Smithing + | Kind::Enchanting ) }) { // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu, AnvilMenu, diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 814c7a15d..8440fac6c 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -147,6 +147,8 @@ pub struct Guest { pub xp_level: i32, pub xp_progress: f32, pub xp_total: i32, + /// `Player.enchantmentSeed` (the enchanting table's offers). + pub xp_seed: i32, /// Active status effects (`LivingEntity.activeEffects`). pub effects: crate::effects::PlayerEffects, /// What the client was told of each effect: id, amplifier, flags, and @@ -273,6 +275,7 @@ impl Guest { xp_level: 0, xp_progress: 0.0, xp_total: 0, + xp_seed: 0, effects: Default::default(), sent_effects: Vec::new(), menu_sent: vec![None; 46], diff --git a/crates/horizon-client/src/lan/playerdata.rs b/crates/horizon-client/src/lan/playerdata.rs index d7dc097dd..8797f25a2 100644 --- a/crates/horizon-client/src/lan/playerdata.rs +++ b/crates/horizon-client/src/lan/playerdata.rs @@ -66,6 +66,7 @@ pub fn apply(guest: &mut Guest, level: &Level) { guest.xp_level = level.xp_level; guest.xp_progress = level.xp_progress; guest.xp_total = level.xp_total; + guest.xp_seed = level.xp_seed; guest.effects = crate::effects::PlayerEffects::from_saved(&level.active_effects); guest.game_mode = level.mode(); guest.flying = level.flying; @@ -127,6 +128,7 @@ pub fn store(guest: &Guest, level: &mut Level) { level.xp_level = guest.xp_level; level.xp_progress = guest.xp_progress; level.xp_total = guest.xp_total; + level.xp_seed = guest.xp_seed; level.active_effects = guest.effects.saved(); level.game_mode = guest.game_mode; level.creative = guest.game_mode == 1; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 510a7c7aa..c4354b184 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -86,6 +86,9 @@ pub enum Kind { Anvil, /// `SmithingMenu`: template, base, addition, the result, then the inventory. Smithing, + /// `EnchantmentMenu`: the item, the lapis, then the inventory; its data + /// slots are the three costs, the seed and the clues. + Enchanting, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -115,6 +118,7 @@ impl Kind { "grindstone" => Self::Grindstone, "anvil" => Self::Anvil, "smithing" => Self::Smithing, + "enchanting" => Self::Enchanting, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -162,6 +166,10 @@ enum Role { SmithInput(usize), /// `ItemCombinerMenu`'s result slot (the anvil's and the smithing table's). CombineResult, + /// The enchanting table's item slot (one item). + EnchantItem, + /// The enchanting table's lapis slot. + Lapis, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -227,6 +235,13 @@ pub struct Menu { /// 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, + /// The enchanting table's item changed to an enchantable one: the caller + /// (with a level) fills the costs and clues (`slotsChanged`'s + /// `access.execute`). + pub enchant_changed: bool, + /// An enchanting button the menu took (`clickMenuButton` passed its + /// checks): the caller (with a level) enchants. + pub enchant_button: Option, } /// `AnvilMenu`'s state besides its slots and `cost`. @@ -435,6 +450,22 @@ impl Menu { // hasRecipeError. data = 1; } + Kind::Enchanting => { + containers[MAIN] = vec![None; 2]; + slots.push(Slot { + container: MAIN, + index: 0, + role: Role::EnchantItem, + }); + slots.push(Slot { + container: MAIN, + index: 1, + role: Role::Lapis, + }); + player(&mut slots); + // costs[3], enchantmentSeed, enchantClue[3], levelClue[3]. + data = 10; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -526,7 +557,18 @@ impl Menu { level_change: 0, anvil: Anvil::default(), combined: false, + enchant_changed: false, + enchant_button: None, } + .with_initial_data() + } + + /// Data slots that do not start at 0: the enchanting table's clues are -1. + fn with_initial_data(mut self) -> Self { + if self.kind == Kind::Enchanting { + self.data[4..].fill(-1); + } + self } pub fn kind(&self) -> Kind { @@ -536,6 +578,9 @@ impl Menu { /// `clickMenuButton`: the loom's pattern buttons and the stonecutter's /// recipes. False when refused. pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind == Kind::Enchanting { + return self.enchant_click(id); + } if self.kind == Kind::Stonecutter { // StonecutterMenu.clickMenuButton: an invalid index is taken too. if self.data[0] == id { @@ -709,6 +754,7 @@ impl Menu { } Kind::CrafterBlock => self.crafter_result(env), Kind::Anvil => self.anvil_result(env), + Kind::Enchanting => self.enchant_changed(env), Kind::Smithing => { self.smith_result(env); self.smith_error(); @@ -717,6 +763,44 @@ impl Menu { } } + /// `EnchantmentMenu.clickMenuButton`'s checks: the lapis, the cost and + /// the levels (creative pays nothing). The enchanting itself needs a + /// level and is the caller's (`enchant_button`). + fn enchant_click(&mut self, id: i32) -> bool { + let Some(i) = usize::try_from(id).ok().filter(|&i| i < 3) else { + return false; + }; + let need = id + 1; + let lapis = self.containers[MAIN][1] + .as_ref() + .map_or(0, |l| l.count as i32); + if lapis < need && !self.creative { + return false; + } + if self.data[i] <= 0 + || self.containers[MAIN][0].is_none() + || (self.levels < need || self.levels < self.data[i]) && !self.creative + { + return false; + } + self.enchant_button = Some(i); + true + } + + /// `EnchantmentMenu.slotsChanged`: no costs or clues without an + /// enchantable item; with one, a level fills them (`enchant_changed`). + fn enchant_changed(&mut self, env: &Env) { + let enchantable = self.containers[MAIN][0].as_ref().is_some_and(|s| { + env.enchantments.enchantable(&s.item) > 0 && s.enchantments().is_empty() + }); + if enchantable { + self.enchant_changed = true; + } else { + self.data[..3].fill(0); + self.data[4..].fill(-1); + } + } + /// `AnvilMenu.createResult`. fn anvil_result(&mut self, env: &Env) { let hover = self.containers[MAIN][0] @@ -887,6 +971,8 @@ impl Menu { Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), Role::GrindInput => crate::stations::grindstone_accepts(env.items, stack), Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), + Role::EnchantItem => true, + Role::Lapis => &*stack.item == "minecraft:lapis_lazuli", Role::LoomResult | Role::MerchantResult | Role::StoneResult @@ -931,7 +1017,7 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) | Role::Potion => 1, + Role::Armor(_) | Role::Potion | Role::EnchantItem => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -1033,6 +1119,7 @@ impl Menu { | Kind::Grindstone | Kind::Anvil | Kind::Smithing + | Kind::Enchanting ) { self.slot_changed(env, s); @@ -1625,6 +1712,33 @@ impl Menu { return None; } } + Kind::Enchanting => { + after_take = true; + if index < 2 { + if !self.move_to(env, &mut stack, 2, 38, true) { + return None; + } + } else if &*stack.item == "minecraft:lapis_lazuli" { + if !self.move_to(env, &mut stack, 1, 2, true) { + return None; + } + } else { + // One item into the empty item slot (setByPlayer). + if self.containers[MAIN][0].is_some() { + return None; + } + let single = ItemStack { + count: 1, + ..stack.clone() + }; + stack.count -= 1; + // The source slot keeps the rest while the item slot changes. + let slot = self.slots[index]; + self.containers[slot.container][slot.index] = + (stack.count > 0).then(|| stack.clone()); + self.set_by_player(env, 0, Some(single)); + } + } Kind::Anvil | Kind::Smithing => { // ItemCombinerMenu.quickMoveStack. after_take = true; 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 d55417e7c..5a3db5977 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -182,6 +182,7 @@ public final class VanillaMenuOracle { case "grindstone" -> new GrindstoneMenu(0, inv); case "anvil" -> new AnvilMenu(0, inv); case "smithing" -> new SmithingMenu(0, inv); + case "enchanting" -> new EnchantmentMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } @@ -231,6 +232,8 @@ public final class VanillaMenuOracle { 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); + // EnchantmentMenu.clickMenuButton names the player on an invalid button. + set(player, Player.class, "gameProfile", new com.mojang.authlib.GameProfile(new java.util.UUID(0, 1), "Oracle")); player.experienceLevel = f.has("levels") ? f.get("levels").getAsInt() : 0; var inv = new Inventory(player, new EntityEquipment()); player.inv = inv; diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 10b654adb..958b80b4d 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -48,6 +48,9 @@ address. The script then checks, from both sides, what a guest's game used to ge - 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); +- enchanting: an enchanting table opens on the guest's screen with the server's offers for the + sword the guest puts in; the guest clicks the first offer and the server enchants the + sword for a level and a lapis (#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; @@ -144,7 +147,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', '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'] +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', 'enchanting', '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: @@ -1109,6 +1112,35 @@ def check_smithing(host, guest, out): return seen +def check_enchanting(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='xp set @s 30 levels') + guest('command', command='give @s minecraft:iron_sword') + guest('command', command='give @s minecraft:lapis_lazuli 3') + at = open_station(guest, 'enchanting_table', out, 'enchanting') + # EnchantmentMenu.quickMoveStack: the sword to the item slot, the lapis to its own. + for item in ('iron_sword', 'lapis_lazuli'): + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + guest.wait(10) + costs = guest.raw('menu')['info']['costs'] + guest.shot(out, 'enchanting-offers') + # EnchantmentScreen's first offer button (clickMenuButton 0). + guest.raw('click-gui', 110, 23) + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}]', 'iron_sword') + levels = server_reply(guest, 'xp query @s levels', 'experience levels') + seen = {'offered': costs[0] > 0, 'enchanted': 'minecraft:enchantments' in sword, + 'left': left.get(601), 'levels': int(re.search(r'has (\d+) experience', levels).group(1)), + 'lapis': server_count(guest, 'lapis_lazuli')} + want = {'offered': True, 'enchanted': True, 'left': ('minecraft:lapis_lazuli', 2), 'levels': 29, 'lapis': 2} + assert seen == want, f'the enchanting table on the guest: {seen} ({costs}, {sword!r})' + 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']: @@ -2305,6 +2337,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'grindstone': check_grindstone, 'anvil': check_anvil, 'smithing': check_smithing, + 'enchanting': check_enchanting, '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 06ba00dd9..41561fbb9 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -13,7 +13,8 @@ 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), the anvil (repairs, enchantment merges and renames, -with the player's levels) and the smithing table (upgrades and trims) and the +with the player's levels), the smithing table (upgrades and trims), the +enchanting table (its button checks against the costs, lapis and levels) 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. @@ -29,9 +30,9 @@ 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, 'anvil': 39, 'smithing': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, '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, + 'stonecutter': 1, 'enchanting': 10, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] @@ -223,6 +224,10 @@ class Gen: 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 == 'enchanting' and rng.random() < 0.25: + # An offer button (clickMenuButton), sometimes out of range. + out.append([rng.choice([0, 1, 2, 2, 3, -1]), 0, 'BUTTON']) + 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 @@ -316,6 +321,14 @@ def main(): 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 == 'enchanting': + lapis = lambda: snbt('minecraft:lapis_lazuli', rng.choice([1, 2, 3, 5, 64])) + enchantable = lambda: snbt('minecraft:' + rng.choice(['iron_sword', 'book', 'diamond_pickaxe', 'bow', + 'golden_helmet', 'fishing_rod']), 1) + for i in rng.sample(range(2, size), 10): + slots[i] = rng.choice([lapis, enchantable, g.grind_stack])() + slots[0] = rng.choice([enchantable, enchantable, g.grind_stack, g.stack])() if rng.random() < 0.8 else '-' + slots[1] = lapis() if rng.random() < 0.7 else rng.choice(['-', g.stack()]) if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -343,6 +356,10 @@ def main(): return rng.choice([0, 0, 1]) if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) + if menu == 'enchanting': + # costs, the seed, then the clues + return [rng.choice([0, 1, 2, 5, 15, 30]) for _ in range(3)][0] if i < 3 else \ + rng.randrange(-2**15, 2**15) if i == 3 else rng.choice([-1, -1, 0, 3, 12]) return 0 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 '-' From ca5404e52dcdf4c2cfcff16876e84946fba5bf79 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 07:11:32 +0200 Subject: [PATCH 6/8] Beacon on the menu engine; LAN guests use beacons BeaconMenu now runs on horizon_client::menu (Kind::Beacon): the payment slot (beacon_payment_items, one item), quickMoveStack and updateEffects with BeaconBlockEntity.validateEffects, verified against the vanilla class by test_menu_click_parity with a new SET_BEACON op (valid and invalid powers for each pyramid level). ServerboundSetBeaconPacket is now in the protocol. The LAN host opens minecraft:beacon for guests with the block entity's levels and powers as data slots (kept current while the menu is open), applies a guest's powers to the block entity (power_select while the beam is up) and drops the payment when the menu closes, as BeaconMenu.removed does. Guests show the server's levels and powers and their Done button sends the packet. Single player's beacon clicks go through the engine too. Part of #868. Co-Authored-By: Claude Opus 5.5 --- .../horizon-client/examples/menu_fixture.rs | 22 ++++ crates/horizon-client/src/game.rs | 6 ++ crates/horizon-client/src/game/beacon.rs | 22 ++-- crates/horizon-client/src/game/lan_actions.rs | 1 + .../horizon-client/src/game/lan_stations.rs | 95 +++++++++++++++- crates/horizon-client/src/game/remote.rs | 10 +- .../src/game/remote_stations.rs | 11 ++ crates/horizon-client/src/game/stations.rs | 25 ++--- crates/horizon-client/src/lan/hub.rs | 5 + crates/horizon-client/src/menu.rs | 102 +++++++++++++++++- crates/horizon-protocol/src/packets/play.rs | 13 +++ .../horizonlab/parity/VanillaMenuOracle.java | 15 +++ tools/lan_e2e.py | 44 +++++++- tools/test_menu_click_parity.py | 28 ++++- 14 files changed, 370 insertions(+), 29 deletions(-) diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 984f024c1..20d79e168 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -11,6 +11,7 @@ use horizon_client::{ items::Items, menu::{Env, Input, Kind, Menu}, }; +use horizon_protocol::registry::Ids; use serde_json::Value; use std::{fs, path::Path}; @@ -57,6 +58,13 @@ fn main() -> horizon_client::Result<()> { names: &names, trade: None, }; + // The mob effects' network ids (BeaconMenu.encodeEffect). + let builtin = horizon_protocol::registry::Builtin::find(root) + .and_then(|p| horizon_protocol::registry::Builtin::load(&p).ok()); + let effects = builtin + .as_ref() + .and_then(|b| b.get("minecraft:mob_effect")) + .cloned(); let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; @@ -113,6 +121,20 @@ fn main() -> horizon_client::Result<()> { out += &format!("{}\n", state(&menu)); continue; } + // ServerboundSetBeaconPacket: BeaconMenu.updateEffects. + "SET_BEACON" => { + fn power<'a>(ids: Option<&Ids>, v: &'a Value) -> Option<(i32, &'a str)> { + let name = v.as_str()?; + Some((ids?.id(name)?, name)) + } + let (primary, secondary) = ( + power(effects.as_ref(), &op[3]), + power(effects.as_ref(), &op[4]), + ); + menu.beacon_update(&env, primary, secondary); + out += &format!("{}\n", state(&menu)); + continue; + } // ServerboundContainerSlotStateChangedPacket. "SLOT_STATE" => { if (0..9).contains(&slot) { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index dec8588eb..d858aeaef 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5439,6 +5439,7 @@ impl Game<'_> { let anvil_open = station_kind == Some(stations::Kind::Anvil); let smithing_open = station_kind == Some(stations::Kind::Smithing); let enchanting_open = station_kind == Some(stations::Kind::Enchanting); + let beacon_open = station_kind == Some(stations::Kind::Beacon); 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]; @@ -5484,6 +5485,11 @@ impl Game<'_> { let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Enchanting, v) + } else if beacon_open { + // BeaconMenu: the payment, then the inventory. + let mut v = vec![Some(stations::INPUT)]; + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Beacon, v) } else if anvil_open || smithing_open { // ItemCombinerMenu: the inputs, the result, then the inventory. let inputs = if anvil_open { 2 } else { 3 }; diff --git a/crates/horizon-client/src/game/beacon.rs b/crates/horizon-client/src/game/beacon.rs index 79cf14541..c8a0bcba6 100644 --- a/crates/horizon-client/src/game/beacon.rs +++ b/crates/horizon-client/src/game/beacon.rs @@ -15,6 +15,7 @@ use horizon_client::{ mesher::Vertex, mobs::render::{DYE, DYE_NAMES}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; /// The beacon screen is 54 px wider than the 176-px menus it shares an origin with. pub(super) const SHIFT: f32 = -27.0; @@ -35,9 +36,6 @@ const PAYMENT: [&str; 5] = [ "minecraft:diamond", "minecraft:netherite_ingot", ]; -pub(super) fn is_payment(item: &str) -> bool { - PAYMENT.contains(&item) -} /// `BeaconMenu.PaymentSlot` and the player inventory, relative to the 176 origin. pub(super) fn slot_position(i: usize) -> Option<(f32, f32)> { Some(match i { @@ -171,7 +169,7 @@ impl Game<'_> { } } } - fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { + pub(super) fn beacon_sound(&mut self, p: [i32; 3], sound: &str) { let at = [ f64::from(p[0]) + 0.5, f64::from(p[1]) + 0.5, @@ -255,9 +253,13 @@ impl Game<'_> { } } fn beacon_levels(&self) -> i32 { - let Some(pos) = self.station.as_ref().map(|s| s.pos) else { + let Some(s) = self.station.as_ref() else { return 0; }; + if let Some(levels) = s.beacon_levels { + return levels; + } + let pos = s.pos; match self.world.block_entities.get(&(pos[0], pos[1], pos[2])) { Some(BlockEntity::Beacon(b)) => b.levels, _ => 0, @@ -346,8 +348,16 @@ impl Game<'_> { self.screen = super::Screen::Playing; self.capture(true); } - /// `BeaconMenu.updateEffects`: spend the payment and set the powers. + /// `BeaconMenu.updateEffects`: spend the payment and set the powers. On + /// a server, `BeaconScreen`'s confirm button sends them + /// (`ServerboundSetBeaconPacket`) and the server's menu does it. fn confirm_beacon(&mut self, sel: [Option; 2]) { + if self.remote.is_some() { + let id = |e: Option| e.and_then(|e| self.remote_effect_network_id(EFFECTS[e].0)); + let (primary, secondary) = (id(sel[0]), id(sel[1])); + self.send(S::SetBeacon(play::SetBeacon { primary, secondary })); + return; + } let Some(s) = self.station.as_mut() else { return; }; diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 655a11cbd..2ebe7a90b 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -921,6 +921,7 @@ impl Game<'_> { self.lan_station_button(host, conn, p.container, p.button); } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary), 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_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 5dfb79752..0d04dfe11 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -11,6 +11,7 @@ use super::{ stations::{Kind as StationKind, Station}, }; use horizon_client::{ + containers::BlockEntity, items::ItemStack, menu::{Kind, Menu}, }; @@ -40,6 +41,7 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:anvil", Kind::Anvil, 0..2), StationKind::Smithing => ("minecraft:smithing", Kind::Smithing, 0..3), StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), + StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1), _ => return None, }) } @@ -74,6 +76,9 @@ impl Game<'_> { } menu.data[3] = g.xp_seed; } + if kind == Kind::Beacon { + menu.data = self.beacon_data(host, station.pos).to_vec(); + } host.play.entry(conn).or_default().station = Some(GuestStation { window, state: 0, @@ -329,13 +334,92 @@ impl Game<'_> { }; // AbstractContainerMenu.removed: the carried stack first, then the inputs. let mut back: Vec = host.hub.guests[gi].carried.take().into_iter().collect(); - back.extend(station_inputs(&gs)); + let inputs = station_inputs(&gs); + if gs.kind == StationKind::Beacon { + // BeaconMenu.removed drops the payment (player.drop). + if !back.is_empty() { + self.lan_place_back(host, gi, std::mem::take(&mut back)); + } + self.drop_guest_items(host, gi, inputs); + } else { + back.extend(inputs); + } if !back.is_empty() { self.lan_place_back(host, gi, back); } true } + /// `BeaconBlockEntity.dataAccess`: the pyramid's levels and the powers + /// (`BeaconMenu.encodeEffect`: the `mob_effect` id + 1, 0 for none). + fn beacon_data(&self, host: &LanHost, pos: [i32; 3]) -> [i32; 3] { + let Some(BlockEntity::Beacon(b)) = self.world.block_entities.get(&(pos[0], pos[1], pos[2])) + else { + return [0; 3]; + }; + let encode = |e: &Option| { + e.as_deref() + .and_then(|n| host.hub.registry_id("minecraft:mob_effect", n)) + .map_or(0, |id| id + 1) + }; + [b.levels, encode(&b.primary), encode(&b.secondary)] + } + + /// `ServerGamePacketListenerImpl.handleSetBeaconPacket`: the guest's + /// beacon menu takes the powers (`BeaconMenu.updateEffects`), and they + /// become the block entity's (`dataAccess.set`: the power_select sound + /// while the beam is up). + pub(super) fn lan_station_beacon( + &mut self, + host: &mut LanHost, + conn: u32, + primary: Option, + secondary: Option, + ) { + let Some(pos) = host + .play + .get(&conn) + .and_then(|p| p.station.as_ref()) + .filter(|s| s.kind == StationKind::Beacon) + .map(|s| s.pos) + else { + return; + }; + // An id the registry doesn't have fails the packet's codec. + let mut powers: [Option<(i32, String)>; 2] = [None, None]; + for (k, id) in [primary, secondary].into_iter().enumerate() { + if let Some(id) = id { + let Some(name) = host.hub.registry_name("minecraft:mob_effect", id) else { + return; + }; + powers[k] = Some((id, name.to_owned())); + } + } + let data = self.beacon_data(host, pos); + let mut updated = false; + self.lan_station_op(host, conn, None, |menu, env| { + menu.data.copy_from_slice(&data); + let power = |k: usize| powers[k].as_ref().map(|(id, n)| (*id, n.as_str())); + updated = menu.beacon_update(env, power(0), power(1)); + }); + if !updated { + return; + } + let [primary, secondary] = powers.map(|p| p.map(|(_, n)| n)); + let mut select_sound = false; + if let Some(BlockEntity::Beacon(b)) = + self.world.block_entities.get_mut(&(pos[0], pos[1], pos[2])) + { + b.primary = primary; + b.secondary = secondary; + select_sound = !b.sections.is_empty(); + } + if select_sound { + self.beacon_sound(pos, "minecraft:block.beacon.power_select"); + } + self.world.modified.insert((pos[0] >> 4, pos[2] >> 4)); + } + /// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its /// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`). pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) { @@ -375,6 +459,15 @@ impl Game<'_> { conn, &C::ContainerClose(play::ContainerClose { container: window }), ); + } else if gs.kind == StationKind::Beacon { + // The beacon's data slots follow its block entity. + let data = self.beacon_data(host, gs.pos); + if let Some(gs) = host.play.get_mut(&conn).and_then(|p| p.station.as_mut()) + && gs.menu.data[..] != data[..] + { + gs.menu.data.copy_from_slice(&data); + self.lan_send_station(host, conn); + } } } } diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index ed900ebf9..a8ebffdf8 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -446,8 +446,15 @@ impl Game<'_> { .unwrap_or("minecraft:air"), ) } + /// The server's network id of a mob effect (`brewing::EFFECTS` id). + pub(super) fn remote_effect_network_id(&self, effect: &str) -> Option { + let r = self.remote.as_ref()?; + r.builtin + .get("minecraft:mob_effect")? + .id(&format!("minecraft:{effect}")) + } /// A mob effect's network id as the effect (`brewing::EFFECTS` id). - fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { + pub(super) fn remote_effect_id(&self, effect: i32) -> Option<&'static str> { let r = self.remote.as_ref()?; let name = r.builtin.get("minecraft:mob_effect")?.name(effect)?; horizon_client::brewing::effect(name).map(|d| d.id) @@ -1269,6 +1276,7 @@ impl Game<'_> { "minecraft:anvil" => Kind::Anvil, "minecraft:smithing" => Kind::Smithing, "minecraft:enchantment" => Kind::Enchanting, + "minecraft:beacon" => Kind::Beacon, _ => return None, }) } diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index 52e60ed76..c6b61a76f 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -97,6 +97,17 @@ impl Game<'_> { *level = value.max(0) as u32; } } + // BeaconMenu: the levels, then the powers (BeaconScreen's + // dataChanged shows the menu's). + (Kind::Beacon, 0) => s.beacon_levels = Some(i32::from(value)), + (Kind::Beacon, 1 | 2) => { + let effect = self.remote_effect_id(i32::from(value) - 1); + let index = + effect.and_then(|e| super::beacon::EFFECTS.iter().position(|(n, _)| *n == e)); + if let Some(s) = self.station.as_mut() { + s.beacon[id - 1] = index; + } + } _ => {} } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index 7820bd88b..d0d1e10bb 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -152,6 +152,8 @@ pub(super) struct Station { pub(super) merchant: Option>, /// Beacon menu: the selected primary and secondary power (EFFECTS index). pub(super) beacon: [Option; 2], + /// A server's beacon menu: the pyramid's levels (its data slot 0). + pub(super) beacon_levels: Option, /// The loom's patterns, selection and scroller (game/loom.rs). pub(super) loom: super::loom::LoomState, } @@ -175,6 +177,7 @@ impl Station { last_sound: 0, merchant: None, beacon: [None; 2], + beacon_levels: None, loom: Default::default(), } } @@ -531,7 +534,6 @@ impl Game<'_> { } let i = slot - INPUT; match s.kind { - Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), Kind::Loom => (false, 64), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), Kind::Cartography => ( @@ -667,7 +669,6 @@ impl Game<'_> { return false; }; let start = stack.count; - let empty = |game: &mut Self, i: usize| game.station_slot_mut(INPUT + i).is_none(); // The other half of the inventory: main rows to the hotbar and back. let halves: Vec = if slot < 9 { (9..36).collect() @@ -675,20 +676,10 @@ impl Game<'_> { (0..9).collect() }; if slot >= INPUT { - // An input slot: into the inventory, the hotbar's last slot first - // where vanilla moves in reverse. - let reverse = kind == Kind::Beacon; - self.move_to(&mut stack, &Self::player_slots(), reverse); + // An input slot: into the inventory. + self.move_to(&mut stack, &Self::player_slots(), false); } else { match kind { - Kind::Beacon => { - if empty(self, 0) && super::beacon::is_payment(&stack.item) && stack.count == 1 - { - self.move_to(&mut stack, &[INPUT], false); - } else { - self.move_to(&mut stack, &halves, false); - } - } Kind::Cartography => { if super::maps::map_id(&stack).is_some() { self.move_to(&mut stack, &[INPUT], false); @@ -708,7 +699,8 @@ impl Game<'_> { | Kind::Grindstone | Kind::Anvil | Kind::Smithing - | Kind::Enchanting => {} + | Kind::Enchanting + | Kind::Beacon => {} } } let moved = stack.count != start; @@ -1062,10 +1054,11 @@ impl Game<'_> { | Kind::Anvil | Kind::Smithing | Kind::Enchanting + | Kind::Beacon ) }) { // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu, AnvilMenu, - // SmithingMenu and the brewing stand's + // SmithingMenu, EnchantmentMenu, BeaconMenu and the brewing stand's // BrewingStandMenu clicks run on the verified menu engine. let input = if shift { horizon_client::menu::Input::QuickMove diff --git a/crates/horizon-client/src/lan/hub.rs b/crates/horizon-client/src/lan/hub.rs index 9c65e9292..2ff89809a 100644 --- a/crates/horizon-client/src/lan/hub.rs +++ b/crates/horizon-client/src/lan/hub.rs @@ -311,6 +311,11 @@ impl Hub { self.sync.id(registry, name) } + /// The name of a network id in a built-in registry. + pub fn registry_name(&self, registry: &str, id: i32) -> Option<&str> { + self.sync.builtin.get(registry)?.name(id) + } + pub fn item_id(&mut self, item: &Arc) -> i32 { if let Some(id) = self.item_ids.get(item) { return *id; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index c4354b184..b72b74762 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -89,6 +89,9 @@ pub enum Kind { /// `EnchantmentMenu`: the item, the lapis, then the inventory; its data /// slots are the three costs, the seed and the clues. Enchanting, + /// `BeaconMenu`: the payment slot, then the inventory; its data slots are + /// the pyramid's levels and the two powers (`encodeEffect`: id + 1). + Beacon, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -119,6 +122,7 @@ impl Kind { "anvil" => Self::Anvil, "smithing" => Self::Smithing, "enchanting" => Self::Enchanting, + "beacon" => Self::Beacon, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -170,6 +174,8 @@ enum Role { EnchantItem, /// The enchanting table's lapis slot. Lapis, + /// `BeaconMenu.PaymentSlot`: one beacon payment item. + BeaconPay, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -182,6 +188,26 @@ struct Slot { role: Role, } +/// `BeaconBlockEntity.BEACON_EFFECTS`: the powers of each pyramid level. +pub const BEACON_EFFECTS: [&[&str]; 4] = [ + &["minecraft:speed", "minecraft:haste"], + &["minecraft:resistance", "minecraft:jump_boost"], + &["minecraft:strength"], + &["minecraft:regeneration"], +]; + +/// `BeaconBlockEntity.getRequiredLevelsFor`: 0 for no power, `i32::MAX` +/// for one no level gives. +pub fn beacon_required_levels(effect: Option<&str>) -> i32 { + let Some(effect) = effect else { + return 0; + }; + BEACON_EFFECTS + .iter() + .position(|tier| tier.contains(&effect)) + .map_or(i32::MAX, |i| i as i32 + 1) +} + /// The containers a menu spans. const PLAYER: usize = 0; const MAIN: usize = 1; @@ -466,6 +492,13 @@ impl Menu { // costs[3], enchantmentSeed, enchantClue[3], levelClue[3]. data = 10; } + Kind::Beacon => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::BeaconPay)); + player(&mut slots); + // levels, primary, secondary. + data = 3; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -827,6 +860,38 @@ impl Menu { /// `AnvilMenu.setItemName` (`ServerboundRenameItemPacket`): false when /// the name is refused or unchanged. + /// `BeaconMenu.updateEffects` (`ServerboundSetBeaconPacket`): with a + /// payment, powers `BeaconBlockEntity.validateEffects` allows for the + /// pyramid's levels (data 0) become data 1 and 2 and the payment is used. + /// Each power is its `mob_effect` id and name. False when refused. + pub fn beacon_update( + &mut self, + env: &Env, + primary: Option<(i32, &str)>, + secondary: Option<(i32, &str)>, + ) -> bool { + if self.kind != Kind::Beacon || self.containers[MAIN][0].is_none() { + return false; + } + let levels = self.data[0]; + let (p, s) = ( + beacon_required_levels(primary.map(|e| e.1)), + beacon_required_levels(secondary.map(|e| e.1)), + ); + let valid = !(secondary.is_some() && levels < 4) + && p <= levels + && s <= levels + && p < 4 + && !(s != 0 && s < 4 && primary.map(|e| e.0) != secondary.map(|e| e.0)); + if !valid { + return false; + } + self.data[1] = primary.map_or(0, |e| e.0 + 1); + self.data[2] = secondary.map_or(0, |e| e.0 + 1); + self.remove(env, 0, 1); + true + } + pub fn rename(&mut self, env: &Env, name: &str) -> bool { // StringUtil.filterText, then validateName's length limit. let name: String = name @@ -973,6 +1038,11 @@ impl Menu { Role::SmithInput(i) => env.station_recipes.smithing_accepts(i, stack), Role::EnchantItem => true, Role::Lapis => &*stack.item == "minecraft:lapis_lazuli", + Role::BeaconPay => env + .items + .item_tags + .get("minecraft:beacon_payment_items") + .is_some_and(|t| t.contains(&*stack.item)), Role::LoomResult | Role::MerchantResult | Role::StoneResult @@ -1017,7 +1087,7 @@ impl Menu { /// `Slot.getMaxStackSize(stack)`. fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { - Role::Armor(_) | Role::Potion | Role::EnchantItem => 1, + Role::Armor(_) | Role::Potion | Role::EnchantItem | Role::BeaconPay => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -1034,6 +1104,10 @@ impl Menu { && let Some(st) = stack.as_mut() { st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st))); + // The beacon's container holds one item (getMaxStackSize 1). + if self.kind == Kind::Beacon { + st.count = st.count.min(1); + } } // CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it. if self.kind == Kind::CrafterBlock @@ -1712,6 +1786,32 @@ impl Menu { return None; } } + Kind::Beacon => { + // BeaconMenu.quickMoveStack. + after_take = true; + if index == 0 { + if !self.move_to(env, &mut stack, 1, 37, true) { + return None; + } + } else if self.containers[MAIN][0].is_none() + && self.may_place(env, 0, &stack) + && stack.count == 1 + { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if (1..28).contains(&index) { + if !self.move_to(env, &mut stack, 28, 37, false) { + return None; + } + } else if (28..37).contains(&index) { + if !self.move_to(env, &mut stack, 1, 28, false) { + return None; + } + } else if !self.move_to(env, &mut stack, 1, 37, false) { + return None; + } + } Kind::Enchanting => { after_take = true; if index < 2 { diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 11166408a..36bca7bbc 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1719,6 +1719,11 @@ packet!( /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. RenameItem { name: String => Str } ); +packet!( + /// ServerboundSetBeaconPacket: `BeaconMenu.updateEffects`, each power an + /// optional `mob_effect` id. + SetBeacon { primary: Option => Opt, secondary: Option => Opt } +); packet!(Interact { id: i32 => VarInt, hand: i32 => VarInt, location: [f64; 3] => LpVec3, secondary: bool => Bool }); packet!( /// ServerboundMovePlayerPacket flags: 1 on ground, 2 horizontal collision. @@ -1805,6 +1810,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, SelectTrade(SelectTrade) = SELECT_TRADE, + SetBeacon(SetBeacon) = SET_BEACON, SetCarriedItem(SetCarriedItem) = SET_CARRIED_ITEM, SetCreativeModeSlot(SetCreativeModeSlot) = SET_CREATIVE_MODE_SLOT, UseItem(UseItem) = USE_ITEM, @@ -2384,6 +2390,13 @@ mod tests { }); assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']); round_trip(rename, Serverbound::encode, Serverbound::decode); + // Two optional mob effect ids: a presence byte, then the VarInt. + let beacon = Serverbound::SetBeacon(SetBeacon { + primary: Some(2), + secondary: None, + }); + assert_eq!(&beacon.encode()[1..], &[1, 2, 0]); + round_trip(beacon, 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 5a3db5977..1491c5a28 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -183,10 +183,19 @@ public final class VanillaMenuOracle { case "anvil" -> new AnvilMenu(0, inv); case "smithing" -> new SmithingMenu(0, inv); case "enchanting" -> new EnchantmentMenu(0, inv); + case "beacon" -> new BeaconMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } + /** A SET_BEACON power: a mob effect's name, or null for none. */ + static Optional> effect(JsonElement name) { + if (name.isJsonNull()) return Optional.empty(); + return net.minecraft.core.registries.BuiltInRegistries.MOB_EFFECT + .get(net.minecraft.resources.Identifier.parse(name.getAsString())) + .map(h -> (net.minecraft.core.Holder) h); + } + static String state(AbstractContainerMenu menu, Inventory inv) throws Exception { StringBuilder out = new StringBuilder(); for (int i = 0; i < menu.slots.size(); i++) { @@ -267,6 +276,12 @@ public final class VanillaMenuOracle { out.println(clickState(menu, inv)); continue; } + if (kind.equals("SET_BEACON")) { + // ServerGamePacketListenerImpl.handleSetBeaconPacket: BeaconMenu.updateEffects + if (menu instanceof BeaconMenu beacon) beacon.updateEffects(effect(op.get(3)), effect(op.get(4))); + 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 958b80b4d..a7168fb2c 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -147,7 +147,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', 'anvil', 'smithing', 'enchanting', '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', 'enchanting', 'beacon', '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: @@ -1141,6 +1141,47 @@ def check_enchanting(host, guest, out): return seen +def check_beacon(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='effect clear @s') + guest('command', command='give @s minecraft:iron_ingot') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + # A one-level pyramid under the beacon; its levels come with the first base check (80 ticks). + guest('command', command=f'fill {x - 1} {y - 1} {z + 1} {x + 1} {y - 1} {z + 3} minecraft:iron_block') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:beacon') + guest.wait(100) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'station', '--timeout', 10) + guest.wait(10) + # BeaconMenu.quickMoveStack: the ingot to the payment slot. + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:iron_ingot'), 'shift') + guest.wait(10) + paid = station_slots(guest).get(600) + # BeaconScreen (54 px wider, 27 to the left): Haste, the first level's second power, then Done, + # which sends ServerboundSetBeaconPacket and closes the menu. + guest.raw('click-gui', 77 - 27 + 11, 22 + 11) + guest.wait(5) + guest.shot(out, 'beacon') + guest.raw('click-gui', 164 - 27 + 11, 107 + 11) + guest.wait(10) + screen = guest('state').get('screen') + effects = [] + # BeaconBlockEntity.applyEffects runs every 80 ticks. + for _ in range(12): + guest.wait(20) + effects = effect_ids(guest) + if 'haste' in effects: + break + seen = {'paid': paid, 'haste': 'haste' in effects, 'ingots': server_count(guest, 'iron_ingot'), + 'screen': screen} + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + want = {'paid': ('minecraft:iron_ingot', 1), 'haste': True, 'ingots': 0, 'screen': 'playing'} + assert seen == want, f'the beacon on the guest: {seen} ({effects})' + 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']: @@ -2338,6 +2379,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'anvil': check_anvil, 'smithing': check_smithing, 'enchanting': check_enchanting, + 'beacon': check_beacon, '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 41561fbb9..ce97183b4 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -14,7 +14,9 @@ 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), the anvil (repairs, enchantment merges and renames, with the player's levels), the smithing table (upgrades and trims), the -enchanting table (its button checks against the costs, lapis and levels) and the +enchanting table (its button checks against the costs, lapis and levels), the +beacon (its payment slot and ServerboundSetBeaconPacket against the pyramid's +levels) 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. @@ -30,9 +32,9 @@ 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, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, '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, 'enchanting': 10, + 'stonecutter': 1, 'enchanting': 10, 'beacon': 3, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] @@ -50,6 +52,9 @@ CUTTABLE = ['stone', 'cobblestone', 'andesite', 'granite', 'copper_block', 'sand 'stone_bricks', 'oak_planks'] # Grindstone inputs: tools and armor, books, and their enchantments (curses too). GRINDABLE = ['iron_sword', 'diamond_pickaxe', 'bow', 'iron_helmet', 'elytra', 'shield', 'fishing_rod', 'trident'] +# Beacon powers (BEACON_EFFECTS by level, and one no level gives) and payments. +POWERS = ['speed', 'haste', 'resistance', 'jump_boost', 'strength', 'regeneration', 'night_vision'] +PAYMENTS = ['iron_ingot', 'gold_ingot', 'emerald', 'diamond', 'netherite_ingot'] ENCHANTS = ['sharpness', 'unbreaking', 'mending', 'efficiency', 'protection', 'power', 'looting', 'fortune', 'binding_curse', 'vanishing_curse'] @@ -228,6 +233,15 @@ class Gen: # An offer button (clickMenuButton), sometimes out of range. out.append([rng.choice([0, 1, 2, 2, 3, -1]), 0, 'BUTTON']) continue + if menu == 'beacon' and rng.random() < 0.3: + # ServerboundSetBeaconPacket: powers, valid or not, or none. + pick = lambda: 'minecraft:' + rng.choice(POWERS) if rng.random() < 0.8 else None + primary, secondary = pick(), pick() + if primary is None and secondary not in (None, 'minecraft:regeneration', 'minecraft:night_vision'): + # validateEffects compares a null primary (Holder.equals: a NullPointerException). + primary = secondary + out.append([0, 0, 'SET_BEACON', primary, secondary]) + 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 @@ -329,6 +343,11 @@ def main(): slots[i] = rng.choice([lapis, enchantable, g.grind_stack])() slots[0] = rng.choice([enchantable, enchantable, g.grind_stack, g.stack])() if rng.random() < 0.8 else '-' slots[1] = lapis() if rng.random() < 0.7 else rng.choice(['-', g.stack()]) + if menu == 'beacon': + pay = lambda: snbt('minecraft:' + rng.choice(PAYMENTS), rng.choice([1, 1, 1, 2, 64])) + for i in rng.sample(range(1, size), 8): + slots[i] = pay() + slots[0] = pay() if rng.random() < 0.7 else rng.choice(['-', g.stack()]) if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -356,6 +375,9 @@ def main(): return rng.choice([0, 0, 1]) if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) + if menu == 'beacon': + # the levels, then the powers (encodeEffect: id + 1) + return rng.choice([0, 1, 2, 3, 4, 4]) if i == 0 else rng.choice([0, 0, 2, 4, 11]) if menu == 'enchanting': # costs, the seed, then the clues return [rng.choice([0, 1, 2, 5, 15, 30]) for _ in range(3)][0] if i < 3 else \ From dbb1ca0907cc6b4c1863ecf9d5eb398dea6d9f31 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 08:08:58 +0200 Subject: [PATCH 7/8] LAN guests use crafters A guest's use of a crafter now opens CrafterMenu (minecraft:crafter_3x3) over the block entity. The host runs its clicks on the menu engine's verified Kind::CrafterBlock (a disabled slot refuses items, filling one enables it), sends the disabled slots and triggered as data slots (CrafterBlockEntity.containerData), and handles ServerboundContainerSlotStateChangedPacket (new in horizon-protocol) as CrafterBlockEntity.setSlotState. The guest shows the server's crafter, predicts its clicks and sends a slot toggle before the click as CrafterScreen.slotClicked does. Part of #868. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game/lan_actions.rs | 10 ++++ .../horizon-client/src/game/lan_crafting.rs | 53 +++++++++++++++++++ .../src/game/machines/crafter.rs | 10 ++++ crates/horizon-client/src/game/remote.rs | 15 ++++++ crates/horizon-client/src/lan/containers.rs | 20 +++++-- crates/horizon-protocol/src/packets/play.rs | 14 +++++ tools/lan_e2e.py | 32 ++++++++++- 7 files changed, 149 insertions(+), 5 deletions(-) diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 2ebe7a90b..962949a0d 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -639,6 +639,13 @@ impl Game<'_> { _ => ("minecraft:furnace", "container.furnace"), }; (menu, title, Slots::Block(pos)) + } else if let Some(BlockEntity::Crafter(_)) = self.world.block_entities.get(&pos) { + // CrafterBlock.useWithoutItem: CrafterMenu over the block entity. + ( + "minecraft:crafter_3x3", + "container.crafter", + Slots::Block(pos), + ) } else if let Some(BlockEntity::Brewing(_)) = self.world.block_entities.get(&pos) { // BrewingStandBlock.useWithoutItem: BrewingStandMenu. ( @@ -921,6 +928,9 @@ impl Game<'_> { self.lan_station_button(host, conn, p.container, p.button); } S::RenameItem(p) => self.lan_station_rename(host, conn, &p.name), + S::ContainerSlotStateChanged(p) => { + self.lan_crafter_slot_state(host, conn, p.container, p.slot, p.enabled); + } S::SetBeacon(p) => self.lan_station_beacon(host, conn, p.primary, p.secondary), S::SelectTrade(p) => self.lan_select_trade(host, conn, p.item), S::ContainerClose(p) if self.lan_merchant_closed(host, conn, Some(p.container)) => { diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 96dc99c14..64cf0dd0d 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -205,8 +205,14 @@ impl Game<'_> { (Kind::Furnace(recipe), f.items.to_vec()) } Some(BlockEntity::Brewing(b)) => (Kind::Brewing, b.items.to_vec()), + Some(BlockEntity::Crafter(c)) => (Kind::CrafterBlock, c.items.to_vec()), _ => return false, }; + // CrafterBlockEntity.containerData: the disabled slots, then triggered. + let crafter_data = match self.world.block_entities.get(&pos) { + Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), + _ => None, + }; if host.hub.guests[gi].spectator() { return true; } @@ -223,6 +229,13 @@ impl Game<'_> { for (k, s) in items.iter().enumerate() { menu.set_slot(env, k, s.clone()); } + // After the slots: setting a disabled slot (CrafterBlockEntity.setItem) enables it. + if let Some((disabled, triggered)) = crafter_data { + for (k, d) in disabled.iter().enumerate() { + menu.data[k] = i32::from(*d); + } + menu.data[9] = i32::from(triggered); + } let before: Vec<_> = (0..menu.slot_count()) .map(|s| menu.slot(s).cloned()) .collect(); @@ -245,6 +258,13 @@ impl Game<'_> { b.items[k] = menu.slot(k).cloned(); } } + // CrafterBlockEntity.setItem: filling a disabled slot enables it. + Some(BlockEntity::Crafter(c)) => { + for k in 0..9 { + c.items[k] = menu.slot(k).cloned(); + c.disabled[k] = menu.data[k] == 1; + } + } _ => {} } host.play.entry(conn).or_default().crafting.machine = Some((p.container, menu)); @@ -252,6 +272,39 @@ impl Game<'_> { true } + /// `ServerGamePacketListenerImpl.handleContainerSlotStateChanged`: a + /// guest's crafter slot toggle (`CrafterBlockEntity.setSlotState`) in + /// their open crafter window. + pub(super) fn lan_crafter_slot_state( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + slot: i32, + enabled: bool, + ) { + let Some(pos) = host + .hub + .guest(conn) + .filter(|g| !g.spectator()) + .and_then(|g| g.menu.as_ref()) + .filter(|m| window != 0 && m.window == window) + .and_then(|m| match m.slots { + Slots::Block(pos) => Some(pos), + _ => None, + }) + else { + return; + }; + if let (Some(BlockEntity::Crafter(c)), Ok(slot)) = ( + self.world.block_entities.get_mut(&pos), + usize::try_from(slot), + ) { + c.set_slot_state(slot, enabled); + self.world.modified.insert((pos.0 >> 4, pos.2 >> 4)); + } + } + /// ServerGamePacketListenerImpl.handlePlaceRecipe: the guest's recipe /// book places a known recipe in their inventory grid or crafting table /// (`ServerPlaceRecipe`), and answers with a ghost recipe when the items diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index d87646fe0..0fe66f7c8 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -8,6 +8,7 @@ use horizon_client::{ containers::Crafter, hud::{HudBatch, rgba}, }; +use horizon_protocol::packets::play::{self, Serverbound as S}; use serde_json::Value; /// `CrafterBlock`'s crafting animation length. @@ -323,6 +324,15 @@ impl Game<'_> { menu.set_slot_state(i, enabled); Some(true) }); + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.clone()) { + self.send(S::ContainerSlotStateChanged( + play::ContainerSlotStateChanged { + slot: i as i32, + container, + enabled, + }, + )); + } let pitch = if enabled { 1.0 } else { 0.75 }; self.audio .play("minecraft:ui.button.click", None, 0.4, pitch); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index a8ebffdf8..fb0aa2356 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -1251,6 +1251,9 @@ impl Game<'_> { "minecraft:hopper" => slots(5), "minecraft:generic_3x3" => slots(9), "minecraft:brewing_stand" => slots(5), + // CrafterMenu: the grid, the inventory, then the result (the + // client's own). + "minecraft:crafter_3x3" => slots(9), // A workstation: its inputs, its result, then the inventory. m => { let kind = Self::remote_station_kind(m)?; @@ -1961,6 +1964,12 @@ impl Game<'_> { 3 => f.cooking_total = v, _ => {} }, + // CrafterBlockEntity.containerData. + Some(BlockEntity::Crafter(c)) => match usize::try_from(p.id) { + Ok(k @ 0..9) => c.disabled[k] = v == 1, + Ok(9) => c.triggered = v == 1, + _ => {} + }, // BrewingStandBlockEntity.dataAccess. Some(BlockEntity::Brewing(b)) => match p.id { 0 => b.brew_time = v, @@ -3799,6 +3808,10 @@ impl Game<'_> { /// engine doesn't model sends the clicks unpredicted. False when a click's /// slot isn't one of the menu's. pub(super) fn remote_menu_ops(&mut self, ops: &[(Option, i32, Input)]) -> bool { + // CrafterScreen.slotClicked: a slot toggle goes out before the click. + if let [(Some(slot), button, input)] = ops { + self.crafter_slot_clicked(*slot, *button, *input); + } let (container, menu) = self.remote_menu(); let mut clicks = Vec::with_capacity(ops.len()); for &(slot, button, input) in ops { @@ -4078,6 +4091,8 @@ impl Game<'_> { horizon_client::brewing::BrewingStand::new(), ))), "minecraft:generic_3x3" => Some(BlockEntity::Chest(vec![None; 9])), + // CrafterMenu: the disabled slots and triggered come in ContainerSetData. + "minecraft:crafter_3x3" => Some(BlockEntity::Crafter(Default::default())), m if m.starts_with("minecraft:generic_9x") || m == "minecraft:shulker_box" => { let rows = m .strip_prefix("minecraft:generic_9x") diff --git a/crates/horizon-client/src/lan/containers.rs b/crates/horizon-client/src/lan/containers.rs index 66fbfe4b6..88f50aa3b 100644 --- a/crates/horizon-client/src/lan/containers.rs +++ b/crates/horizon-client/src/lan/containers.rs @@ -455,18 +455,30 @@ impl Hub { let Slots::Block(pos) = m.slots else { return; }; - // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess. + // AbstractFurnaceBlockEntity.dataAccess, BrewingStandBlockEntity.dataAccess, + // CrafterBlockEntity.containerData. let data = match world.block_entities.get(&pos) { - Some(BlockEntity::Furnace(f)) => [ + Some(BlockEntity::Furnace(f)) => vec![ f.lit_remaining, f.lit_total, f.cooking_timer, f.cooking_total, ], - Some(BlockEntity::Brewing(b)) => [b.brew_time, b.fuel, b.total_brew_time, b.total_fuel], + Some(BlockEntity::Brewing(b)) => { + vec![b.brew_time, b.fuel, b.total_brew_time, b.total_fuel] + } + // CrafterBlockEntity.containerData: the disabled slots, then triggered. + Some(BlockEntity::Crafter(c)) => c + .disabled + .iter() + .chain([&c.triggered]) + .map(|&d| i32::from(d)) + .collect(), _ => return, } - .map(|v| v as i16); + .into_iter() + .map(|v| v as i16) + .collect::>(); m.sent_data.resize(data.len(), i16::MIN); let window = m.window; let changed: Vec<(usize, i16)> = data diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 36bca7bbc..b52fca93e 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1715,6 +1715,11 @@ packet!( /// (the loom's patterns, the stonecutter's recipes, the enchanting table's offers). ContainerButtonClick { container: i32 => VarInt, button: i32 => VarInt } ); +packet!( + /// ServerboundContainerSlotStateChangedPacket: the crafter's slot toggle + /// (`CrafterBlockEntity.setSlotState`). + ContainerSlotStateChanged { slot: i32 => VarInt, container: i32 => VarInt, enabled: bool => Bool } +); packet!( /// ServerboundRenameItemPacket: `AnvilMenu.setItemName`. RenameItem { name: String => Str } @@ -1807,6 +1812,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { PlayerLoaded(Empty) = PLAYER_LOADED, Pong(Ping) = PONG, RenameItem(RenameItem) = RENAME_ITEM, + ContainerSlotStateChanged(ContainerSlotStateChanged) = CONTAINER_SLOT_STATE_CHANGED, Punch(Empty) = PUNCH, ResourcePack(ResourcePackResponse) = RESOURCE_PACK, SelectTrade(SelectTrade) = SELECT_TRADE, @@ -2390,6 +2396,14 @@ mod tests { }); assert_eq!(&rename.encode()[1..], &[5, b'B', b'l', b'a', b'd', b'e']); round_trip(rename, Serverbound::encode, Serverbound::decode); + // The slot, the container id (VarInts), then the new state. + let toggle = Serverbound::ContainerSlotStateChanged(ContainerSlotStateChanged { + slot: 4, + container: 2, + enabled: false, + }); + assert_eq!(&toggle.encode()[1..], &[4, 2, 0]); + round_trip(toggle, Serverbound::encode, Serverbound::decode); // Two optional mob effect ids: a presence byte, then the VarInt. let beacon = Serverbound::SetBeacon(SetBeacon { primary: Some(2), diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index a7168fb2c..96749a41e 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -147,7 +147,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', 'anvil', 'smithing', 'enchanting', 'beacon', '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', 'enchanting', 'beacon', 'crafter', '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: @@ -1182,6 +1182,35 @@ def check_beacon(host, guest, out): return seen +def check_crafter(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command='give @s minecraft:oak_planks 4') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:crafter') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'container', '--timeout', 10) + guest.wait(10) + # CrafterScreen.slotClicked: an empty-handed click disables the first slot + # (ServerboundContainerSlotStateChangedPacket); the planks then skip it. + guest.raw('click-slot', 300) + guest.wait(5) + guest.raw('click-slot', hotbar_slot(guest, 'minecraft:oak_planks'), 'shift') + guest.wait(10) + guest.shot(out, 'crafter') + guest.raw('key', 'esc', 'tap') + guest.wait(10) + # Opening it again shows the server's crafter. + items = open_container(guest, at, out, 'crafter-after') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + seen = {'items': items[0] if isinstance(items, tuple) else items, 'planks': server_count(guest, 'oak_planks')} + want = {'items': {1: 'minecraft:oak_planks'}, 'planks': 0} + assert seen == want, f'the crafter 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']: @@ -2380,6 +2409,7 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'smithing': check_smithing, 'enchanting': check_enchanting, 'beacon': check_beacon, + 'crafter': check_crafter, 'hurt': check_hurt, 'commands': check_commands, 'recipes': check_recipes, 'trials': check_trials, 'walls': check_walls, From de8cb0dfa6991c847715722e0c0b5a08467aa345 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:35:45 +0200 Subject: [PATCH 8/8] LAN guests: the lectern and the cartography table (#868) The last two workstation menus guests couldn't use, both now on the shared menu engine, which single player runs too: - Lectern: LecternMenu on the engine (Kind::Lectern): the page buttons (1, 2, 100+) and Take Book (3, mayBuild) as ContainerButtonClick, the page as data slot 0 clamped to the book, the book in its one slot (removeItem, setItem a no-op, max 1). The host opens minecraft:lectern for a guest, applies the menu to the block entity (powered pulse, page turn level event 1043, has_book), resends changes and closes it on stillValid. Guests drive it from the book screen. - Cartography table: CartographyTableMenu on the engine (Kind::Cartography, setupResultSlot, onTake, onCraftedBy's new map ids through a Maps env), replacing the old station code; guests get the same through guest_menu_op. - LAN item stacks carry map_post_processing and writable/written book contents (they were blank for guests); map_post_processing is no longer saved (ItemStack.CODEC never saves it). - A guest who enchants gets the enchant_item stat. - Click parity: VanillaMenuOracle and menu_fixture gain both menus. - lan_e2e: new lectern and cartography checks; enchanting checks the stat; server_count/server_reply ignore the guest's own operator broadcast echo on --server-thread; the grindstone check counts levels as well as points. Fixes #868 Co-Authored-By: Claude Opus 5.5 --- .../examples/cauldron_fixture.rs | 1 + .../horizon-client/examples/menu_fixture.rs | 75 ++++- .../examples/place_recipe_fixture.rs | 1 + .../examples/trading_fixture.rs | 1 + crates/horizon-client/src/game.rs | 41 ++- crates/horizon-client/src/game/books.rs | 245 +++++++++++++--- crates/horizon-client/src/game/cartography.rs | 126 ++++---- crates/horizon-client/src/game/lan_actions.rs | 14 +- .../horizon-client/src/game/lan_crafting.rs | 19 +- .../horizon-client/src/game/lan_stations.rs | 195 ++++++++++++- 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 | 39 +++ .../src/game/remote_stations.rs | 7 +- .../src/game/station_control.rs | 2 + crates/horizon-client/src/game/stations.rs | 222 +-------------- crates/horizon-client/src/item_data.rs | 8 +- crates/horizon-client/src/lan/guest.rs | 31 ++ crates/horizon-client/src/menu.rs | 269 +++++++++++++++++- crates/horizon-protocol/src/item.rs | 105 ++++++- .../horizonlab/parity/VanillaMenuOracle.java | 67 +++++ tools/lan_e2e.py | 115 +++++++- tools/test_menu_click_parity.py | 75 ++++- 23 files changed, 1314 insertions(+), 346 deletions(-) diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index 9c4d0f8df..6aa942d42 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -94,6 +94,7 @@ fn main() -> horizon_client::Result<()> { enchantments: &enchantments, names: &names, trade: None, + maps: None, }; let mut out = String::new(); for line in input.lines() { diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 20d79e168..1da4a0278 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -13,7 +13,39 @@ use horizon_client::{ }; use horizon_protocol::registry::Ids; use serde_json::Value; -use std::{fs, path::Path}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, + fs, + path::Path, +}; + +/// The case's maps: (locked, scale) by id, and the next free id. +#[derive(Default)] +struct CaseMaps { + maps: RefCell>, + next: Cell, +} + +impl horizon_client::menu::Maps for CaseMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.maps.borrow().get(&id).copied() + } + + /// `MapItemSavedData.scaled` (unlocked, one scale up) or `locked`. + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next.get(); + self.next.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.maps.borrow_mut().insert(new, made); + Some(new) + } +} fn state(menu: &Menu) -> String { let slots: Vec = (0..menu.slot_count()) @@ -25,13 +57,21 @@ fn state(menu: &Menu) -> String { .iter() .map(|(slot, stack)| format!("{slot}:{}", canon_stack(stack.as_ref()))) .collect(); - format!( + let line = format!( "{} | {} |{data} | {} | {}", slots.join(" "), canon_stack(menu.carried.as_ref()), menu.drops.join(";"), equipped.join(";") - ) + ); + if menu.kind() != Kind::Lectern { + return line; + } + // No inventory slots: the inventory Take Book fills. + let items: String = (0..36) + .map(|i| format!(" {}", canon_stack(menu.player_item(i)))) + .collect(); + format!("{line} | inv{items}") } fn main() -> horizon_client::Result<()> { @@ -48,6 +88,7 @@ fn main() -> horizon_client::Result<()> { 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 case_maps = CaseMaps::default(); let env = Env { items: &items, recipes: &recipes, @@ -57,6 +98,7 @@ fn main() -> horizon_client::Result<()> { enchantments: &enchantments, names: &names, trade: None, + maps: Some(&case_maps), }; // The mob effects' network ids (BeaconMenu.encodeEffect). let builtin = horizon_protocol::registry::Builtin::find(root) @@ -82,6 +124,23 @@ fn main() -> horizon_client::Result<()> { .unwrap_or(name), ) .ok_or("menu kind")?; + // [id, scale, locked] each; the level's new maps from 1000. + case_maps.next.set(1000); + *case_maps.maps.borrow_mut() = case["maps"] + .as_array() + .into_iter() + .flatten() + .map(|m| { + let id = m[0].as_i64().unwrap_or(0) as i32; + ( + id, + ( + m[2].as_bool().unwrap_or(false), + m[1].as_u64().unwrap_or(0) as u8, + ), + ) + }) + .collect(); 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; @@ -89,9 +148,17 @@ fn main() -> horizon_client::Result<()> { menu.set_slot(&env, i, parse_stack(slot.as_str().unwrap_or("-"))?); } menu.carried = parse_stack(case["carried"].as_str().unwrap_or("-"))?; + for (i, item) in case["inventory"] + .as_array() + .into_iter() + .flatten() + .enumerate() + { + menu.set_player_item(i, parse_stack(item.as_str().unwrap_or("-"))?); + } menu.settle(&env); for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { - menu.data[i] = v.as_i64().unwrap_or(0) as i32; + menu.set_data(i, v.as_i64().unwrap_or(0) as i32); } let mut furnace = furnace_kind.map(|kind| Furnace { kind, diff --git a/crates/horizon-client/examples/place_recipe_fixture.rs b/crates/horizon-client/examples/place_recipe_fixture.rs index 5d22e28f9..1e2b66dbf 100644 --- a/crates/horizon-client/examples/place_recipe_fixture.rs +++ b/crates/horizon-client/examples/place_recipe_fixture.rs @@ -50,6 +50,7 @@ fn main() -> horizon_client::Result<()> { enchantments: &enchantments, names: &names, trade: None, + maps: None, }; let mut out = String::new(); for (line, order) in cases.lines().zip(orders.lines()) { diff --git a/crates/horizon-client/examples/trading_fixture.rs b/crates/horizon-client/examples/trading_fixture.rs index 0bbfb0775..58824257c 100644 --- a/crates/horizon-client/examples/trading_fixture.rs +++ b/crates/horizon-client/examples/trading_fixture.rs @@ -384,6 +384,7 @@ fn main() -> horizon_client::Result<()> { enchantments: &enchantments, names: &names, trade: Some(&env_trade), + maps: None, }; trade(&mut out, name, &kv, &mut world, &env, origin)?; } diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index d858aeaef..07bf0b849 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -2551,6 +2551,8 @@ impl Game<'_> { 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)), + // LevelEvent.SOUND_PAGE_TURN (a lectern's page). + 1043 => Some(("minecraft:item.book.page_turn", 1.0)), _ => None, }; if let Some((name, volume)) = sound { @@ -2560,7 +2562,9 @@ impl Game<'_> { - self.world.random.next_float()) * 0.8 } - 1029 | 1030 | 1042 | 1044 => self.world.random.next_float() * 0.1 + 0.9, + 1029 | 1030 | 1042 | 1043 | 1044 => { + self.world.random.next_float() * 0.1 + 0.9 + } _ => 1.0, }; self.audio.play(name, c, volume, pitch); @@ -5436,6 +5440,7 @@ impl Game<'_> { .is_some_and(|s| s.kind == stations::Kind::Stonecutter); let station_kind = self.station.as_ref().map(|s| s.kind); let grindstone_open = station_kind == Some(stations::Kind::Grindstone); + let cartography_open = station_kind == Some(stations::Kind::Cartography); let anvil_open = station_kind == Some(stations::Kind::Anvil); let smithing_open = station_kind == Some(stations::Kind::Smithing); let enchanting_open = station_kind == Some(stations::Kind::Enchanting); @@ -5471,15 +5476,21 @@ impl Game<'_> { let mut v = vec![Some(stations::INPUT), Some(stations::RESULT)]; v.extend((9..36).chain(0..9).map(Some)); (Kind::Stonecutter, v) - } else if grindstone_open { - // GrindstoneMenu: the two inputs, the result, then the inventory. + } else if grindstone_open || cartography_open { + // GrindstoneMenu and CartographyTableMenu: the two inputs, the + // result, then the inventory. let mut v = vec![ Some(stations::INPUT), Some(stations::INPUT + 1), Some(stations::RESULT), ]; v.extend((9..36).chain(0..9).map(Some)); - (Kind::Grindstone, v) + let kind = if grindstone_open { + Kind::Grindstone + } else { + Kind::Cartography + }; + (kind, v) } else if enchanting_open { // EnchantmentMenu: the item, the lapis, then the inventory. let mut v = vec![Some(stations::INPUT), Some(stations::INPUT + 1)]; @@ -5604,6 +5615,18 @@ impl Game<'_> { if let Some((s, mob)) = session.as_mut() { self.merchant_sync_in(s, *mob); } + // The cartography table reads and makes the level's maps; a + // server's (the client menu's ContainerLevelAccess.NULL) doesn't. + let level_maps = (kind == Kind::Cartography && self.remote.is_none()).then(|| { + let held: Vec = before + .iter() + .flatten() + .chain(self.inventory.iter().flatten()) + .chain(self.carried.iter()) + .cloned() + .collect(); + self.level_maps(&held) + }); let next_map = if merchant_open { self.peek_map_id() } else { 0 }; let tag = |t: &str| self.structure_tag(t); let maps = trading::GameMaps { @@ -5626,6 +5649,9 @@ impl Game<'_> { enchantments: &self.res.stations().enchantments, names: &self.pack.names, trade: Some(&trade_env), + maps: level_maps + .as_ref() + .map(|m| m as &dyn horizon_client::menu::Maps), }; menu.creative = creative; menu.selected = self.selected; @@ -5729,6 +5755,10 @@ impl Game<'_> { self.station_sound(sound); } self.loom_screen_changed(); + } else if kind == Kind::Cartography { + for sound in sounds.into_iter().filter(|_| !predicting) { + self.station_sound(sound); + } } else if kind == Kind::Stonecutter { if let Some(s) = self.station.as_mut() { s.selected = usize::try_from(menu.data[0]).ok(); @@ -5778,6 +5808,9 @@ impl Game<'_> { } } self.apply_equipment(); + if let Some(maps) = level_maps { + self.register_made_maps(maps); + } true } /// Number keys, F and Q over a slot of the open menu: SWAP with a hotbar diff --git a/crates/horizon-client/src/game/books.rs b/crates/horizon-client/src/game/books.rs index 3dd49c005..ccc1c6e19 100644 --- a/crates/horizon-client/src/game/books.rs +++ b/crates/horizon-client/src/game/books.rs @@ -9,6 +9,7 @@ use horizon_client::{ hud::{HudBatch, rgba}, item_data::WrittenBook, items::ItemStack, + menu::{Kind, Menu}, text::Text, ui, }; @@ -89,6 +90,17 @@ impl Game<'_> { self.capture(false); } pub(super) fn close_book(&mut self) { + // A server's lectern: LecternScreen's menu closes (closeContainer). + if matches!( + self.book, + Some(BookScreen::View { + lectern: Some(_), + .. + }) + ) && self.remote.is_some() + { + self.remote_close_container(); + } self.book = None; self.capture(true); } @@ -319,38 +331,25 @@ impl Game<'_> { } } Some(BookScreen::View { - pages, - page, - lectern, - }) => { - let before = *page; + lectern: Some(key), .. + }) => lectern_page = Some(*key), + Some(BookScreen::View { pages, page, .. }) => { if forward && *page + 1 < pages.len() { *page += 1; } else if !forward && *page > 0 { *page -= 1; } - if *page != before - && let Some(pos) = *lectern - { - lectern_page = Some((pos, *page)); - } } None => return, } + // LecternScreen's page buttons click the menu's (1 back, 2 forward); + // the page turns with the server's data slot and level event 1043. + if let Some(key) = lectern_page { + self.lectern_button(key, if forward { 2 } else { 1 }); + return; + } self.audio .play("minecraft:item.book.page_turn", None, 1.0, 1.0); - if let Some((pos, page)) = lectern_page { - self.set_lectern_page(pos, page as i32); - } - } - /// `LecternBlockEntity.setPage` and `LecternBlock.signalPageChange`. - fn set_lectern_page(&mut self, key: (i32, i32, i32), page: i32) { - if let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) { - l.page = page; - } - self.set_lectern_powered(key, true); - self.lectern_pulses.push((key, 2)); - self.container_changed(key); } fn set_lectern_powered(&mut self, key: (i32, i32, i32), powered: bool) { self.set_lectern_property(key, "powered", powered); @@ -380,6 +379,7 @@ impl Game<'_> { } /// The 2-tick pulses of turned lecterns. pub(super) fn tick_lecterns(&mut self) { + self.follow_lectern(); let mut done = Vec::new(); for (key, left) in &mut self.lectern_pulses { *left -= 1; @@ -452,6 +452,7 @@ impl Game<'_> { .or_else(|| data.map(|d| d.writable_pages.clone())) .unwrap_or_default(); let page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); + self.stats.custom("interact_with_lectern", 1); self.open_book(BookScreen::View { pages, page, @@ -459,24 +460,189 @@ impl Game<'_> { }); true } - /// `LecternMenu` "Take Book". - fn take_lectern_book(&mut self, key: (i32, i32, i32)) { - let book = match self.world.block_entities.get_mut(&key) { - Some(BlockEntity::Lectern(l)) => { - l.page = 0; - l.book.take() + /// A `LecternMenu` button of the open lectern screen: on a server it is + /// sent (`handleInventoryButtonClick`); here the lectern's menu takes it + /// with the player's inventory, and the screen follows the block entity. + fn lectern_button(&mut self, key: (i32, i32, i32), id: i32) { + if self.remote.is_some() { + if let Some((container, _)) = self.remote.as_ref().and_then(|r| r.menu.as_ref()) { + self.send( + horizon_protocol::packets::play::Serverbound::ContainerButtonClick( + horizon_protocol::packets::play::ContainerButtonClick { + container: *container, + button: id, + }, + ), + ); } - _ => None, - }; - if let Some(book) = book - && let Some(rest) = self.give(book) - && let Some(eye) = self.eye_position() - { - self.spawn_item(rest, [eye[0], eye[1] - 0.3, eye[2]], [0.0, 0.1, 0.0], 40); + return; + } + let Some(mut menu) = self.lectern_menu(key) else { + return; + }; + for i in 0..36 { + menu.set_player_item(i, self.inventory[i].clone()); + } + menu.set_player_item(40, self.offhand.clone()); + menu.creative = self.creative; + menu.selected = self.selected; + menu.may_build = self.may_build(); + if !menu.button(&self.menu_env(), id) { + return; + } + for i in 0..36 { + self.inventory[i] = menu.player_item(i).cloned(); + } + self.offhand = menu.player_item(40).cloned(); + for stack in std::mem::take(&mut menu.dropped) { + self.player_drop(stack); + } + self.lectern_menu_done(key, &menu); + self.follow_lectern(); + } + /// The `book` control command: a button of the open book or lectern + /// screen (the page arrows, Take Book, Done), then its page. + pub(super) fn book_control( + &mut self, + action: Option<&str>, + ) -> horizon_client::Result { + let lectern = match &self.book { + Some(BookScreen::View { lectern, .. }) => *lectern, + Some(BookScreen::Edit { .. }) => None, + None => return Err("no book is open".into()), + }; + match action { + None => {} + Some("next") => self.turn_page(true), + Some("back") => self.turn_page(false), + Some("take") => match lectern { + Some(key) => self.lectern_button(key, 3), + None => return Err("not a lectern".into()), + }, + Some("done") => self.close_book(), + Some(other) => return Err(format!("unknown book button {other}").into()), + } + Ok(match &self.book { + Some(BookScreen::View { + pages, + page, + lectern, + }) => serde_json::json!({ + "page": page, "pages": pages.len(), "lectern": lectern.map(|k| [k.0, k.1, k.2]), + }), + Some(BookScreen::Edit { pages, page, .. }) => { + serde_json::json!({ "page": page, "pages": pages.len(), "lectern": null }) + } + None => serde_json::json!({ "closed": true }), + }) + } + /// A server's `minecraft:lectern` menu: LecternScreen, its book and + /// page to come (`remote_lectern_book`, `remote_lectern_page`). + pub(super) fn remote_open_lectern(&mut self, key: (i32, i32, i32)) { + self.open_book(BookScreen::View { + pages: Vec::new(), + page: 0, + lectern: Some(key), + }); + } + /// `LecternScreen.bookChanged`: the menu's book slot. + pub(super) fn remote_lectern_book(&mut self, book: Option) { + if let Some(BookScreen::View { + lectern: Some(_), + pages, + page, + }) = self.book.as_mut() + { + let data = book.as_ref().and_then(ItemStack::data); + *pages = data + .and_then(|d| d.written.as_ref().map(|w| w.pages.clone())) + .or_else(|| data.map(|d| d.writable_pages.clone())) + .unwrap_or_default(); + *page = (*page).min(pages.len().saturating_sub(1)); + } + } + /// `LecternScreen.pageChanged`: the menu's page data slot. + pub(super) fn remote_lectern_page(&mut self, value: i32) { + if let Some(BookScreen::View { + lectern: Some(_), + pages, + page, + }) = self.book.as_mut() + { + *page = (value.max(0) as usize).min(pages.len().saturating_sub(1)); + } + } + /// The server closed its lectern menu; false when none is open. + pub(super) fn remote_lectern_closed(&mut self) -> bool { + if !matches!( + self.book, + Some(BookScreen::View { + lectern: Some(_), + .. + }) + ) { + return false; + } + if let Some(r) = self.remote.as_mut() { + r.menu = None; + r.menu_title = None; + } + self.book = None; + self.capture(true); + true + } + /// `LecternMenu` over the lectern at `key` (the menu engine, for the + /// local player and LAN guests alike): its book and page. + pub(super) fn lectern_menu(&self, key: (i32, i32, i32)) -> Option { + let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get(&key) else { + return None; + }; + let mut menu = Menu::new(Kind::Lectern); + menu.set_slot(&self.menu_env(), 0, l.book.clone()); + menu.data[0] = l.page; + Some(menu) + } + /// The lectern menu's book and page back in the block entity: a new page + /// is `LecternBlock.signalPageChange` (the 2-tick pulse, level event + /// 1043), a book gone `onBookItemRemove` (`resetBookState`). + pub(super) fn lectern_menu_done(&mut self, key: (i32, i32, i32), menu: &Menu) { + let Some(BlockEntity::Lectern(l)) = self.world.block_entities.get_mut(&key) else { + return; + }; + let (had, before) = (l.book.is_some(), l.page); + l.book = menu.slot(0).cloned(); + l.page = menu.data[0]; + if had && l.book.is_none() { + self.set_lectern_powered(key, false); + self.set_lectern_property(key, "has_book", false); + self.container_changed(key); + } else if menu.data[0] != before { + self.set_lectern_powered(key, true); + self.lectern_pulses.push((key, 2)); + self.level_event_at(1043, [key.0, key.1, key.2], 0); + self.container_changed(key); + } + } + /// The open lectern screen follows its block entity (`LecternScreen`'s + /// menu listener): the page, and closing once the book is gone. + pub(super) fn follow_lectern(&mut self) { + let Some(BookScreen::View { + lectern: Some(key), + page, + pages, + }) = self.book.as_mut() + else { + return; + }; + if self.remote.is_some() { + return; + } + match self.world.block_entities.get(key) { + Some(BlockEntity::Lectern(l)) if l.book.is_some() => { + *page = (l.page.max(0) as usize).min(pages.len().saturating_sub(1)); + } + _ => self.close_book(), } - self.set_lectern_property(key, "has_book", false); - self.container_changed(key); - self.close_book(); } pub(super) fn book_click(&mut self, size: [u32; 2]) { let b = HudBatch::new(size); @@ -537,7 +703,8 @@ impl Game<'_> { self.close_book(); } else if inside(w / 2.0 + 2.0, 196.0, 98.0, 20.0) { click(self); - self.take_lectern_book(key); + // LecternScreen's Take Book: the menu's button 3. + self.lectern_button(key, 3); } } else if inside((w - 200.0) / 2.0, 196.0, 200.0, 20.0) { click(self); diff --git a/crates/horizon-client/src/game/cartography.rs b/crates/horizon-client/src/game/cartography.rs index 4a5738f6e..b8b57666a 100644 --- a/crates/horizon-client/src/game/cartography.rs +++ b/crates/horizon-client/src/game/cartography.rs @@ -1,70 +1,80 @@ -//! The cartography table (`CartographyTableMenu`, `CartographyTableScreen`): -//! zooming a map out with paper, cloning it with an empty map, locking it -//! with a glass pane, the post-processing on take (`MapItem.scaleMap`, -//! `lockMap`) and the preview with its error and lock sprites. +//! The cartography table (`CartographyTableMenu` on the menu engine, +//! `CartographyTableScreen`): zooming a map out with paper, cloning it with +//! an empty map, locking it with a glass pane. The engine reads the level's +//! maps through `LevelMaps`; the scaled and locked copies a take makes +//! (`MapItem.scaleMap`, `lockMap`) are registered after the click. The +//! screen draws the preview with its error and lock sprites. use super::{ Game, maps::{MapData, map_id}, - stations::Station, }; -use horizon_client::{hud::HudBatch, items::ItemStack}; +use horizon_client::{hud::HudBatch, items::ItemStack, menu::Maps}; +use std::{ + cell::{Cell, RefCell}, + collections::HashMap, +}; + +/// The level's maps as a menu sees them (`ContainerLevelAccess`): the +/// states of the maps the click can reach, and the copies it makes. +pub(super) struct LevelMaps { + states: RefCell>, + next_id: Cell, + /// (new id, source id, scaled) for each copy made. + made: RefCell>, +} + +impl Maps for LevelMaps { + fn state(&self, id: i32) -> Option<(bool, u8)> { + self.states.borrow().get(&id).copied() + } + + fn derive(&self, id: i32, scale: bool) -> Option { + let (_, s) = self.state(id)?; + let new = self.next_id.get(); + self.next_id.set(new + 1); + let made = if scale { + (false, (s + 1).min(4)) + } else { + (true, s) + }; + self.states.borrow_mut().insert(new, made); + self.made.borrow_mut().push((new, id, scale)); + Some(new) + } +} impl Game<'_> { - /// `setupResultSlot`. - pub(super) fn cartography_result(&self, s: &Station) -> Option { - let (map, extra) = (s.inputs[0].as_ref()?, s.inputs[1].as_ref()?); - let data = self.maps.data.get(&map_id(map)?)?; - match &*extra.item { - "minecraft:paper" if !data.locked && data.scale < 4 => Some(ItemStack { - count: 1, - ..map.clone() - }), - "minecraft:glass_pane" if !data.locked => Some(ItemStack { - count: 1, - ..map.clone() - }), - "minecraft:map" => Some(ItemStack { - count: 2, - ..map.clone() - }), - _ => None, + /// The maps of `stacks` (loaded as needed) for a menu over this level. + pub(super) fn level_maps<'s>( + &mut self, + stacks: impl IntoIterator, + ) -> LevelMaps { + let ids: Vec = stacks.into_iter().filter_map(map_id).collect(); + let mut states = HashMap::new(); + for id in ids { + if let Some(m) = self.map(id) { + states.insert(id, (m.locked, m.scale)); + } + } + LevelMaps { + states: RefCell::new(states), + next_id: Cell::new(self.peek_map_id()), + made: RefCell::new(Vec::new()), } } - /// `onCraftedPostProcess` for the taken result: a scaled or locked copy - /// under a new map id. Also spends the inputs' extra item kind check. - pub(super) fn cartography_post(&mut self, mut result: ItemStack) -> ItemStack { - let extra = self - .station - .as_ref() - .and_then(|s| s.inputs[1].as_ref()) - .map(|e| e.item.clone()); - let Some(id) = map_id(&result) else { - return result; - }; - let new = match extra.as_deref() { - Some("minecraft:paper") => self.map(id).map(|m| m.scaled()), - Some("minecraft:glass_pane") => self.map(id).map(|m| m.locked_copy()), - _ => None, - }; - if let Some(data) = new { - let new_id = self.new_map_id(data); - result.data_mut().map_id = Some(new_id); + + /// The scaled and locked copies a menu made (`level.setMapData`). + pub(super) fn register_made_maps(&mut self, maps: LevelMaps) { + for (id, source, scale) in maps.made.into_inner() { + let Some(data) = self + .map(source) + .map(|m| if scale { m.scaled() } else { m.locked_copy() }) + else { + continue; + }; + let new = self.new_map_id(data); + debug_assert_eq!(new, id, "map ids follow peek_map_id"); } - result - } - /// The take sound (once per tick). - pub(super) fn cartography_taken(&mut self, pos: [i32; 3]) { - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; - self.audio.play( - "minecraft:ui.cartography_table.take_result", - Some(at), - 1.0, - 1.0, - ); } /// `CartographyTableScreen.extractBackground` after the background. pub(super) fn draw_cartography(&mut self, batch: &mut HudBatch, ox: f32, oy: f32) { diff --git a/crates/horizon-client/src/game/lan_actions.rs b/crates/horizon-client/src/game/lan_actions.rs index 962949a0d..c602a3c63 100644 --- a/crates/horizon-client/src/game/lan_actions.rs +++ b/crates/horizon-client/src/game/lan_actions.rs @@ -55,6 +55,8 @@ pub(super) struct GuestPlay { pub(super) crafting: super::lan_crafting::GuestCrafting, /// The workstation menu the guest has open (game/lan_stations.rs). pub(super) station: Option, + /// The lectern the guest reads (game/lan_stations.rs). + pub(super) lectern: Option, /// What the guest's body was given for its effects and enchantments. potions: super::potions::BodyPotions, /// `ServerPlayer.getStats` and the inventory `inventory_changed` last saw. @@ -478,7 +480,13 @@ impl Game<'_> { self.container = container; self.screen = screen; self.sign_edit = host_sign; - self.book = host_book; + // A lectern the guest's use opened (LecternBlock.openScreen). + let guest_lectern = match std::mem::replace(&mut self.book, host_book) { + Some(super::books::BookScreen::View { + lectern: Some(key), .. + }) => Some(key), + _ => None, + }; self.command_block_screen = host_command_block; self.mount_menu = host_mount_menu; self.keys = host_keys; @@ -573,6 +581,9 @@ impl Game<'_> { if let Some(station) = opened_station { self.lan_station_opened(host, conn, station); } + if let Some(key) = guest_lectern { + self.lan_open_lectern(host, conn, key); + } if opened_table { self.lan_open_crafting(host, conn); } @@ -924,6 +935,7 @@ impl Game<'_> { S::ContainerClick(p) if self.lan_crafting_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_machine_click(host, conn, &p) => {} S::ContainerClick(p) if self.lan_station_click(host, conn, &p) => {} + S::ContainerClick(p) if self.lan_lectern_click(host, conn, &p) => {} S::ContainerButtonClick(p) => { self.lan_station_button(host, conn, p.container, p.button); } diff --git a/crates/horizon-client/src/game/lan_crafting.rs b/crates/horizon-client/src/game/lan_crafting.rs index 64cf0dd0d..cb3b0a2c9 100644 --- a/crates/horizon-client/src/game/lan_crafting.rs +++ b/crates/horizon-client/src/game/lan_crafting.rs @@ -94,6 +94,7 @@ impl Game<'_> { enchantments: &self.res.stations().enchantments, names: &self.pack.names, trade: None, + maps: None, } } @@ -105,9 +106,25 @@ impl Game<'_> { menu: &mut Menu, op: impl FnOnce(&mut Menu, &Env) -> R, ) -> R { - let env = self.menu_env(); + // The cartography table reads and makes the host level's maps. + let maps = (menu.kind() == Kind::Cartography).then(|| { + let g = &host.hub.guests[gi]; + let held: Vec = (0..menu.slot_count()) + .filter_map(|s| menu.slot(s).cloned()) + .chain(g.inventory.iter().flatten().cloned()) + .chain(g.carried.clone()) + .collect(); + self.level_maps(&held) + }); + let env = Env { + maps: maps.as_ref().map(|m| m as &dyn horizon_client::menu::Maps), + ..self.menu_env() + }; load_player(menu, &host.hub.guests[gi]); let result = op(menu, &env); + if let Some(maps) = maps { + self.register_made_maps(maps); + } let dropped = std::mem::take(&mut menu.dropped); let equipped = std::mem::take(&mut menu.equipped); menu.drops.clear(); diff --git a/crates/horizon-client/src/game/lan_stations.rs b/crates/horizon-client/src/game/lan_stations.rs index 0d04dfe11..25921f936 100644 --- a/crates/horizon-client/src/game/lan_stations.rs +++ b/crates/horizon-client/src/game/lan_stations.rs @@ -31,6 +31,16 @@ pub(super) struct GuestStation { last_sound: u64, } +/// A guest's open lectern: `LecternMenu` over the block entity, made on the +/// menu engine for each click (`Game::lectern_menu`). +pub(super) struct GuestLectern { + window: i32, + state: i32, + key: (i32, i32, i32), + /// The book and page the client was last sent (`broadcastChanges`). + sent: Option<(Option, i32)>, +} + /// The `MenuType`, the engine's menu and the input slots /// (`clearContainer`'s container) of a station a guest can use. fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range)> { @@ -42,6 +52,7 @@ fn menu_of(kind: StationKind) -> Option<(&'static str, Kind, std::ops::Range ("minecraft:smithing", Kind::Smithing, 0..3), StationKind::Enchanting => ("minecraft:enchantment", Kind::Enchanting, 0..2), StationKind::Beacon => ("minecraft:beacon", Kind::Beacon, 0..1), + StationKind::Cartography => ("minecraft:cartography_table", Kind::Cartography, 0..2), _ => return None, }) } @@ -130,6 +141,115 @@ impl Game<'_> { true } + /// `LecternBlock.openScreen` for a guest: `minecraft:lectern` over the + /// block entity, with its book and page. + pub(super) fn lan_open_lectern(&mut self, host: &mut LanHost, conn: u32, key: (i32, i32, i32)) { + self.lan_station_closed(host, conn, None); + self.lan_crafting_closed(host, conn, None); + self.guest_container_closed(host, conn); + let title = horizon_protocol::text::translatable("container.lectern", &[]); + let Some(window) = host.hub.open_window(conn, "minecraft:lectern", title) else { + return; + }; + host.play.entry(conn).or_default().lectern = Some(GuestLectern { + window, + state: 0, + key, + sent: None, + }); + self.lan_send_lectern(host, conn, true); + } + + /// The lectern's book and page for the client: everything (`all`), or + /// what changed since it was last sent. + fn lan_send_lectern(&mut self, host: &mut LanHost, conn: u32, all: bool) { + let Some(gl) = host.play.get_mut(&conn).and_then(|p| p.lectern.as_mut()) else { + return; + }; + let (book, page) = match self.world.block_entities.get(&gl.key) { + Some(BlockEntity::Lectern(l)) => (l.book.clone(), l.page), + _ => (None, 0), + }; + let now = Some((book.clone(), page)); + if !all && gl.sent == now { + return; + } + let page_changed = gl.sent.as_ref().is_none_or(|(_, p)| *p != page); + gl.sent = now; + gl.state = (gl.state + 1) & 0x7FFF; + let (window, state) = (gl.window, gl.state); + let carried = host + .hub + .guests + .iter() + .find(|g| g.conn == conn) + .and_then(|g| g.carried.clone()); + let content = C::ContainerSetContent(play::ContainerSetContent { + container: window, + state, + items: vec![host.hub.stack(&book)], + carried: host.hub.stack(&carried), + }); + host.hub.send_to(conn, &content); + if all || page_changed { + host.hub.send_to( + conn, + &C::ContainerSetData(play::ContainerSetData { + container: window, + id: 0, + value: page as i16, + }), + ); + } + } + + /// Runs `op` on the guest's lectern menu (window `window`) with their + /// inventory, the block entity takes the book and page back, and the + /// client gets what changed. False when no such window is open. + fn lan_lectern_op( + &mut self, + host: &mut LanHost, + conn: u32, + window: i32, + op: impl FnOnce(&mut Menu, &horizon_client::menu::Env), + ) -> bool { + let Some(key) = host + .play + .get(&conn) + .and_then(|p| p.lectern.as_ref()) + .filter(|l| l.window == window) + .map(|l| l.key) + else { + return false; + }; + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && !host.hub.guests[gi].spectator() + && let Some(mut menu) = self.lectern_menu(key) + { + // Player.mayBuild: survival and creative. + let may_build = matches!(host.hub.guests[gi].game_mode, 0 | 1); + self.guest_menu_op(host, gi, &mut menu, |menu, env| { + menu.may_build = may_build; + op(menu, env); + }); + self.lectern_menu_done(key, &menu); + } + self.lan_send_lectern(host, conn, true); + true + } + + /// A click on the guest's lectern window; false for other windows. + pub(super) fn lan_lectern_click( + &mut self, + host: &mut LanHost, + conn: u32, + p: &play::ContainerClick, + ) -> bool { + self.lan_lectern_op(host, conn, p.container, |menu, env| { + let _ = menu.click(env, i32::from(p.slot), i32::from(p.button), input(p.input)); + }) + } + /// 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). @@ -193,8 +313,11 @@ impl Game<'_> { return; }; let need = button as i32 + 1; - // Player.onEnchantmentPerformed. - self.as_guest(host, conn, |game| game.give_levels(-need)); + // Player.onEnchantmentPerformed, and EnchantmentMenu's awardStat(ENCHANT_ITEM). + self.as_guest(host, conn, |game| { + game.give_levels(-need); + game.stats.custom("enchant_item", 1); + }); host.hub.guests[gi].xp_seed = self.world.random.next_int(); let env = self.menu_env(); let lapis = gs.menu.slot(1).cloned().filter(|_| !creative).map(|mut l| { @@ -267,6 +390,12 @@ impl Game<'_> { window: i32, id: i32, ) { + // LecternMenu's page buttons and Take Book. + if self.lan_lectern_op(host, conn, window, |menu, env| { + menu.button(env, id); + }) { + return; + } self.lan_station_op(host, conn, Some(window), |menu, env| { menu.button(env, id); }); @@ -322,6 +451,22 @@ impl Game<'_> { conn: u32, window: Option, ) -> bool { + // A lectern's menu keeps nothing of its own (the book is the block entity's). + let lectern = host + .play + .get_mut(&conn) + .and_then(|p| p.lectern.take_if(|l| window.is_none_or(|w| l.window == w))); + if lectern.is_some() { + // AbstractContainerMenu.removed: the carried stack goes back. + if let Some(gi) = host.hub.guests.iter().position(|g| g.conn == conn) + && let Some(carried) = host.hub.guests[gi].carried.take() + { + self.lan_place_back(host, gi, vec![carried]); + } + if window.is_some() { + return true; + } + } let Some(gs) = host .play .get_mut(&conn) @@ -423,6 +568,7 @@ impl Game<'_> { /// `ServerPlayer.doTick`'s `stillValid`: a guest's station closes once its /// block is gone or the guest is out of reach (`isWithinBlockInteractionRange(pos, 4)`). pub(super) fn lan_stations_tick(&mut self, host: &mut LanHost) { + self.lan_lecterns_tick(host); let conns: Vec = host .play .iter() @@ -473,6 +619,51 @@ impl Game<'_> { } } +impl Game<'_> { + /// The guests' lecterns each tick: `stillValid` (the block entity, its + /// book, the reach) closes them, and `broadcastChanges` sends a book or + /// page another player changed. + fn lan_lecterns_tick(&mut self, host: &mut LanHost) { + let open: Vec<(u32, i32, (i32, i32, i32))> = host + .play + .iter() + .filter_map(|(c, p)| p.lectern.as_ref().map(|l| (*c, l.window, l.key))) + .collect(); + for (conn, window, key) in open { + let Some(g) = host.hub.guests.iter().find(|g| g.conn == conn) else { + continue; + }; + if !host.hub.here(g) { + continue; + } + let has_book = matches!( + self.world.block_entities.get(&key), + Some(BlockEntity::Lectern(l)) if l.book.is_some() + ); + // Container.stillValidBlockEntity: the interaction range and its buffer. + let eye = [g.position[0], g.position[1] + g.eye_height(), g.position[2]]; + let reach = if g.creative() { 5.0 } else { 4.5 } + 4.0; + let pos = [key.0, key.1, key.2]; + let near = (0..3) + .map(|k| { + let lo = f64::from(pos[k]); + (lo - eye[k]).max(eye[k] - lo - 1.0).max(0.0).powi(2) + }) + .sum::() + < reach * reach; + if has_book && near { + self.lan_send_lectern(host, conn, false); + } else { + self.lan_station_closed(host, conn, Some(window)); + host.hub.send_to( + conn, + &C::ContainerClose(play::ContainerClose { container: window }), + ); + } + } + } +} + /// What `clearContainer` gives back from a station's menu. pub(super) fn station_inputs(gs: &GuestStation) -> Vec { menu_of(gs.kind) diff --git a/crates/horizon-client/src/game/lan_trading.rs b/crates/horizon-client/src/game/lan_trading.rs index 587e67fa8..786399dac 100644 --- a/crates/horizon-client/src/game/lan_trading.rs +++ b/crates/horizon-client/src/game/lan_trading.rs @@ -259,6 +259,7 @@ impl Game<'_> { enchantments: &self.res.stations().enchantments, names: &self.pack.names, trade: Some(&trade_env), + maps: None, }; 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 ec19c0caf..d3c14ffc7 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -283,6 +283,7 @@ impl Game<'_> { enchantments: &self.res.stations().enchantments, names: &self.pack.names, trade: None, + maps: None, }; for i in 0..36 { menu.set_player_item(i, self.inventory[i].clone()); diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index fb0aa2356..ddac1d7de 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -503,6 +503,26 @@ impl Game<'_> { if let Some(Component::Int(cost)) = s.component(component::REPAIR_COST) { out.data_mut().repair_cost = (*cost).max(0) as u32; } + if let Some(Component::Int(mode)) = s.component(component::MAP_POST_PROCESSING) { + out.data_mut().map_post_processing = Some((*mode).clamp(0, 1) as u8); + } + if let Some(Component::WritableBook(pages)) = s.component(component::WRITABLE_BOOK_CONTENT) + { + out.data_mut().writable_pages = pages.clone(); + } + if let Some(Component::WrittenBook(b)) = s.component(component::WRITTEN_BOOK_CONTENT) { + let lang = self + .remote + .as_ref() + .map(|r| r.lang.clone()) + .unwrap_or_default(); + out.data_mut().written = Some(horizon_client::item_data::WrittenBook { + title: b.title.clone(), + author: b.author.clone(), + generation: b.generation.clamp(0, 3) as u8, + pages: b.pages.iter().map(|p| plain(p, &lang)).collect(), + }); + } if let Some(Component::Text(name)) = s.component(component::CUSTOM_NAME) { let lang = self .remote @@ -1280,6 +1300,7 @@ impl Game<'_> { "minecraft:smithing" => Kind::Smithing, "minecraft:enchantment" => Kind::Enchanting, "minecraft:beacon" => Kind::Beacon, + "minecraft:cartography_table" => Kind::Cartography, _ => return None, }) } @@ -1291,6 +1312,12 @@ impl Game<'_> { } fn set_menu_slot(&mut self, container: i32, slot: i32, item: Option) { let menu = self.open_menu_name(container); + if menu == "minecraft:lectern" { + if slot == 0 { + self.remote_lectern_book(item); + } + return; + } if container != 0 && menu == "inventory" { return; } @@ -1948,6 +1975,9 @@ impl Game<'_> { } self.remote_synced(); } + C::ContainerSetData(p) if self.open_menu_name(p.container) == "minecraft:lectern" => { + self.remote_lectern_page(i32::from(p.value)); + } C::ContainerSetData(p) if self.remote_station_open(p.container) => { self.remote_station_data(usize::try_from(p.id).unwrap_or(usize::MAX), p.value); } @@ -1987,6 +2017,7 @@ impl Game<'_> { C::RecipeBookSettings(p) => self.remote_recipe_book_settings(p), C::PlaceGhostRecipe(p) => self.remote_ghost_recipe(p), C::MerchantOffers(p) => self.remote_merchant_offers(p), + C::ContainerClose(_) if self.remote_lectern_closed() => {} C::ContainerClose(_) => { if self.screen == Screen::Inventory { self.remote_close_local(); @@ -4039,6 +4070,14 @@ impl Game<'_> { .as_ref() .and_then(|r| r.use_target) .map(|t| (t[0], t[1], t[2])); + if menu == "minecraft:lectern" { + // LecternScreen: the book and page come in the menu's content and data. + if let Some(r) = self.remote.as_mut() { + r.menu = Some((p.container, menu)); + } + self.remote_open_lectern(target.unwrap_or_default()); + return; + } if let Some(kind) = Self::remote_station_kind(&menu) { let title = plain( &p.title, diff --git a/crates/horizon-client/src/game/remote_stations.rs b/crates/horizon-client/src/game/remote_stations.rs index c6b61a76f..b46725345 100644 --- a/crates/horizon-client/src/game/remote_stations.rs +++ b/crates/horizon-client/src/game/remote_stations.rs @@ -51,7 +51,12 @@ impl Game<'_> { if !self.station.as_ref().is_some_and(|s| { matches!( s.kind, - Kind::Loom | Kind::Stonecutter | Kind::Grindstone | Kind::Anvil | Kind::Smithing + Kind::Loom + | Kind::Stonecutter + | Kind::Grindstone + | Kind::Anvil + | Kind::Smithing + | Kind::Cartography ) }) { return; diff --git a/crates/horizon-client/src/game/station_control.rs b/crates/horizon-client/src/game/station_control.rs index 75ad9225e..ecbbad0b8 100644 --- a/crates/horizon-client/src/game/station_control.rs +++ b/crates/horizon-client/src/game/station_control.rs @@ -10,6 +10,7 @@ pub(super) const HELP: &[&str] = &[ "use X Y Z open the block's menu as if right-clicked", "click-slot ID [right] [shift] click a menu slot (0-35 inventory, 300+ container, 600+ station, 650 result)", "click-gui X Y [right] [shift] click at GUI pixel X Y relative to the menu's top-left corner", + "book [next|back|take|done] the open book or lectern: its page, or press one of its buttons", "type TEXT | type-back type into the anvil name box / delete one character", "enchant ID LEVEL enchant the held item (books store the enchantment)", "potion ITEM POTION give a potion item (potion, splash_potion, lingering_potion, tipped_arrow)", @@ -136,6 +137,7 @@ impl Game<'_> { self.apply_equipment(); ok() } + "book" => Ok(Some(self.book_control(words.get(1).copied())?)), "potion" => { let stack = ItemStack::new(&id(arg(1)?), 1).with_potion(&id(arg(2)?)); let rest = self.give(stack); diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index d0d1e10bb..ffe56d699 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -494,11 +494,9 @@ impl Game<'_> { // The menu engine keeps the merchant's result (Game::menu_session). Kind::Merchant => {} Kind::Beacon => {} - Kind::Cartography => s.result = self.cartography_result(&s), - // The menu engine keeps the loom's state (Game::menu_session). - Kind::Loom => {} - // The menu engine keeps the stonecutter's state (Game::menu_session). - Kind::Stonecutter => {} + // The menu engine keeps the cartography table's, the loom's and + // the stonecutter's state (Game::menu_session). + Kind::Cartography | Kind::Loom | Kind::Stonecutter => {} } self.station = Some(s); } @@ -532,19 +530,7 @@ impl Game<'_> { if slot == RESULT { return (false, 64); } - let i = slot - INPUT; - match s.kind { - Kind::Loom => (false, 64), - Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), - Kind::Cartography => ( - matches!( - &*stack.item, - "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" - ), - 64, - ), - _ => (true, 64), - } + (s.kind != Kind::Loom, 64) } /// `AbstractContainerMenu.doClick` PICKUP on a filtered slot. pub(super) fn click_filtered(&mut self, slot: usize, right: bool) { @@ -643,72 +629,6 @@ impl Game<'_> { } stack.count != start } - /// The player inventory in menu order: main rows, then the hotbar. - fn player_slots() -> Vec { - (9..36).chain(0..9).collect() - } - /// A shift-click: `AbstractContainerMenu.doClick`'s QUICK_MOVE repeats - /// `quickMoveStack` while it moves something and the slot still holds the - /// same item. - fn quick_move(&mut self, slot: usize) { - while let Some(item) = self.slot_mut(slot).as_ref().map(|s| s.item.clone()) - && self.quick_move_once(slot) - && self.slot_mut(slot).as_ref().is_some_and(|s| s.item == item) - {} - } - /// The station menu's `quickMoveStack` for one slot (`EnchantmentMenu`, - /// `BeaconMenu`, `GrindstoneMenu`, `StonecutterMenu`, - /// `CartographyTableMenu`, and `ItemCombinerMenu` with `SmithingMenu`'s - /// `canMoveIntoInputSlots`); whether the stack's count changed. Each - /// rule that names its target slots moves nowhere else when they are full. - fn quick_move_once(&mut self, slot: usize) -> bool { - let Some(kind) = self.station.as_ref().map(|s| s.kind) else { - return false; - }; - let Some(mut stack) = self.slot_mut(slot).take() else { - return false; - }; - let start = stack.count; - // The other half of the inventory: main rows to the hotbar and back. - let halves: Vec = if slot < 9 { - (9..36).collect() - } else { - (0..9).collect() - }; - if slot >= INPUT { - // An input slot: into the inventory. - self.move_to(&mut stack, &Self::player_slots(), false); - } else { - match kind { - Kind::Cartography => { - if super::maps::map_id(&stack).is_some() { - self.move_to(&mut stack, &[INPUT], false); - } else if matches!( - &*stack.item, - "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" - ) { - self.move_to(&mut stack, &[INPUT + 1], false); - } else { - self.move_to(&mut stack, &halves, false); - } - } - // Their clicks run on the menu engine. - Kind::Merchant - | Kind::Loom - | Kind::Stonecutter - | Kind::Grindstone - | Kind::Anvil - | Kind::Smithing - | Kind::Enchanting - | Kind::Beacon => {} - } - } - let moved = stack.count != start; - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); - } - 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 @@ -821,95 +741,6 @@ impl Game<'_> { _ => true, } } - /// The result slot's `onTake`. - fn take_result(&mut self) { - let Some(mut s) = self.station.take() else { - return; - }; - let pos = s.pos; - match s.kind { - // 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 { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - self.cartography_taken(pos); - } - } - Kind::Loom => {} - Kind::Enchanting => {} - } - self.station = Some(s); - self.station_changed(); - } - fn click_result(&mut self, shift: bool) { - loop { - let Some(result) = self.station.as_ref().and_then(|s| s.result.clone()) else { - return; - }; - if !self.may_take_result() { - return; - } - let result = if self - .station - .as_ref() - .is_some_and(|s| s.kind == Kind::Cartography) - { - self.cartography_post(result) - } else { - result - }; - if shift { - let mut stack = result.clone(); - let player = Self::player_slots(); - // Simulate first so nothing is lost when the inventory is full. - let saved: Vec> = self.inventory.clone(); - self.move_to(&mut stack, &player, true); - if stack.count > 0 { - self.inventory = saved; - return; - } - } else { - match &mut self.carried { - None => self.carried = Some(result.clone()), - Some(c) - if c.same_item_same_components(&result) - && c.count + result.count - <= self.res.items().get(&c.item).map_or(64, |i| i.max_stack) => - { - c.count += result.count - } - _ => return, - } - } - if let Some(s) = self.station.as_mut() { - s.result = None; - } - self.take_result(); - let again = shift - && self - .station - .as_ref() - .and_then(|s| s.result.as_ref()) - .is_some_and(|r| r.item == result.item); - if !again { - return; - } - } - } /// `EnchantmentMenu.clickMenuButton`. fn click_enchant(&mut self, button: usize) { let Some(s) = self.station.as_ref() else { @@ -1044,45 +875,14 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; - if self.station.as_ref().is_none_or(|s| { - matches!( - s.kind, - Kind::Loom - | Kind::Merchant - | Kind::Stonecutter - | Kind::Grindstone - | Kind::Anvil - | Kind::Smithing - | Kind::Enchanting - | Kind::Beacon - ) - }) { - // LoomMenu, MerchantMenu, StonecutterMenu, GrindstoneMenu, AnvilMenu, - // SmithingMenu, EnchantmentMenu, BeaconMenu and the brewing stand's - // BrewingStandMenu clicks run on the verified menu engine. - let input = if shift { - horizon_client::menu::Input::QuickMove - } else { - horizon_client::menu::Input::Pickup - }; - self.menu_click(Some(slot), i32::from(right), input); - return true; - } - if slot == RESULT { - self.click_result(shift); - return true; - } - if shift { - self.quick_move(slot); - } else if slot >= INPUT { - self.click_filtered(slot, right); + // Every station's clicks (and the brewing stand's) run on the + // verified menu engine. + let input = if shift { + horizon_client::menu::Input::QuickMove } else { - return false; - } - if let Some(key) = self.container { - self.world.modified.insert((key.0 >> 4, key.2 >> 4)); - } - self.station_after_input(); + horizon_client::menu::Input::Pickup + }; + self.menu_click(Some(slot), i32::from(right), input); true } /// Recompute after slot changes; the anvil box follows its input item. diff --git a/crates/horizon-client/src/item_data.rs b/crates/horizon-client/src/item_data.rs index adc4e0f18..2ba8d39a9 100644 --- a/crates/horizon-client/src/item_data.rs +++ b/crates/horizon-client/src/item_data.rs @@ -594,12 +594,8 @@ pub fn components_tag(damage: u32, data: Option<&StackData>) -> Option { ), )); } - if let Some(mode) = d.map_post_processing { - entries.push(( - "minecraft:map_post_processing", - Tag::String(if mode == 0 { "lock" } else { "scale" }.into()), - )); - } + // minecraft:map_post_processing is transient: ItemStack.CODEC never + // saves it (only the network carries it). if !d.charged.is_empty() { entries.push(( "minecraft:charged_projectiles", diff --git a/crates/horizon-client/src/lan/guest.rs b/crates/horizon-client/src/lan/guest.rs index 8440fac6c..4be5aa29f 100644 --- a/crates/horizon-client/src/lan/guest.rs +++ b/crates/horizon-client/src/lan/guest.rs @@ -427,6 +427,37 @@ pub fn stack_to_network( horizon_protocol::item::Component::Int(d.repair_cost as i32), )); } + if let Some(mode) = d.map_post_processing { + stack.added.push(( + horizon_protocol::item::component::MAP_POST_PROCESSING, + horizon_protocol::item::Component::Int(i32::from(mode)), + )); + } + // The books a lectern shows and a guest reads. + if !d.writable_pages.is_empty() { + stack.added.push(( + horizon_protocol::item::component::WRITABLE_BOOK_CONTENT, + horizon_protocol::item::Component::WritableBook(d.writable_pages.clone()), + )); + } + if let Some(w) = &d.written { + stack.added.push(( + horizon_protocol::item::component::WRITTEN_BOOK_CONTENT, + horizon_protocol::item::Component::WrittenBook( + horizon_protocol::item::WrittenBook { + title: w.title.clone(), + author: w.author.clone(), + generation: i32::from(w.generation), + pages: w + .pages + .iter() + .map(|p| horizon_protocol::text::literal(p)) + .collect(), + resolved: true, + }, + ), + )); + } } if let Some(name) = s.custom_name() { stack.added.push(( diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index b72b74762..cb804e15b 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -33,6 +33,20 @@ pub struct Env<'a> { 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>>, + /// The level's maps (`ContainerLevelAccess`): the cartography table reads + /// and makes them. None is a client's menu (`ContainerLevelAccess.NULL`): + /// it makes no result, and a taken result keeps its map id. + pub maps: Option<&'a dyn Maps>, +} + +/// The maps of the level a menu is in. +pub trait Maps { + /// `MapItem.getSavedData`: whether map `id` is locked, and its scale; + /// None when the level has no such map. + fn state(&self, id: i32) -> Option<(bool, u8)>; + /// `MapItem.scaleMap` (`scale`) or `lockMap`: the copy of map `id` the + /// level makes under a new id (`getFreeMapId`), None without the map. + fn derive(&self, id: i32, scale: bool) -> Option; } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -92,6 +106,12 @@ pub enum Kind { /// `BeaconMenu`: the payment slot, then the inventory; its data slots are /// the pyramid's levels and the two powers (`encodeEffect`: id + 1). Beacon, + /// `CartographyTableMenu`: the map, the paper / map / glass pane, the + /// result, then the inventory. + Cartography, + /// `LecternMenu` over the `LecternBlockEntity`: the book's one slot (no + /// inventory slots); its data slot is the open page. + Lectern, /// `MerchantMenu`: two payment slots, the result, then the inventory. Merchant, /// `CreativeModeInventoryScreen.ItemPickerMenu`: an item tab's 45 @@ -123,6 +143,8 @@ impl Kind { "smithing" => Self::Smithing, "enchanting" => Self::Enchanting, "beacon" => Self::Beacon, + "cartography" => Self::Cartography, + "lectern" => Self::Lectern, "merchant" => Self::Merchant, "item_picker" => Self::ItemPicker, _ => return None, @@ -176,6 +198,12 @@ enum Role { Lapis, /// `BeaconMenu.PaymentSlot`: one beacon payment item. BeaconPay, + /// The cartography table's map slot (anything with a map id). + CartoMap, + /// Its paper, empty map or glass pane slot. + CartoExtra, + /// Its result (`onTake`: one of each input, the map post-processed). + CartoResult, /// `CustomCreativeSlot`: a creative tab's display slot, which the /// screen clicks itself; drags and PICKUP_ALL pass it by. CreativeDisplay, @@ -268,6 +296,8 @@ pub struct Menu { /// An enchanting button the menu took (`clickMenuButton` passed its /// checks): the caller (with a level) enchants. pub enchant_button: Option, + /// `Player.mayBuild` (not adventure mode): the lectern's Take Book. + pub may_build: bool, } /// `AnvilMenu`'s state besides its slots and `cost`. @@ -304,6 +334,15 @@ fn split(stack: &mut ItemStack, amount: u32) -> ItemStack { out } +/// `LecternBlockEntity.getPageCount`: a written book's pages, else a +/// writable book's. +pub fn book_pages(stack: &ItemStack) -> usize { + stack.data().map_or(0, |d| match &d.written { + Some(w) => w.pages.len(), + None => d.writable_pages.len(), + }) +} + fn tidy(slot: &mut Option) { if slot.as_ref().is_some_and(|s| s.count == 0) { *slot = None; @@ -499,6 +538,28 @@ impl Menu { // levels, primary, secondary. data = 3; } + Kind::Cartography => { + containers[MAIN] = vec![None; 2]; + for (index, role) in [Role::CartoMap, Role::CartoExtra].into_iter().enumerate() { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::CartoResult, + }); + player(&mut slots); + } + Kind::Lectern => { + containers[MAIN] = vec![None; 1]; + slots.extend(main(1, Role::Plain)); + // The open page (LecternBlockEntity.dataAccess). + data = 1; + } Kind::ItemPicker => { containers[MAIN] = vec![None; 45]; slots.extend(main(45, Role::CreativeDisplay)); @@ -592,6 +653,7 @@ impl Menu { combined: false, enchant_changed: false, enchant_button: None, + may_build: true, } .with_initial_data() } @@ -611,6 +673,9 @@ impl Menu { /// `clickMenuButton`: the loom's pattern buttons and the stonecutter's /// recipes. False when refused. pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind == Kind::Lectern { + return self.lectern_button(env, id); + } if self.kind == Kind::Enchanting { return self.enchant_click(id); } @@ -634,6 +699,41 @@ impl Menu { true } + /// `LecternMenu.clickMenuButton`: the page buttons (1 back, 2 forward, + /// 100 + n to page n) and Take Book (3), which puts the book in the + /// inventory or drops it. + fn lectern_button(&mut self, env: &Env, id: i32) -> bool { + match id { + 100.. => self.set_data(0, id - 100), + 1 => self.set_data(0, self.data[0] - 1), + 2 => self.set_data(0, self.data[0] + 1), + 3 if self.may_build => { + // removeItemNoUpdate: the whole book, and onBookItemRemove. + let book = self.containers[MAIN][0].take(); + self.data[0] = 0; + if let Some(mut book) = book + && !self.inventory_add(env, &mut book) + { + self.drop_stack(&book); + } + } + _ => return false, + } + true + } + + /// `AbstractContainerMenu.setData`: the lectern's is + /// `LecternBlockEntity.setPage`, kept within the book's pages. + pub fn set_data(&mut self, id: usize, value: i32) { + if self.kind == Kind::Lectern && id == 0 { + // Mth.clamp(page, 0, pageCount - 1). + let count = self.containers[MAIN][0].as_ref().map_or(0, book_pages) as i32; + self.data[0] = value.max(0).min(count - 1); + return; + } + self.data[id] = value; + } + /// `CrafterBlockEntity.setSlotState` (the slot state packet): only an /// empty slot can be disabled or enabled. pub fn set_slot_state(&mut self, slot: usize, enabled: bool) { @@ -770,6 +870,11 @@ impl Menu { self.smith_error(); return; } + // CartographyTableMenu: its result container calls slotsChanged too. + if self.kind == Kind::Cartography && self.slots[s].container != PLAYER { + self.carto_changed(env); + return; + } if self.slots[s].container != MAIN { return; } @@ -928,6 +1033,68 @@ impl Menu { self.data[0] = i32::from(error); } + /// `CartographyTableMenu.slotsChanged` and `setupResultSlot`: a result + /// only where the level has the map (`access.execute`), with the post + /// processing its take runs (`MAP_POST_PROCESSING`: 0 lock, 1 scale). + fn carto_changed(&mut self, env: &Env) { + let [map, extra] = [0, 1].map(|i| self.containers[MAIN][i].clone()); + if self.containers[RESULT][0].is_some() && (map.is_none() || extra.is_none()) { + self.containers[RESULT][0] = None; + return; + } + let (Some(map), Some(extra), Some(maps)) = (map, extra, env.maps) else { + return; + }; + let Some((locked, scale)) = map + .data() + .and_then(|d| d.map_id) + .and_then(|id| maps.state(id)) + else { + return; + }; + let extendable = env + .items + .item_tags + .get("minecraft:extendable_maps") + .is_some_and(|t| t.contains(&*map.item)); + let copy = |count: u32, post: Option| { + let mut out = ItemStack { + count, + ..map.clone() + }; + if post.is_some() { + out.data_mut().map_post_processing = post; + } + out + }; + self.containers[RESULT][0] = match &*extra.item { + "minecraft:paper" if extendable && !locked && scale < 4 => Some(copy(1, Some(1))), + "minecraft:glass_pane" if !locked => Some(copy(1, Some(0))), + "minecraft:map" => Some(copy(2, None)), + _ => None, + }; + } + + /// `Item.onCraftedBy` of a taken cartography result + /// (`MapItem.onCraftedPostProcess`): the post processing goes, and on a + /// level with maps the stack names the scaled or locked copy. + fn map_crafted(env: &Env, stack: &mut ItemStack) { + if &*stack.item != "minecraft:filled_map" { + return; + } + let Some(post) = stack.data().and_then(|d| d.map_post_processing) else { + return; + }; + stack.data_mut().map_post_processing = None; + let id = stack.data().and_then(|d| d.map_id); + if let (Some(maps), Some(id)) = (env.maps, id) + && let Some(new) = maps.derive(id, post == 1) + { + stack.data_mut().map_id = Some(new); + } + stack.tidy(); + } + pub fn slot_count(&self) -> usize { self.slots.len() } @@ -939,6 +1106,11 @@ impl Menu { /// Sets a slot as a test fixture does (`Slot.set`). pub fn set_slot(&mut self, env: &Env, i: usize, stack: Option) { + if self.kind == Kind::Lectern { + // LecternBlockEntity.setBook: the book its slot can't set. + self.containers[MAIN][0] = stack; + return; + } self.put(env, i, stack); } @@ -1043,14 +1215,25 @@ impl Menu { .item_tags .get("minecraft:beacon_payment_items") .is_some_and(|t| t.contains(&*stack.item)), + Role::CartoMap => stack.data().is_some_and(|d| d.map_id.is_some()), + Role::CartoExtra => Self::is_carto_extra(stack), Role::LoomResult | Role::MerchantResult | Role::StoneResult | Role::GrindResult - | Role::CombineResult => false, + | Role::CombineResult + | Role::CartoResult => false, } } + /// What the cartography table's second slot takes. + fn is_carto_extra(stack: &ItemStack) -> bool { + matches!( + &*stack.item, + "minecraft:paper" | "minecraft:map" | "minecraft:glass_pane" + ) + } + /// `BannerItem`. fn is_banner(stack: &ItemStack) -> bool { stack.item.ends_with("_banner") @@ -1088,6 +1271,8 @@ impl Menu { fn slot_max(&self, env: &Env, s: usize, stack: &ItemStack) -> u32 { let own = match self.slots[s].role { Role::Armor(_) | Role::Potion | Role::EnchantItem | Role::BeaconPay => 1, + // The lectern's bookAccess holds one. + Role::Plain if self.kind == Kind::Lectern && self.slots[s].container == MAIN => 1, Role::Fuel if Self::is_bucket(stack) => return 1, _ => CONTAINER_MAX, }; @@ -1098,6 +1283,10 @@ impl Menu { fn put(&mut self, env: &Env, s: usize, mut stack: Option) { tidy(&mut stack); let slot = self.slots[s]; + // LecternBlockEntity's bookAccess.setItem does nothing. + if self.kind == Kind::Lectern && slot.container == MAIN { + return; + } // SimpleContainer / BaseContainerBlockEntity.setItem: limitSize to // getMaxStackSize(stack). The loom's result is a SimpleContainer too. if (slot.container == MAIN || slot.role == Role::LoomResult) @@ -1179,6 +1368,10 @@ impl Menu { .filter(|c| c.count > 0) .map(|c| split(c, amount)); tidy(cell); + // LecternBlockEntity: an emptied book slot is onBookItemRemove (page 0). + if self.kind == Kind::Lectern && slot.container == MAIN && cell.is_none() { + self.data[0] = 0; + } if out.is_some() && slot.container == GRID { self.recompute(env); } @@ -1194,6 +1387,7 @@ impl Menu { | Kind::Anvil | Kind::Smithing | Kind::Enchanting + | Kind::Cartography ) { self.slot_changed(env, s); @@ -1289,6 +1483,17 @@ impl Menu { self.combined = true; return; } + if self.slots[s].role == Role::CartoResult { + // CartographyTableMenu's result onTake: one of each input, the + // take sound, then Slot.onTake's setChanged. The taken stack's + // onCraftedBy is the caller's (map_crafted). + self.remove(env, 0, 1); + self.remove(env, 1, 1); + self.sounds + .push("minecraft:ui.cartography_table.take_result"); + self.slot_changed(env, s); + 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); @@ -1399,8 +1604,11 @@ impl Menu { amount: u32, max_amount: u32, ) -> Option { - let result = self.try_remove(env, s, amount, max_amount)?; + let mut result = self.try_remove(env, s, amount, max_amount)?; self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + Self::map_crafted(env, &mut result); + } Some(result) } @@ -1786,6 +1994,38 @@ impl Menu { return None; } } + Kind::Cartography => { + after_take = true; + if index == 2 { + // onCraftedBy edits the result in its slot first. + Self::map_crafted(env, &mut stack); + self.containers[RESULT][0] = Some(stack.clone()); + if !self.move_to(env, &mut stack, 3, 39, true) { + return None; + } + } else if index == 0 || index == 1 { + if !self.move_to(env, &mut stack, 3, 39, false) { + return None; + } + } else if stack.data().is_some_and(|d| d.map_id.is_some()) { + if !self.move_to(env, &mut stack, 0, 1, false) { + return None; + } + } else if Self::is_carto_extra(&stack) { + if !self.move_to(env, &mut stack, 1, 2, false) { + return None; + } + } else if (3..30).contains(&index) { + if !self.move_to(env, &mut stack, 30, 39, false) { + return None; + } + } else if (30..39).contains(&index) && !self.move_to(env, &mut stack, 3, 30, false) + { + return None; + } + } + // LecternMenu.quickMoveStack moves nothing. + Kind::Lectern => return None, Kind::Beacon => { // BeaconMenu.quickMoveStack. after_take = true; @@ -2181,6 +2421,10 @@ impl Menu { if let Some(stack) = self.slot(slot_index as usize) { let mut copy = stack.clone(); copy.count = Self::max_stack(env, stack); + // The cartography result's safeClone runs onCraftedBy. + if self.slots[slot_index as usize].role == Role::CartoResult { + Self::map_crafted(env, &mut copy); + } self.carried = Some(copy); } } else if input == Input::Throw && self.carried.is_none() && slot_index >= 0 { @@ -2248,9 +2492,14 @@ impl Menu { } else { clicked.count.div_ceil(2) }; - if let Some(taken) = self.try_remove(env, s, amount, u32::MAX) { - self.carried = Some(taken); + if let Some(mut taken) = self.try_remove(env, s, amount, u32::MAX) { + self.carried = Some(taken.clone()); self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + // onTake's onCraftedBy edits the carried stack. + Self::map_crafted(env, &mut taken); + self.carried = Some(taken); + } } } Some(mut carried) => { @@ -2275,11 +2524,15 @@ impl Menu { } else if clicked.same_item_same_components(&carried) { let room = Self::max_stack(env, &carried).saturating_sub(carried.count); self.carried = Some(carried.clone()); - if let Some(taken) = self.try_remove(env, s, clicked.count, room) { + if let Some(mut taken) = self.try_remove(env, s, clicked.count, room) { if let Some(c) = self.carried.as_mut() { c.count += taken.count; } self.on_take(env, s); + if self.slots[s].role == Role::CartoResult { + // onCraftedBy edits the taken stack, not the carried one. + Self::map_crafted(env, &mut taken); + } } } else { self.carried = Some(carried); @@ -2304,6 +2557,11 @@ impl Menu { self.containers[PLAYER][inv_slot] = Some(taken.clone()); self.set_by_player(env, target, None); self.on_take(env, target); + if self.slots[target].role == Role::CartoResult + && let Some(stack) = self.containers[PLAYER][inv_slot].as_mut() + { + Self::map_crafted(env, stack); + } } } (Some(mut source), None) => { @@ -2681,6 +2939,7 @@ pub(crate) mod tests { enchantments: &enchantments, names: &names, trade: None, + maps: None, }; let mut menu = Menu::new(kind); menu.creative = true; diff --git a/crates/horizon-protocol/src/item.rs b/crates/horizon-protocol/src/item.rs index 90ea5b6cd..02c9e4966 100644 --- a/crates/horizon-protocol/src/item.rs +++ b/crates/horizon-protocol/src/item.rs @@ -28,6 +28,21 @@ pub mod component { pub const STORED_ENCHANTMENTS: i32 = 45; pub const DYED_COLOR: i32 = 47; pub const MAP_ID: i32 = 48; + pub const MAP_POST_PROCESSING: i32 = 50; + pub const WRITABLE_BOOK_CONTENT: i32 = 56; + pub const WRITTEN_BOOK_CONTENT: i32 = 57; +} + +/// A written book's content (`WrittenBookContent.STREAM_CODEC`): the +/// filtered variants of the title and pages are read and dropped. +#[derive(Clone, Debug, PartialEq)] +pub struct WrittenBook { + pub title: String, + pub author: String, + pub generation: i32, + /// Each page's text component. + pub pages: Vec, + pub resolved: bool, } /// The value of one patched data component. Components whose stream codec @@ -52,13 +67,49 @@ pub enum Component { hide: bool, hidden: Vec, }, + /// `WritableBookContent`: the pages (raw text). + WritableBook(Vec), + WrittenBook(WrittenBook), +} + +/// `Filterable.streamCodec`: the raw value, then an optional filtered one +/// (dropped). +fn filterable(r: &mut Reader, value: impl Fn(&mut Reader) -> Result) -> Result { + let raw = value(r)?; + if r.bool()? { + value(r)?; + } + Ok(raw) } impl Component { fn read(kind: i32, r: &mut Reader) -> Result { use component::*; Ok(match kind { - MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID => { - Self::Int(r.varint()?) + MAX_STACK_SIZE | MAX_DAMAGE | DAMAGE | RARITY | REPAIR_COST | MAP_ID + | MAP_POST_PROCESSING => Self::Int(r.varint()?), + WRITABLE_BOOK_CONTENT => { + let n = r.count(100)?; + Self::WritableBook( + (0..n) + .map(|_| filterable(r, |r| r.string(1024))) + .collect::>()?, + ) + } + WRITTEN_BOOK_CONTENT => { + let title = filterable(r, |r| r.string(32))?; + let author = r.string(32767)?; + let generation = r.varint()?; + let n = r.count(r.remaining())?; + let pages = (0..n) + .map(|_| filterable(r, |r| r.nbt())) + .collect::>()?; + Self::WrittenBook(WrittenBook { + title, + author, + generation, + pages, + resolved: r.bool()?, + }) } DYED_COLOR => Self::Int(r.i32()?), UNBREAKABLE | CREATIVE_SLOT_LOCK => Self::Unit, @@ -144,6 +195,25 @@ impl Component { w.varint(hidden.len() as i32); hidden.iter().for_each(|h| w.varint(*h)); } + Self::WritableBook(pages) => { + w.varint(pages.len() as i32); + for page in pages { + w.string(page); + w.bool(false); + } + } + Self::WrittenBook(b) => { + w.string(&b.title); + w.bool(false); + w.string(&b.author); + w.varint(b.generation); + w.varint(b.pages.len() as i32); + for page in &b.pages { + w.nbt(page); + w.bool(false); + } + w.bool(b.resolved); + } } } } @@ -349,12 +419,43 @@ mod tests { Component::Lore(vec![literal("a"), literal("b")]), )); sword.removed.push(component::REPAIR_COST); + let mut book = Stack::new(1100, 1); + book.added.push(( + component::WRITTEN_BOOK_CONTENT, + Component::WrittenBook(WrittenBook { + title: "Notes".into(), + author: "Guest".into(), + generation: 1, + pages: vec![literal("one"), literal("two")], + resolved: true, + }), + )); + book.added + .push((component::MAP_POST_PROCESSING, Component::Int(1))); + round::, Slot>(Some(book)); + let mut quill = Stack::new(1099, 1); + quill.added.push(( + component::WRITABLE_BOOK_CONTENT, + Component::WritableBook(vec!["a".into(), String::new()]), + )); + round::, Slot>(Some(quill)); assert_eq!(sword.damage(), 17); round::, Slot>(Some(sword.clone())); round::, HashedSlot>(Some(Hashed::of(&sword))); round::, HashedSlot>(None); } + #[test] + fn filtered_book_pages_are_read_and_dropped() { + // A writable book with one page "hi" and its filtered "**". + let bytes = [1, 7, 1, 0, 56, 1, 2, b'h', b'i', 1, 2, b'*', b'*']; + let stack = Slot::read(&mut Reader::new(&bytes)).unwrap().unwrap(); + assert_eq!( + stack.component(component::WRITABLE_BOOK_CONTENT), + Some(&Component::WritableBook(vec!["hi".into()])) + ); + } + #[test] fn empty_stack_is_a_zero_count() { let mut w = Writer::new(); 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 1491c5a28..9b4e6e8f5 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -39,6 +39,8 @@ public final class VanillaMenuOracle { 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; + /** The block entity behind a "lectern" menu. */ + static net.minecraft.world.level.block.entity.LecternBlockEntity lectern; @SuppressWarnings("unchecked") static T make(Class type) { @@ -87,8 +89,22 @@ public final class VanillaMenuOracle { // BlockEntity.setChanged of the "*_be" furnaces: no chunks here. @Override public void blockEntityChanged(BlockPos pos) { } @Override public void updateNeighbourForOutputSignal(BlockPos pos, net.minecraft.world.level.block.Block block) { } + // The case's maps (MapItem.getSavedData) and the ones the cartography table makes. + @Override public net.minecraft.world.level.saveddata.maps.MapItemSavedData getMapData(net.minecraft.world.level.saveddata.maps.MapId id) { return maps.get(id.id()); } + @Override public net.minecraft.world.level.saveddata.maps.MapId getFreeMapId() { return new net.minecraft.world.level.saveddata.maps.MapId(nextMap++); } + @Override public void setMapData(net.minecraft.world.level.saveddata.maps.MapId id, net.minecraft.world.level.saveddata.maps.MapItemSavedData data) { maps.put(id.id(), data); } + @Override public long getGameTime() { return 0L; } + // LecternBlock.signalPageChange and resetBookState: no chunks or ticks here. + @Override public boolean setBlock(BlockPos pos, net.minecraft.world.level.block.state.BlockState state, int flags, int recursion) { return true; } + @Override public void scheduleTick(BlockPos pos, net.minecraft.world.level.block.Block block, int delay) { } + @Override public void updateNeighborsAt(BlockPos pos, net.minecraft.world.level.block.Block block, net.minecraft.world.level.redstone.Orientation o) { } + @Override public void playSound(net.minecraft.world.entity.Entity e, BlockPos pos, net.minecraft.sounds.SoundEvent s, net.minecraft.sounds.SoundSource c, float v, float pitch) { } } + /** The maps of the case's level, by id, and the next free id. */ + static final Map maps = new HashMap<>(); + static int nextMap; + static final class FakePlayer extends ServerPlayer { World world; boolean creative; @@ -184,6 +200,24 @@ public final class VanillaMenuOracle { case "smithing" -> new SmithingMenu(0, inv); case "enchanting" -> new EnchantmentMenu(0, inv); case "beacon" -> new BeaconMenu(0, inv); + // Over the level (its maps), as the server's menu is. + case "cartography" -> new CartographyTableMenu(0, inv, access); + case "lectern" -> { + // The server's menu: the block entity's bookAccess and dataAccess. + lectern = new net.minecraft.world.level.block.entity.LecternBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.LECTERN.defaultBlockState()); + lectern.setLevel(player.world); + try { + var type = net.minecraft.world.level.block.entity.LecternBlockEntity.class; + Field book = type.getDeclaredField("bookAccess"); + Field data = type.getDeclaredField("dataAccess"); + book.setAccessible(true); + data.setAccessible(true); + yield new LecternMenu(0, (Container) book.get(lectern), (ContainerData) data.get(lectern)); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } default -> throw new IllegalArgumentException(kind); }; } @@ -213,6 +247,12 @@ public final class VanillaMenuOracle { /** {@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 { + if (menu instanceof LecternMenu) { + // No inventory slots: the inventory Take Book fills. + StringBuilder items = new StringBuilder(); + for (int i = 0; i < 36; i++) items.append(' ').append(ParityData.canon(inv.getItem(i))); + return state(menu, inv) + " | " + String.join(";", equips) + " | inv" + items; + } return state(menu, inv) + " | " + String.join(";", equips); } @@ -244,6 +284,20 @@ public final class VanillaMenuOracle { // EnchantmentMenu.clickMenuButton names the player on an invalid button. set(player, Player.class, "gameProfile", new com.mojang.authlib.GameProfile(new java.util.UUID(0, 1), "Oracle")); player.experienceLevel = f.has("levels") ? f.get("levels").getAsInt() : 0; + maps.clear(); + nextMap = 1000; + lectern = null; + // LecternMenu's Take Book asks Player.mayBuild. + set(player, Player.class, "abilities", new net.minecraft.world.entity.player.Abilities()); + if (f.has("maps")) { + // [id, scale, locked] each. + for (var m : f.getAsJsonArray("maps")) { + var a = m.getAsJsonArray(); + var data = net.minecraft.world.level.saveddata.maps.MapItemSavedData.createFresh(0, 0, + (byte) a.get(1).getAsInt(), false, false, net.minecraft.world.level.Level.OVERWORLD); + maps.put(a.get(0).getAsInt(), a.get(2).getAsBoolean() ? data.locked() : data); + } + } var inv = new Inventory(player, new EntityEquipment()); player.inv = inv; AbstractContainerMenu menu = menu(f.get("menu").getAsString(), player, inv); @@ -252,6 +306,19 @@ public final class VanillaMenuOracle { var slotsJson = f.getAsJsonArray("slots"); for (int i = 0; i < menu.slots.size(); i++) menu.getSlot(i).set(ParityData.stack(slotsJson.get(i).getAsString())); menu.setCarried(ParityData.stack(f.get("carried").getAsString())); + if (lectern != null && menu instanceof LecternMenu) { + // LecternBlockEntity.setBook without resolving the book: its slot can't set it. + var type = net.minecraft.world.level.block.entity.LecternBlockEntity.class; + ItemStack book = ParityData.stack(slotsJson.get(0).getAsString()); + set(lectern, type, "book", book); + var count = type.getDeclaredMethod("getPageCount", ItemStack.class); + count.setAccessible(true); + set(lectern, type, "pageCount", count.invoke(null, book)); + } + if (f.has("inventory")) { + var items = f.getAsJsonArray("inventory"); + for (int i = 0; i < items.size(); i++) inv.setItem(i, ParityData.stack(items.get(i).getAsString())); + } // The slot listener of the block crafter's menu refreshes the result. if (f.get("menu").getAsString().equals("crafter_be")) menu.broadcastChanges(); var dataJson = f.getAsJsonArray("data"); diff --git a/tools/lan_e2e.py b/tools/lan_e2e.py index 96749a41e..4064da3ec 100755 --- a/tools/lan_e2e.py +++ b/tools/lan_e2e.py @@ -50,9 +50,14 @@ address. The script then checks, from both sides, what a guest's game used to ge server has the repaired, renamed sword (#868); - enchanting: an enchanting table opens on the guest's screen with the server's offers for the sword the guest puts in; the guest clicks the first offer and the server enchants the - sword for a level and a lapis (#868); + sword for a level and a lapis, and counts it in the guest's enchant_item stat (#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); +- lectern: a lectern's written book opens on the guest's screen; the guest turns its pages + (ContainerButtonClick) and the server's lectern follows, then the guest takes the book + and the server has it in the guest's inventory (#868); +- cartography: a cartography table opens on the guest's screen; the guest puts in a map the host + made and paper, takes the zoomed-out map, and the server has a new map for 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; @@ -147,7 +152,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', 'anvil', 'smithing', 'enchanting', 'beacon', 'crafter', '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', 'enchanting', 'beacon', 'crafter', 'lectern', 'cartography', '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: @@ -962,13 +967,20 @@ def check_loom(host, guest, out): return seen +def own_reply(event): + """A chat event that answers the guest's own command. On the server thread the guest also gets + its own command's `[Guest: ...]` operator broadcast, a moment later, which an answer to the next + command must not be taken for.""" + return event.get('event') == 'chat' and not event.get('text', '').startswith(f'[{GUEST_NAME}: ') + + def server_count(guest, item): """How many of `item` the server says the guest has (`clear` with a count of 0 only counts).""" since = guest.raw('events')['last'] guest('command', command=f'clear @s minecraft:{item} 0') for n in range(0, 65): reply = guest.raw('events', '--since', since) - lines = [e.get('text', '') for e in reply['events'] if e.get('event') == 'chat'] + lines = [e.get('text', '') for e in reply['events'] if own_reply(e)] for line in lines: if 'matching item' in line or 'No items were found' in line: return 0 if 'No items' in line else int(line.split('Found ')[1].split(' ')[0]) @@ -1012,7 +1024,7 @@ def server_reply(guest, command, *needles): reply = guest.raw('events', '--since', since) for e in reply['events']: line = e.get('text', '') - if e.get('event') == 'chat' and all(n in line for n in needles): + if own_reply(e) and all(n in line for n in needles): return line guest.wait(2) raise Failed(f'no answer to {command}') @@ -1038,11 +1050,13 @@ def check_grindstone(host, guest, out): close_station(guest, at) sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}].components', 'minecraft:damage') - xp = server_reply(guest, 'xp query @s points', 'experience points') + # 16 points make exactly two levels and leave 0 points: count the levels too. + xp = (server_reply(guest, 'xp query @s points', 'experience points') + + server_reply(guest, 'xp query @s levels', 'experience levels')) seen = {'loaded': loaded, 'left': left, 'curse kept': 'vanishing_curse' in sword, 'sharpness gone': 'sharpness' not in sword, 'damage': re.search(r'minecraft:damage"?: 100\b', sword) is not None, - 'xp': int(re.search(r'has (\d+) experience', xp).group(1)) > 0} + 'xp': any(int(n) > 0 for n in re.findall(r'has (\d+) experience', xp))} want = {'loaded': {600: ('minecraft:iron_sword', 1), 650: ('minecraft:iron_sword', 1)}, 'left': {}, 'curse kept': True, 'sharpness gone': True, 'damage': True, 'xp': True} assert seen == want, f'the grindstone on the guest: {seen} ({sword!r}, {xp!r})' @@ -1118,6 +1132,8 @@ def check_enchanting(host, guest, out): guest('command', command='xp set @s 30 levels') guest('command', command='give @s minecraft:iron_sword') guest('command', command='give @s minecraft:lapis_lazuli 3') + # EnchantmentMenu awards the enchant_item stat; a stat objective shows the guest's count. + guest('command', command='scoreboard objectives add lanench minecraft.custom:minecraft.enchant_item') at = open_station(guest, 'enchanting_table', out, 'enchanting') # EnchantmentMenu.quickMoveStack: the sword to the item slot, the lapis to its own. for item in ('iron_sword', 'lapis_lazuli'): @@ -1133,10 +1149,13 @@ def check_enchanting(host, guest, out): close_station(guest, at) sword = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:iron_sword"}]', 'iron_sword') levels = server_reply(guest, 'xp query @s levels', 'experience levels') + stat = server_reply(guest, 'scoreboard players get @s lanench', 'lanench') + guest('command', command='scoreboard objectives remove lanench') seen = {'offered': costs[0] > 0, 'enchanted': 'minecraft:enchantments' in sword, 'left': left.get(601), 'levels': int(re.search(r'has (\d+) experience', levels).group(1)), - 'lapis': server_count(guest, 'lapis_lazuli')} - want = {'offered': True, 'enchanted': True, 'left': ('minecraft:lapis_lazuli', 2), 'levels': 29, 'lapis': 2} + 'lapis': server_count(guest, 'lapis_lazuli'), 'stat': ' has 1 ' in stat} + want = {'offered': True, 'enchanted': True, 'left': ('minecraft:lapis_lazuli', 2), 'levels': 29, 'lapis': 2, + 'stat': True} assert seen == want, f'the enchanting table on the guest: {seen} ({costs}, {sword!r})' return seen @@ -1211,6 +1230,84 @@ def check_crafter(host, guest, out): return seen +def check_lectern(host, guest, out): + guest('command', command='gamemode survival') + guest('command', command='clear @s') + x, y, z = (int(v // 1) for v in pos_of(guest)) + at = (x, y, z + 2) + book = ('{id:"minecraft:written_book",count:1,components:{"minecraft:written_book_content":' + '{title:"Lan",author:"Host",pages:["one","two","three"]}}}') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:lectern[has_book=true]{{Book:{book}}}') + guest.wait(10) + guest.raw('interact', *at) + guest.raw('wait-for', 'screen', 'book', '--timeout', 10) + guest.wait(10) + opened = guest.raw('book') + guest.shot(out, 'lectern') + # LecternScreen's page arrows: ContainerButtonClick 2 (forward) and 1 (back); the server's + # LecternMenu.setData clamps to the book's last page and sends the page back (data slot 0). + for button in ('next', 'next', 'next', 'back'): + guest.raw('book', button) + guest.wait(5) + guest.wait(10) + turned = guest.raw('book') + page = server_reply(guest, f'data get block {at[0]} {at[1]} {at[2]} Page', 'block data') + guest.shot(out, 'lectern-page') + # Take Book: ContainerButtonClick 3; the server empties the lectern and closes the menu. + guest.raw('book', 'take') + guest.wait(20) + screen = guest('state').get('screen') + held = server_count(guest, 'written_book') + has_book = server_reply(guest, f'execute if block {at[0]} {at[1]} {at[2]} minecraft:lectern[has_book=false]', + 'Test passed') + guest('command', command=f'setblock {at[0]} {at[1]} {at[2]} minecraft:air') + seen = {'opened': (opened.get('page'), opened.get('pages')), 'turned': turned.get('page'), + 'server page': int(re.search(r'(-?\d+)\s*$', page).group(1)), 'screen': screen, 'held': held, + 'emptied': 'Test passed' in has_book} + want = {'opened': (0, 3), 'turned': 1, 'server page': 1, 'screen': 'playing', 'held': 1, 'emptied': True} + assert seen == want, f'the lectern on the guest: {seen} ({page!r})' + return seen + + +def check_cartography(host, guest, out): + # The host makes a map (EmptyMapItem.use), the guest gets a copy of it. + host('command', command='clear @s') + host('command', command='item replace entity @s weapon.mainhand with minecraft:map') + host.wait(5) + host.raw('use-item') + host.wait(20) + made = server_reply(host, 'data get entity @s Inventory[{id:"minecraft:filled_map"}].components', 'map_id') + map_id = int(re.search(r'map_id"?: (\d+)', made).group(1)) + host('command', command='clear @s') + guest('command', command='gamemode survival') + guest('command', command='clear @s') + guest('command', command=f'give @s minecraft:filled_map[minecraft:map_id={map_id}]') + guest('command', command='give @s minecraft:paper') + at = open_station(guest, 'cartography_table', out, 'cartography') + # CartographyTableMenu.quickMoveStack: a map with an id to the map slot, paper to the other. + for item in ('filled_map', 'paper'): + guest.raw('click-slot', hotbar_slot(guest, f'minecraft:{item}'), 'shift') + guest.wait(5) + guest.wait(10) + loaded = station_slots(guest) + guest.shot(out, 'cartography-result') + # The result's onTake uses the map and the paper; MapItem.onCraftedPostProcess gives the zoomed + # out map a new id on the server. + guest.raw('click-slot', 650, 'shift') + guest.wait(10) + left = station_slots(guest) + close_station(guest, at) + taken = server_reply(guest, 'data get entity @s Inventory[{id:"minecraft:filled_map"}].components', 'map_id') + new_id = int(re.search(r'map_id"?: (\d+)', taken).group(1)) + seen = {'loaded': loaded, 'left': left, 'new map': new_id != map_id, + 'server': {item: server_count(guest, item) for item in ('filled_map', 'paper')}} + want = {'loaded': {600: ('minecraft:filled_map', 1), 601: ('minecraft:paper', 1), + 650: ('minecraft:filled_map', 1)}, + 'left': {}, 'new map': True, 'server': {'filled_map': 1, 'paper': 0}} + assert seen == want, f'the cartography table on the guest: {seen} ({made!r}, {taken!r})' + 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']: @@ -2410,6 +2507,8 @@ CHECK_FNS = {'tab': check_tab, 'self': check_self, 'armour': check_armour, 'name 'enchanting': check_enchanting, 'beacon': check_beacon, 'crafter': check_crafter, + 'lectern': check_lectern, + 'cartography': check_cartography, '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 ce97183b4..4e34b39cc 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -16,7 +16,11 @@ cursed tools and books), the anvil (repairs, enchantment merges and renames, with the player's levels), the smithing table (upgrades and trims), the enchanting table (its button checks against the costs, lapis and levels), the beacon (its payment slot and ServerboundSetBeaconPacket against the pyramid's -levels) and the +levels), the +cartography table (over a level with locked, scaled and missing maps: its +results, and the scaled and locked copies a take makes), the lectern (over the +block entity: its page buttons, clamped to the book's pages, and Take Book, +with the inventory compared too) 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. @@ -32,9 +36,9 @@ 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, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} + 'crafter_be': 46, 'loom': 40, 'stonecutter': 38, 'grindstone': 39, 'anvil': 39, 'smithing': 40, 'enchanting': 38, 'beacon': 37, 'cartography': 39, 'lectern': 1, '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, 'enchanting': 10, 'beacon': 3, + 'stonecutter': 1, 'enchanting': 10, 'beacon': 3, 'lectern': 1, 'furnace_be': 4, 'blast_furnace_be': 4, 'smoker_be': 4} DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', 'blue', 'brown', 'green', 'red', 'black'] @@ -189,6 +193,32 @@ class Gen: return '{id:%s,count:1,components:{"minecraft:enchantments":{"minecraft:unbreaking":2}}}' % quote(item) return snbt(item, count) + def carto_stack(self): + """A filled map (some ids without data), paper, an empty map, a glass pane or anything.""" + rng = self.rng + roll = rng.random() + if roll < 0.4: + return '{id:"minecraft:filled_map",count:%d,components:{"minecraft:map_id":%d}}' % ( + rng.choice([1, 1, 2, 3, 64]), rng.randrange(0, 7)) + if roll < 0.75: + return snbt('minecraft:' + rng.choice(['paper', 'map', 'glass_pane']), rng.choice([1, 1, 2, 5, 64])) + if roll < 0.78: + # Something else with a map id: the map slot takes it. + return '{id:"minecraft:paper",count:1,components:{"minecraft:map_id":%d}}' % rng.randrange(0, 7) + return self.stack() + + def book(self): + """A written or writable book with a few pages, or something else.""" + rng = self.rng + pages = ','.join('"p%d"' % i for i in range(rng.choice([0, 1, 2, 3, 5]))) + roll = rng.random() + if roll < 0.45: + return ('{id:"minecraft:written_book",count:1,components:{"minecraft:written_book_content":' + '{title:"T",author:"A",pages:[%s]}}}' % pages) + if roll < 0.85: + return '{id:"minecraft:writable_book",count:1,components:{"minecraft:writable_book_content":{pages:[%s]}}}' % pages + return self.stack() + def recipe(self, slots, width, start=1): """Fills the crafting grid (slots `start`..) with a small known recipe.""" rng = self.rng @@ -245,6 +275,20 @@ class Gen: 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 + if menu == 'cartography' and rng.random() < 0.3: + # The result: take it, shift it out, throw it, swap it, clone it. + out.append([2, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'QUICK_MOVE', 'THROW', 'SWAP', 'CLONE'])]) + continue + if menu == 'lectern': + # The page buttons, a page jump, Take Book, and buttons it doesn't have; now and + # then a click on the book's slot. Not SWAP or the drags: vanilla's bookAccess + # hands out the block entity's own stack, which the swapped slot then shares. + if rng.random() < 0.7: + out.append([rng.choice([1, 1, 2, 2, 2, 3, 100, 101, 102, 104, 0, 4, 99, -1]), 0, 'BUTTON']) + else: + out.append([rng.choice([0, 0, -999]), rng.randrange(0, 2), + rng.choice(['PICKUP', 'THROW', 'QUICK_MOVE', 'CLONE'])]) + continue if menu == 'crafter_be' and rng.random() < 0.2: out.append([rng.choice([0, 1, 4, 8, 8, 9, -1]), rng.randrange(0, 2), 'SLOT_STATE']) continue @@ -348,6 +392,15 @@ def main(): for i in rng.sample(range(1, size), 8): slots[i] = pay() slots[0] = pay() if rng.random() < 0.7 else rng.choice(['-', g.stack()]) + if menu == 'cartography': + for i in rng.sample(range(3, size), 12): + slots[i] = g.carto_stack() + slots[0] = g.carto_stack() if rng.random() < 0.8 else '-' + slots[1] = g.carto_stack() if rng.random() < 0.75 else '-' + # The result follows the inputs; a fixture stack there is rare. + slots[2] = '-' if rng.random() < 0.9 else g.carto_stack() + if menu == 'lectern': + slots[0] = g.book() if rng.random() < 0.85 else '-' if menu == 'crafter_be': slots[45] = '-' if rng.random() < 0.6: @@ -375,6 +428,8 @@ def main(): return rng.choice([0, 0, 1]) if menu in ('loom', 'stonecutter'): return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) + if menu == 'lectern': + return rng.choice([-1, 0, 0, 1, 2, 4, 9]) if menu == 'beacon': # the levels, then the powers (encodeEffect: id + 1) return rng.choice([0, 1, 2, 3, 4, 4]) if i == 0 else rng.choice([0, 0, 2, 4, 11]) @@ -387,7 +442,19 @@ def main(): '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, + if menu == 'lectern': + carried = '-' + extra = {} + if menu == 'cartography': + # Maps 0-4 exist (5 and 6 don't): [id, scale, locked]. + extra['maps'] = [[i, rng.choice([0, 0, 1, 3, 4]), rng.random() < 0.25] for i in range(5)] + if rng.random() < 0.5: + carried = g.carto_stack() + if menu == 'lectern': + # The inventory Take Book adds to (full, so the book drops, now and then). + density = rng.choice([0.0, 0.3, 1.0]) + extra['inventory'] = [g.stack() if rng.random() < density else '-' for _ in range(36)] + cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, **extra, '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)})