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,