Order the recipe book's buttons as the vanilla client does

ClientRecipeBook keeps the displays it was sent in a HashMap of display
ids, whose iteration order (buckets, then arrival) orders the
collections; the game now keeps such a client book (on the verified
Java HashMap port) synced with the server book, with display ids
numbered as RecipeManager does. A new harness runs the client's
ClientRecipeBook, RecipeCollection selection and the tab and page logic
of RecipeBookComponent over 1,200 cases.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-12 17:14:14 +02:00
parent 621fca874c
commit 8ba728287f
6 changed files with 576 additions and 71 deletions
@@ -0,0 +1,121 @@
//! What the recipe book lists, for tools/test_recipe_book_view_parity.py:
//! reads one JSON case per line (the history of displays the client was
//! sent, the book type and grid, the inventory and menu slots, the filter)
//! and prints every tab's visibility, page count and buttons from
//! `horizon_client::recipe_book::ClientBook`.
//!
//! usage: recipe_book_view_fixture RESOURCES CASES OUTPUT
use horizon_client::{
crafting::Recipes,
item_data::parse_stack,
items::Items,
menu::place::Stacked,
recipe_book::{Book, BookType, ClientBook, Display, RecipeIndex, Tab},
};
use serde_json::Value;
use std::{fmt::Write as _, fs, path::Path};
fn main() -> horizon_client::Result<()> {
let args: Vec<String> = std::env::args().collect();
let usage = "usage: recipe_book_view_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 max = |s: &horizon_client::items::ItemStack| items.get(&s.item).map_or(64, |i| i.max_stack);
let mut out = String::new();
for line in cases.lines() {
let case: Value = serde_json::from_str(line)?;
let mut client = ClientBook::default();
for batch in case["history"].as_array().ok_or("history")? {
let op = batch["op"].as_str().unwrap_or_default();
if op == "replace" {
client.clear();
}
for id in batch["ids"].as_array().into_iter().flatten() {
for d in index.display_ids(id.as_str().unwrap_or_default()) {
if op == "remove" {
client.remove(d);
} else {
client.add(d);
}
}
}
}
let kind = case["type"].as_str().unwrap_or_default();
let grid = case["grid"].as_u64().unwrap_or(3) as usize;
let mut stock = Stacked::default();
for s in case["inventory"].as_array().into_iter().flatten() {
if let Some(stack) = parse_stack(s.as_str().unwrap_or("-"))? {
stock.account_simple(&stack, max(&stack));
}
}
for s in case["slots"].as_array().into_iter().flatten() {
if let Some(stack) = parse_stack(s.as_str().unwrap_or("-"))? {
if kind == "crafting" {
stock.account_simple(&stack, max(&stack));
} else {
stock.account_stack(&stack, max(&stack));
}
}
}
let book_type = match kind {
"crafting" => BookType::Crafting,
"furnace" => BookType::Furnace,
"blast_furnace" => BookType::BlastFurnace,
_ => BookType::Smoker,
};
let filtering = case["filtering"].as_bool().unwrap_or(false);
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) {
(Display::Furnace(_), BookType::Crafting) => false,
(Display::Furnace(_), _) => true,
(_, BookType::Crafting) => book.entries[i].fits(grid, grid),
_ => false,
};
let craftable = |i: usize| selected(i) && book.can_craft(&book.entries[i], &stock);
let visible = tab == Tab::Search
|| collections
.iter()
.any(|c| c.entries.iter().any(|&i| selected(i)));
let shown: Vec<_> = collections
.iter()
.filter(|c| c.entries.iter().any(|&i| selected(i)))
.filter(|c| !filtering || c.entries.iter().any(|&i| craftable(i)))
.collect();
let name = match tab {
Tab::Search => "search".to_owned(),
Tab::Category(c) => c.name().to_owned(),
};
let _ = write!(
out,
"{name} {} pages={}",
if visible { "shown" } else { "hidden" },
shown.len().div_ceil(20)
);
for c in shown {
let parts: Vec<String> = c
.entries
.iter()
.map(|&i| {
format!(
"{}{}{}",
book.entries[i].display_id,
if selected(i) { "s" } else { "" },
if craftable(i) { "c" } else { "" }
)
})
.collect();
let _ = write!(out, " [{}]", parts.join(","));
}
out.push_str(" | ");
}
out.push('\n');
}
fs::write(args.get(3).ok_or(usage)?, out)?;
Ok(())
}
+51 -12
View File
@@ -10,7 +10,7 @@ use horizon_client::{
hud::{HudBatch, Rect, rgba},
items::ItemStack,
menu::place::{PostPlace, Stacked},
recipe_book::{Book, BookType, Collection, Display, Entry, Tab},
recipe_book::{Book, BookType, ClientBook, Collection, Display, Entry, Tab},
ui::EditBox,
};
use std::{
@@ -72,6 +72,11 @@ pub(super) struct RecipeUi {
/// Squeeze animations of new recipes: ticks left per button index and tab.
button_anim: Vec<(usize, f32)>,
tab_anim: Vec<(Tab, f32)>,
/// The client's copy of the known recipes (`ClientRecipeBook`), its
/// order deciding the buttons', and the recipes it was last synced with.
client: ClientBook,
client_known: Option<BTreeSet<String>>,
client_version: u64,
}
impl RecipeUi {
@@ -219,12 +224,44 @@ impl Game<'_> {
});
out
}
fn unlocked_recipes(&self) -> BTreeSet<String> {
self.level.recipe_book.recipes.clone()
/// Sends the client book what changed in the server's: the first time a
/// replacing batch (vanilla's server iterates an identity hash set; this
/// one goes in id order), then each unlock and removal.
fn sync_client_book(&mut self) {
let known = &self.level.recipe_book.recipes;
let index = &self.res.stations.recipe_index;
let ui = &mut self.recipe_ui;
match ui.client_known.as_ref() {
Some(previous) if previous == known => return,
Some(previous) => {
for id in previous.difference(known) {
for d in index.display_ids(id) {
ui.client.remove(d);
}
}
for id in known.difference(previous) {
for d in index.display_ids(id) {
ui.client.add(d);
}
}
}
None => {
ui.client.clear();
for id in known {
for d in index.display_ids(id) {
ui.client.add(d);
}
}
}
}
ui.client_known = Some(known.clone());
ui.client_version += 1;
}
fn ensure_book(&mut self) {
if self.recipe_ui.book.is_none() {
self.recipe_ui.book = Some(Book::build(&self.res.recipes, &self.res.items));
let mut book = Book::build(&self.res.recipes, &self.res.items);
book.set_display_ids(&self.res.stations.recipe_index);
self.recipe_ui.book = Some(book);
}
if self.recipe_ui.search.is_none() {
let mut search = EditBox::new(0.0, 0.0, 81.0, 14.0);
@@ -237,6 +274,7 @@ impl Game<'_> {
/// Rebuilds the tab and button lists when anything they depend on changed.
fn refresh_book_view(&mut self, book_type: BookType) {
self.ensure_book();
self.sync_client_book();
let mut h = std::collections::hash_map::DefaultHasher::new();
for s in self.inventory.iter().flatten() {
(&s.item, s.count, s.damage).hash(&mut h);
@@ -253,7 +291,7 @@ impl Game<'_> {
stack.map(|s| (s.item, s.count)).hash(&mut h);
}
self.craft_size.hash(&mut h);
self.level.recipe_book.recipes.len().hash(&mut h);
self.recipe_ui.client_version.hash(&mut h);
self.book_filtering(book_type).hash(&mut h);
self.recipe_ui.tab.map(|t| format!("{t:?}")).hash(&mut h);
self.recipe_ui
@@ -287,7 +325,6 @@ impl Game<'_> {
let Some(book) = self.recipe_ui.book.take() else {
return;
};
let unlocked = self.unlocked_recipes();
let filtering = self.book_filtering(book_type);
let (gw, gh) = self.book_grid();
let available = self.book_available(book_type);
@@ -301,8 +338,10 @@ impl Game<'_> {
if tab == Tab::Search {
continue;
}
let hit = book
.collections(&unlocked, book_type, tab)
let hit = self
.recipe_ui
.client
.collections(&book, book_type, tab)
.iter()
.flat_map(|c| c.entries.iter())
.any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i]));
@@ -345,7 +384,6 @@ impl Game<'_> {
let Some(book) = ui.book.as_ref() else {
return View::default();
};
let unlocked = self.unlocked_recipes();
let available = self.book_available(book_type);
let (gw, gh) = self.book_grid();
let selected = |e: &Entry| match book_type {
@@ -357,8 +395,9 @@ impl Game<'_> {
let mut tabs = Vec::new();
for tab in book_type.tabs() {
let visible = tab == Tab::Search
|| book
.collections(&unlocked, book_type, tab)
|| ui
.client
.collections(book, book_type, tab)
.iter()
.any(|c| c.entries.iter().any(|&i| selected(&book.entries[i])));
if visible {
@@ -371,7 +410,7 @@ impl Game<'_> {
.as_ref()
.map(|s| s.value.clone())
.unwrap_or_default();
let collections: Vec<Collection> = book.collections(&unlocked, book_type, tab);
let collections: Vec<Collection> = ui.client.collections(book, book_type, tab);
let mut buttons = Vec::new();
for c in collections {
if !c.entries.iter().any(|&i| selected(&book.entries[i])) {
+3 -2
View File
@@ -79,9 +79,10 @@ impl Stacked {
&self.keys
}
/// `canCraft(ingredients, null)` without touching the counts (the recipe
/// book's craftable test; the answer does not depend on the order).
/// book's craftable test; the answer does not depend on the order; no
/// ingredients at all can always be found).
pub fn can_craft(&self, ingredients: &[&Ingredient]) -> bool {
!ingredients.is_empty() && self.clone().try_pick(ingredients, 1, None)
self.clone().try_pick(ingredients, 1, None)
}
/// `getResultUpperBound`.
fn upper_bound(&self, ingredients: &[&Ingredient]) -> i32 {
+168 -57
View File
@@ -89,6 +89,23 @@ pub enum Category {
BlastMisc,
SmokerFood,
}
impl Category {
/// The `RecipeBookCategories` registry path.
pub fn name(self) -> &'static str {
match self {
Self::CraftingBuilding => "crafting_building_blocks",
Self::CraftingRedstone => "crafting_redstone",
Self::CraftingEquipment => "crafting_equipment",
Self::CraftingMisc => "crafting_misc",
Self::FurnaceFood => "furnace_food",
Self::FurnaceBlocks => "furnace_blocks",
Self::FurnaceMisc => "furnace_misc",
Self::BlastBlocks => "blast_furnace_blocks",
Self::BlastMisc => "blast_furnace_misc",
Self::SmokerFood => "smoker_food",
}
}
}
/// A tab button: the search tab or one category.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum Tab {
@@ -133,6 +150,9 @@ pub enum Display {
pub struct Entry {
/// The recipe id, `minecraft:name`.
pub id: String,
/// `RecipeDisplayId`: the display's index among every recipe's displays
/// (`Book::set_display_ids`; -1 until then).
pub display_id: i32,
pub category: Category,
pub group: Option<String>,
pub display: Display,
@@ -289,6 +309,7 @@ impl Book {
for (display, result) in special.book_displays() {
entries.push(Entry {
id: format!("minecraft:{name}"),
display_id: -1,
category: crafting_category(&category),
group: group(&grp),
display,
@@ -300,6 +321,7 @@ impl Book {
};
entries.push(Entry {
id: format!("minecraft:{name}"),
display_id: -1,
category: crafting_category(&category),
group: group(&grp),
display,
@@ -318,6 +340,7 @@ impl Book {
};
entries.push(Entry {
id: format!("minecraft:{}", c.id),
display_id: -1,
category,
group: group(&c.group),
display: Display::Furnace(c.ingredient.clone()),
@@ -340,42 +363,6 @@ impl Book {
order,
}
}
/// The unlocked recipes of one tab as collections (`ClientRecipeBook.rebuildCollections`).
pub fn collections(
&self,
unlocked: &BTreeSet<String>,
book: BookType,
tab: Tab,
) -> Vec<Collection> {
let categories: Vec<Category> = match tab {
Tab::Search => book.search_categories().to_vec(),
Tab::Category(c) => vec![c],
};
let mut out = Vec::new();
for category in categories {
let mut by_group: HashMap<&str, usize> = HashMap::new();
let start = out.len();
for (i, e) in self.entries.iter().enumerate() {
if e.category != category || !unlocked.contains(&e.id) {
continue;
}
match e.group.as_deref().and_then(|g| by_group.get(g).copied()) {
Some(c) => {
let c: usize = c;
let collection: &mut Collection = &mut out[start + c];
collection.entries.push(i);
}
None => {
if let Some(g) = e.group.as_deref() {
by_group.insert(g, out.len() - start);
}
out.push(Collection { entries: vec![i] });
}
}
}
}
out
}
/// Which book a recipe id belongs to.
pub fn book_of(&self, id: &str) -> Option<BookType> {
let e = self.entries.iter().find(|e| e.id == id)?;
@@ -391,12 +378,29 @@ impl Book {
Category::SmokerFood => BookType::Smoker,
})
}
/// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients can
/// all be found in `stock`.
/// `RecipeDisplayEntry.canCraft`: the recipe's placement ingredients
/// (`craftingRequirements`) can all be found in `stock`.
pub fn can_craft(&self, entry: &Entry, stock: &crate::menu::place::Stacked) -> bool {
self.placements.get(&entry.id).is_some_and(|p| {
!p.impossible() && stock.can_craft(&p.ingredients.iter().collect::<Vec<_>>())
})
self.placements
.get(&entry.id)
.is_some_and(|p| stock.can_craft(&p.ingredients.iter().collect::<Vec<_>>()))
}
/// Numbers the entries as `RecipeManager.unpackRecipeInfo` numbers the
/// displays: every recipe in id order, each with its displays.
pub fn set_display_ids(&mut self, index: &RecipeIndex) {
let mut previous: Option<(String, i32)> = None;
for e in &mut self.entries {
let next = match &previous {
Some((id, last)) if *id == e.id => last + 1,
_ => index.first_display(&e.id).unwrap_or(-1),
};
e.display_id = next;
previous = Some((e.id.clone(), next));
}
}
/// The entry of a display id.
pub fn entry_of_display(&self, display: i32) -> Option<usize> {
self.entries.iter().position(|e| e.display_id == display)
}
pub fn entry(&self, id: &str) -> Option<&Entry> {
self.entries.iter().find(|e| e.id == id)
@@ -437,12 +441,94 @@ impl Book {
}
}
/// A `RecipeDisplayId` as a `HashMap` key: a record of one int hashes as it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct DisplayKey(i32);
impl horizon_world::java_hash_map::JavaKey for DisplayKey {
fn java_hash(&self) -> i32 {
self.0
}
fn tie_break(&self, other: &Self) -> std::cmp::Ordering {
if self.0 < other.0 {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Greater
}
}
}
/// `ClientRecipeBook`: the displays the client was sent, in a `HashMap` whose
/// iteration order (the display ids' buckets, then arrival order) decides the
/// order of the book's buttons.
#[derive(Default)]
pub struct ClientBook {
known: horizon_world::java_hash_map::JavaHashMap<DisplayKey, ()>,
pub highlight: std::collections::HashSet<i32>,
}
impl ClientBook {
pub fn add(&mut self, display: i32) {
self.known.put(DisplayKey(display), ());
}
pub fn remove(&mut self, display: i32) {
self.known.remove(&DisplayKey(display));
self.highlight.remove(&display);
}
/// `clear` (a replacing `ClientboundRecipeBookAddPacket`): the table keeps its size.
pub fn clear(&mut self) {
self.known.clear();
self.highlight.clear();
}
/// The known display ids in iteration order.
pub fn displays(&self) -> Vec<i32> {
self.known.entries().map(|(k, _)| k.0).collect()
}
/// `rebuildCollections` then `getCollection(tab)`: per category, a
/// collection per entry without a group or per group, in the order the
/// known displays iterate; the search tab lists its categories in turn.
pub fn collections(&self, book: &Book, book_type: BookType, tab: Tab) -> Vec<Collection> {
let by_display: HashMap<i32, usize> = book
.entries
.iter()
.enumerate()
.map(|(i, e)| (e.display_id, i))
.collect();
let mut by_category: HashMap<Category, Vec<Collection>> = HashMap::new();
let mut groups: HashMap<(Category, String), (Category, usize)> = HashMap::new();
for display in self.displays() {
let Some(&i) = by_display.get(&display) else {
continue;
};
let e = &book.entries[i];
let list = by_category.entry(e.category).or_default();
match &e.group {
None => list.push(Collection { entries: vec![i] }),
Some(g) => match groups.get(&(e.category, g.clone())) {
Some(&(_, at)) => list[at].entries.push(i),
None => {
groups.insert((e.category, g.clone()), (e.category, list.len()));
list.push(Collection { entries: vec![i] });
}
},
}
}
let categories: Vec<Category> = match tab {
Tab::Search => book_type.search_categories().to_vec(),
Tab::Category(c) => vec![c],
};
categories
.into_iter()
.flat_map(|c| by_category.remove(&c).unwrap_or_default())
.collect()
}
}
/// What the server knows of each recipe of the datapack: whether it is
/// special (`Recipe.isSpecial`: never learnable) and how many recipe book
/// displays it has (`RecipeManager.listDisplaysForRecipe`).
#[derive(Clone, Debug, Default)]
pub struct RecipeIndex {
recipes: std::collections::BTreeMap<String, (bool, usize)>,
/// Recipe id -> (special, display count, first display id).
recipes: std::collections::BTreeMap<String, (bool, usize, i32)>,
}
impl RecipeIndex {
/// Reads `data/minecraft/recipe/*.json` under `root`.
@@ -480,7 +566,13 @@ impl RecipeIndex {
} else {
1
};
recipes.insert(format!("minecraft:{stem}"), (special, displays));
recipes.insert(format!("minecraft:{stem}"), (special, displays, 0));
}
// RecipeManager keeps its recipes sorted by id and numbers the displays in that order.
let mut next = 0;
for r in recipes.values_mut() {
r.2 = next;
next += r.1 as i32;
}
Self { recipes }
}
@@ -497,6 +589,13 @@ impl RecipeIndex {
pub fn ids(&self) -> impl Iterator<Item = &String> {
self.recipes.keys()
}
/// The display ids of a recipe (none for a special one).
pub fn display_ids(&self, id: &str) -> std::ops::Range<i32> {
self.recipes.get(id).map_or(0..0, |r| r.2..r.2 + r.1 as i32)
}
pub fn first_display(&self, id: &str) -> Option<i32> {
self.recipes.get(id).filter(|r| r.1 > 0).map(|r| r.2)
}
}
/// `ServerRecipeBook`: the player's `recipeBook` compound, the known recipes
@@ -642,8 +741,9 @@ mod tests {
}
#[test]
fn collections_group_recipes_of_a_category() {
let entry = |id: &str, group: Option<&str>, category| Entry {
let entry = |id: &str, display_id, group: Option<&str>, category| Entry {
id: id.into(),
display_id,
category,
group: group.map(str::to_owned),
display: Display::Shapeless(vec![ing(&["minecraft:stick"])]),
@@ -651,34 +751,45 @@ mod tests {
};
let book = Book {
entries: vec![
entry("minecraft:a", Some("planks"), Category::CraftingBuilding),
entry("minecraft:b", Some("planks"), Category::CraftingBuilding),
entry("minecraft:c", None, Category::CraftingBuilding),
entry("minecraft:d", Some("planks"), Category::CraftingMisc),
entry("minecraft:a", 0, Some("planks"), Category::CraftingBuilding),
entry("minecraft:b", 1, Some("planks"), Category::CraftingBuilding),
entry("minecraft:c", 2, None, Category::CraftingBuilding),
entry("minecraft:d", 3, Some("planks"), Category::CraftingMisc),
],
placements: HashMap::new(),
order: HashMap::new(),
};
let unlocked: BTreeSet<String> = ["a", "b", "c", "d"]
.iter()
.map(|n| format!("minecraft:{n}"))
.collect();
let mut client = ClientBook::default();
for d in 0..4 {
client.add(d);
}
let tab = Tab::Category(Category::CraftingBuilding);
let c = book.collections(&unlocked, BookType::Crafting, tab);
let c = client.collections(&book, BookType::Crafting, tab);
assert_eq!(c.len(), 2);
assert_eq!(c[0].entries, vec![0, 1]);
// The search tab lists every category; the same group in another category is separate.
let all = book.collections(&unlocked, BookType::Crafting, Tab::Search);
let all = client.collections(&book, BookType::Crafting, Tab::Search);
assert_eq!(all.len(), 3);
// Locked recipes are hidden.
let some: BTreeSet<String> = ["minecraft:c".to_owned()].into();
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
// Displays the client was not sent are not listed.
client.clear();
client.add(2);
assert_eq!(client.collections(&book, BookType::Crafting, tab).len(), 1);
}
#[test]
fn display_ids_collide_in_a_small_table() {
// A 16-bucket table: 17 and 1 share a bucket and keep arrival order.
let mut client = ClientBook::default();
for d in [17, 3, 1] {
client.add(d);
}
assert_eq!(client.displays(), vec![17, 1, 3]);
}
#[test]
fn search_reads_tooltip_lines_and_ids() {
let book = Book {
entries: vec![Entry {
id: "minecraft:stick".into(),
display_id: 0,
category: Category::CraftingMisc,
group: None,
display: Display::Shapeless(Vec::new()),
@@ -0,0 +1,140 @@
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 java.util.function.Predicate;
import net.minecraft.client.ClientRecipeBook;
import net.minecraft.client.gui.screens.recipebook.RecipeCollection;
import net.minecraft.client.gui.screens.recipebook.SearchRecipeBookCategory;
import net.minecraft.core.registries.Registries;
import net.minecraft.resources.Identifier;
import net.minecraft.resources.ResourceKey;
import net.minecraft.world.entity.player.StackedItemContents;
import net.minecraft.world.flag.FeatureFlags;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.item.crafting.ExtendedRecipeBookCategory;
import net.minecraft.world.item.crafting.RecipeBookCategories;
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;
/**
* Original oracle for what the recipe book screen lists: the client's
* ClientRecipeBook receives the displays of the known recipes (in the order
* the server sent them, then later unlocks and removals) and rebuilds its
* collections; each collection selects its recipes for the open menu
* (CraftingRecipeBookComponent / FurnaceRecipeBookComponent.selectMatchingRecipes)
* with the stacked contents of the inventory and the menu slots; then for
* 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.
*/
public final class VanillaRecipeBookViewOracle {
record Tab(ExtendedRecipeBookCategory category, String name) {}
static List<Tab> tabs(String type) {
return switch (type) {
case "crafting" -> List.of(new Tab(SearchRecipeBookCategory.CRAFTING, "search"),
new Tab(RecipeBookCategories.CRAFTING_EQUIPMENT, "crafting_equipment"),
new Tab(RecipeBookCategories.CRAFTING_BUILDING_BLOCKS, "crafting_building_blocks"),
new Tab(RecipeBookCategories.CRAFTING_MISC, "crafting_misc"),
new Tab(RecipeBookCategories.CRAFTING_REDSTONE, "crafting_redstone"));
case "furnace" -> List.of(new Tab(SearchRecipeBookCategory.FURNACE, "search"),
new Tab(RecipeBookCategories.FURNACE_FOOD, "furnace_food"),
new Tab(RecipeBookCategories.FURNACE_BLOCKS, "furnace_blocks"),
new Tab(RecipeBookCategories.FURNACE_MISC, "furnace_misc"));
case "blast_furnace" -> List.of(new Tab(SearchRecipeBookCategory.BLAST_FURNACE, "search"),
new Tab(RecipeBookCategories.BLAST_FURNACE_BLOCKS, "blast_furnace_blocks"),
new Tab(RecipeBookCategories.BLAST_FURNACE_MISC, "blast_furnace_misc"));
default -> List.of(new Tab(SearchRecipeBookCategory.SMOKER, "search"),
new Tab(RecipeBookCategories.SMOKER_FOOD, "smoker_food"));
};
}
static List<RecipeDisplayEntry> displays(RecipeManager recipes, String id) {
List<RecipeDisplayEntry> out = new ArrayList<>();
recipes.listDisplaysForRecipe(ResourceKey.create(Registries.RECIPE, Identifier.parse(id)), out::add);
return out;
}
public static void main(String[] args) throws Exception {
ParityData.init();
RecipeManager recipes = new RecipeManager(ParityData.lookup);
recipes.finalizeRecipeLoading(FeatureFlags.VANILLA_SET);
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<String>) lines::iterator) {
var f = JsonParser.parseString(line).getAsJsonObject();
try {
ClientRecipeBook book = new ClientRecipeBook();
// ClientPacketListener.handleRecipeBookAdd / handleRecipeBookRemove.
for (var batch : f.getAsJsonArray("history")) {
var b = batch.getAsJsonObject();
String op = b.get("op").getAsString();
if (op.equals("replace")) book.clear();
for (var id : b.getAsJsonArray("ids")) {
for (RecipeDisplayEntry entry : displays(recipes, id.getAsString())) {
if (op.equals("remove")) book.remove(entry.id());
else book.add(entry);
}
}
book.rebuildCollections();
}
StackedItemContents contents = new StackedItemContents();
for (var s : f.getAsJsonArray("inventory")) contents.accountSimpleStack(ParityData.stack(s.getAsString()));
String type = f.get("type").getAsString();
int grid = f.get("grid").getAsInt();
for (var s : f.getAsJsonArray("slots")) {
ItemStack stack = ParityData.stack(s.getAsString());
// A furnace's SimpleContainer counts every slot; the crafting grid only simple stacks.
if (type.equals("crafting")) contents.accountSimpleStack(stack);
else contents.accountStack(stack);
}
Predicate<RecipeDisplay> canDisplay = type.equals("crafting")
? display -> switch (display) {
case ShapedCraftingRecipeDisplay shaped -> grid >= shaped.width() && grid >= shaped.height();
case ShapelessCraftingRecipeDisplay shapeless -> grid * grid >= shapeless.ingredients().size();
default -> false;
}
: display -> display instanceof FurnaceRecipeDisplay;
List<Tab> tabs = tabs(type);
for (Tab tab : tabs) {
for (RecipeCollection c : book.getCollection(tab.category())) c.selectRecipes(contents, canDisplay);
}
boolean filtering = f.get("filtering").getAsBoolean();
StringBuilder result = new StringBuilder();
for (Tab tab : tabs) {
List<RecipeCollection> 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 (filtering) collections.removeIf(c -> !c.hasCraftable());
result.append(" pages=").append((int) Math.ceil(collections.size() / 20.0));
for (RecipeCollection c : collections) {
result.append(" [");
boolean first = true;
for (RecipeDisplayEntry e : c.getRecipes()) {
boolean selected = c.getSelectedRecipes(RecipeCollection.CraftableStatus.ANY).contains(e);
result.append(first ? "" : ",").append(e.id().index()).append(selected ? "s" : "").append(c.isCraftable(e.id()) ? "c" : "");
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();
}
}
}
}
}
+93
View File
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
"""Compare what the recipe book lists with the vanilla client's.
Each case sends the client recipe book a history of displays as the server
does (the initial replacing batch in some order, later unlocks and
removals), opens a book type (the inventory's 2x2 or a crafting table's 3x3
grid, the furnace, blast furnace or smoker) with random inventory and menu
contents and the craftable filter on or off. The Java oracle
(VanillaRecipeBookViewOracle, on the client jar) runs ClientRecipeBook,
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).
"""
import argparse
import json
import os
import random
import subprocess
import sys
try:
from . import interaction_lab as lib, lab, test_place_recipe_parity as place, test_model_baking_parity as baking
from . import test_crafter_parity as crafter, test_rust_parity as base
except ImportError:
import interaction_lab as lib
import lab
import test_place_recipe_parity as place
import test_model_baking_parity as baking
import test_crafter_parity as crafter
import test_rust_parity as base
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--seed', type=int, default=17)
parser.add_argument('--cases', type=int, default=1200)
parser.add_argument('--limit', type=int, default=2)
args = parser.parse_args()
lock, jars, _ = base.verify_artifacts()
work = lib.work_dir('recipe-book-view-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', 'VanillaRecipeBookViewOracle'))],
capture_output=True, text=True)
if done.returncode:
print(done.stderr[-4000:])
sys.exit('javac failed')
items = json.loads((lib.RESOURCES / 'items.json').read_text())
recipes = crafter.Recipes(lib.RESOURCES)
gen = place.Gen(random.Random(args.seed), items, recipes)
rng = gen.rng
ids = sorted('minecraft:' + n for n in recipes.recipes)
cases = []
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.
known = rng.sample(ids, rng.choice([5, 30, 100, 300, 600, 900, len(ids)]))
history = [{'op': 'replace', 'ids': known}]
for _ in range(rng.choice([0, 0, 1, 2, 3])):
if rng.random() < 0.6:
history.append({'op': 'add', 'ids': rng.sample(ids, rng.choice([1, 3, 20]))})
else:
history.append({'op': 'remove', 'ids': rng.sample(known, min(len(known), rng.choice([1, 5, 40])))})
if rng.random() < 0.1:
history.append({'op': 'replace', 'ids': rng.sample(ids, 50)})
menu = {'crafting': rng.choice(['inventory', 'crafting']), 'furnace': 'furnace', 'blast_furnace': 'blast_furnace',
'smoker': 'smoker'}[kind]
case = gen.case(menu)
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})
(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)
if run.returncode:
print(run.stderr[-4000:])
sys.exit('oracle failed')
lib.cargo_example('horizon-client', 'recipe_book_view_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
def describe(case):
return json.dumps({k: (v if k != 'history' else [(h['op'], len(h['ids'])) for h in v]) for k, v in case.items()
if k not in ('inventory', 'slots')})
bad = lib.compare(cases, work / 'native.txt', work / 'rust.txt', lambda case, line: case['type'] if not line.startswith('error')
else 'oracle error', describe=describe, limit=args.limit)
raise SystemExit(1 if bad else 0)
if __name__ == '__main__':
main()