From b28fcec7f0fbda0a7027af9864c5dc763462f4fa Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:43:31 +0200 Subject: [PATCH] Compare the ghost recipe of a recipe book click with the vanilla client's Book::ghost is the one place that places a recipe's ingredients into the grid or furnace slots; the harness runs fillGhostRecipe against the real menus. Fixes found: the result and the dyed, potion and map demo ingredients cycle through every stack (not the first), a furnace's fuels follow the registry's component lookup, and items keep their registry order. Co-Authored-By: Claude Sonnet 5.5 --- .../examples/ghost_recipe_fixture.rs | 73 +++++++++ crates/horizon-client/src/crafting.rs | 140 +++++++++++------- crates/horizon-client/src/game/recipe_book.rs | 78 +++------- crates/horizon-client/src/items.rs | 25 ++++ crates/horizon-client/src/recipe_book.rs | 130 ++++++++++++++-- .../parity/VanillaGhostRecipeOracle.java | 130 ++++++++++++++++ tools/test_ghost_recipe_parity.py | 77 ++++++++++ 7 files changed, 528 insertions(+), 125 deletions(-) create mode 100644 crates/horizon-client/examples/ghost_recipe_fixture.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGhostRecipeOracle.java create mode 100644 tools/test_ghost_recipe_parity.py diff --git a/crates/horizon-client/examples/ghost_recipe_fixture.rs b/crates/horizon-client/examples/ghost_recipe_fixture.rs new file mode 100644 index 000000000..0860fd409 --- /dev/null +++ b/crates/horizon-client/examples/ghost_recipe_fixture.rs @@ -0,0 +1,73 @@ +//! The ghost recipe a recipe book click fades into the menu, for +//! tools/test_ghost_recipe_parity.py: reads one JSON case per line (menu, recipe +//! id, the stack in the furnace's fuel slot) and prints, for every display of +//! the recipe, the slots `Book::ghost` fills and the stacks each cycles through. +//! +//! usage: ghost_recipe_fixture RESOURCES CASES OUTPUT +use horizon_client::{ + crafting::Recipes, + item_data::{canon_stack, parse_stack}, + items::Items, + recipe_book::{Book, BookType, GhostTarget, RecipeIndex}, +}; +use serde_json::Value; +use std::{fmt::Write as _, fs, path::Path}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: ghost_recipe_fixture RESOURCES CASES OUTPUT"; + let root = Path::new(args.get(1).ok_or(usage)?); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let items = Items::catalog(root)?; + let recipes = Recipes::load(root, &items)?; + let index = RecipeIndex::load(root); + let mut book = Book::build(&recipes, &items); + book.set_display_ids(&index); + let mut out = String::new(); + for line in cases.lines() { + let case: Value = serde_json::from_str(line)?; + let menu = case["menu"].as_str().unwrap_or_default(); + let id = case["recipe"].as_str().unwrap_or_default(); + let (book_type, grid) = match menu { + "inventory" => (BookType::Crafting, 2), + "crafting" => (BookType::Crafting, 3), + "furnace" => (BookType::Furnace, 0), + "blast_furnace" => (BookType::BlastFurnace, 0), + _ => (BookType::Smoker, 0), + }; + let fuel = match case["fuel"].as_str() { + Some(s) => parse_stack(s)?, + None => None, + }; + for entry in book.entries.iter().filter(|e| e.id == id) { + let crafting = book_type == BookType::Crafting; + let is_furnace = matches!( + entry.display, + horizon_client::recipe_book::Display::Furnace(_) + ); + if is_furnace == crafting || (crafting && !entry.fits(grid, grid)) { + out.push_str("skip | "); + continue; + } + for slot in book.ghost(entry, book_type, grid, fuel.is_none(), &items) { + let (index, result) = match slot.target { + GhostTarget::Result => (if crafting { 0 } else { 2 }, true), + GhostTarget::Grid(i) => (1 + i, false), + GhostTarget::Input => (0, false), + GhostTarget::Fuel => (1, false), + }; + let stacks: Vec = slot.items.iter().map(|s| canon_stack(Some(s))).collect(); + let _ = write!( + out, + "{index}{}={} ", + if result { "R" } else { "I" }, + stacks.join(",") + ); + } + out.push_str("| "); + } + out.push('\n'); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index a06d380ea..f6ec337d3 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -296,41 +296,20 @@ pub enum Special { RepairItem, } impl Special { - /// Every result the display of a learnable recipe can show - /// (`SlotDisplay.resolve*` of its result): empty when it is one stack. - pub fn result_variants(&self) -> Vec { - match self { - // The result keeps the input's item: any item of the ingredient. - Self::Transmute { input, result, .. } if result.item.is_none() => { - let mut items: Vec<&String> = input.0.iter().collect(); - items.sort(); - items - .into_iter() - .map(|item| { - let mut made = result.create(); - made.item = Arc::from(item.as_str()); - made - }) - .collect() - } - // DyedSlotDemo: the target dyed. - Self::Dye { result, .. } => { - let mut made = result.create(); - made.data_mut().dyed_color = Some(0); - vec![made] - } - // Any potion's tipped arrow. - Self::Imbue { result, .. } => crate::brewing::POTIONS - .iter() - .map(|p| result.create().with_potion(p.id)) - .collect(), - _ => Vec::new(), - } - } /// The recipe-book displays of a learnable (non-custom) crafting recipe: - /// its layout and result. - pub fn book_displays(&self) -> Vec<(crate::recipe_book::Display, ItemStack)> { + /// its layout, its result as the button shows it, and every stack the + /// result display cycles through when it is more than that one + /// (`SlotDisplay.resolveForStacks`). + pub fn book_displays(&self) -> Vec { use crate::recipe_book::Display; + let first_of = + |all: &Vec, single: ItemStack| all.first().cloned().unwrap_or(single); + let shown = |display, result, variants| BookDisplay { + display, + result, + variants, + stacks: Vec::new(), + }; match self { Self::Transmute { input, @@ -344,26 +323,54 @@ impl Special { let mut ingredients = vec![input.clone()]; ingredients.extend(std::iter::repeat_n(material.clone(), n)); let mut made = result.create(); - if result.item.is_none() { - // The result keeps the input's item: show the first one. - if let Some(first) = input.0.iter().min() { - made.item = Arc::from(first.as_str()); - } - } if *add_count { made.count += n as u32; } - (Display::Shapeless(ingredients), made) + // The result keeps the input's item: any item of the ingredient. + let all: Vec = if result.item.is_none() { + input + .1 + .iter() + .map(|item| { + let mut stack = made.clone(); + stack.item = Arc::from(item.as_str()); + stack + }) + .collect() + } else { + Vec::new() + }; + shown(Display::Shapeless(ingredients), first_of(&all, made), all) }) .collect(), Self::Dye { target, dye, result, - } => vec![( - Display::Shapeless(vec![target.clone(), dye.clone()]), - result.create(), - )], + } => { + // DyedSlotDemo: the targets cycle fastest, 16 stacks at most. + let (targets, dyes) = (&target.1, &dye.1); + let all: Vec = (0..targets.len() * dyes.len()) + .map(|i| { + let mut made = result.create(); + made.item = Arc::from(targets[i % targets.len()].as_str()); + let name = dyes[i / targets.len()].trim_start_matches("minecraft:"); + let color = crate::block_entity_render::DYES + .iter() + .find(|(c, _)| name.strip_suffix("_dye") == Some(c)) + .map_or(crate::block_entity_render::DYES[0].1, |d| d.1); + made.data_mut().dyed_color = Some(color as i32); + made + }) + .take(16) + .collect(); + let first = result.create(); + vec![shown( + Display::Shapeless(vec![target.clone(), dye.clone()]), + first_of(&all, first), + all, + )] + } Self::Imbue { source, material, @@ -372,19 +379,48 @@ impl Special { let cells = (0..9) .map(|i| Some(if i == 4 { source } else { material }.clone())) .collect(); - vec![( - Display::Shaped { - width: 3, - height: 3, - cells, - }, - result.create(), - )] + // Any potion's tipped arrow. + let potions = |item: ItemStack| -> Vec { + crate::brewing::POTIONS + .iter() + .map(|p| item.clone().with_potion(&format!("minecraft:{}", p.id))) + .collect() + }; + let all = potions(result.create()); + // The source ingredient is shown as a lingering potion of each kind. + let lingering = source + .1 + .iter() + .flat_map(|item| potions(ItemStack::new(item, 1))) + .collect(); + vec![BookDisplay { + stacks: vec![(4, lingering)], + ..shown( + Display::Shaped { + width: 3, + height: 3, + cells, + }, + first_of(&all, result.create()), + all, + ) + }] } _ => Vec::new(), } } } +/// One recipe-book display of a special recipe. +pub struct BookDisplay { + pub display: crate::recipe_book::Display, + /// The result as the button shows it (the first of `variants`). + pub result: ItemStack, + /// Every stack the result display cycles through; empty for one stack. + pub variants: Vec, + /// Ingredients shown as other stacks than their items, by index in + /// `Entry::requirements`. + pub stacks: Vec<(usize, Vec)>, +} /// `CraftingInput`: the occupied bounding box of the grid. pub struct Input<'a> { pub width: usize, diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 747da4904..4a65feb0f 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -10,7 +10,7 @@ use horizon_client::{ hud::{HudBatch, Rect, rgba}, items::ItemStack, menu::place::{PostPlace, Stacked}, - recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab}, + recipe_book::{Book, BookType, ClientBook, Collection, Entry, GhostTarget, Tab}, recipe_book_screen::{ self as screen, ButtonView, Call, Drawn, GhostView, ItemCall, OverlayRecipe, OverlayView, Screen as Layout, Search, TabView, @@ -716,68 +716,26 @@ impl Game<'_> { /// `fillGhostRecipe`: the recipe's ingredients faded into the slots. fn fill_ghost(&mut self, book_type: BookType, entry: &Entry) { + let grid = self.craft_size; + let fuel_empty = self.slot_mut(301).is_none(); let Some(book) = self.recipe_ui.book.as_ref() else { return; }; - let stacks = |ingredient: &horizon_client::crafting::Ingredient| -> Vec { - book.items_of(ingredient) - .iter() - .map(|i| ItemStack::new(i, 1)) - .collect() - }; - let mut ghost = Vec::new(); - match book_type { - BookType::Crafting => { - let (gw, gh) = (self.craft_size, self.craft_size); - ghost.push(Ghost { - slot: 200, - items: vec![entry.result.clone()], - result: true, - }); - let requirements = entry.requirements(); - for (ingredient, grid_index) in entry.grid_cells(gw, gh) { - if let Some(i) = ingredient { - let items = stacks(requirements[i]); - if !items.is_empty() { - ghost.push(Ghost { - slot: 100 + grid_index, - items, - result: false, - }); - } - } - } - } - _ => { - ghost.push(Ghost { - slot: 302, - items: vec![entry.result.clone()], - result: true, - }); - if let Display::Furnace(ingredient) = &entry.display { - ghost.push(Ghost { - slot: 300, - items: stacks(ingredient), - result: false, - }); - if self.slot_mut(301).is_none() { - let mut fuels: Vec<&std::sync::Arc> = self - .res - .items - .order - .iter() - .filter(|i| self.res.items.get(i).is_some_and(|i| i.fuel.is_some())) - .collect(); - fuels.dedup(); - ghost.push(Ghost { - slot: 301, - items: fuels.iter().map(|i| ItemStack::new(i, 1)).collect(), - result: false, - }); - } - } - } - } + let ghost = book + .ghost(entry, book_type, grid, fuel_empty, &self.res.items) + .into_iter() + .map(|g| Ghost { + slot: match (g.target, book_type) { + (GhostTarget::Result, BookType::Crafting) => 200, + (GhostTarget::Result, _) => 302, + (GhostTarget::Grid(i), _) => 100 + i, + (GhostTarget::Input, _) => 300, + (GhostTarget::Fuel, _) => 301, + }, + result: g.target == GhostTarget::Result, + items: g.items, + }) + .collect(); self.recipe_ui.ghost = ghost; } diff --git a/crates/horizon-client/src/items.rs b/crates/horizon-client/src/items.rs index 33d30f6f5..abba286f1 100644 --- a/crates/horizon-client/src/items.rs +++ b/crates/horizon-client/src/items.rs @@ -158,11 +158,32 @@ pub struct ItemStack { /// Components beyond count and damage (see `item_data`); None when default. pub extra: Option>, } +/// `order`'s items in the registry's order (`command-registries.json`'s +/// `items`, exported from the game); `order` itself when that is missing. +fn registry_order(root: &Path, order: &[Arc]) -> Vec> { + let listed: Vec = fs::read(root.join("command-registries.json")) + .ok() + .and_then(|b| serde_json::from_slice::(&b).ok()) + .and_then(|v| serde_json::from_value(v["items"].clone()).ok()) + .unwrap_or_default(); + if listed.is_empty() { + return order.to_vec(); + } + let known: HashSet<&str> = order.iter().map(|i| &**i).collect(); + listed + .iter() + .filter(|i| known.contains(i.as_str())) + .map(|i| Arc::from(i.as_str())) + .collect() +} /// Item ids standing for a loot table's `minecraft:dynamic` entries. const DYNAMIC: &str = "#dynamic:"; pub struct Items { pub items: HashMap, ItemInfo>, pub order: Vec>, + /// The same items in item registry (network id) order, as vanilla lists + /// them; sorted by name when the registry export is missing. + pub registry_order: Vec>, /// Block tag name (without '#') -> member block names. pub block_tags: HashMap>, pub item_tags: HashMap>, @@ -456,9 +477,11 @@ impl Items { } let loot_root = root.join("data/minecraft/loot_table"); walk_loot(&loot_root, &loot_root, &mut loot)?; + let registry_order = registry_order(root, &order); Ok(Self { items, order, + registry_order, block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, item_tag_order: load_tag_lists(root, "item")?, @@ -474,6 +497,7 @@ impl Items { Ok(Self { items: HashMap::new(), order: Vec::new(), + registry_order: Vec::new(), block_tags: load_tags(root, "block")?, item_tags: load_tags(root, "item")?, item_tag_order: load_tag_lists(root, "item")?, @@ -487,6 +511,7 @@ impl Items { Self { items: HashMap::new(), order: Vec::new(), + registry_order: Vec::new(), block_tags: HashMap::new(), item_tag_order: item_tags .iter() diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 036269136..6de6416c2 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -161,8 +161,19 @@ pub struct Entry { /// `result` (a map copy of any map, an arrow of any potion): the search /// tree reads them all, the button shows the first. pub variants: Vec, + /// Ingredients shown as other stacks than their items (by index in + /// `requirements`): the potions an imbued arrow's lingering potion is. + pub stacks: Vec<(usize, Vec)>, } impl Entry { + /// Every stack the result display cycles through. + pub fn results(&self) -> &[ItemStack] { + if self.variants.is_empty() { + std::slice::from_ref(&self.result) + } else { + &self.variants + } + } /// The ingredients that must be matched to craft it, in order. pub fn requirements(&self) -> Vec<&Ingredient> { match &self.display { @@ -310,16 +321,16 @@ impl Book { // Custom recipes are never learnable; the others show one // display per material count (TransmuteRecipe.display). Recipe::Special(special) => { - let variants = special.result_variants(); - for (display, result) in special.book_displays() { + for shown in special.book_displays() { entries.push(Entry { id: format!("minecraft:{name}"), display_id: -1, category: crafting_category(&category), group: group(&grp), - display, - result, - variants: variants.clone(), + display: shown.display, + result: shown.result, + variants: shown.variants, + stacks: shown.stacks, }); } continue; @@ -333,6 +344,7 @@ impl Book { display, result: result.create(), variants: Vec::new(), + stacks: Vec::new(), }); } for c in &recipes.cooking { @@ -353,6 +365,7 @@ impl Book { display: Display::Furnace(c.ingredient.clone()), result: c.result.clone(), variants: Vec::new(), + stacks: Vec::new(), }); } let order = items @@ -418,6 +431,85 @@ impl Book { pub fn items_of(&self, ingredient: &Ingredient) -> Vec { ingredient.1.clone() } + /// `RecipeBookComponent.fillGhostRecipe` of a book type: the result and the + /// ingredients faded into the menu's slots, in the order the component + /// sets them. `grid` is the side of the crafting grid, `fuel_empty` + /// whether the furnace's fuel slot is empty. + pub fn ghost( + &self, + entry: &Entry, + book_type: BookType, + grid: usize, + fuel_empty: bool, + items: &crate::items::Items, + ) -> Vec { + let stacks = |ingredient: &Ingredient| -> Vec { + self.items_of(ingredient) + .iter() + .map(|i| ItemStack::new(i, 1)) + .collect() + }; + let mut out = Vec::new(); + match book_type { + BookType::Crafting => { + out.push(GhostSlot { + target: GhostTarget::Result, + items: entry.results().to_vec(), + }); + let requirements = entry.requirements(); + for (ingredient, index) in entry.grid_cells(grid, grid) { + let Some(i) = ingredient else { continue }; + let list = match entry.stacks.iter().find(|s| s.0 == i) { + Some(shown) => shown.1.clone(), + None => stacks(requirements[i]), + }; + if !list.is_empty() { + out.push(GhostSlot { + target: GhostTarget::Grid(index), + items: list, + }); + } + } + } + _ => { + out.push(GhostSlot { + target: GhostTarget::Result, + items: entry.results().to_vec(), + }); + if let Display::Furnace(ingredient) = &entry.display { + out.push(GhostSlot { + target: GhostTarget::Input, + items: stacks(ingredient), + }); + if fuel_empty { + // `SlotDisplay.AnyFuel`: every item with a cooking fuel + // component, the registry's component lookup listing the + // items of one component value together, the values in + // the order of their first item. + let mut groups: Vec<(String, Vec)> = Vec::new(); + for item in &items.registry_order { + let Some(fuel) = items.get(item).and_then(|i| i.fuel.as_ref()) else { + continue; + }; + let key = format!("{fuel:?}"); + match groups.iter_mut().find(|g| g.0 == key) { + Some(group) => group.1.push(ItemStack::new(item, 1)), + None => groups.push((key, vec![ItemStack::new(item, 1)])), + } + } + let fuels = groups.into_iter().flat_map(|g| g.1).collect(); + out.push(GhostSlot { + target: GhostTarget::Fuel, + items: fuels, + }); + } + } + } + } + // `GhostSlots.setSlot` keeps only slots with something to show. + out.retain(|g| !g.items.is_empty()); + out + } /// The recipe-book search tree (`SessionSearchTrees.updateRecipes`, a /// `FullTextSearchTree`): without a colon the text must occur in a /// tooltip line of a result item of the collection; `namespace:path` @@ -431,14 +523,7 @@ impl Book { let query = query.to_lowercase(); let results: Vec<&ItemStack> = entries .iter() - .flat_map(|&i| { - let e = &self.entries[i]; - if e.variants.is_empty() { - std::slice::from_ref(&e.result).iter() - } else { - e.variants.iter() - } - }) + .flat_map(|&i| self.entries[i].results()) .collect(); let in_lines = |text: &str| { results @@ -458,6 +543,23 @@ impl Book { } } +/// Where a ghost recipe's stacks are drawn. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum GhostTarget { + Result, + /// A crafting grid slot, row by row. + Grid(usize), + /// A furnace's input and fuel slots. + Input, + Fuel, +} +/// One slot of a ghost recipe and the stacks it cycles through. +#[derive(Clone, Debug)] +pub struct GhostSlot { + pub target: GhostTarget, + pub items: Vec, +} + /// A `RecipeDisplayId` as a `HashMap` key: a record of one int hashes as it. #[derive(Clone, Copy, Debug, PartialEq, Eq)] struct DisplayKey(i32); @@ -766,6 +868,7 @@ mod tests { display: Display::Shapeless(vec![ing(&["minecraft:stick"])]), result: ItemStack::new("minecraft:stick", 1), variants: Vec::new(), + stacks: Vec::new(), }; let book = Book { entries: vec![ @@ -813,6 +916,7 @@ mod tests { display: Display::Shapeless(Vec::new()), result: ItemStack::new("minecraft:stick", 4), variants: Vec::new(), + stacks: Vec::new(), }], placements: HashMap::new(), order: HashMap::new(), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGhostRecipeOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGhostRecipeOracle.java new file mode 100644 index 000000000..bb0d74fcb --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaGhostRecipeOracle.java @@ -0,0 +1,130 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.lang.reflect.Field; +import java.lang.reflect.Method; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.gui.screens.recipebook.CraftingRecipeBookComponent; +import net.minecraft.client.gui.screens.recipebook.FurnaceRecipeBookComponent; +import net.minecraft.client.gui.screens.recipebook.GhostSlots; +import net.minecraft.client.gui.screens.recipebook.RecipeBookComponent; +import net.minecraft.core.registries.Registries; +import net.minecraft.resources.Identifier; +import net.minecraft.resources.ResourceKey; +import net.minecraft.server.level.ServerPlayer; +import net.minecraft.util.context.ContextMap; +import net.minecraft.world.entity.EntityEquipment; +import net.minecraft.world.entity.player.Inventory; +import net.minecraft.world.entity.player.Player; +import net.minecraft.world.flag.FeatureFlags; +import net.minecraft.world.inventory.*; +import net.minecraft.world.item.ItemStack; +import net.minecraft.world.item.crafting.RecipeManager; +import net.minecraft.world.item.crafting.display.FurnaceRecipeDisplay; +import net.minecraft.world.item.crafting.display.RecipeDisplay; +import net.minecraft.world.item.crafting.display.RecipeDisplayEntry; +import net.minecraft.world.item.crafting.display.ShapedCraftingRecipeDisplay; +import net.minecraft.world.item.crafting.display.ShapelessCraftingRecipeDisplay; +import net.minecraft.world.item.crafting.display.SlotDisplayContext; + +/** + * Original oracle for the ghost recipe the recipe book fades into the menu + * when a recipe is clicked: for every display of a recipe, the client's + * CraftingRecipeBookComponent / FurnaceRecipeBookComponent.fillGhostRecipe + * runs against the real inventory, crafting table or furnace menu (the + * component is allocated without its constructor and given the menu) and + * fills a GhostSlots. Printed per display, in the order the component set + * them: the menu slot, whether it is the result, and the stacks the slot + * cycles through (PlaceRecipeHelper's grid placement for shaped recipes, the + * first slots for shapeless ones, the ingredient, the result and every fuel + * for a furnace whose fuel slot is empty). + */ +public final class VanillaGhostRecipeOracle { + @SuppressWarnings("unchecked") + public static void main(String[] args) throws Exception { + ParityData.init(); + var field = Class.forName("sun.misc.Unsafe").getDeclaredField("theUnsafe"); + field.setAccessible(true); + VanillaMenuOracle.unsafe = field.get(null); + VanillaMenuOracle.allocate = VanillaMenuOracle.unsafe.getClass().getMethod("allocateInstance", Class.class); + RecipeManager recipes = new RecipeManager(ParityData.lookup); + recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET); + VanillaMenuOracle.recipes = recipes; + ContextMap context = ContextMap.builder().set(SlotDisplayContext.REGISTRIES, ParityData.access).buildAndValidate(SlotDisplayContext.CONTEXT); + Field ghostField = GhostSlots.class.getDeclaredField("ingredients"); + ghostField.setAccessible(true); + Field menuField = RecipeBookComponent.class.getDeclaredField("menu"); + menuField.setAccessible(true); + try (var out = new PrintWriter(Files.newBufferedWriter(Path.of(args[1]), StandardCharsets.UTF_8)); + var lines = Files.lines(Path.of(args[0]))) { + for (String line : (Iterable) lines::iterator) { + var f = JsonParser.parseString(line).getAsJsonObject(); + try { + var world = VanillaMenuOracle.make(VanillaMenuOracle.World.class); + world.server = VanillaMenuOracle.make(VanillaMenuOracle.Server.class); + var player = VanillaMenuOracle.make(VanillaMenuOracle.FakePlayer.class); + player.world = world; + var inv = new Inventory(player, new EntityEquipment()); + player.inv = inv; + String kind = f.get("menu").getAsString(); + AbstractContainerMenu menu = VanillaMenuOracle.menu(kind, player, inv); + VanillaMenuOracle.set(player, Player.class, "containerMenu", menu); + if (f.has("fuel") && !f.get("fuel").isJsonNull()) { + menu.getSlot(1).set(ParityData.stack(f.get("fuel").getAsString())); + } + RecipeBookComponent component = kind.equals("inventory") || kind.equals("crafting") + ? VanillaMenuOracle.make(CraftingRecipeBookComponent.class) + : VanillaMenuOracle.make(FurnaceRecipeBookComponent.class); + menuField.set(component, menu); + Method fill = (component instanceof CraftingRecipeBookComponent ? CraftingRecipeBookComponent.class : FurnaceRecipeBookComponent.class) + .getDeclaredMethod("fillGhostRecipe", GhostSlots.class, RecipeDisplay.class, ContextMap.class); + fill.setAccessible(true); + int grid = kind.equals("inventory") ? 2 : 3; + List displays = new ArrayList<>(); + recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(f.get("recipe").getAsString())), displays::add); + StringBuilder result = new StringBuilder(); + for (RecipeDisplayEntry entry : displays) { + RecipeDisplay display = entry.display(); + // CraftingRecipeBookComponent.canDisplay: only what fits the grid is listed. + boolean fits = switch (display) { + case ShapedCraftingRecipeDisplay shaped -> grid >= shaped.width() && grid >= shaped.height(); + case ShapelessCraftingRecipeDisplay shapeless -> grid * grid >= shapeless.ingredients().size(); + case FurnaceRecipeDisplay furnace -> !kind.equals("inventory") && !kind.equals("crafting"); + default -> false; + }; + if (kind.equals("inventory") || kind.equals("crafting") ? display instanceof FurnaceRecipeDisplay : !(display instanceof FurnaceRecipeDisplay)) fits = false; + if (!fits) { + result.append("skip | "); + continue; + } + GhostSlots ghost = new GhostSlots(() -> 0); + fill.invoke(component, ghost, display, context); + var map = (Map) ghostField.get(ghost); + for (var e : map.entrySet()) { + Object slot = e.getValue(); + Method items = slot.getClass().getDeclaredMethod("items"); + Method isResult = slot.getClass().getDeclaredMethod("isResultSlot"); + items.setAccessible(true); + isResult.setAccessible(true); + result.append(menu.slots.indexOf(e.getKey())).append((boolean) isResult.invoke(slot) ? "R" : "I").append('='); + boolean first = true; + for (ItemStack stack : (List) items.invoke(slot)) { + result.append(first ? "" : ",").append(ParityData.canon(stack)); + first = false; + } + result.append(' '); + } + result.append("| "); + } + out.println(result); + } catch (Throwable e) { + out.println("error-case " + e.getClass().getSimpleName() + " " + e.getMessage()); + if (System.getenv("MENU_TRACE") != null) e.printStackTrace(); + } + } + } + } +} diff --git a/tools/test_ghost_recipe_parity.py b/tools/test_ghost_recipe_parity.py new file mode 100644 index 000000000..ad722109b --- /dev/null +++ b/tools/test_ghost_recipe_parity.py @@ -0,0 +1,77 @@ +#!/usr/bin/env python3 +"""Compare the ghost recipe of a recipe book click with the vanilla client's. + +Each case opens the inventory (2x2), a crafting table (3x3), a furnace, a +blast furnace or a smoker and clicks a recipe of its book (every crafting and +cooking recipe, the furnaces with their fuel slot empty or holding coal). The +Java oracle (VanillaGhostRecipeOracle) runs vanilla's +CraftingRecipeBookComponent / FurnaceRecipeBookComponent.fillGhostRecipe +against the real menu for every display of the recipe and prints the GhostSlots +it fills: the menu slot, whether it is the result and the stacks the slot +cycles through (PlaceRecipeHelper's centred placement of shaped recipes, the +first slots for shapeless ones, every fuel for an empty fuel slot); +examples/ghost_recipe_fixture prints the same from +horizon_client::recipe_book::Book::ghost, which the game fills its ghost +slots from. The lines must agree. +""" +import argparse +import json +import os +import random +import subprocess +import sys +try: + from . import interaction_lab as lib, test_model_baking_parity as baking, test_rust_parity as base +except ImportError: + import interaction_lab as lib + import test_model_baking_parity as baking + import test_rust_parity as base + +CRAFTING = ('minecraft:crafting_shaped', 'minecraft:crafting_shapeless', 'minecraft:crafting_transmute', + 'minecraft:crafting_dye', 'minecraft:crafting_imbue') +COOKING = {'minecraft:smelting': 'furnace', 'minecraft:blasting': 'blast_furnace', 'minecraft:smoking': 'smoker'} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=11) + parser.add_argument('--limit', type=int, default=3) + args = parser.parse_args() + rng = random.Random(args.seed) + lock, jars, _ = base.verify_artifacts() + work = lib.work_dir('ghost-recipe-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + sources = ('ParityData', 'VanillaMenuOracle', 'VanillaGhostRecipeOracle') + done = subprocess.run(['javac', '--release', str(lock['minecraft']['java_major']), '-proc:none', '-nowarn', '-cp', deps, + '-d', str(classes), *(str(lib.PARITY / f'{n}.java') for n in sources)], capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + cases = [] + for path in sorted((lib.RESOURCES / 'data/minecraft/recipe').glob('*.json')): + kind = json.loads(path.read_text()).get('type') + recipe = 'minecraft:' + path.stem + if kind in CRAFTING: + for menu in ('inventory', 'crafting'): + cases.append({'menu': menu, 'recipe': recipe}) + elif kind in COOKING: + for fuel in (None, '{id:"minecraft:coal",count:3}'): + cases.append({'menu': COOKING[kind], 'recipe': recipe, 'fuel': fuel}) + rng.shuffle(cases) + (work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases)) + run = subprocess.run(['java', '-Xmx2G', '-cp', str(classes) + os.pathsep + deps, 'dev.horizonlab.parity.VanillaGhostRecipeOracle', + str(work / 'cases.jsonl'), str(work / 'native.txt')], capture_output=True, text=True) + if run.returncode: + print(run.stderr[-4000:]) + sys.exit('oracle failed') + lib.cargo_example('horizon-client', 'ghost_recipe_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + bad = lib.compare(cases, work / 'native.txt', work / 'rust.txt', + lambda case, line: case['menu'] if not line.startswith('error') else 'oracle error', + describe=json.dumps, limit=args.limit) + raise SystemExit(1 if bad else 0) + + +if __name__ == '__main__': + main()