diff --git a/crates/horizon-client/examples/menu_fixture.rs b/crates/horizon-client/examples/menu_fixture.rs index 2434a5b5d..863e3786e 100644 --- a/crates/horizon-client/examples/menu_fixture.rs +++ b/crates/horizon-client/examples/menu_fixture.rs @@ -1,9 +1,11 @@ //! Menu clicks for tools/test_menu_click_parity.py: reads one JSON case per //! line (menu, creative, slots, carried, data, ops) and prints the oracle's -//! state lines after every click. +//! state lines after every click. The `*_be` furnace menus run over a furnace +//! block entity: its data slots follow `Furnace::input_clicked`. //! //! usage: menu_fixture RESOURCES INPUT OUTPUT use horizon_client::{ + containers::{Furnace, FurnaceKind}, crafting::Recipes, item_data::{canon_stack, parse_stack}, items::Items, @@ -46,7 +48,20 @@ fn main() -> horizon_client::Result<()> { let mut out = String::new(); for line in input.lines() { let case: Value = serde_json::from_str(line)?; - let kind = Kind::parse(case["menu"].as_str().unwrap_or_default()).ok_or("menu kind")?; + let name = case["menu"].as_str().unwrap_or_default(); + // FurnaceMenu over the server's AbstractFurnaceBlockEntity. + let furnace_kind = match name { + "furnace_be" => Some(FurnaceKind::Furnace), + "blast_furnace_be" => Some(FurnaceKind::BlastFurnace), + "smoker_be" => Some(FurnaceKind::Smoker), + _ => None, + }; + let kind = Kind::parse( + name.strip_suffix("_be") + .filter(|_| furnace_kind.is_some()) + .unwrap_or(name), + ) + .ok_or("menu kind")?; let mut menu = Menu::new(kind); menu.creative = case["creative"].as_bool().unwrap_or(false); for (i, slot) in case["slots"].as_array().ok_or("slots")?.iter().enumerate() { @@ -57,6 +72,15 @@ fn main() -> horizon_client::Result<()> { for (i, v) in case["data"].as_array().ok_or("data")?.iter().enumerate() { menu.data[i] = v.as_i64().unwrap_or(0) as i32; } + let mut furnace = furnace_kind.map(|kind| Furnace { + kind, + items: [0, 1, 2].map(|i| menu.slot(i).cloned()), + lit_remaining: menu.data[0], + lit_total: menu.data[1], + cooking_timer: menu.data[2], + cooking_total: menu.data[3], + speed: 1.0, + }); menu.drops.clear(); out += &format!("init {}\n", state(&menu)); for op in case["ops"].as_array().ok_or("ops")? { @@ -80,7 +104,15 @@ fn main() -> horizon_client::Result<()> { _ => {} } let kind = Input::parse(op[2].as_str().unwrap_or_default()).ok_or("input")?; - match menu.click(&env, slot, button, kind) { + let clicked = menu.click(&env, slot, button, kind); + if let Some(f) = furnace.as_mut() { + let before = f.items[0].clone(); + f.items = [0, 1, 2].map(|i| menu.slot(i).cloned()); + f.input_clicked(&recipes, before); + menu.data[2] = f.cooking_timer; + menu.data[3] = f.cooking_total; + } + match clicked { Ok(()) => out += &format!("{}\n", state(&menu)), Err(name) => out += &format!("error {name}\n"), } diff --git a/crates/horizon-client/src/containers.rs b/crates/horizon-client/src/containers.rs index abb72583d..9688af5eb 100644 --- a/crates/horizon-client/src/containers.rs +++ b/crates/horizon-client/src/containers.rs @@ -427,6 +427,32 @@ fn remainder(item: &str) -> Option<&'static str> { } } impl Furnace { + /// `AbstractFurnaceBlockEntity.setItem` on the input slot: anything but + /// the same item with the same components restarts cooking, with the + /// total time of the new input's recipe (200 ticks without one). + pub fn set_input(&mut self, recipes: &Recipes, stack: Option) { + let same = match (&self.items[0], &stack) { + (Some(old), Some(new)) => old.same_item_same_components(new), + _ => false, + }; + self.items[0] = stack; + if !same { + self.cooking_total = self.items[0] + .as_ref() + .and_then(|input| recipes.cook(self.kind.recipe_type(), input)) + .map_or(200, |recipe| total_time(recipe.time, self.speed)); + self.cooking_timer = 0; + } + } + /// A menu click wrote its slots into `items`, and `before` was the input + /// slot until then: the menu called `setItem` on it only if it changed + /// (`Slot.setByPlayer`; partial takes and merges keep the stack). + pub fn input_clicked(&mut self, recipes: &Recipes, before: Option) { + if self.items[0] != before { + let after = std::mem::replace(&mut self.items[0], before); + self.set_input(recipes, after); + } + } /// One server tick. Returns `Some(lit)` when the LIT block state must change. pub fn tick( &mut self, diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index c12744a77..b1eb2b0c0 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -4015,7 +4015,8 @@ impl Game<'_> { .container .and_then(|k| self.world.block_entities.get_mut(&k)) { - f.cooking_timer = 0; + // AbstractFurnaceBlockEntity.setItem: only a new input restarts cooking. + f.input_clicked(&self.res.recipes, before[0].clone()); } self.apply_equipment(); true @@ -4205,15 +4206,8 @@ impl Game<'_> { } return; } - if is_furnace - && slot == 300 - && let Some(BlockEntity::Furnace(f)) = self - .container - .and_then(|k| self.world.block_entities.get_mut(&k)) - { - // Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem). - f.cooking_timer = 0; - } + // Changing the input restarts cooking (AbstractFurnaceBlockEntity.setItem). + let furnace_input = (is_furnace && slot == 300).then(|| self.slot_mut(300).clone()); if slot == 200 { // ResultSlot: take the crafted stack and consume one of each ingredient. let mut crafted = 0; @@ -4324,8 +4318,15 @@ impl Game<'_> { } (Some(c), Some(s)) => (Some(c), Some(s)), }; - *self.slot_mut(slot) = new_slot; self.carried = new_carried; + *self.slot_mut(slot) = new_slot; + if let Some(before) = furnace_input + && let Some(BlockEntity::Furnace(f)) = self + .container + .and_then(|k| self.world.block_entities.get_mut(&k)) + { + f.input_clicked(&self.res.recipes, before); + } } /// ItemEntityRenderer: items bob and spin; blocks render as small cubes. fn entity_geometry(&mut self, camera: glam::DVec3, alpha: f64) -> Vec { 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 f6d0c41ef..8a5adc5c2 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaMenuOracle.java @@ -82,6 +82,9 @@ public final class VanillaMenuOracle { @Override public void playSeededSound(net.minecraft.world.entity.Entity p, double x, double y, double z, net.minecraft.core.Holder s, net.minecraft.sounds.SoundSource c, float v, float pitch, long seed) { } @Override public boolean addFreshEntity(net.minecraft.world.entity.Entity e) { return true; } @Override public void gameEvent(net.minecraft.core.Holder e, BlockPos p, net.minecraft.world.level.gameevent.GameEvent.Context c) { } + // 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) { } } static final class FakePlayer extends ServerPlayer { @@ -145,6 +148,31 @@ public final class VanillaMenuOracle { throw new AssertionError(e); } } + case "furnace_be", "blast_furnace_be", "smoker_be" -> { + // The server's menu: the block entity is the container and its data, + // so AbstractFurnaceBlockEntity.setItem restarts cooking. + net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity be = switch (kind) { + case "furnace_be" -> new net.minecraft.world.level.block.entity.FurnaceBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.FURNACE.defaultBlockState()); + case "blast_furnace_be" -> new net.minecraft.world.level.block.entity.BlastFurnaceBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.BLAST_FURNACE.defaultBlockState()); + default -> new net.minecraft.world.level.block.entity.SmokerBlockEntity(BlockPos.ZERO, + net.minecraft.world.level.block.Blocks.SMOKER.defaultBlockState()); + }; + be.setLevel(player.world); + try { + Field data = net.minecraft.world.level.block.entity.AbstractFurnaceBlockEntity.class.getDeclaredField("dataAccess"); + data.setAccessible(true); + ContainerData furnaceData = (ContainerData) data.get(be); + yield switch (kind) { + case "furnace_be" -> new FurnaceMenu(0, inv, be, furnaceData); + case "blast_furnace_be" -> new BlastFurnaceMenu(0, inv, be, furnaceData); + default -> new SmokerMenu(0, inv, be, furnaceData); + }; + } catch (ReflectiveOperationException e) { + throw new AssertionError(e); + } + } case "loom" -> new LoomMenu(0, inv); default -> throw new IllegalArgumentException(kind); }; diff --git a/tools/test_menu_click_parity.py b/tools/test_menu_click_parity.py index 3a02efdb1..b6e43e020 100644 --- a/tools/test_menu_click_parity.py +++ b/tools/test_menu_click_parity.py @@ -8,7 +8,9 @@ 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, 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 +entity with slot state packets), the loom (with its pattern buttons) and the +server's furnace menus over their block entities (`*_be`: a new input restarts +cooking, other clicks keep its progress). After every click the slots, carried stack, data slots and drops are compared. """ import argparse @@ -22,8 +24,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} -DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1} + 'crafter_be': 46, 'loom': 40, 'furnace_be': 39, 'blast_furnace_be': 39, 'smoker_be': 39} +DATA = {'furnace': 4, 'blast_furnace': 4, 'smoker': 4, 'brewing': 4, 'crafter': 10, 'crafter_be': 10, 'loom': 1, + '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'] PATTERNS = ['minecraft:' + p for p in ('base', 'square_bottom_left', 'stripe_bottom', 'cross', 'border', 'gradient', @@ -180,13 +183,29 @@ def main(): slots[0] = '-' if menu in ('inventory', 'crafting') and rng.random() < 0.6: g.recipe(slots, 2 if menu == 'inventory' else 3) + if menu.endswith('_be') and menu != 'crafter_be' and rng.random() < 0.7: + # Mostly something cooking: a smeltable input, the same in the + # inventory and in hand, so merges and partial takes happen. + food = snbt('minecraft:' + rng.choice(['raw_iron', 'beef', 'potato', 'sand', 'cobblestone', 'oak_log']), + rng.choice([1, 2, 5, 32, 64])) + slots[0] = food + for i in rng.sample(range(3, size), 4): + slots[i] = food if rng.random() < 0.6 else g.stack() + carried_food = food if rng.random() < 0.5 else None + else: + carried_food = None def datum(i): + if menu.endswith('_be') and menu != 'crafter_be': + # litTimeRemaining, litTotalTime, cookingTimer, cookingTotalTime + return [rng.choice([0, 37, 1600]), 1600, rng.choice([0, 1, 57, 199]), rng.choice([200, 100])][i] if menu in ('crafter', 'crafter_be'): return rng.choice([0, 0, 1]) if menu == 'loom': 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 '-' + if carried_food is not None: + carried = carried_food cases.append({'menu': menu, 'creative': rng.random() < 0.25, 'slots': slots, 'carried': carried, 'data': [datum(i) for i in range(DATA.get(menu, 0))], 'ops': g.ops(size, menu)})