From 23d7ebdfaa659249717ffd5aac7e791b27b62bc9 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 05:35:49 +0200 Subject: [PATCH 1/4] Search the recipe book as vanilla's FullTextSearchTree does, over the full tooltip lines of every result The recipe book view harness now searches: names, parts of names, ids with a colon, odd texts. Horizon's recipe tooltips lacked attribute modifiers, smithing template, potion, dyed, pot, rocket and disc lines, and the results a display cycles through (map copies, tipped arrows, dyed armour). Co-Authored-By: Claude Sonnet 5.5 --- .../examples/recipe_book_view_fixture.rs | 9 + crates/horizon-client/src/crafting.rs | 31 ++ crates/horizon-client/src/game/recipe_book.rs | 6 +- crates/horizon-client/src/item_tooltip.rs | 297 ++++++++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/recipe_book.rs | 22 +- .../parity/VanillaRecipeBookViewOracle.java | 40 ++- tools/test_recipe_book_view_parity.py | 53 +++- 8 files changed, 454 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/item_tooltip.rs diff --git a/crates/horizon-client/examples/recipe_book_view_fixture.rs b/crates/horizon-client/examples/recipe_book_view_fixture.rs index 5c4f5bb26..8a1e5da0e 100644 --- a/crates/horizon-client/examples/recipe_book_view_fixture.rs +++ b/crates/horizon-client/examples/recipe_book_view_fixture.rs @@ -26,6 +26,11 @@ fn main() -> horizon_client::Result<()> { let mut book = Book::build(&recipes, &items); book.set_display_ids(&index); let max = |s: &horizon_client::items::ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack); + let names = horizon_client::creative::Names::load(root); + let translate = |k: &str| names.get(k).map(str::to_owned); + let tooltip = |s: &horizon_client::items::ItemStack| { + horizon_client::item_tooltip::lines(s, items.get(&s.item), &translate) + }; let mut out = String::new(); for line in cases.lines() { let case: Value = serde_json::from_str(line)?; @@ -69,6 +74,7 @@ fn main() -> horizon_client::Result<()> { _ => BookType::Smoker, }; let filtering = case["filtering"].as_bool().unwrap_or(false); + let query = case["search"].as_str().unwrap_or_default(); for tab in book_type.tabs() { let collections = client.collections(&book, book_type, tab); let selected = |i: usize| match (&book.entries[i].display, book_type) { @@ -85,6 +91,9 @@ fn main() -> horizon_client::Result<()> { let shown: Vec<_> = collections .iter() .filter(|c| c.entries.iter().any(|&i| selected(i))) + .filter(|c| { + query.is_empty() || book.collection_matches(&c.entries, query, &tooltip) + }) .filter(|c| !filtering || c.entries.iter().any(|&i| craftable(i))) .collect(); let name = match tab { diff --git a/crates/horizon-client/src/crafting.rs b/crates/horizon-client/src/crafting.rs index fbcbb1b11..a06d380ea 100644 --- a/crates/horizon-client/src/crafting.rs +++ b/crates/horizon-client/src/crafting.rs @@ -296,6 +296,37 @@ 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)> { diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 8bf4e3340..747da4904 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -423,7 +423,11 @@ impl Game<'_> { } if !query.is_empty() && !book.collection_matches(&c.entries, &query, &|stack| { - self.stack_tooltip(stack).into_iter().map(|l| l.0).collect() + horizon_client::item_tooltip::lines( + stack, + self.res.items.get(&stack.item), + &|k| self.res.names.get(k).map(str::to_owned), + ) }) { continue; diff --git a/crates/horizon-client/src/item_tooltip.rs b/crates/horizon-client/src/item_tooltip.rs new file mode 100644 index 000000000..764470149 --- /dev/null +++ b/crates/horizon-client/src/item_tooltip.rs @@ -0,0 +1,297 @@ +//! The lines of an item's tooltip as `ItemStack.getTooltipLines` writes them +//! without a player and without advanced tooltips, for stacks as recipes +//! produce them. The recipe book's search tree matches them, so recipes of +//! tools and armour answer to "attack speed" or "when on head". +use crate::items::{ItemInfo, ItemStack}; + +/// `EquipmentSlotGroup` in declaration order, the order tooltips list them in. +const SLOT_GROUPS: [&str; 11] = [ + "any", "mainhand", "offhand", "hand", "feet", "legs", "chest", "head", "armor", "body", + "saddle", +]; + +/// `ItemAttributeModifiers.ATTRIBUTE_MODIFIER_FORMAT`, `DecimalFormat("#.##")` +/// of a positive amount (half-even on the exact value). +fn format_amount(value: f64) -> String { + let text = format!("{:.2}", value); + text.trim_end_matches('0').trim_end_matches('.').to_owned() +} + +/// `ItemAttributeModifiers.Display.Default.apply`: a modifier's line, none +/// for a zero amount. `percent` is the modifier's operation id (0: added +/// value, 1 and 2: multiplied). +fn modifier_line( + translate: &dyn Fn(&str) -> Option, + attribute: &str, + amount: f64, + operation: usize, +) -> Option { + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let scale = match operation { + 0 if attribute == "knockback_resistance" => 10.0, + 0 => 1.0, + _ => 100.0, + }; + let (kind, shown) = if amount > 0.0 { + ("plus", amount * scale) + } else if amount < 0.0 { + ("take", -amount * scale) + } else { + return None; + }; + Some( + text(&format!("attribute.modifier.{kind}.{operation}")) + .replacen("%s", &format_amount(shown), 1) + .replacen("%s", &text(&format!("attribute.name.{attribute}")), 1) + .replace("%%", "%"), + ) +} + +/// `ItemStack.addAttributeTooltips` for the item's own modifiers: per slot +/// group an empty line, the group's heading and a line per modifier. +fn attribute_lines(info: &ItemInfo, translate: &dyn Fn(&str) -> Option) -> Vec { + let mut lines = Vec::new(); + for group in SLOT_GROUPS { + let mut first = true; + for (attribute, _, amount, operation, slot) in &info.modifiers { + if slot != group { + continue; + } + if std::mem::take(&mut first) { + lines.push(String::new()); + lines.push( + translate(&format!("item.modifiers.{group}")) + .unwrap_or_else(|| format!("item.modifiers.{group}")), + ); + } + let id = match operation.as_str() { + "add_multiplied_base" => 1, + "add_multiplied_total" => 2, + _ => 0, + }; + let path = attribute.strip_prefix("minecraft:").unwrap_or(attribute); + lines.extend(modifier_line(translate, path, *amount, id)); + } + } + lines +} + +/// The attribute modifiers a mob effect adds per amplifier level +/// (`MobEffects`): attribute, amount, operation id. +fn effect_modifier(effect: &str) -> Option<(&'static str, f64, usize)> { + Some(match effect { + "speed" => ("movement_speed", 0.2, 2), + "slowness" => ("movement_speed", -0.15, 2), + "strength" => ("attack_damage", 3.0, 0), + "weakness" => ("attack_damage", -4.0, 0), + "jump_boost" => ("safe_fall_distance", 1.0, 0), + "luck" => ("luck", 1.0, 0), + "invisibility" => ("waypoint_transmit_range", -1.0, 2), + _ => return None, + }) +} + +fn is_potion_item(item: &str) -> bool { + item.ends_with("potion") || item == "minecraft:tipped_arrow" +} + +/// The name line of `stack`, as the item's translation or, for potions and +/// smithing templates, its name component gives it. +pub fn name_line(stack: &ItemStack, translate: &dyn Fn(&str) -> Option) -> String { + let path = stack.item.trim_start_matches("minecraft:"); + if let Some(name) = stack.custom_name() { + return name.to_owned(); + } + let key = if is_potion_item(&stack.item) { + Some(crate::brewing::potion_name_key(&stack.item, stack.potion())) + } else if let Some(pattern) = path.strip_suffix("_armor_trim_smithing_template") { + Some(format!("trim_pattern.minecraft.{pattern}")) + } else if path == "netherite_upgrade_smithing_template" { + Some("upgrade.minecraft.netherite_upgrade".to_owned()) + } else if path.ends_with("_banner_pattern") { + // The item name component of the pattern items that have one. + Some(format!("item.minecraft.{path}.new")) + } else { + None + }; + key.and_then(|k| translate(&k)) + .or_else(|| translate(&format!("item.minecraft.{path}"))) + .or_else(|| translate(&format!("block.minecraft.{path}"))) + .unwrap_or_else(|| path.replace('_', " ")) +} + +/// The lines of `stack` below its name that its components give, in +/// `ItemStack.addDetailsToTooltip` order. +pub fn detail_lines( + stack: &ItemStack, + info: Option<&ItemInfo>, + translate: &dyn Fn(&str) -> Option, +) -> Vec { + let text = |key: &str| translate(key).unwrap_or_else(|| key.to_owned()); + let path = stack.item.trim_start_matches("minecraft:"); + let mut lines = Vec::new(); + // SmithingTemplateItem.appendHoverText. + if path.ends_with("_smithing_template") { + let kind = if path == "netherite_upgrade_smithing_template" { + "netherite_upgrade" + } else { + "armor_trim" + }; + lines.push(text("item.minecraft.smithing_template")); + lines.push(String::new()); + lines.push(text("item.minecraft.smithing_template.applies_to")); + lines.push(format!( + " {}", + text(&format!( + "item.minecraft.smithing_template.{kind}.applies_to" + )) + )); + lines.push(text("item.minecraft.smithing_template.ingredients")); + lines.push(format!( + " {}", + text(&format!( + "item.minecraft.smithing_template.{kind}.ingredients" + )) + )); + } + // BeehiveBlock: the block state components of the item. + if path == "beehive" { + lines.push( + text("container.beehive.bees") + .replacen("%s", "0", 1) + .replacen("%s", "3", 1), + ); + lines.push( + text("container.beehive.honey") + .replacen("%s", "0", 1) + .replacen("%s", "5", 1), + ); + } + let data = stack.data(); + // FireworkRocketItem: the flight duration (an unset component is 1). + if path == "firework_rocket" { + let flight = data.and_then(|d| d.fireworks.as_ref()).map_or(1, |f| f.0); + lines.push(format!( + "{} {flight}", + text("item.minecraft.firework_rocket.flight") + )); + } + // PotDecorations.addToTooltip. + if let Some(sherds) = data + .and_then(|d| d.pot_decorations.as_ref()) + .filter(|s| s.iter().any(Option::is_some)) + { + lines.push(String::new()); + for sherd in sherds.iter() { + let item = sherd.as_ref().map_or("minecraft:brick", |s| &*s.item); + lines.push(name_line(&ItemStack::new(item, 1), translate)); + } + } + // PotionContents.addToTooltip: the effects, then their attribute modifiers. + if is_potion_item(&stack.item) { + let scale = match path { + "lingering_potion" => 0.25, + "tipped_arrow" => 0.125, + _ => 1.0, + }; + lines.extend( + crate::brewing::tooltip(stack.potion(), scale, translate) + .into_iter() + .map(|l| l.0), + ); + let applied: Vec = stack + .potion() + .and_then(crate::brewing::potion) + .into_iter() + .flat_map(|p| p.effects.iter()) + .filter_map(|(effect, _, amplifier)| { + let (attribute, amount, operation) = effect_modifier(effect)?; + modifier_line( + translate, + attribute, + amount * (*amplifier + 1) as f64, + operation, + ) + }) + .collect(); + if !applied.is_empty() { + lines.push(String::new()); + lines.push(text("potion.whenDrank")); + lines.extend(applied); + } + } + // JukeboxPlayable.addToTooltip: the song's description. + if path.starts_with("music_disc_") { + lines.push(text(&format!("item.minecraft.{path}.desc"))); + } + // Trim.addToTooltip. + if let Some((material, pattern)) = data.and_then(|d| d.trim.as_ref()) { + let short = |s: &str| s.trim_start_matches("minecraft:").to_owned(); + lines.push(text("item.minecraft.smithing_template.upgrade")); + lines.push(format!( + " {}", + text(&format!("trim_pattern.minecraft.{}", short(pattern))) + )); + lines.push(format!( + " {}", + text(&format!("trim_material.minecraft.{}", short(material))) + )); + } + // DyedItemColor.addToTooltip (without advanced tooltips). + if data.is_some_and(|d| d.dyed_color.is_some()) { + lines.push(text("item.dyed")); + } + if let Some(info) = info { + lines.extend(attribute_lines(info, translate)); + } + lines +} + +/// Every line of `stack`'s tooltip, name first. +pub fn lines( + stack: &ItemStack, + info: Option<&ItemInfo>, + translate: &dyn Fn(&str) -> Option, +) -> Vec { + let mut lines = vec![name_line(stack, translate)]; + lines.extend(detail_lines(stack, info, translate)); + lines +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn amounts_use_two_decimals_at_most() { + assert_eq!(format_amount(8.0), "8"); + assert_eq!(format_amount(3.2000000953674316), "3.2"); + assert_eq!(format_amount(2.8200000524520874), "2.82"); + assert_eq!(format_amount(0.125), "0.12"); + assert_eq!(format_amount(0.375), "0.38"); + } + + #[test] + fn modifier_lines_follow_the_sign_and_operation() { + let lang = |k: &str| { + Some( + match k { + "attribute.modifier.plus.2" => "+%s%% %s", + "attribute.modifier.take.2" => "-%s%% %s", + "attribute.name.movement_speed" => "Speed", + _ => return None, + } + .to_owned(), + ) + }; + assert_eq!( + modifier_line(&lang, "movement_speed", 0.2, 2).as_deref(), + Some("+20% Speed") + ); + assert_eq!( + modifier_line(&lang, "movement_speed", -0.6, 2).as_deref(), + Some("-60% Speed") + ); + assert_eq!(modifier_line(&lang, "movement_speed", 0.0, 2), None); + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 4e6d6bf05..6300abbbf 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -54,6 +54,7 @@ pub mod hunger; pub mod input; pub mod item_data; pub mod item_render; +pub mod item_tooltip; pub mod items; pub mod java_text; pub mod key_names; diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 407502f55..036269136 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -157,6 +157,10 @@ pub struct Entry { pub group: Option, pub display: Display, pub result: ItemStack, + /// Every stack its display can show as the result when that is more than + /// `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, } impl Entry { /// The ingredients that must be matched to craft it, in order. @@ -306,6 +310,7 @@ 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() { entries.push(Entry { id: format!("minecraft:{name}"), @@ -314,6 +319,7 @@ impl Book { group: group(&grp), display, result, + variants: variants.clone(), }); } continue; @@ -326,6 +332,7 @@ impl Book { group: group(&grp), display, result: result.create(), + variants: Vec::new(), }); } for c in &recipes.cooking { @@ -345,6 +352,7 @@ impl Book { group: group(&c.group), display: Display::Furnace(c.ingredient.clone()), result: c.result.clone(), + variants: Vec::new(), }); } let order = items @@ -421,7 +429,17 @@ impl Book { tooltip: &dyn Fn(&ItemStack) -> Vec, ) -> bool { let query = query.to_lowercase(); - let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect(); + 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() + } + }) + .collect(); let in_lines = |text: &str| { results .iter() @@ -747,6 +765,7 @@ mod tests { group: group.map(str::to_owned), display: Display::Shapeless(vec![ing(&["minecraft:stick"])]), result: ItemStack::new("minecraft:stick", 1), + variants: Vec::new(), }; let book = Book { entries: vec![ @@ -793,6 +812,7 @@ mod tests { group: None, display: Display::Shapeless(Vec::new()), result: ItemStack::new("minecraft:stick", 4), + variants: Vec::new(), }], placements: HashMap::new(), order: HashMap::new(), diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java index 98e1add63..3d0ffc7fc 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaRecipeBookViewOracle.java @@ -6,7 +6,16 @@ import java.nio.charset.StandardCharsets; import java.nio.file.*; import java.util.*; import java.util.function.Predicate; +import java.util.stream.Stream; +import net.minecraft.ChatFormatting; import net.minecraft.client.ClientRecipeBook; +import net.minecraft.client.searchtree.FullTextSearchTree; +import net.minecraft.client.searchtree.SearchTree; +import net.minecraft.core.Registry; +import net.minecraft.util.context.ContextMap; +import net.minecraft.world.item.Item; +import net.minecraft.world.item.TooltipFlag; +import net.minecraft.world.item.crafting.display.SlotDisplayContext; import net.minecraft.client.gui.screens.recipebook.RecipeCollection; import net.minecraft.client.gui.screens.recipebook.SearchRecipeBookCategory; import net.minecraft.core.registries.Registries; @@ -34,7 +43,10 @@ import net.minecraft.world.item.crafting.display.ShapelessCraftingRecipeDisplay; * every tab of the book RecipeBookTabButton.updateVisibility and * RecipeBookComponent.updateCollections (without a search) decide the * buttons. Printed per tab: visibility, the page count, and each button's - * displays with their selected and craftable flags. + * displays with their selected and craftable flags. A case may carry a search + * text: the collections are searched as SessionSearchTrees.updateRecipes builds + * the tree (a FullTextSearchTree over the tooltip lines and ids of the results) + * and RecipeBookComponent.updateCollections applies it. */ public final class VanillaRecipeBookViewOracle { record Tab(ExtendedRecipeBookCategory category, String name) {} @@ -109,12 +121,38 @@ public final class VanillaRecipeBookViewOracle { for (RecipeCollection c : book.getCollection(tab.category())) c.selectRecipes(contents, canDisplay); } boolean filtering = f.get("filtering").getAsBoolean(); + String query = f.has("search") ? f.get("search").getAsString() : ""; + Set found = null; + if (!query.isEmpty()) { + // SessionSearchTrees.updateRecipes. + List all = book.getCollections(); + Registry itemRegistry = ParityData.access.lookupOrThrow(net.minecraft.core.registries.Registries.ITEM); + Item.TooltipContext tooltipContext = Item.TooltipContext.of(ParityData.access); + ContextMap recipeContext = SlotDisplayContext.fromLevel(ParityData.level); + SearchTree tree = new FullTextSearchTree<>( + collection -> collection.getRecipes().stream().flatMap(e -> e.resultItems(recipeContext).stream()) + .flatMap(item -> item.getTooltipLines(tooltipContext, null, TooltipFlag.Default.NORMAL).stream()) + .map(l -> ChatFormatting.stripFormatting(l.getString()).trim()).filter(x -> !x.isEmpty()), + collection -> collection.getRecipes().stream().flatMap(e -> e.resultItems(recipeContext).stream()) + .map(stack -> itemRegistry.getKey(stack.getItem())), + all); + if (System.getenv("DUMP_TOOLTIPS") != null) { + for (RecipeCollection c : all) for (var e : c.getRecipes()) for (var stack : e.resultItems(recipeContext)) { + System.err.println("TT " + e.id().index() + " " + itemRegistry.getKey(stack.getItem()) + " " + stack.getTooltipLines(tooltipContext, null, TooltipFlag.Default.NORMAL).stream().map(l -> l.getString()).toList()); + } + } + found = new java.util.LinkedHashSet<>(tree.search(query.toLowerCase(Locale.ROOT))); + } StringBuilder result = new StringBuilder(); for (Tab tab : tabs) { List collections = new ArrayList<>(book.getCollection(tab.category())); boolean visible = tab.category() instanceof SearchRecipeBookCategory || collections.stream().anyMatch(RecipeCollection::hasAnySelected); result.append(tab.name()).append(visible ? " shown" : " hidden"); collections.removeIf(c -> !c.hasAnySelected()); + if (found != null) { + Set set = found; + collections.removeIf(c -> !set.contains(c)); + } if (filtering) collections.removeIf(c -> !c.hasCraftable()); result.append(" pages=").append((int) Math.ceil(collections.size() / 20.0)); for (RecipeCollection c : collections) { diff --git a/tools/test_recipe_book_view_parity.py b/tools/test_recipe_book_view_parity.py index eeca5c4fb..a38d04eca 100644 --- a/tools/test_recipe_book_view_parity.py +++ b/tools/test_recipe_book_view_parity.py @@ -11,7 +11,10 @@ RecipeCollection.selectRecipes and the tab and page logic of RecipeBookComponent; examples/recipe_book_view_fixture runs horizon_client::recipe_book::ClientBook. Per tab: visibility, pages and every button's displays with their selected and craftable flags, in order -(the client's HashMap of display ids decides it). +(the client's HashMap of display ids decides it). Most cases also carry a +search text (names, parts of them, ids with a colon, odd ones); the oracle +searches the collections with the FullTextSearchTree of SessionSearchTrees +over the tooltip lines and ids of every result a display can show. """ import argparse import json @@ -31,6 +34,51 @@ except ImportError: import test_rust_parity as base +def queries(rng, items): + """Search texts: a name or part of one, with case and spacing changes, ids with a colon, and odd ones.""" + lang = json.loads((lib.RESOURCES / 'assets/minecraft/lang/en_us.json').read_text()) + names = [] + for i in items: + path = i.split(':')[-1] + names.append((path, lang.get('item.minecraft.' + path) or lang.get('block.minecraft.' + path) or path)) + + def make(): + path, name = rng.choice(names) + a = rng.randrange(len(name)) + part = name[a:a + rng.randint(1, 8)] + kind = rng.randrange(14) + if kind == 0: + return name + if kind == 1: + return name.upper() + if kind == 2: + return part + if kind == 3: + return part.lower() + if kind == 4: + return 'minecraft:' + path[a % max(1, len(path)):][:rng.randint(0, 6)] + if kind == 5: + return 'minecraft:' + part + if kind == 6: + return ' ' + rng.choice(['minecraft', 'mine', 'craft', 'x', '']) + ' : ' + path.split('_')[0] + ' ' + if kind == 7: + return ':' + part + if kind == 8: + return rng.choice(['minecraft:', ':', 'a:b:c', 'minecraft:oak', 'minecraft:stone', 'oak', 'plank', 'ingot', 'Block of', ' ', + 'İ', 'ΣΑΣ', 'ß', 'tool', 'enchant', 'dye']) + if kind == 9: + return path + if kind == 10: + return path.replace('_', ' ') + if kind == 11: + return 'minecraft:' + path + if kind == 12: + return rng.choice(['Wooden', 'Iron', 'Golden', 'Diamond', 'Stone', 'Netherite', 'Copper', 'Smooth', 'Cut', 'Chiseled']) \ + + rng.choice(['', ' ', ' Pickaxe', ' Slab', ' Stairs']) + return '' + return make + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--seed', type=int, default=17) @@ -54,6 +102,7 @@ def main(): rng = gen.rng ids = sorted('minecraft:' + n for n in recipes.recipes) cases = [] + query = queries(rng, items) for n in range(args.cases): kind = ['crafting', 'crafting', 'furnace', 'blast_furnace', 'smoker'][n % 5] # Few to most recipes known: the table grows and display ids collide. @@ -72,7 +121,7 @@ def main(): inventory = [s for _, s in case['inventory']] slots = [s for _, s in case['grid']] cases.append({'type': kind, 'grid': 2 if menu == 'inventory' else 3, 'history': history, 'inventory': inventory, - 'slots': slots, 'filtering': rng.random() < 0.5}) + 'slots': slots, 'filtering': rng.random() < 0.5, 'search': query() if rng.random() < 0.7 else ''}) (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.VanillaRecipeBookViewOracle', str(work / 'cases.jsonl'), str(work / 'native.txt')], capture_output=True, text=True) 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 2/4] 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() From 35f0b5ec303b41c49d6dd0615a2b6664ca516265 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 06:21:56 +0200 Subject: [PATCH 3/4] Read creative toolbars (hotbar.nbt) through the HOTBAR data fixers, compared with HotbarManager EmptyItemInHotbarFix was missing from the data fixers. horizon_client::hotbar loads the nine rows of nine stacks of an older file as vanilla does: lenient counts, unregistered items empty, stray entries dropped from their row, a row that is no list ending the reading, short rows lost and long ones cut. Co-Authored-By: Claude Sonnet 5.5 --- .../horizon-client/examples/hotbar_fixture.rs | 42 +++++ crates/horizon-client/src/hotbar.rs | 121 +++++++++++++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-world/src/datafix/fixes_a.rs | 16 ++ crates/horizon-world/src/datafix/mod.rs | 7 + .../parity/VanillaHotbarOracle.java | 50 ++++++ tools/test_hotbar_parity.py | 163 ++++++++++++++++++ 7 files changed, 400 insertions(+) create mode 100644 crates/horizon-client/examples/hotbar_fixture.rs create mode 100644 crates/horizon-client/src/hotbar.rs create mode 100644 mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java create mode 100644 tools/test_hotbar_parity.py diff --git a/crates/horizon-client/examples/hotbar_fixture.rs b/crates/horizon-client/examples/hotbar_fixture.rs new file mode 100644 index 000000000..beac564ec --- /dev/null +++ b/crates/horizon-client/examples/hotbar_fixture.rs @@ -0,0 +1,42 @@ +//! Creative toolbars read through the data fixers, for +//! tools/test_hotbar_parity.py: reads one JSON case per line (the SNBT of a +//! `hotbar.nbt`, or null for a missing file) and prints the stacks of the nine +//! rows after `horizon_client::hotbar::from_tag`. +//! +//! usage: hotbar_fixture RESOURCES CASES OUTPUT +use horizon_client::{hotbar, item_data::canon_stack, items::Items}; +use horizon_world::nbt::{Tag, parse_snbt}; +use serde_json::Value; +use std::path::Path; +use std::{fmt::Write as _, fs}; + +fn main() -> horizon_client::Result<()> { + let args: Vec = std::env::args().collect(); + let usage = "usage: hotbar_fixture RESOURCES CASES OUTPUT"; + let items = Items::catalog(Path::new(args.first().and(args.get(1)).ok_or(usage)?))?; + let known = |id: &str| items.get(id).is_some(); + let cases = fs::read_to_string(args.get(2).ok_or(usage)?)?; + let mut out = String::new(); + for line in cases.lines() { + let case: Value = serde_json::from_str(line)?; + let rows = match case["snbt"].as_str() { + Some(text) => match parse_snbt(text) { + Ok((tag @ Tag::Compound(_), _)) => hotbar::from_tag(tag, &known), + _ => return Err("case snbt".into()), + }, + None => (0..hotbar::GROUPS) + .map(|_| vec![None; hotbar::SIZE]) + .collect(), + }; + for (i, row) in rows.iter().enumerate() { + let _ = write!(out, "{i}:"); + for stack in row { + let _ = write!(out, " {}", canon_stack(stack.as_ref())); + } + out.push_str(" | "); + } + out.push('\n'); + } + fs::write(args.get(3).ok_or(usage)?, out)?; + Ok(()) +} diff --git a/crates/horizon-client/src/hotbar.rs b/crates/horizon-client/src/hotbar.rs new file mode 100644 index 000000000..a60f28287 --- /dev/null +++ b/crates/horizon-client/src/hotbar.rs @@ -0,0 +1,121 @@ +//! The creative mode toolbars of `hotbar.nbt` (`HotbarManager`, +//! `Hotbar`): nine saved rows of nine stacks, read through the `HOTBAR` +//! data fixers when the file is from an older version. +use crate::{items::ItemStack, save}; +use horizon_world::nbt::{JavaString, Tag}; +use std::path::Path; + +/// `HotbarManager.NUM_HOTBAR_GROUPS`. +pub const GROUPS: usize = 9; +/// `Inventory.getSelectionSize`: the stacks of one saved row. +pub const SIZE: usize = 9; + +/// One saved toolbar row. +pub type Hotbar = Vec>; + +fn empty() -> Hotbar { + vec![None; SIZE] +} + +/// `Hotbar.CODEC` and `Hotbar.load` on the row's tag: a row of fewer than nine +/// entries is lost, a longer one is cut (`Util.fixedSize` returns the first +/// nine as a partial result), an entry that is not a stack is empty. +fn row(tag: Option<&Tag>, known: &dyn Fn(&str) -> bool) -> Hotbar { + let Some(Tag::List(items)) = tag else { + return empty(); + }; + if items.len() < SIZE { + return empty(); + } + items.iter().take(SIZE).map(|t| stack(t, known)).collect() +} + +/// `ItemStack.OPTIONAL_CODEC` of a saved stack: the count is lenient (1 +/// unless it is a number from 1 to 99), an item that is not registered is an +/// error. +fn stack(tag: &Tag, known: &dyn Fn(&str) -> bool) -> Option { + let stack = save::item_from_nbt(tag)?; + if !known(&stack.item) { + return None; + } + let count = match tag.get("count") { + Some(Tag::Byte(n)) => i32::from(*n), + Some(Tag::Short(n)) => i32::from(*n), + Some(Tag::Int(n)) => *n, + _ => 1, + }; + Some(ItemStack { + count: if (1..=99).contains(&count) { + count as u32 + } else { + 1 + }, + ..stack + }) +} + +/// `HotbarManager.load` on the file's tag. +pub fn from_tag(mut tag: Tag, known: &dyn Fn(&str) -> bool) -> Vec { + let version = match tag.get("DataVersion") { + Some(Tag::Int(v)) => *v, + _ => 1343, + }; + // Until the last fixer that rewrites item stacks (`UnfilledBuriedTreasureMapFix`, + // 5016) the fixers read each row as a list of stacks: an entry that is + // none is dropped from its row (a bare item id is a stack from 3818.5 on) + // and a row that is no list ends the reading. After that fixer nothing + // reads the rows and bare ids are no stacks. + const LAST_STACK_FIXER: i32 = 5016; + if version < horizon_world::DATA_VERSION + && let Tag::Compound(rows) = &mut tag + { + if version < LAST_STACK_FIXER { + // A row that is no list stops the traversal there: it and the + // rows after it (in key order) are lost. + let broken = (0..GROUPS).find(|i| { + rows.get(&JavaString::from(i.to_string().as_str())) + .is_some_and(|r| { + !matches!( + r, + Tag::List(_) | Tag::ByteArray(_) | Tag::IntArray(_) | Tag::LongArray(_) + ) + }) + }); + if let Some(broken) = broken { + for i in broken..GROUPS { + rows.remove(&JavaString::from(i.to_string().as_str())); + } + } + // Entries that are no stacks are dropped from their row. + for row in rows.values_mut() { + if let Tag::List(items) = row { + items.retain(|i| { + matches!(i, Tag::Compound(_)) + || (version > 3818 && matches!(i, Tag::String(_))) + }); + } + } + } else { + for row in rows.values_mut() { + if let Tag::List(items) = row { + for item in items.iter_mut().filter(|i| matches!(i, Tag::String(_))) { + *item = Tag::Compound(Default::default()); + } + } + } + } + } + horizon_world::datafix::update_hotbar(&mut tag); + (0..GROUPS) + .map(|i| row(tag.get(&i.to_string()), known)) + .collect() +} + +/// `HotbarManager.load` of the `hotbar.nbt` at `path`: every row empty when +/// the file is missing or unreadable. +pub fn load(path: &Path, known: &dyn Fn(&str) -> bool) -> Vec { + match save::read_dat(path) { + Some(tag @ Tag::Compound(_)) => from_tag(tag, known), + _ => (0..GROUPS).map(|_| empty()).collect(), + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 6300abbbf..03fe05d3a 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -47,6 +47,7 @@ pub mod gamerules; pub mod gfx; pub mod gossip; pub mod health; +pub mod hotbar; pub mod hud; pub mod hud_layout; pub mod hud_overlays; diff --git a/crates/horizon-world/src/datafix/fixes_a.rs b/crates/horizon-world/src/datafix/fixes_a.rs index 3d89ec990..e47cf15e4 100644 --- a/crates/horizon-world/src/datafix/fixes_a.rs +++ b/crates/horizon-world/src/datafix/fixes_a.rs @@ -56,6 +56,7 @@ pub(super) fn register(out: &mut Vec<(Key, FixFn)>) { }) })); out.push((key(3818, 0), beehive_fields)); + out.push((key(3818, 0), empty_item_in_hotbar)); out.push((key(3818, 1), banner_patterns)); out.push((key(3818, 2), tipped_arrow_potion)); out.push((key(3818, 4), particle_unflattening)); @@ -714,6 +715,21 @@ fn beehive_fields(cx: &mut Cx) { }); } +/// `EmptyItemInHotbarFix`: a saved toolbar's air or zero-count stacks become +/// the empty compound. +fn empty_item_in_hotbar(cx: &mut Cx) { + if !matches!(cx.root, Ty::Hotbar) { + return; + } + cx.each(Ty::ItemStack, |stack| { + let air = as_str(stack.get("id")).is_none_or(|id| id == "minecraft:air"); + let empty = as_int(stack.get("Count"), 0) <= 0; + if air || empty { + *stack = empty_map(); + } + }); +} + const PATTERN_IDS: [(&str, &str); 41] = [ ("b", "minecraft:base"), ("bl", "minecraft:square_bottom_left"), diff --git a/crates/horizon-world/src/datafix/mod.rs b/crates/horizon-world/src/datafix/mod.rs index 014c84614..eb5740fa7 100644 --- a/crates/horizon-world/src/datafix/mod.rs +++ b/crates/horizon-world/src/datafix/mod.rs @@ -334,6 +334,13 @@ pub fn update_player_to(tag: &mut Tag, to: i32) { dynamic::set(tag, "DataVersion", Tag::Int(to)); } +/// `HotbarManager.load`: a creative toolbar file (`hotbar.nbt`, its DataVersion +/// 1343 when missing) brought to the current version. +pub fn update_hotbar(tag: &mut Tag) { + let version = dynamic::as_int(tag.get("DataVersion"), 1343); + update(Ty::Hotbar, tag, version, CURRENT); +} + /// The saved data type of a file below a `data` folder (`namespace/path.dat`). pub fn saved_data_type(relative: &str) -> Option { let name = relative.strip_suffix(".dat").unwrap_or(relative); diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java new file mode 100644 index 000000000..99233ab77 --- /dev/null +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHotbarOracle.java @@ -0,0 +1,50 @@ +package dev.horizonlab.parity; + +import com.google.gson.*; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.nio.file.*; +import java.util.*; +import net.minecraft.client.HotbarManager; +import net.minecraft.nbt.CompoundTag; +import net.minecraft.nbt.NbtIo; +import net.minecraft.nbt.TagParser; +import net.minecraft.util.datafix.DataFixers; +import net.minecraft.world.item.ItemStack; + +/** + * Original oracle for creative toolbars read from a hotbar.nbt of any version: + * each case's SNBT is written as the file and the real HotbarManager (with the + * game's DataFixer, so DataFixTypes.HOTBAR and its item stack fixers) loads it; + * each of the nine rows is then loaded with Hotbar.load and printed. + */ +public final class VanillaHotbarOracle { + public static void main(String[] args) throws Exception { + ParityData.init(); + Path dir = Files.createTempDirectory("hotbar"); + 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 { + Files.deleteIfExists(dir.resolve("hotbar.nbt")); + if (!f.get("snbt").isJsonNull()) { + CompoundTag tag = TagParser.parseCompoundFully(f.get("snbt").getAsString()); + NbtIo.write(tag, dir.resolve("hotbar.nbt")); + } + HotbarManager manager = new HotbarManager(dir, DataFixers.getDataFixer()); + StringBuilder result = new StringBuilder(); + for (int i = 0; i < HotbarManager.NUM_HOTBAR_GROUPS; i++) { + result.append(i).append(':'); + for (ItemStack stack : manager.get(i).load(ParityData.lookup)) result.append(' ').append(ParityData.canon(stack)); + 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_hotbar_parity.py b/tools/test_hotbar_parity.py new file mode 100644 index 000000000..336bda274 --- /dev/null +++ b/tools/test_hotbar_parity.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Compare creative toolbars read from an older hotbar.nbt with the vanilla client's. + +Each case is the SNBT of a hotbar.nbt of some DataVersion (the version tag +missing means 1343): nine rows of nine stacks in the item format of that era +(damage values of 1.12, `tag` compounds of 1.13 to 1.20.4, components of +1.20.5 on), with empty stacks (air, count zero or negative, no +id), rows of the wrong size or type and garbage. The Java oracle +(VanillaHotbarOracle) writes the file and loads it with the client's real +HotbarManager and DataFixers (DataFixTypes.HOTBAR, so EmptyItemInHotbarFix +and every item stack fixer), then Hotbar.load on each row; +examples/hotbar_fixture runs horizon_client::hotbar on the same tag. The nine +rows' stacks are compared. +""" +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 + +VERSIONS = [None, 1343, 1344, 1451, 1519, 1631, 1976, 2200, 2504, 2586, 2730, 2975, 3105, 3218, 3337, 3465, 3578, 3698, + 3700, 3817, 3818, 3820, 3824, 3825, 3900, 4059, 4082, 4189, 4325, 4540, 4650, 4780, 4900, 5023] + +LEGACY = [ + '{id:"minecraft:planks",Damage:2s,Count:3b}', '{id:"minecraft:wool",Damage:14s,Count:64b}', + '{id:"minecraft:stone",Damage:3s,Count:1b}', '{id:"minecraft:log",Damage:1s,Count:1b}', + '{id:"minecraft:log2",Damage:1s,Count:7b}', '{id:"minecraft:potion",Damage:8193s,Count:1b}', + '{id:"minecraft:diamond_pickaxe",Damage:12s,Count:1b,tag:{ench:[{id:32s,lvl:3s}],display:{Name:"Pick"}}}', + '{id:"minecraft:golden_apple",Damage:1s,Count:2b}', '{id:"minecraft:dye",Damage:4s,Count:5b}', + '{id:"minecraft:stained_glass_pane",Damage:5s,Count:9b}', '{id:"minecraft:skull",Damage:3s,Count:1b,tag:{SkullOwner:"Notch"}}', + '{id:"minecraft:banner",Damage:1s,Count:1b,tag:{BlockEntityTag:{Base:1,Patterns:[{Pattern:"cre",Color:15}]}}}', + '{id:"minecraft:tallgrass",Damage:1s,Count:1b}', '{id:"minecraft:stick",Count:1b}', '{id:"minecraft:iron_sword",Count:1b,Damage:40s}', + '{id:"minecraft:bed",Damage:14s,Count:1b}', '{id:"minecraft:monster_egg",Damage:2s,Count:3b}', + '{id:"minecraft:written_book",Count:1b,tag:{title:"t",author:"a",pages:["{\\"text\\":\\"p\\"}"]}}', +] +CLASSIC = [ + '{id:"minecraft:diamond_sword",Count:1b,tag:{Damage:5,Enchantments:[{id:"minecraft:sharpness",lvl:3s}],display:{Name:\'{"text":"Cool"}\'}}}', + '{id:"minecraft:potion",Count:1b,tag:{Potion:"minecraft:strong_healing"}}', '{id:"minecraft:stone",Count:64b}', + '{id:"minecraft:firework_rocket",Count:3b,tag:{Fireworks:{Flight:2b}}}', '{id:"minecraft:cobblestone",Count:12b}', + '{id:"minecraft:player_head",Count:1b,tag:{SkullOwner:"Notch"}}', '{id:"minecraft:dirt",Count:2b}', + '{id:"minecraft:white_banner",Count:1b,tag:{BlockEntityTag:{Patterns:[{Pattern:"cre",Color:15}]}}}', + '{id:"minecraft:enchanted_book",Count:1b,tag:{StoredEnchantments:[{id:"minecraft:mending",lvl:1s}]}}', + '{id:"minecraft:tipped_arrow",Count:8b,tag:{Potion:"minecraft:weakness"}}', '{id:"minecraft:string",Count:3b}', + '{id:"minecraft:iron_axe",Count:1b,tag:{Damage:3,RepairCost:7,Unbreakable:1b}}', + '{id:"minecraft:filled_map",Count:1b,tag:{map:12}}', '{id:"minecraft:leather_chestplate",Count:1b,tag:{display:{color:255}}}', + '{id:"minecraft:shield",Count:1b,tag:{BlockEntityTag:{Base:3}}}', '{id:"minecraft:bundle",Count:1b,tag:{Items:[{id:"minecraft:stone",Count:2b}]}}', + '{id:"minecraft:diamond_sword",Count:1b,tag:{AttributeModifiers:[{AttributeName:"generic.attack_damage",Name:"x",Amount:2.5d,Operation:0,UUID:[I;1,2,3,4],Slot:"mainhand"}]}}', +] +COMPONENTS = [ + '{id:"minecraft:diamond_sword",count:1,components:{"minecraft:damage":5}}', '{id:"minecraft:stone",count:64}', + '{id:"minecraft:potion",count:1,components:{"minecraft:potion_contents":{potion:"minecraft:strong_healing"}}}', + '{id:"minecraft:firework_rocket",count:3,components:{"minecraft:fireworks":{flight_duration:2b}}}', + '{id:"minecraft:white_banner",count:1}', '{id:"minecraft:iron_axe",count:1,components:{"minecraft:repair_cost":7}}', + '{id:"minecraft:grass_block",count:2}', '{id:"minecraft:cobblestone",count:12}', '{id:"minecraft:stone"}', +] +JUNK = ['{}', '{id:"minecraft:air",Count:1b}', '{id:"minecraft:stone",Count:0b}', '{id:"minecraft:stone",Count:-3b}', + '{Count:5b}', '{id:"minecraft:stone"}', '{id:"minecraft:air",count:3}', '{id:"minecraft:stone",count:0}', + '{id:"minecraft:stone",count:200}', '{id:"minecraft:stone",Count:100b}', '{id:"minecraft:nonexistent",Count:1b}', + '{id:5s,Count:1b}', '{id:"minecraft:stone",Count:"x"}'] +# Entries that are no stacks, and rows that are no lists: the fixers drop the entry from its row (so a row of ten +# with one is a full row, and a row of nine a short one) and a row that is no list ends the reading. Several of +# them in one file interact in ways this does not follow, so each gets its own file. +ODD = ['"stone"', '5', '[]', '1b', '{}', '[I;1,2]'] + + +def pool(version): + v = version or 1343 + if v < 1451: + return LEGACY + if v < 3819: + return CLASSIC + return COMPONENTS + + +def stack(rng, version): + r = rng.random() + if r < 0.75: + return rng.choice(pool(version)) + if r < 0.92: + return rng.choice(JUNK) + return rng.choice(pool(rng.choice(VERSIONS))) + + +def case(rng): + version = rng.choice(VERSIONS) + rows = [] + elements = {} + for i in range(9): + r = rng.random() + if r < 0.04: + continue + if r < 0.07: + rows.append(f'"{i}":5') + continue + size = 9 if r < 0.93 else rng.choice([0, 8, 10]) + stacks = [stack(rng, version) for _ in range(size)] + elements[i] = stacks + rows.append(f'"{i}":[' + ','.join(stacks) + ']') + head = '' if version is None else f'DataVersion:{version},' + return {'snbt': '{' + head + ','.join(rows) + '}', 'version': version, 'elements': elements} + + +def odd_cases(): + cases = [] + for version in [None, 1343, 1631, 3337, 3700, 3818, 3819, 3824, 4325, 4540, 5015, 5016, 5022, 5023]: + v = version or 1343 + ok = '{id:"minecraft:stone",Count:2b}' if v < 3819 else '{id:"minecraft:stone",count:2}' + head = '' if version is None else f'DataVersion:{version},' + good = '[' + ','.join([ok] * 9) + ']' + for odd in ODD: + for position in (0, 4, 8): + row = [ok] * 9 + row[position] = odd + cases.append({'snbt': '{' + head + f'"0":[{",".join(row)}],"1":{good}' + '}'}) + for row_size in (8, 10): + row = [ok] * row_size + row[3] = odd + cases.append({'snbt': '{' + head + f'"0":[{",".join(row)}],"1":{good}' + '}'}) + # A row that is none: the rows after it. + cases.append({'snbt': '{' + head + ','.join(f'"{i}":{odd if i == 2 else good}' for i in range(9)) + '}'}) + return cases + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--seed', type=int, default=23) + parser.add_argument('--cases', type=int, default=400) + 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('hotbar-parity') + classes = work / 'classes' + classes.mkdir(exist_ok=True) + deps = os.pathsep.join(map(str, [jars['client'], *baking.client_libraries()])) + 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 ('ParityData', 'VanillaHotbarOracle'))], + capture_output=True, text=True) + if done.returncode: + print(done.stderr[-4000:]) + sys.exit('javac failed') + cases = [{'snbt': None}] + odd_cases() + [case(rng) for _ in range(args.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.VanillaHotbarOracle', + 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', 'hotbar_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt') + bad = lib.compare(cases, work / 'native.txt', work / 'rust.txt', lambda c, line: 'hotbar' if not line.startswith('error') else 'oracle error', + describe=lambda c: c['snbt'][:300] if c['snbt'] else 'missing file', limit=args.limit) + raise SystemExit(1 if bad else 0) + + +if __name__ == '__main__': + main() From e70c9fdd691f42a25e67d74af3b8ca0b7a0df4fe Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Tue, 13 Oct 2026 06:22:53 +0200 Subject: [PATCH 4/4] Document the recipe book search, ghost recipe and hotbar harnesses; more old options.txt bodies Co-Authored-By: Claude Sonnet 5.5 --- docs/rust-parity.md | 26 +++++++++++++++++++++++--- tools/test_options_parity.py | 9 +++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/docs/rust-parity.md b/docs/rust-parity.md index 977076575..b2027464e 100644 --- a/docs/rust-parity.md +++ b/docs/rust-parity.md @@ -1426,14 +1426,34 @@ vanilla's own classes, and the game uses that code: paints them. `tools/test_recipe_book_render_parity.py` builds vanilla's widgets for 600 states (`VanillaRecipeBookScreenOracle`) and compares every call. Ingredients cycle in their `HolderSet` order (tags in `TagLoader` order). +- **The book's text search.** `recipe_book_view` also searches: the oracle + builds `SessionSearchTrees`' `FullTextSearchTree` over the tooltip lines and + ids of every result a display can show, and `item_tooltip` writes those + lines (attribute modifiers, smithing template, potion, dyed, pot, rocket and + disc lines; the names of potions, templates and banner patterns). Displays + with several results (map copies, tipped arrows, dyed armour) keep them in + `Entry::variants`. +- **The ghost recipe.** `Book::ghost` is the one place that fills a recipe's + ingredients into the grid or furnace slots (`PlaceRecipeHelper`'s centring, + the first slots for shapeless recipes, every fuel for an empty fuel slot, in + the registry's component-lookup order); `tools/test_ghost_recipe_parity.py` + runs `fillGhostRecipe` against the real menus for all 2,698 recipe and menu + pairs. - **The loom's banner preview.** `item_render::gui::draw_banner_result` draws `GuiBannerResultRenderer`'s flag model and layers in the 20x40 picture in picture, lit with `ITEMS_FLAT`; the block entity render harness compares its quads under the picture-in-picture pose. -Not compared yet: the recipe book's text search, furnaces awarding their -recipes and experience when their output is taken, and the limited crafting -game rule. +Not compared yet: furnaces awarding their recipes and experience when their +output is taken, and the limited crafting game rule. Tooltips in general lack +the lines `item_tooltip` writes for recipe results (the game's hover tooltips +do not show attribute modifiers yet). + +`horizon_client::hotbar` reads the creative toolbars of an older `hotbar.nbt` +through the `HOTBAR` data fixers (`EmptyItemInHotbarFix`, every item stack +fixer): `tools/test_hotbar_parity.py` loads generated files of 34 versions with +the real `HotbarManager`. The toolbar screen (save and load keys) is not wired +to it yet. ## Player list and world border rendering diff --git a/tools/test_options_parity.py b/tools/test_options_parity.py index c1c17bf23..95732663d 100644 --- a/tools/test_options_parity.py +++ b/tools/test_options_parity.py @@ -145,6 +145,15 @@ def make_cases(build): 'graphicsMode:1\nlang:Fr_Ca\nresourcePacks:["a","programer_art"]\nincompatibleResourcePacks:["programer_art"]\n', 'key_key.forward:abc\n', 'key_key.forward:\n', 'key_key.attack:k\n', 'chatOpacity:Infinity\n', 'chatOpacity: 0.5d\n', 'menuBackgroundBlurriness:0.25\n', 'menuBackgroundBlurriness:1.04999\n', + # OptionsForceVBOFix writes a key nothing reads; the lower-casing, key and graphics fixers on odd values. + 'useVbo:false\nao:true\nao:3\n', 'ao:\n', 'graphicsMode:3\nao:2\n', 'graphicsMode:abc\n', 'fancyGraphics:abc\n', + 'fancyGraphics:TRUE\n', 'lang:\u039f\u0394\u03a5\u03a3\u03a3\u0395\u03a5\u03a3\n', 'lang:\u0130_TR\n', 'lang:\u00df_\u00dc\n', + 'key_key.attack:-101\nkey_key.use:-92\nkey_key.forward:2147483647\nkey_key.back:99999\nkey_key.left:-2147483648\n', + 'key_key.hotbar.1:2\nkey_key.hotbar.9:10\nkey_key.swapHands:33\nkey_key.drop:16\nkey_key.debug.modifier:292\n', + 'showNowPlayingToast:maybe\n', 'showNowPlayingToast:true\nmusicToast:never\n', + 'resourcePacks:["programer_art","x"]\nincompatibleResourcePacks:[]\n', 'resourcePacks:[\'programer_art\']\n', + 'menuBackgroundBlurriness:-3\n', 'menuBackgroundBlurriness:1e3\n', 'menuBackgroundBlurriness:\n', 'chatOpacity:0\n', + 'chatOpacity:1\ntextBackgroundOpacity:0.2\n', 'preferredGraphicsBackend:vulkan\n', 'onboardAccessibility:true\n', ] versions = [-1, 0, 100, 504, 505, 815, 816, 1343, 1344, 1445, 1446, 1935, 1936, 2555, 2556, 2557, 2558, 3200, 3201, 3213, 3214, 3318, 3319, 3942, 3943, 4650, 4651, 4660, 4661, 4891, 4892, 5022, 5023, 5024, 9999]