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] 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)})