diff --git a/crates/horizon-client/examples/cauldron_fixture.rs b/crates/horizon-client/examples/cauldron_fixture.rs index f2cd257cd..7de043b11 100644 --- a/crates/horizon-client/examples/cauldron_fixture.rs +++ b/crates/horizon-client/examples/cauldron_fixture.rs @@ -80,10 +80,13 @@ fn main() -> horizon_client::Result<()> { let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); + // The inventory menu never reads banner patterns. + let banners = horizon_client::banner::Banners::default(); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, + banners: &banners, }; 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 0909d3de4..0d1d496ed 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -35,10 +35,12 @@ fn main() -> horizon_client::Result<()> { let items = Items::catalog(root)?; let recipes = Recipes::load(root, &items)?; let brewing = horizon_client::brewing::Brewing::load(root, &items); + let banners = horizon_client::banner::Banners::load(root); let env = Env { items: &items, recipes: &recipes, brewing: &brewing, + banners: &banners, }; let mut out = String::new(); for line in input.lines() { @@ -50,6 +52,7 @@ 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("-"))?; + 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; } @@ -58,6 +61,23 @@ fn main() -> horizon_client::Result<()> { for op in case["ops"].as_array().ok_or("ops")? { let slot = op[0].as_i64().unwrap_or(0) as i32; let button = op[1].as_i64().unwrap_or(0) as i32; + match op[2].as_str().unwrap_or_default() { + // ServerboundContainerButtonClickPacket: clickMenuButton. + "BUTTON" => { + menu.button(&env, slot); + out += &format!("{}\n", state(&menu)); + continue; + } + // ServerboundContainerSlotStateChangedPacket. + "SLOT_STATE" => { + if (0..9).contains(&slot) { + menu.set_slot_state(slot as usize, button == 1); + } + out += &format!("{}\n", state(&menu)); + continue; + } + _ => {} + } let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?; match menu.click(&env, slot, button, kind) { Ok(()) => out += &format!("{}\n", state(&menu)), diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 21e3400cb..8fd558374 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -3528,6 +3528,50 @@ impl Game<'_> { } /// Several clicks on one menu instance (a quick craft drag is three). fn menu_ops(&mut self, ops: &[(Option, i32, horizon_client::menu::Input)]) -> bool { + use horizon_client::menu::Input; + if let [(Some(slot), button, input)] = ops { + self.crafter_slot_clicked(*slot, *button, *input); + } + let ops = ops.to_vec(); + self.menu_session(move |menu, env, to_menu| { + let mut clicks = Vec::new(); + for &(slot, button, input) in &ops { + let menu_slot = match slot { + Some(g) => { + if g == 200 && input != Input::QuickMove { + return None; + } + match to_menu(g) { + Some(i) => i as i32, + None => return None, + } + } + None => -999, + }; + clicks.push((menu_slot, button, input)); + } + for (menu_slot, button, input) in clicks { + if menu.click(env, menu_slot, button, input).is_err() { + // Vanilla's server throws: nothing of this click is kept. + return Some(false); + } + } + Some(true) + }) + } + /// The open menu as the verified engine (`horizon_client::menu`): the + /// game's slots are copied in, `run` acts on it, and the slots, carried + /// stack, menu data and drops are copied back when it returns Some(true) + /// (Some(false): handled, nothing kept; None: not handled). False when the + /// open screen is not one the engine models or `run` did not handle it. + pub(super) fn menu_session( + &mut self, + run: impl FnOnce( + &mut horizon_client::menu::Menu, + &horizon_client::menu::Env, + &dyn Fn(usize) -> Option, + ) -> Option, + ) -> bool { use horizon_client::menu::{Env, Kind, Menu}; #[derive(Clone, Copy)] struct Map { @@ -3586,107 +3630,145 @@ impl Game<'_> { } } } - let (kind, map) = if self.container.is_some() { - let size = self.container_size(); - let (kind, count) = match self.container_kind() { - Some(BlockEntity::Chest(_)) => { - let shulker = self.container.is_some_and(|k| { - let id = self.world.block(k.0, k.1, k.2); - storage::is_shulker_box(&self.res.facts.get(id).name) - }); - let kind = match size { - 5 => Kind::Hopper, - 9 => Kind::Dispenser, - 27 if shulker => Kind::Shulker, - n => Kind::Chest((n / 9).clamp(1, 6)), - }; - (kind, size) - } - Some(BlockEntity::Furnace(f)) => ( - Kind::Furnace( - match f.kind.recipe_type().trim_start_matches("minecraft:") { - "blasting" => "blasting", - "smoking" => "smoking", - _ => "smelting", - }, - ), - 3, - ), - _ => return false, - }; - let map = Map { - container: count, - table: false, - cells: 0, - plain: false, - }; - (kind, map) - } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { - let table = self.craft_size == 3; - let map = Map { - container: 0, - table, - cells: self.craft_size * self.craft_size, - plain: true, - }; - ( - if table { - Kind::Crafting - } else { - Kind::Inventory - }, - map, - ) + // Menu slot -> game slot, for every menu slot. + let mut plain_map = None; + let crafter_open = matches!(self.container_kind(), Some(BlockEntity::Crafter(_))); + let loom_open = self + .station + .as_ref() + .is_some_and(|s| s.kind == stations::Kind::Loom); + let (kind, game_of): (Kind, Vec>) = if crafter_open { + // CrafterMenu: the grid, the inventory, then the result. + let mut v: Vec> = (300..309).map(Some).collect(); + v.extend((9..36).chain(0..9).map(Some)); + v.push(None); + (Kind::CrafterBlock, v) + } else if loom_open { + // LoomMenu: banner, dye, pattern, result, then the inventory. + let mut v: Vec> = (0..3).map(|i| Some(stations::INPUT + i)).collect(); + v.push(Some(stations::RESULT)); + v.extend((9..36).chain(0..9).map(Some)); + (Kind::Loom, v) } else { - return false; - }; - let mut clicks = Vec::new(); - for &(slot, button, input) in ops { - let menu_slot = match slot { - Some(g) => { - if g == 200 && input != horizon_client::menu::Input::QuickMove { - return false; + let (kind, map) = if self.container.is_some() { + let size = self.container_size(); + let (kind, count) = match self.container_kind() { + Some(BlockEntity::Chest(_)) => { + let shulker = self.container.is_some_and(|k| { + let id = self.world.block(k.0, k.1, k.2); + storage::is_shulker_box(&self.res.facts.get(id).name) + }); + let kind = match size { + 5 => Kind::Hopper, + 9 => Kind::Dispenser, + 27 if shulker => Kind::Shulker, + n => Kind::Chest((n / 9).clamp(1, 6)), + }; + (kind, size) } - match map.to_menu(g) { - Some(i) => i as i32, - None => return false, - } - } - None => -999, + Some(BlockEntity::Furnace(f)) => ( + Kind::Furnace( + match f.kind.recipe_type().trim_start_matches("minecraft:") { + "blasting" => "blasting", + "smoking" => "smoking", + _ => "smelting", + }, + ), + 3, + ), + _ => return false, + }; + let map = Map { + container: count, + table: false, + cells: 0, + plain: false, + }; + (kind, map) + } else if self.station.is_none() && !self.mount_active() && self.remote.is_none() { + let table = self.craft_size == 3; + let map = Map { + container: 0, + table, + cells: self.craft_size * self.craft_size, + plain: true, + }; + ( + if table { + Kind::Crafting + } else { + Kind::Inventory + }, + map, + ) + } else { + return false; }; - clicks.push((menu_slot, button, input)); - } + let total = Menu::new(kind).slot_count(); + plain_map = Some(map); + (kind, (0..total).map(|i| map.to_game(i)).collect()) + }; + // The plain map also takes the crafting result slot (a shift-click on it). + let to_menu = |g: usize| match plain_map { + Some(map) => map.to_menu(g), + None => game_of.iter().position(|x| *x == Some(g)), + }; let mut menu = Menu::new(kind); let total = menu.slot_count(); - let before: Vec> = (0..total) - .map(|i| map.to_game(i).and_then(|g| self.slot_mut(g).clone())) + let before: Vec> = game_of + .iter() + .map(|g| g.and_then(|g| self.slot_mut(g).clone())) .collect(); let carried = self.carried.clone(); let creative = self.creative; - let (after, carried, dropped): (Vec>, Option, Vec) = { - let env = Env { - items: &self.res.items, - recipes: &self.res.recipes, - brewing: &self.res.stations.brewing, - }; - menu.creative = creative; - for (i, stack) in before.iter().enumerate() { - menu.set_slot(&env, i, stack.clone()); - } - menu.carried = carried; - for (menu_slot, button, input) in clicks { - if menu.click(&env, menu_slot, button, input).is_err() { - return true; - } - } + let station_menu = self.station.as_ref().map(|s| { ( - (0..total).map(|i| menu.slot(i).cloned()).collect(), - menu.carried.take(), - std::mem::take(&mut menu.dropped), + s.loom.selected.map_or(-1, |i| i as i32), + s.loom.patterns.clone(), ) + }); + let crafter_data = match self.container_kind() { + Some(BlockEntity::Crafter(c)) => Some((c.disabled, c.triggered)), + _ => None, }; + let env = Env { + items: &self.res.items, + recipes: &self.res.recipes, + brewing: &self.res.stations.brewing, + banners: &self.res.stations.banners, + }; + menu.creative = creative; + for (i, stack) in before.iter().enumerate() { + menu.set_slot(&env, i, stack.clone()); + } + menu.settle(&env); + if kind == Kind::Loom + && let Some((selected, patterns)) = station_menu + { + // The menu's state between clicks: what set_slot recomputed is replaced. + menu.data[0] = selected; + menu.loom_patterns = patterns; + menu.set_slot(&env, 3, before[3].clone()); + } + if let Some((disabled, triggered)) = crafter_data { + for (i, d) in disabled.iter().enumerate() { + menu.data[i] = i32::from(*d); + } + menu.data[9] = i32::from(triggered); + } + menu.carried = carried; + menu.drops.clear(); + match run(&mut menu, &env, &to_menu) { + None => return false, + Some(false) => return true, + Some(true) => {} + } + let after: Vec> = (0..total).map(|i| menu.slot(i).cloned()).collect(); + let carried = menu.carried.take(); + let dropped = std::mem::take(&mut menu.dropped); + let sounds = std::mem::take(&mut menu.sounds); for (i, stack) in after.into_iter().enumerate() { - if let Some(g) = map.to_game(i) { + if let Some(g) = game_of[i] { *self.slot_mut(g) = stack; } } @@ -3694,6 +3776,25 @@ impl Game<'_> { for stack in dropped { self.player_drop(stack); } + if kind == Kind::Loom { + if let Some(s) = self.station.as_mut() { + s.loom.selected = usize::try_from(menu.data[0]).ok(); + s.loom.patterns = std::mem::take(&mut menu.loom_patterns); + } + for sound in sounds { + self.loom_sound(sound); + } + self.loom_screen_changed(); + } + if kind == Kind::CrafterBlock + && let Some(BlockEntity::Crafter(c)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + for (i, d) in c.disabled.iter_mut().enumerate() { + *d = menu.data[i] == 1; + } + } if matches!(kind, Kind::Furnace(_)) && let Some(BlockEntity::Furnace(f)) = self .container @@ -3849,7 +3950,7 @@ impl Game<'_> { }; let held_shift = self.keys.contains(&KeyCode::ShiftLeft) || self.keys.contains(&KeyCode::ShiftRight); - if self.crafter_click(slot, held_shift) { + if self.crafter_click(slot, held_shift, right) { return; } if held_shift && self.container.is_some() && self.container_quick_move(slot) { diff --git a/crates/horizon-client/src/game/loom.rs b/crates/horizon-client/src/game/loom.rs index 39663c298..561713d8a 100644 --- a/crates/horizon-client/src/game/loom.rs +++ b/crates/horizon-client/src/game/loom.rs @@ -1,10 +1,8 @@ -//! The loom (`LoomMenu`, `LoomScreen`): stacking banner patterns onto a -//! banner with a dye (and a pattern item for the special patterns), the -//! six-layer limit, the scrolling pattern list and the banner preview. -use super::{ - Game, - stations::{INPUT, Station}, -}; +//! The loom screen (`LoomScreen`): the scrolling pattern list, the banner +//! preview and the six-layer error. The menu itself (`LoomMenu`: slots, +//! selectable patterns, the pattern buttons, quick moves, the result) runs on +//! the verified engine, `horizon_client::menu`, through `Game::menu_session`. +use super::{Game, stations::Kind}; use horizon_client::{ banner::{self, BannerLayer}, hud::{HudBatch, Rect, rgba}, @@ -24,6 +22,8 @@ pub(super) struct LoomState { pub(super) scroll: f32, pub(super) start_row: usize, pub(super) scrolling: bool, + /// The inputs the screen last saw (`bannerStack`, `dyeStack`, `patternStack`). + last_inputs: [Option; 3], } impl LoomState { fn total_rows(&self) -> usize { @@ -65,138 +65,77 @@ pub(super) fn dye_color(name: &str) -> u32 { } impl Game<'_> { - /// `LoomMenu.slotsChanged` and the screen's `containerChanged`. - pub(super) fn loom_changed(&self, s: &mut Station) { - let banners = &self.res.stations.banners; - let items = &self.res.items; - let (banner_in, dye_in) = (s.inputs[0].as_ref(), s.inputs[1].as_ref()); + /// `LoomScreen.containerChanged`: the error flag, whether the pattern + /// buttons show (only when an input changed), and the scroller reset. + pub(super) fn loom_screen_changed(&mut self) { + let Some(s) = self.station.as_mut().filter(|s| s.kind == Kind::Loom) else { + return; + }; + let inputs = [ + s.inputs[0].clone(), + s.inputs[1].clone(), + s.inputs[2].clone(), + ]; let l = &mut s.loom; - let mut result = None; - if let (Some(banner_stack), Some(dye_stack)) = (banner_in, dye_in) { - let valid = l.selected.is_some_and(|i| i < l.patterns.len()); - let previous = std::mem::take(&mut l.patterns); - l.patterns = banners.selectable(s.inputs[2].as_ref()); - let shown = if l.patterns.len() == 1 { - l.selected = Some(0); - Some(l.patterns[0].clone()) - } else if !valid { - l.selected = None; - None - } else { - let value = previous[l.selected.unwrap_or(0)].clone(); - match l.patterns.iter().position(|p| *p == value) { - Some(i) => { - l.selected = Some(i); - Some(value) - } - None => { - l.selected = None; - None - } - } - }; - l.has_max = banner::has_max_layers(banner_stack); - if let Some(pattern) = shown { - if l.has_max { - l.selected = None; - } else if let Some(dye) = banners.loom_dye(items, dye_stack) { - result = Some(banner::loom_result(banner_stack, &dye, &pattern)); - } - } - l.display = !l.has_max && !l.patterns.is_empty(); - } else { - l.patterns.clear(); - l.selected = None; - l.has_max = banner_in.is_some_and(banner::has_max_layers); - l.display = false; + l.has_max = inputs[0].as_ref().is_some_and(banner::has_max_layers); + if inputs != l.last_inputs { + l.display = + inputs[0].is_some() && inputs[1].is_some() && !l.has_max && !l.patterns.is_empty(); } if l.start_row >= l.total_rows() { l.start_row = 0; l.scroll = 0.0; } - s.result = result; + l.last_inputs = inputs; } - /// The loom slots' `mayPlace`. - pub(super) fn loom_slot_rules(&self, input: usize, stack: &ItemStack) -> (bool, u32) { - let banners = &self.res.stations.banners; - let ok = match input { - 0 => stack.item.ends_with("_banner"), - 1 => banners.loom_dye(&self.res.items, stack).is_some(), - _ => banners.is_pattern_item(&self.res.items, stack), + /// A sound the loom menu played: the result's once per tick. + pub(super) fn loom_sound(&mut self, sound: &str) { + let ticks = self.ticks; + let Some(s) = self.station.as_mut() else { + return; }; - (ok, 64) + if s.last_sound == ticks { + return; + } + s.last_sound = ticks; + let pos = s.pos; + let at = [ + f64::from(pos[0]) + 0.5, + f64::from(pos[1]) + 0.5, + f64::from(pos[2]) + 0.5, + ]; + self.audio.play(sound, Some(at), 1.0, 1.0); } - /// The result slot's `onTake`: one banner and one dye are used up. - pub(super) fn loom_taken(&mut self, s: &mut Station) { - for slot in &mut s.inputs[..2] { - if let Some(x) = slot.as_mut() { - x.count -= 1; - if x.count == 0 { - *slot = None; - } - } - } - if s.inputs[0].is_none() || s.inputs[1].is_none() { - s.loom.selected = None; - } - if s.last_sound != self.ticks { - s.last_sound = self.ticks; - let pos = s.pos; - let at = [ - f64::from(pos[0]) + 0.5, - f64::from(pos[1]) + 0.5, - f64::from(pos[2]) + 0.5, - ]; + /// `LoomScreen.mouseClicked` on a pattern button: `clickMenuButton`, and + /// the select sound when the menu took it. + fn loom_button(&mut self, index: usize) -> bool { + let mut taken = false; + let flag = &mut taken; + self.menu_session(|menu, env, _| { + *flag = menu.button(env, index as i32); + Some(*flag) + }); + if taken { self.audio - .play("minecraft:ui.loom.take_result", Some(at), 1.0, 1.0); - } - } - /// `LoomMenu.quickMoveStack` from an inventory slot. - pub(super) fn loom_quick_move(&mut self, slot: usize, stack: &mut ItemStack) -> bool { - let banners = &self.res.stations.banners; - let items = &self.res.items; - let target = if stack.item.ends_with("_banner") { - Some(INPUT) - } else if banners.loom_dye(items, stack).is_some() { - Some(INPUT + 1) - } else if banners.is_pattern_item(items, stack) { - Some(INPUT + 2) - } else { - None - }; - match target { - Some(t) => self.move_to(stack, &[t], false), - None if (9..36).contains(&slot) => { - let hotbar: Vec = (0..9).collect(); - self.move_to(stack, &hotbar, false) - } - None if slot < 9 => { - let main: Vec = (9..36).collect(); - self.move_to(stack, &main, false) - } - None => false, + .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); } + taken } /// A left click inside the loom's pattern grid or scroller. pub(super) fn loom_click(&mut self, local: (f32, f32)) -> bool { - let Some(s) = self.station.as_ref() else { + let Some(start_row) = self + .station + .as_ref() + .filter(|s| s.loom.display) + .map(|s| s.loom.start_row) + else { return false; }; - let l = &s.loom; - if !l.display { - return false; - } for row in 0..4 { for column in 0..4 { - let index = (row + l.start_row) * 4 + column; + let index = (row + start_row) * 4 + column; let (x, y) = (60.0 + column as f32 * BUTTON, 13.0 + row as f32 * BUTTON); - if index < l.patterns.len() && inside(local, x, y, BUTTON, BUTTON) { - if let Some(s) = self.station.as_mut() { - s.loom.selected = Some(index); - } - self.audio - .play("minecraft:ui.loom.select_pattern", None, 1.0, 1.0); - self.station_changed(); + if inside(local, x, y, BUTTON, BUTTON) && self.loom_button(index) { return true; } } diff --git a/crates/horizon-client/src/game/machines/crafter.rs b/crates/horizon-client/src/game/machines/crafter.rs index ea795fe35..32b28ad70 100644 --- a/crates/horizon-client/src/game/machines/crafter.rs +++ b/crates/horizon-client/src/game/machines/crafter.rs @@ -291,64 +291,67 @@ impl Game<'_> { (self.carried.is_none() && c.items[i].is_none() && !c.disabled[i] && !self.spectator()) .then(|| self.translate("gui.togglable_slot", "Click to disable slot")) } - /// A click in the crafter menu before the generic handling; true when - /// it was fully handled (the result, shift-clicks). - pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool) -> bool { + /// A click in the crafter menu: `CrafterMenu` on the verified menu engine. + pub(in crate::game) fn crafter_click(&mut self, slot: usize, shift: bool, right: bool) -> bool { if !self.crafter_open() { return false; } - if slot == RESULT_SLOT { - return true; - } - if (300..309).contains(&slot) { - // CrafterScreen.slotClicked: toggle an empty slot. - let i = slot - 300; - if !shift && !self.spectator() && self.slot_mut(slot).is_none() { - let carried_empty = self.carried.is_none(); - let key = self.container; - let mut toggled = None; - if let Some(BlockEntity::Crafter(c)) = - key.and_then(|k| self.world.block_entities.get_mut(&k)) - { - if c.disabled[i] { - c.set_slot_state(i, true); - toggled = Some(true); - } else if carried_empty { - c.set_slot_state(i, false); - toggled = Some(false); - } - } - if let Some(enabled) = toggled { - let pitch = if enabled { 1.0 } else { 0.75 }; - self.audio - .play("minecraft:ui.button.click", None, 0.4, pitch); - } - } - } - if shift { - self.crafter_quick_move(slot); - return true; - } - false + let input = if shift { + horizon_client::menu::Input::QuickMove + } else { + horizon_client::menu::Input::Pickup + }; + self.menu_click(Some(slot), i32::from(right), input); + true } - /// `CrafterMenu.quickMoveStack`. - fn crafter_quick_move(&mut self, slot: usize) { - if slot >= 309 { + /// `CrafterScreen.slotClicked`: an empty grid slot is enabled by a click + /// (or a number key with a hotbar item) when disabled, and disabled by a + /// click with nothing carried; the menu then gets the click itself. + pub(in crate::game) fn crafter_slot_clicked( + &mut self, + slot: usize, + button: i32, + input: horizon_client::menu::Input, + ) { + use horizon_client::menu::Input; + if !self.crafter_open() || !(300..309).contains(&slot) || self.spectator() { return; } - let Some(mut stack) = self.slot_mut(slot).take() else { + let i = slot - 300; + let Some(c) = self.container.and_then(|k| self.crafter_at(k)) else { return; }; - if slot >= 300 { - let player: Vec = (9..36).chain(0..9).collect(); - self.move_to(&mut stack, &player, true); - } else { - let grid: Vec = (300..309).collect(); - self.move_to(&mut stack, &grid, false); - } - if stack.count > 0 { - *self.slot_mut(slot) = Some(stack); + if c.items[i].is_some() { + return; } + let disabled = c.disabled[i]; + let enable = match input { + Input::Pickup if disabled => Some(true), + Input::Pickup if self.carried.is_none() => Some(false), + Input::Swap if disabled => usize::try_from(button) + .ok() + .and_then(|b| { + if b == 40 { + Some(&self.offhand) + } else { + self.inventory.get(b) + } + }) + .is_some_and(Option::is_some) + .then_some(true), + _ => None, + }; + let Some(enabled) = enable else { + return; + }; + // ServerboundContainerSlotStateChangedPacket: CrafterBlockEntity.setSlotState. + self.menu_session(|menu, _, _| { + menu.set_slot_state(i, enabled); + Some(true) + }); + let pitch = if enabled { 1.0 } else { 0.75 }; + self.audio + .play("minecraft:ui.button.click", None, 0.4, pitch); } } diff --git a/crates/horizon-client/src/game/stations.rs b/crates/horizon-client/src/game/stations.rs index e75db5b6f..a06ed2a9c 100644 --- a/crates/horizon-client/src/game/stations.rs +++ b/crates/horizon-client/src/game/stations.rs @@ -447,7 +447,8 @@ impl Game<'_> { Kind::Merchant => super::trading::update(&mut s, items), Kind::Beacon => {} Kind::Cartography => s.result = self.cartography_result(&s), - Kind::Loom => self.loom_changed(&mut s), + // The menu engine keeps the loom's state (Game::menu_session). + Kind::Loom => {} Kind::Stonecutter => { let item = s.inputs[0].as_ref().map(|i| i.item.clone()); if item != s.input_item { @@ -522,7 +523,7 @@ impl Game<'_> { match s.kind { Kind::Enchanting if i == 0 => (true, 1), Kind::Beacon => (super::beacon::is_payment(&stack.item), 1), - Kind::Loom => self.loom_slot_rules(i, stack), + Kind::Loom => (false, 64), Kind::Cartography if i == 0 => (super::maps::map_id(stack).is_some(), 64), Kind::Cartography => ( matches!( @@ -644,12 +645,8 @@ impl Game<'_> { return false; }; let player = Self::player_slots(); - let loom = self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom); let moved = if (300..305).contains(&slot) || slot >= INPUT { - // LoomMenu moves into the inventory front to back, the others back to front. - self.move_to(&mut stack, &player, !loom) - } else if loom { - self.loom_quick_move(slot, &mut stack) + self.move_to(&mut stack, &player, true) } else if self.brewing_open() { // BrewingStandMenu.quickMoveStack: fuel, ingredient, bottles, then the other half. let data = self.data(); @@ -894,7 +891,7 @@ impl Game<'_> { self.cartography_taken(pos); } } - Kind::Loom => self.loom_taken(&mut s), + Kind::Loom => {} Kind::Enchanting => {} } self.station = Some(s); @@ -1069,6 +1066,16 @@ impl Game<'_> { let Some(slot) = self.slot_at(&batch, self.cursor.0, self.cursor.1) else { return true; }; + if self.station.as_ref().is_some_and(|s| s.kind == Kind::Loom) { + // LoomMenu 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; diff --git a/crates/horizon-client/src/menu.rs b/crates/horizon-client/src/menu.rs index 4ced9e6d0..149e34cc0 100644 --- a/crates/horizon-client/src/menu.rs +++ b/crates/horizon-client/src/menu.rs @@ -1,20 +1,25 @@ //! `AbstractContainerMenu.clicked` over vanilla's slot layouts: every //! `ContainerInput` (pickup, quick move, swap, clone, throw, the three quick //! craft drags, pickup all) for the player inventory, the crafting table, the -//! chest family, hoppers, dispensers, shulker boxes and the furnaces. +//! chest family, hoppers, dispensers, shulker boxes, the furnaces, the brewing +//! stand, the crafter (its client menu and the block entity's server menu with +//! `setSlotState`) and the loom (`clickMenuButton`, `slotsChanged`). //! `tools/test_menu_click_parity.py` compares every click with vanilla's menu //! classes. use crate::{ + banner::{self, Banners}, brewing::Brewing, crafting::Recipes, items::{ItemStack, Items}, }; +use std::sync::Arc; /// What a menu needs to know about items and recipes. pub struct Env<'a> { pub items: &'a Items, pub recipes: &'a Recipes, pub brewing: &'a Brewing, + pub banners: &'a Banners, } #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -54,7 +59,12 @@ pub enum Kind { /// The cooking recipe type: smelting, blasting or smoking. Furnace(&'static str), Brewing, + /// `CrafterMenu` over a plain crafting container (the client's menu). Crafter, + /// `CrafterMenu` over the `CrafterBlockEntity` (the server's menu): the + /// result follows the grid, and filling a disabled slot enables it. + CrafterBlock, + Loom, } impl Kind { @@ -73,6 +83,8 @@ impl Kind { "smoker" => Self::Furnace("smoking"), "brewing" => Self::Brewing, "crafter" => Self::Crafter, + "crafter_be" => Self::CrafterBlock, + "loom" => Self::Loom, _ => return None, }) } @@ -100,6 +112,12 @@ enum Role { Ingredient, /// `BrewingStandMenu.FuelSlot`. BrewFuel, + /// The loom's banner, dye and pattern slots. + LoomBanner, + LoomDye, + LoomPattern, + /// The loom's result slot (a plain slot whose `onTake` uses the inputs). + LoomResult, } #[derive(Clone, Copy)] @@ -133,6 +151,10 @@ pub struct Menu { quick_status: i32, quick_type: i32, quick_slots: Vec, + /// `LoomMenu.selectablePatterns`. + pub loom_patterns: Vec>, + /// Sounds the menu plays (`ui.loom.take_result`), for the caller. + pub sounds: Vec<&'static str>, } fn same_item(a: &ItemStack, b: &ItemStack) -> bool { @@ -238,7 +260,7 @@ impl Menu { slots.extend(main(27, Role::Shulker)); player(&mut slots); } - Kind::Crafter => { + Kind::Crafter | Kind::CrafterBlock => { containers[MAIN] = vec![None; 9]; slots.extend(main(9, Role::CrafterIn)); player(&mut slots); @@ -249,6 +271,26 @@ impl Menu { }); data = 10; } + Kind::Loom => { + containers[MAIN] = vec![None; 3]; + for (index, role) in [Role::LoomBanner, Role::LoomDye, Role::LoomPattern] + .into_iter() + .enumerate() + { + slots.push(Slot { + container: MAIN, + index, + role, + }); + } + slots.push(Slot { + container: RESULT, + index: 0, + role: Role::LoomResult, + }); + player(&mut slots); + data = 1; + } Kind::Brewing => { containers[MAIN] = vec![None; 5]; for (index, role) in [ @@ -308,6 +350,125 @@ impl Menu { quick_status: 0, quick_type: 0, quick_slots: Vec::new(), + loom_patterns: Vec::new(), + sounds: Vec::new(), + } + } + + pub fn kind(&self) -> Kind { + self.kind + } + + /// `clickMenuButton`: the loom's pattern buttons. False when refused. + pub fn button(&mut self, env: &Env, id: i32) -> bool { + if self.kind != Kind::Loom || id < 0 || id as usize >= self.loom_patterns.len() { + return false; + } + self.data[0] = id; + let pattern = self.loom_patterns[id as usize].clone(); + self.loom_setup_result(env, &pattern); + true + } + + /// `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) { + if self.kind == Kind::CrafterBlock && slot < 9 && self.containers[MAIN][slot].is_none() { + self.data[slot] = i32::from(!enabled); + } + } + + /// The menu after a fixture set its slots: the block crafter's slot + /// listener has refreshed the result (`broadcastChanges`). + pub fn settle(&mut self, env: &Env) { + if self.kind == Kind::CrafterBlock { + self.crafter_result(env); + } + } + + /// `CrafterMenu.refreshRecipeResult`. + fn crafter_result(&mut self, env: &Env) { + self.containers[RESULT][0] = env + .recipes + .find(&self.containers[MAIN], 3) + .map(|(_, stack)| stack) + .filter(|s| s.count > 0); + } + + /// `LoomMenu.setupResultSlot`. + fn loom_setup_result(&mut self, env: &Env, pattern: &str) { + let mut result = None; + if let (Some(banner_stack), Some(dye)) = ( + self.containers[MAIN][0].as_ref(), + self.containers[MAIN][1].as_ref(), + ) && let Some(color) = env.banners.loom_dye(env.items, dye) + { + result = Some(banner::loom_result(banner_stack, &color, pattern)); + } + self.containers[RESULT][0] = result; + } + + /// `LoomMenu.slotsChanged`. + fn loom_changed(&mut self, env: &Env) { + let has_inputs = self.containers[MAIN][0].is_some() && self.containers[MAIN][1].is_some(); + if !has_inputs { + self.containers[RESULT][0] = None; + self.loom_patterns.clear(); + self.data[0] = -1; + return; + } + let selected = self.data[0]; + let valid = selected >= 0 && (selected as usize) < self.loom_patterns.len(); + let pattern_item = self.containers[MAIN][2].clone(); + let previous = std::mem::replace( + &mut self.loom_patterns, + env.banners.selectable(pattern_item.as_ref()), + ); + let shown = if self.loom_patterns.len() == 1 { + self.data[0] = 0; + Some(self.loom_patterns[0].clone()) + } else if !valid { + self.data[0] = -1; + None + } else { + let value = previous[selected as usize].clone(); + match self.loom_patterns.iter().position(|p| *p == value) { + Some(i) => { + self.data[0] = i as i32; + Some(value) + } + None => { + self.data[0] = -1; + None + } + } + }; + match shown { + Some(pattern) => { + let full = self.containers[MAIN][0] + .as_ref() + .is_some_and(banner::has_max_layers); + if full { + self.data[0] = -1; + self.containers[RESULT][0] = None; + } else { + self.loom_setup_result(env, &pattern); + } + } + None => self.containers[RESULT][0] = None, + } + } + + /// `Slot.setChanged` on slot `s`: the loom recomputes from its inputs, + /// the block crafter refreshes its result. + fn slot_changed(&mut self, env: &Env, s: usize) { + if self.slots[s].container != MAIN { + return; + } + match self.kind { + Kind::Loom => self.loom_changed(env), + Kind::CrafterBlock => self.crafter_result(env), + _ => {} } } @@ -414,9 +575,18 @@ impl Menu { .items .get(&stack.item) .is_some_and(|i| i.brewing_fuel.is_some()), + Role::LoomBanner => Self::is_banner(stack), + Role::LoomDye => env.banners.loom_dye(env.items, stack).is_some(), + Role::LoomPattern => env.banners.is_pattern_item(env.items, stack), + Role::LoomResult => false, } } + /// `BannerItem`. + fn is_banner(stack: &ItemStack) -> bool { + stack.item.ends_with("_banner") + } + fn may_pickup(&self, s: usize) -> bool { match self.slots[s].role { Role::Inert => false, @@ -444,16 +614,34 @@ impl Menu { fn put(&mut self, env: &Env, s: usize, mut stack: Option) { tidy(&mut stack); let slot = self.slots[s]; + // SimpleContainer / BaseContainerBlockEntity.setItem: limitSize to + // getMaxStackSize(stack). The loom's result is a SimpleContainer too. + if (slot.container == MAIN || slot.role == Role::LoomResult) + && let Some(st) = stack.as_mut() + { + st.count = st.count.min(CONTAINER_MAX.min(Self::max_stack(env, st))); + } + // CrafterBlockEntity.setItem: filling a disabled (empty) slot enables it. + if self.kind == Kind::CrafterBlock + && slot.container == MAIN + && self.data[slot.index] == 1 + && self.containers[MAIN][slot.index].is_none() + { + self.data[slot.index] = 0; + } self.containers[slot.container][slot.index] = stack; if slot.container == GRID { self.recompute(env); } + self.slot_changed(env, s); } /// `Slot.remove`: the container's `removeItem`. fn remove(&mut self, env: &Env, s: usize, amount: u32) -> Option { let slot = self.slots[s]; - if slot.container == RESULT { + // ResultContainer.removeItem takes the whole stack; the loom's result + // is a SimpleContainer slot and splits. + if slot.container == RESULT && slot.role != Role::LoomResult { return self.containers[RESULT][0].take(); } let cell = &mut self.containers[slot.container][slot.index]; @@ -465,6 +653,10 @@ impl Menu { if out.is_some() && slot.container == GRID { self.recompute(env); } + // SimpleContainer.removeItem calls setChanged when it took something. + if out.is_some() && self.kind == Kind::Loom { + self.slot_changed(env, s); + } out } @@ -482,6 +674,21 @@ impl Menu { /// `ResultSlot.onTake` and the other `Slot.onTake` overrides. fn on_take(&mut self, env: &Env, s: usize) { + if self.slots[s].role == Role::LoomResult { + // LoomMenu's result onTake: one banner and one dye are used up. + self.remove(env, 0, 1); + self.remove(env, 1, 1); + if self.containers[MAIN][0].is_none() || self.containers[MAIN][1].is_none() { + self.data[0] = -1; + } + self.sounds.push("minecraft:ui.loom.take_result"); + return; + } + if matches!(self.kind, Kind::CrafterBlock) && self.slots[s].container == MAIN { + // Slot.onTake -> CrafterSlot.setChanged -> the result refresh. + self.slot_changed(env, s); + return; + } if self.slots[s].role != Role::CraftResult { return; } @@ -738,10 +945,12 @@ impl Menu { stack.count = 0; target.count = total; changed = true; + self.slot_changed(env, dest); } else if target.count < max { stack.count -= max - target.count; target.count = max; changed = true; + self.slot_changed(env, dest); } } } @@ -859,7 +1068,44 @@ impl Menu { return None; } } - Kind::Crafter => { + Kind::Loom => { + after_take = true; + if index == 3 { + if !self.move_to(env, &mut stack, 4, 40, true) { + return None; + } + } else if index > 3 { + let target = if Self::is_banner(&stack) { + Some(0) + } else if env.banners.loom_dye(env.items, &stack).is_some() { + Some(1) + } else if env.banners.is_pattern_item(env.items, &stack) { + Some(2) + } else { + None + }; + match target { + Some(t) => { + if !self.move_to(env, &mut stack, t, t + 1, false) { + return None; + } + } + None if index < 31 => { + if !self.move_to(env, &mut stack, 31, 40, false) { + return None; + } + } + None => { + if index < 40 && !self.move_to(env, &mut stack, 4, 31, false) { + return None; + } + } + } + } else if !self.move_to(env, &mut stack, 4, 40, false) { + return None; + } + } + Kind::Crafter | Kind::CrafterBlock => { after_take = true; if index < 9 { if !self.move_to(env, &mut stack, 9, 45, true) { @@ -961,9 +1207,11 @@ impl Menu { // The stack was edited in place in its slot. let slot = self.slots[index]; if stack.count == 0 { + self.containers[slot.container][slot.index] = None; self.put(env, index, None); } else { self.containers[slot.container][slot.index] = Some(stack.clone()); + self.slot_changed(env, index); } if check_count && stack.count == clicked.count { return None; @@ -1173,8 +1421,14 @@ impl Menu { Ok(()) } - /// The PICKUP branch of `doClick` (without the bundle overrides). + /// The PICKUP branch of `doClick` (without the bundle overrides), ending + /// with `slot.setChanged()`. fn pickup(&mut self, env: &Env, s: usize, primary: bool) { + self.pickup_inner(env, s, primary); + self.slot_changed(env, s); + } + + fn pickup_inner(&mut self, env: &Env, s: usize, primary: bool) { let clicked = self.slot(s).cloned(); match clicked { None => { @@ -1312,7 +1566,7 @@ impl Menu { if self.has_item(t) && self.quick_replace(t, &have, env) && self.may_pickup(t) - && self.slots[t].container != RESULT + && (self.slots[t].container != RESULT || self.kind == Kind::Loom) { let item = self.slot(t).expect("has item").clone(); if pass != 0 || item.count != Self::max_stack(env, &item) { 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 af5ca6e3c..f6d0c41ef 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -35,6 +35,8 @@ public final class VanillaMenuOracle { static java.lang.reflect.Method allocate; static RecipeManager recipes; static final List drops = new ArrayList<>(); + /** The block entity behind a "crafter_be" menu (slot state packets go to it). */ + static net.minecraft.world.level.block.entity.CrafterBlockEntity crafter; @SuppressWarnings("unchecked") static T make(Class type) { @@ -131,6 +133,19 @@ public final class VanillaMenuOracle { case "smoker" -> new SmokerMenu(0, inv); case "brewing" -> new BrewingStandMenu(0, inv); case "crafter" -> new CrafterMenu(0, inv); + case "crafter_be" -> { + // The server's menu: the block entity is the container and its data. + crafter = new net.minecraft.world.level.block.entity.CrafterBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.CRAFTER.defaultBlockState()); + try { + Field data = net.minecraft.world.level.block.entity.CrafterBlockEntity.class.getDeclaredField("containerData"); + data.setAccessible(true); + yield new CrafterMenu(0, inv, crafter, (ContainerData) data.get(crafter)); + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } + case "loom" -> new LoomMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; } @@ -180,6 +195,8 @@ 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())); + // 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"); for (int i = 0; i < dataJson.size(); i++) menu.setData(i, dataJson.get(i).getAsInt()); drops.clear(); @@ -188,7 +205,20 @@ public final class VanillaMenuOracle { var op = opJson.getAsJsonArray(); int slot = op.get(0).getAsInt(); int button = op.get(1).getAsInt(); - var input = ContainerInput.valueOf(op.get(2).getAsString()); + String kind = op.get(2).getAsString(); + if (kind.equals("BUTTON")) { + // ServerGamePacketListenerImpl.handleContainerButtonClick + if (menu.clickMenuButton(player, slot)) menu.broadcastChanges(); + out.println(state(menu, inv)); + continue; + } + if (kind.equals("SLOT_STATE")) { + // handleContainerSlotStateChanged: CrafterBlockEntity.setSlotState + if (slot >= 0 && slot < 9) crafter.setSlotState(slot, button == 1); + out.println(state(menu, inv)); + continue; + } + var input = ContainerInput.valueOf(kind); try { menu.clicked(slot, button, input, player); } catch (RuntimeException e) { diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 5137537b2..3a02efdb1 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -6,7 +6,9 @@ class with a stand-in player and level; the Rust example (menu_fixture) runs horizon_client::menu. Cases are randomized slot contents with random click sequences covering every ContainerInput (pickup, quick move, swap, clone, throw, the three quick craft drags, pickup all) over the player inventory, -crafting table, chests, hopper, dispenser, shulker box and the furnaces. After +crafting table, chests, hopper, dispenser, shulker box, the furnaces, the +brewing stand, the crafter (the client's menu, and the server's over the block +entity with slot state packets) and the loom (with its pattern buttons). After every click the slots, carried stack, data slots and drops are compared. """ import argparse @@ -19,8 +21,13 @@ except ImportError: import lab 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} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10} + 'chest6': 90, 'hopper': 41, 'dispenser': 45, 'shulker': 63, 'furnace': 39, 'blast_furnace': 39, 'smoker': 39, 'brewing': 41, 'crafter': 46, + 'crafter_be': 46, 'loom': 40} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1} +DYES = ['white', 'orange', 'magenta', 'light_blue', 'yellow', 'lime', 'pink', 'gray', 'light_gray', 'cyan', 'purple', + 'blue', 'brown', 'green', 'red', 'black'] +PATTERNS = ['minecraft:' + p for p in ('base', 'square_bottom_left', 'stripe_bottom', 'cross', 'border', 'gradient', + 'creeper', 'flower', 'globe', 'rhombus', 'small_stripes', 'half_horizontal')] COMMON = ['stone', 'dirt', 'cobblestone', 'oak_planks', 'stick', 'coal', 'iron_ingot', 'diamond', 'apple', 'bread', 'oak_log', 'sand', 'bucket', 'water_bucket', 'lava_bucket', 'ender_pearl', 'snowball', 'egg', 'white_wool', 'iron_helmet', 'diamond_chestplate', 'leather_leggings', 'iron_boots', 'shield', 'carved_pumpkin', @@ -69,8 +76,24 @@ class Gen: def slots(self, size, density): return [self.stack() if self.rng.random() < density else '-' for _ in range(size)] - def recipe(self, slots, width): - """Fills the crafting grid (slots 1..) with a small known recipe.""" + def loom_stack(self, roll=None): + """A banner (with up to seven layers), a dye, a pattern item or anything.""" + rng = self.rng + roll = rng.random() if roll is None else roll + if roll < 0.3: + layers = ','.join('{pattern:"%s",color:"%s"}' % (rng.choice(PATTERNS), rng.choice(DYES)) + for _ in range(rng.choice([0, 0, 1, 2, 5, 6, 6, 7]))) + extra = ',components:{"minecraft:banner_patterns":[%s]}' % layers if layers else '' + return '{id:"minecraft:%s_banner",count:%d%s}' % (rng.choice(DYES), rng.choice([1, 1, 2, 16]), extra) + if roll < 0.55: + return snbt('minecraft:%s_dye' % rng.choice(DYES), rng.choice([1, 1, 2, 3, 64])) + if roll < 0.75: + pool = [k for k in self.items if k.endswith('_banner_pattern')] + return snbt(rng.choice(pool), 1) + return self.stack() + + def recipe(self, slots, width, start=1): + """Fills the crafting grid (slots `start`..) with a small known recipe.""" rng = self.rng amount = lambda: rng.choice([1, 1, 2, 5, 64]) choices = [[('oak_log',)], [('oak_planks',), ('oak_planks',)], [('oak_planks', 'oak_planks'), ('oak_planks', 'oak_planks')], @@ -81,12 +104,23 @@ class Gen: pattern = [('oak_planks',), ('oak_planks',)] for y, row in enumerate(pattern): for x, name in enumerate(row): - slots[1 + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1) + slots[start + x + y * width] = snbt('minecraft:' + name, amount() if name != 'milk_bucket' else 1) - def ops(self, size): + def ops(self, size, menu=None): rng = self.rng out = [] for _ in range(rng.randrange(1, 9)): + if menu == 'loom' and rng.random() < 0.25: + # A pattern button (clickMenuButton), sometimes out of range. + out.append([rng.choice([0, 0, 1, 2, 3, 5, 10, 20, 39, 40, -1]), 0, 'BUTTON']) + continue + if menu == 'loom' and rng.random() < 0.15: + # The result: take it, shift it out, throw it. + out.append([3, rng.randrange(0, 2), rng.choice(['PICKUP', 'QUICK_MOVE', 'THROW', 'SWAP'])]) + continue + if menu == '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 kind = rng.choices(['PICKUP', 'QUICK_MOVE', 'SWAP', 'CLONE', 'THROW', 'DRAG', 'PICKUP_ALL', 'JUNK'], [30, 20, 8, 3, 6, 14, 6, 2])[0] slot = 0 if rng.random() < 0.2 and size in (46,) else rng.randrange(size) @@ -113,8 +147,9 @@ class Gen: def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--seed', type=int, default=7) - parser.add_argument('--cases', type=int, default=6000) + parser.add_argument('--cases', type=int, default=8000) parser.add_argument('--limit', type=int, default=3) + parser.add_argument('--menus', help='comma-separated menus to run (default: all)') args = parser.parse_args() work = lib.work_dir('menu-click-parity') vanilla = lib.Vanilla(work) @@ -123,17 +158,38 @@ def main(): rng = random.Random(args.seed) g = Gen(rng, items) cases = [] + chosen = args.menus.split(',') if args.menus else list(MENUS) for n in range(args.cases): - menu = list(MENUS)[n % len(MENUS)] + menu = chosen[n % len(chosen)] size = MENUS[menu] slots = g.slots(size, rng.choice([0.1, 0.4, 0.8])) + if menu == 'loom': + for i in rng.sample(range(4, size), 8): + slots[i] = g.loom_stack() + # Mostly a banner, a dye and sometimes a pattern item in their slots. + slots[0] = g.loom_stack(0.0) if rng.random() < 0.75 else rng.choice(['-', g.loom_stack()]) + slots[1] = g.loom_stack(0.4) if rng.random() < 0.75 else rng.choice(['-', g.loom_stack()]) + slots[2] = g.loom_stack(0.6) if rng.random() < 0.4 else rng.choice(['-', '-', g.loom_stack()]) + # The result slot follows the inputs; a fixture stack there is rare. + slots[3] = '-' if rng.random() < 0.9 else g.loom_stack() + if menu == 'crafter_be': + slots[45] = '-' + if rng.random() < 0.6: + g.recipe(slots, 3, start=0) if menu in ('inventory', 'crafting'): slots[0] = '-' if menu in ('inventory', 'crafting') and rng.random() < 0.6: g.recipe(slots, 2 if menu == 'inventory' else 3) + def datum(i): + if menu in ('crafter', 'crafter_be'): + return rng.choice([0, 0, 1]) + if menu == 'loom': + return rng.choice([-1, -1, 0, 0, 1, 2, 3, 30]) + return 0 + carried = (g.loom_stack() if menu == 'loom' else g.stack()) if rng.random() < 0.5 else '-' cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, - 'carried': g.stack() if rng.random() < 0.5 else '-', 'data': [rng.choice([0, 0, 1]) if menu == 'crafter' else 0 for _ in range(DATA.get(menu, 0))], - 'ops': g.ops(size)}) + 'carried': carried, 'data': [datum(i) for i in range(DATA.get(menu, 0))], + 'ops': g.ops(size, menu)}) (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) vanilla.run('VanillaMenuOracle', work / 'cases.jsonl', work / 'native.txt') lib.cargo_example('horizon-client', 'menu_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')