Keep the player's recipe book as vanilla's ServerRecipeBook does
The known and highlighted recipes, the book settings and the saved recipeBook compound now live in one place (recipe_book::Settings with a RecipeIndex of learnability and display counts): advancement rewards, /recipe give and take (counting displays, never special recipes) and crafting a recipe award through it, and loading drops unknown recipes instead of rebuilding the set from done advancements. A new harness compares 1,500 operation sequences with vanilla's ServerRecipeBook and its codec. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,143 @@
|
||||
//! The player's recipe book for tools/test_recipe_book_parity.py: reads one
|
||||
//! JSON case per line (a list of give / take / seen / set / save / load ops)
|
||||
//! and prints the oracle's line after each op, from
|
||||
//! `horizon_client::recipe_book::{Settings, RecipeIndex}`.
|
||||
//!
|
||||
//! usage: recipe_book_fixture RESOURCES CASES OUTPUT
|
||||
use horizon_client::recipe_book::{BookType, RecipeIndex, Settings};
|
||||
use horizon_world::nbt::Tag;
|
||||
use serde_json::Value;
|
||||
use std::{collections::BTreeSet, fs, path::Path};
|
||||
|
||||
fn fnv<'a>(ids: impl IntoIterator<Item = &'a String>) -> u64 {
|
||||
let mut sorted: Vec<&String> = ids.into_iter().collect();
|
||||
sorted.sort();
|
||||
let joined = sorted
|
||||
.iter()
|
||||
.map(|s| s.as_str())
|
||||
.collect::<Vec<_>>()
|
||||
.join(",");
|
||||
let mut h: u64 = 0xcbf2_9ce4_8422_2325;
|
||||
for b in joined.bytes() {
|
||||
h ^= u64::from(b);
|
||||
h = h.wrapping_mul(0x0100_0000_01b3);
|
||||
}
|
||||
h
|
||||
}
|
||||
fn ids(set: &BTreeSet<String>) -> String {
|
||||
format!("{}:{:x}", set.len(), fnv(set))
|
||||
}
|
||||
/// The saved compound as the oracle prints it: keys sorted, lists hashed.
|
||||
fn compound(tag: &Tag) -> String {
|
||||
let Tag::Compound(c) = tag else {
|
||||
return String::new();
|
||||
};
|
||||
let mut keys: Vec<String> = c.keys().map(|k| k.to_string_lossy()).collect();
|
||||
keys.sort();
|
||||
let mut out = String::new();
|
||||
for k in keys {
|
||||
out.push(' ');
|
||||
out.push_str(&k);
|
||||
out.push('=');
|
||||
match tag.get(&k) {
|
||||
Some(Tag::List(list)) => {
|
||||
let v: Vec<String> = list
|
||||
.iter()
|
||||
.map(|t| match t {
|
||||
Tag::String(s) => s.to_string_lossy(),
|
||||
_ => "?".into(),
|
||||
})
|
||||
.collect();
|
||||
out.push_str(&format!("{}:{:x}", v.len(), fnv(&v)));
|
||||
}
|
||||
Some(Tag::Byte(b)) => out.push_str(&format!("{b}b")),
|
||||
_ => out.push('?'),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn main() -> horizon_client::Result<()> {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let usage = "usage: recipe_book_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 index = RecipeIndex::load(root);
|
||||
let mut out = String::new();
|
||||
for line in cases.lines() {
|
||||
let case: Value = serde_json::from_str(line)?;
|
||||
let mut book = Settings::default();
|
||||
let mut saved: Option<Tag> = None;
|
||||
for op in case["ops"].as_array().ok_or("ops")? {
|
||||
let kind = op["op"].as_str().unwrap_or_default();
|
||||
let list = || -> Vec<String> {
|
||||
op["ids"]
|
||||
.as_array()
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.filter_map(|v| v.as_str().map(str::to_owned))
|
||||
.filter(|id| index.contains(id))
|
||||
.collect()
|
||||
};
|
||||
let mut count = 0;
|
||||
let mut extra = String::new();
|
||||
match kind {
|
||||
"give" => count = book.add_recipes(&index, &list()).0,
|
||||
"take" => count = book.remove_recipes(&index, &list()),
|
||||
"seen" => book.remove_highlight(op["id"].as_str().unwrap_or_default()),
|
||||
"set" => {
|
||||
let i = match op["type"].as_str().unwrap_or_default() {
|
||||
"CRAFTING" => BookType::Crafting,
|
||||
"FURNACE" => BookType::Furnace,
|
||||
"BLAST_FURNACE" => BookType::BlastFurnace,
|
||||
_ => BookType::Smoker,
|
||||
}
|
||||
.index();
|
||||
book.open[i] = op["open"].as_bool().unwrap_or(false);
|
||||
book.filtering[i] = op["filtering"].as_bool().unwrap_or(false);
|
||||
}
|
||||
"save" => {
|
||||
let tag = book.write();
|
||||
extra = compound(&tag);
|
||||
saved = Some(tag);
|
||||
}
|
||||
"load" => {
|
||||
let mut tag = saved
|
||||
.clone()
|
||||
.unwrap_or_else(|| Tag::Compound(Default::default()));
|
||||
if let Tag::Compound(c) = &mut tag {
|
||||
for name in ["recipes", "toBeDisplayed"] {
|
||||
if let Some(Tag::List(l)) = c.get_mut(&name.into()) {
|
||||
l.push(Tag::String("minecraft:no_such_recipe".into()));
|
||||
l.push(Tag::String("stick".into()));
|
||||
}
|
||||
}
|
||||
if let Some(drop) = op["drop"].as_str() {
|
||||
c.remove(&drop.into());
|
||||
}
|
||||
}
|
||||
book = Settings::read_valid(Some(&tag), &|id| index.contains(id));
|
||||
}
|
||||
other => return Err(format!("op {other}").into()),
|
||||
}
|
||||
let settings: String = BookType::ALL
|
||||
.iter()
|
||||
.map(|b| {
|
||||
format!(
|
||||
"{}{}",
|
||||
u8::from(book.open[b.index()]),
|
||||
u8::from(book.filtering[b.index()])
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
out += &format!(
|
||||
"{kind} {count} known={} highlight={} settings={settings}{extra}\n",
|
||||
ids(&book.recipes),
|
||||
ids(&book.to_be_displayed)
|
||||
);
|
||||
}
|
||||
out += "end\n";
|
||||
}
|
||||
fs::write(args.get(3).ok_or(usage)?, out)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -3276,6 +3276,13 @@ impl Game<'_> {
|
||||
self.craft_recipe().map(|(_, result)| result)
|
||||
}
|
||||
/// The recipe id and result of the crafting grid.
|
||||
/// `RecipeCraftingHolder.awardUsedRecipes`: a crafted recipe becomes known
|
||||
/// (special ones never do).
|
||||
fn award_crafted(&mut self, recipes: &[String]) {
|
||||
let index = &self.res.stations.recipe_index;
|
||||
let (_, unlocked) = self.level.recipe_book.add_recipes(index, recipes);
|
||||
self.recipe_unlocked(&unlocked);
|
||||
}
|
||||
fn craft_recipe(&self) -> Option<(String, ItemStack)> {
|
||||
let n = self.craft_size;
|
||||
let grid: Vec<Option<ItemStack>> = (0..n * n).map(|i| self.craft_grid[i].clone()).collect();
|
||||
@@ -3773,6 +3780,7 @@ impl Game<'_> {
|
||||
let carried = menu.carried.take();
|
||||
let dropped = std::mem::take(&mut menu.dropped);
|
||||
let sounds = std::mem::take(&mut menu.sounds);
|
||||
let crafted = std::mem::take(&mut menu.crafted);
|
||||
for (i, stack) in after.into_iter().enumerate() {
|
||||
if let Some(g) = game_of[i] {
|
||||
*self.slot_mut(g) = stack;
|
||||
@@ -3785,6 +3793,7 @@ impl Game<'_> {
|
||||
for stack in dropped {
|
||||
self.player_drop(stack);
|
||||
}
|
||||
self.award_crafted(&crafted);
|
||||
if kind == Kind::Loom {
|
||||
if let Some(s) = self.station.as_mut() {
|
||||
s.loom.selected = usize::try_from(menu.data[0]).ok();
|
||||
@@ -4053,6 +4062,7 @@ impl Game<'_> {
|
||||
}
|
||||
crafted += 1;
|
||||
self.stats.add("crafted", &made.0, made.1 as i32);
|
||||
self.award_crafted(&[format!("minecraft:{recipe}")]);
|
||||
if !shift || crafted >= 64 {
|
||||
break;
|
||||
}
|
||||
@@ -5086,6 +5096,11 @@ impl Game<'_> {
|
||||
self.inventory = inventory;
|
||||
self.save = save;
|
||||
self.level = level;
|
||||
// ServerRecipeBook.loadUntrusted: recipes the manager does not have are dropped.
|
||||
let index = &self.res.stations.recipe_index;
|
||||
let book = &mut self.level.recipe_book;
|
||||
book.recipes.retain(|r| index.contains(r));
|
||||
book.to_be_displayed.retain(|r| index.contains(r));
|
||||
self.dim = dim;
|
||||
self.world_root = save_root.clone();
|
||||
self.block_ticks = Ticks::new(self.level.seed as i32);
|
||||
@@ -6966,7 +6981,6 @@ impl Game<'_> {
|
||||
self.ender_items = items.clone();
|
||||
}
|
||||
level.ender_items = self.ender_items.clone();
|
||||
level.recipe_book.recipes = self.adv.recipes.iter().cloned().collect();
|
||||
level.active_effects = self
|
||||
.potions
|
||||
.effects
|
||||
|
||||
@@ -10,7 +10,7 @@ use horizon_client::{
|
||||
};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet, VecDeque},
|
||||
collections::{BTreeMap, VecDeque},
|
||||
sync::Arc,
|
||||
time::Instant,
|
||||
};
|
||||
@@ -46,7 +46,6 @@ pub(super) struct AdvState {
|
||||
pub(super) tree: Arc<Tree>,
|
||||
pub(super) progress: Progress,
|
||||
loaded: bool,
|
||||
pub(super) recipes: BTreeSet<String>,
|
||||
pub(super) toasts: VecDeque<Toast>,
|
||||
/// Awards skip the toast (`/advancement grant ... everything`).
|
||||
pub(super) quiet: bool,
|
||||
@@ -214,13 +213,9 @@ impl Game<'_> {
|
||||
.and_then(|t| serde_json::from_str::<Value>(&t).ok())
|
||||
.map(|v| Progress::from_json(&v))
|
||||
.unwrap_or_default();
|
||||
// Unlocked recipes come from the done recipe advancements' rewards.
|
||||
// The known recipes are the player's own (`recipeBook`), not the
|
||||
// rewards of done advancements: /recipe take sticks.
|
||||
let tree = self.adv.tree.clone();
|
||||
for a in &tree.list {
|
||||
if progress.done(a) {
|
||||
self.adv.recipes.extend(a.rewards.recipes.iter().cloned());
|
||||
}
|
||||
}
|
||||
self.adv.progress = progress;
|
||||
self.ui.registries.advancements = tree.list.iter().map(|a| a.id.clone()).collect();
|
||||
}
|
||||
@@ -375,6 +370,17 @@ impl Game<'_> {
|
||||
}
|
||||
}
|
||||
}
|
||||
/// After `ServerRecipeBook.addRecipes`: the toast and the
|
||||
/// `recipe_unlocked` trigger of each recipe now known.
|
||||
pub(super) fn recipe_unlocked(&mut self, unlocked: &[String]) {
|
||||
self.recipe_toast(unlocked);
|
||||
for r in unlocked {
|
||||
let r = r.clone();
|
||||
self.trigger("minecraft:recipe_unlocked", move |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
});
|
||||
}
|
||||
}
|
||||
/// `PlayerAdvancements.award` once done: rewards, toast, announcement.
|
||||
fn award(&mut self, index: usize) {
|
||||
let tree = self.adv.tree.clone();
|
||||
@@ -383,12 +389,18 @@ impl Game<'_> {
|
||||
if a.rewards.experience > 0 {
|
||||
self.experience.give(a.rewards.experience);
|
||||
}
|
||||
let mut unlocked = Vec::new();
|
||||
for r in &a.rewards.recipes {
|
||||
if self.adv.recipes.insert(r.clone()) {
|
||||
unlocked.push(r.clone());
|
||||
}
|
||||
}
|
||||
// ServerPlayer.awardRecipesByKey: the rewards that name a recipe.
|
||||
let rewards: Vec<String> = a
|
||||
.rewards
|
||||
.recipes
|
||||
.iter()
|
||||
.filter(|r| self.res.stations.recipe_index.contains(r))
|
||||
.cloned()
|
||||
.collect();
|
||||
let (_, unlocked) = self
|
||||
.level
|
||||
.recipe_book
|
||||
.add_recipes(&self.res.stations.recipe_index, &rewards);
|
||||
for table in &a.rewards.loot {
|
||||
let items = self
|
||||
.res
|
||||
@@ -425,12 +437,7 @@ impl Game<'_> {
|
||||
));
|
||||
}
|
||||
}
|
||||
self.recipe_toast(&unlocked);
|
||||
for r in unlocked {
|
||||
self.trigger("minecraft:recipe_unlocked", |c, _| {
|
||||
c["recipes"].as_str() == Some(r.as_str())
|
||||
});
|
||||
}
|
||||
self.recipe_unlocked(&unlocked);
|
||||
}
|
||||
/// `InventoryChangeTrigger`, checked when the inventory changes.
|
||||
pub(super) fn check_inventory_trigger(&mut self) {
|
||||
|
||||
@@ -30,32 +30,9 @@ fn java_double_text(v: f64) -> Text {
|
||||
impl Game<'_> {
|
||||
// ---- /recipe -----------------------------------------------------------
|
||||
|
||||
/// Every `minecraft:` recipe that `/recipe` can give (non-special ones).
|
||||
/// Every recipe id of the recipe manager (what `/recipe` resolves and suggests).
|
||||
pub(super) fn learnable_recipes(&self) -> Vec<String> {
|
||||
let dir = self.options.resources.join("data/minecraft/recipe");
|
||||
let mut out = Vec::new();
|
||||
let Ok(entries) = std::fs::read_dir(&dir) else {
|
||||
return out;
|
||||
};
|
||||
for e in entries.flatten() {
|
||||
let path = e.path();
|
||||
let Some(stem) = path.file_stem().and_then(|s| s.to_str()) else {
|
||||
continue;
|
||||
};
|
||||
if path.extension().and_then(|x| x.to_str()) != Some("json") {
|
||||
continue;
|
||||
}
|
||||
let special = std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok())
|
||||
.and_then(|v| v["type"].as_str().map(|t| t.contains("crafting_special_")))
|
||||
.unwrap_or(false);
|
||||
if !special {
|
||||
out.push(format!("minecraft:{stem}"));
|
||||
}
|
||||
}
|
||||
out.sort();
|
||||
out
|
||||
self.res.stations.recipe_index.ids().cloned().collect()
|
||||
}
|
||||
pub(super) fn cmd_recipe(&mut self, id: &str, ctx: &Context) -> R<i32> {
|
||||
let targets = self.entities(ctx, "targets", true)?;
|
||||
@@ -73,14 +50,15 @@ impl Game<'_> {
|
||||
for &t in &targets {
|
||||
let h = holder(self.target_name(t));
|
||||
let mut n = 0;
|
||||
for r in &recipes {
|
||||
let changed = if give {
|
||||
self.adv.recipes.insert(r.clone())
|
||||
} else {
|
||||
self.adv.recipes.remove(r)
|
||||
};
|
||||
n += i32::from(changed);
|
||||
}
|
||||
// ServerPlayer.awardRecipes / resetRecipes: the displays changed.
|
||||
let index = &self.res.stations.recipe_index;
|
||||
n += if give {
|
||||
let (count, unlocked) = self.level.recipe_book.add_recipes(index, &recipes);
|
||||
self.recipe_unlocked(&unlocked);
|
||||
count as i32
|
||||
} else {
|
||||
self.level.recipe_book.remove_recipes(index, &recipes) as i32
|
||||
};
|
||||
tracker.track(&h, n);
|
||||
}
|
||||
let verb = if give { "give" } else { "take" };
|
||||
|
||||
@@ -183,11 +183,6 @@ impl Game<'_> {
|
||||
return;
|
||||
}
|
||||
self.ensure_book();
|
||||
for id in recipes {
|
||||
if !self.level.recipe_book.to_be_displayed.contains(id) {
|
||||
self.level.recipe_book.to_be_displayed.push(id.clone());
|
||||
}
|
||||
}
|
||||
let icon = self
|
||||
.recipe_ui
|
||||
.book
|
||||
@@ -225,12 +220,7 @@ impl Game<'_> {
|
||||
out
|
||||
}
|
||||
fn unlocked_recipes(&self) -> BTreeSet<String> {
|
||||
self.adv
|
||||
.recipes
|
||||
.iter()
|
||||
.chain(self.level.recipe_book.recipes.iter())
|
||||
.cloned()
|
||||
.collect()
|
||||
self.level.recipe_book.recipes.clone()
|
||||
}
|
||||
fn ensure_book(&mut self) {
|
||||
if self.recipe_ui.book.is_none() {
|
||||
@@ -263,7 +253,6 @@ impl Game<'_> {
|
||||
stack.map(|s| (s.item, s.count)).hash(&mut h);
|
||||
}
|
||||
self.craft_size.hash(&mut h);
|
||||
self.adv.recipes.len().hash(&mut h);
|
||||
self.level.recipe_book.recipes.len().hash(&mut h);
|
||||
self.book_filtering(book_type).hash(&mut h);
|
||||
self.recipe_ui.tab.map(|t| format!("{t:?}")).hash(&mut h);
|
||||
|
||||
@@ -159,6 +159,8 @@ pub struct Menu {
|
||||
pub loom_patterns: Vec<Arc<str>>,
|
||||
/// Sounds the menu plays (`ui.loom.take_result`), for the caller.
|
||||
pub sounds: Vec<&'static str>,
|
||||
/// Recipes whose result was taken (`awardUsedRecipes`), for the caller.
|
||||
pub crafted: Vec<String>,
|
||||
}
|
||||
|
||||
fn same_item(a: &ItemStack, b: &ItemStack) -> bool {
|
||||
@@ -357,6 +359,7 @@ impl Menu {
|
||||
quick_slots: Vec::new(),
|
||||
loom_patterns: Vec::new(),
|
||||
sounds: Vec::new(),
|
||||
crafted: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -699,6 +702,9 @@ impl Menu {
|
||||
}
|
||||
let n = self.grid_size;
|
||||
let grid = self.containers[GRID].clone();
|
||||
if let Some((id, _)) = env.recipes.find(&grid, n) {
|
||||
self.crafted.push(format!("minecraft:{id}"));
|
||||
}
|
||||
let remaining = env
|
||||
.recipes
|
||||
.find(&grid, n)
|
||||
|
||||
@@ -437,42 +437,158 @@ impl Book {
|
||||
}
|
||||
}
|
||||
|
||||
/// The recipe book's saved state: the `recipeBook` compound of the player.
|
||||
/// 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)>,
|
||||
}
|
||||
impl RecipeIndex {
|
||||
/// Reads `data/minecraft/recipe/*.json` under `root`.
|
||||
pub fn load(root: &std::path::Path) -> Self {
|
||||
let mut recipes = std::collections::BTreeMap::new();
|
||||
let dir = root.join("data/minecraft/recipe");
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().is_none_or(|e| e != "json") {
|
||||
continue;
|
||||
}
|
||||
let (Some(stem), Some(v)) = (
|
||||
path.file_stem().and_then(|s| s.to_str()),
|
||||
std::fs::read(&path)
|
||||
.ok()
|
||||
.and_then(|b| serde_json::from_slice::<serde_json::Value>(&b).ok()),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
let kind = v["type"].as_str().unwrap_or_default();
|
||||
let special = kind.starts_with("minecraft:crafting_special_")
|
||||
|| kind == "minecraft:crafting_decorated_pot";
|
||||
let displays = if special {
|
||||
0
|
||||
} else if kind == "minecraft:crafting_transmute" {
|
||||
// TransmuteRecipe.display: one per material count.
|
||||
match &v["material_count"] {
|
||||
serde_json::Value::Object(o) => {
|
||||
let min = o.get("min").and_then(|m| m.as_u64()).unwrap_or(1);
|
||||
let max = o.get("max").and_then(|m| m.as_u64()).unwrap_or(8);
|
||||
(max.saturating_sub(min) + 1) as usize
|
||||
}
|
||||
_ => 1,
|
||||
}
|
||||
} else {
|
||||
1
|
||||
};
|
||||
recipes.insert(format!("minecraft:{stem}"), (special, displays));
|
||||
}
|
||||
Self { recipes }
|
||||
}
|
||||
pub fn contains(&self, id: &str) -> bool {
|
||||
self.recipes.contains_key(id)
|
||||
}
|
||||
pub fn special(&self, id: &str) -> bool {
|
||||
self.recipes.get(id).is_some_and(|r| r.0)
|
||||
}
|
||||
pub fn displays(&self, id: &str) -> usize {
|
||||
self.recipes.get(id).map_or(0, |r| r.1)
|
||||
}
|
||||
/// Every recipe id, in id order.
|
||||
pub fn ids(&self) -> impl Iterator<Item = &String> {
|
||||
self.recipes.keys()
|
||||
}
|
||||
}
|
||||
|
||||
/// `ServerRecipeBook`: the player's `recipeBook` compound, the known recipes
|
||||
/// and the ones still to highlight (`toBeDisplayed`) with the open and
|
||||
/// filter settings of each `RecipeBookType`.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct Settings {
|
||||
/// `isGuiOpen`-style flags per `BookType`.
|
||||
pub open: [bool; 4],
|
||||
pub filtering: [bool; 4],
|
||||
/// Unlocked recipe ids (`recipes`).
|
||||
pub recipes: Vec<String>,
|
||||
/// Known recipe ids (`recipes`).
|
||||
pub recipes: BTreeSet<String>,
|
||||
/// Recipes not yet shown in the book (`toBeDisplayed`): they animate once.
|
||||
pub to_be_displayed: Vec<String>,
|
||||
pub to_be_displayed: BTreeSet<String>,
|
||||
}
|
||||
impl Settings {
|
||||
/// `ServerRecipeBook.addRecipes`: the displays added (the count
|
||||
/// `/recipe give` reports) and the recipes now known, in order.
|
||||
pub fn add_recipes(&mut self, index: &RecipeIndex, ids: &[String]) -> (usize, Vec<String>) {
|
||||
let mut displays = 0;
|
||||
let mut added = Vec::new();
|
||||
for id in ids {
|
||||
if !self.recipes.contains(id) && !index.special(id) {
|
||||
self.recipes.insert(id.clone());
|
||||
self.to_be_displayed.insert(id.clone());
|
||||
displays += index.displays(id);
|
||||
added.push(id.clone());
|
||||
}
|
||||
}
|
||||
(displays, added)
|
||||
}
|
||||
/// `ServerRecipeBook.removeRecipes`: the displays removed.
|
||||
pub fn remove_recipes(&mut self, index: &RecipeIndex, ids: &[String]) -> usize {
|
||||
let mut displays = 0;
|
||||
for id in ids {
|
||||
if self.recipes.remove(id) {
|
||||
self.to_be_displayed.remove(id);
|
||||
displays += index.displays(id);
|
||||
}
|
||||
}
|
||||
displays
|
||||
}
|
||||
/// `removeHighlight` (`ServerboundRecipeBookSeenRecipePacket`).
|
||||
pub fn remove_highlight(&mut self, id: &str) {
|
||||
self.to_be_displayed.remove(id);
|
||||
}
|
||||
pub fn knows(&self, id: &str) -> bool {
|
||||
self.recipes.contains(id)
|
||||
}
|
||||
/// The compound as saved, every recipe kept.
|
||||
pub fn read(tag: Option<&Tag>) -> Self {
|
||||
Self::read_valid(tag, &|_| true)
|
||||
}
|
||||
/// `ServerRecipeBook.loadUntrusted`: unknown recipes are dropped. Without
|
||||
/// both lists the compound does not decode and nothing is read.
|
||||
pub fn read_valid(tag: Option<&Tag>, valid: &dyn Fn(&str) -> bool) -> Self {
|
||||
let mut s = Self::default();
|
||||
let Some(tag) = tag else { return s };
|
||||
let ids = |key: &str| match tag.get(key) {
|
||||
Some(Tag::List(list)) => Some(
|
||||
list.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::String(id) => Some(id.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
.map(|id| {
|
||||
if id.contains(':') {
|
||||
id
|
||||
} else {
|
||||
format!("minecraft:{id}")
|
||||
}
|
||||
})
|
||||
.filter(|id| valid(id))
|
||||
.collect::<BTreeSet<String>>(),
|
||||
),
|
||||
_ => None,
|
||||
};
|
||||
let (Some(recipes), Some(to_be_displayed)) = (ids("recipes"), ids("toBeDisplayed")) else {
|
||||
return s;
|
||||
};
|
||||
let flag = |k: &str| matches!(tag.get(k), Some(Tag::Byte(b)) if *b != 0);
|
||||
for b in BookType::ALL {
|
||||
let (open, filter) = b.keys();
|
||||
s.open[b.index()] = flag(open);
|
||||
s.filtering[b.index()] = flag(filter);
|
||||
}
|
||||
let ids = |key: &str| match tag.get(key) {
|
||||
Some(Tag::List(list)) => list
|
||||
.iter()
|
||||
.filter_map(|t| match t {
|
||||
Tag::String(id) => Some(id.to_string_lossy()),
|
||||
_ => None,
|
||||
})
|
||||
.collect(),
|
||||
_ => Vec::new(),
|
||||
};
|
||||
s.recipes = ids("recipes");
|
||||
s.to_be_displayed = ids("toBeDisplayed");
|
||||
s.recipes = recipes;
|
||||
s.to_be_displayed = to_be_displayed;
|
||||
s
|
||||
}
|
||||
/// The compound written to the player file.
|
||||
/// The compound written to the player file (vanilla's lists follow an
|
||||
/// identity hash order; these are sorted).
|
||||
pub fn write(&self) -> Tag {
|
||||
let mut entries: Vec<(&str, Tag)> = Vec::new();
|
||||
for b in BookType::ALL {
|
||||
@@ -485,7 +601,7 @@ impl Settings {
|
||||
entries.push((filter, Tag::Byte(1)));
|
||||
}
|
||||
}
|
||||
let list = |ids: &[String]| {
|
||||
let list = |ids: &BTreeSet<String>| {
|
||||
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
|
||||
};
|
||||
entries.push(("recipes", list(&self.recipes)));
|
||||
@@ -583,7 +699,7 @@ mod tests {
|
||||
let mut s = Settings::default();
|
||||
s.open[BookType::Furnace.index()] = true;
|
||||
s.filtering[BookType::Crafting.index()] = true;
|
||||
s.recipes = vec!["minecraft:stick".into()];
|
||||
s.recipes = ["minecraft:stick".to_owned()].into();
|
||||
let back = Settings::read(Some(&s.write()));
|
||||
assert_eq!(back.open, s.open);
|
||||
assert_eq!(back.filtering, s.filtering);
|
||||
|
||||
@@ -19,6 +19,8 @@ pub struct StationData {
|
||||
pub brewing: crate::brewing::Brewing,
|
||||
pub trades: crate::merchant::Trades,
|
||||
pub banners: crate::banner::Banners,
|
||||
/// Every recipe's learnability and display count (the server recipe book).
|
||||
pub recipe_index: crate::recipe_book::RecipeIndex,
|
||||
}
|
||||
impl StationData {
|
||||
pub fn load(root: &Path, items: &Items) -> Self {
|
||||
@@ -28,6 +30,7 @@ impl StationData {
|
||||
brewing: crate::brewing::Brewing::load(root, items),
|
||||
trades: crate::merchant::Trades::load(root),
|
||||
banners: crate::banner::Banners::load(root),
|
||||
recipe_index: crate::recipe_book::RecipeIndex::load(root),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
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.core.registries.Registries;
|
||||
import net.minecraft.nbt.*;
|
||||
import net.minecraft.resources.Identifier;
|
||||
import net.minecraft.resources.ResourceKey;
|
||||
import net.minecraft.server.level.ServerPlayer;
|
||||
import net.minecraft.stats.ServerRecipeBook;
|
||||
import net.minecraft.world.entity.EntityEquipment;
|
||||
import net.minecraft.world.entity.player.Inventory;
|
||||
import net.minecraft.world.flag.FeatureFlags;
|
||||
import net.minecraft.world.inventory.RecipeBookType;
|
||||
import net.minecraft.world.item.crafting.Recipe;
|
||||
import net.minecraft.world.item.crafting.RecipeHolder;
|
||||
import net.minecraft.world.item.crafting.RecipeManager;
|
||||
|
||||
/**
|
||||
* Original oracle: the player's ServerRecipeBook under a sequence of
|
||||
* operations: awarding recipes (advancement rewards, /recipe give, crafting),
|
||||
* taking them (/recipe take), the client seeing a highlighted recipe, the
|
||||
* book settings, and saving and loading the recipeBook compound
|
||||
* (ServerRecipeBook.Packed.CODEC, loadUntrusted). After each step the count
|
||||
* the operation returned, the known and highlighted recipes (count and an
|
||||
* FNV-1a hash of the sorted ids) and, for a save, the compound are printed.
|
||||
*/
|
||||
public final class VanillaRecipeBookOracle {
|
||||
static long fnv(Collection<String> ids) {
|
||||
List<String> sorted = new ArrayList<>(ids);
|
||||
Collections.sort(sorted);
|
||||
long h = 0xcbf29ce484222325L;
|
||||
for (byte b : String.join(",", sorted).getBytes(StandardCharsets.UTF_8)) {
|
||||
h ^= (b & 0xff);
|
||||
h *= 0x100000001b3L;
|
||||
}
|
||||
return h;
|
||||
}
|
||||
|
||||
static String ids(Collection<ResourceKey<Recipe<?>>> keys) {
|
||||
List<String> out = new ArrayList<>();
|
||||
for (var k : keys) out.add(k.identifier().toString());
|
||||
return out.size() + ":" + Long.toHexString(fnv(out));
|
||||
}
|
||||
|
||||
static ResourceKey<Recipe<?>> key(String id) {
|
||||
return ResourceKey.create(Registries.RECIPE, Identifier.parse(id));
|
||||
}
|
||||
|
||||
static String compound(CompoundTag tag) {
|
||||
List<String> keys = new ArrayList<>(tag.keySet());
|
||||
Collections.sort(keys);
|
||||
StringBuilder out = new StringBuilder();
|
||||
for (String k : keys) {
|
||||
Tag t = tag.get(k);
|
||||
out.append(' ').append(k).append('=');
|
||||
if (t instanceof ListTag list) {
|
||||
List<String> v = new ArrayList<>();
|
||||
for (Tag e : list) v.add(e.asString().orElse("?"));
|
||||
out.append(v.size()).append(':').append(Long.toHexString(fnv(v)));
|
||||
} else {
|
||||
out.append(t);
|
||||
}
|
||||
}
|
||||
return out.toString();
|
||||
}
|
||||
|
||||
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);
|
||||
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 {
|
||||
var player = VanillaMenuOracle.make(VanillaMenuOracle.FakePlayer.class);
|
||||
player.advancements = VanillaMenuOracle.make(net.minecraft.server.PlayerAdvancements.class);
|
||||
VanillaMenuOracle.set(player.advancements, net.minecraft.server.PlayerAdvancements.class, "activeTriggers", new IdentityHashMap<>());
|
||||
VanillaMenuOracle.set(player, ServerPlayer.class, "connection", VanillaMenuOracle.make(VanillaMenuOracle.Connection.class));
|
||||
player.inv = new Inventory(player, new EntityEquipment());
|
||||
ServerRecipeBook book = new ServerRecipeBook(recipes::listDisplaysForRecipe);
|
||||
CompoundTag saved = null;
|
||||
for (var opJson : f.getAsJsonArray("ops")) {
|
||||
var op = opJson.getAsJsonObject();
|
||||
String kind = op.get("op").getAsString();
|
||||
int count = 0;
|
||||
String extra = "";
|
||||
switch (kind) {
|
||||
case "give", "take" -> {
|
||||
List<RecipeHolder<?>> holders = new ArrayList<>();
|
||||
for (var id : op.getAsJsonArray("ids")) {
|
||||
recipes.byKey(key(id.getAsString())).ifPresent(holders::add);
|
||||
}
|
||||
count = kind.equals("give") ? book.addRecipes(holders, player) : book.removeRecipes(holders, player);
|
||||
}
|
||||
case "seen" -> book.removeHighlight(key(op.get("id").getAsString()));
|
||||
case "set" -> book.setBookSetting(RecipeBookType.valueOf(op.get("type").getAsString()),
|
||||
op.get("open").getAsBoolean(), op.get("filtering").getAsBoolean());
|
||||
case "save" -> {
|
||||
saved = (CompoundTag) ServerRecipeBook.Packed.CODEC.encodeStart(NbtOps.INSTANCE, book.pack()).getOrThrow();
|
||||
extra = compound(saved);
|
||||
}
|
||||
case "load" -> {
|
||||
// The saved compound with ids the manager does not know; maybe a list missing.
|
||||
CompoundTag tag = saved == null ? new CompoundTag() : saved.copy();
|
||||
for (String list : List.of("recipes", "toBeDisplayed")) {
|
||||
if (tag.get(list) instanceof ListTag l) {
|
||||
l.add(StringTag.valueOf("minecraft:no_such_recipe"));
|
||||
l.add(StringTag.valueOf("stick"));
|
||||
}
|
||||
}
|
||||
if (op.has("drop")) tag.remove(op.get("drop").getAsString());
|
||||
book = new ServerRecipeBook(recipes::listDisplaysForRecipe);
|
||||
ServerRecipeBook fresh = book;
|
||||
ServerRecipeBook.Packed.CODEC.parse(NbtOps.INSTANCE, tag).result()
|
||||
.ifPresent(p -> fresh.loadUntrusted(p, k -> recipes.byKey(k).isPresent()));
|
||||
}
|
||||
default -> throw new IllegalArgumentException(kind);
|
||||
}
|
||||
var packed = book.pack();
|
||||
StringBuilder settings = new StringBuilder();
|
||||
for (RecipeBookType t : RecipeBookType.values()) {
|
||||
settings.append(book.isOpen(t) ? '1' : '0').append(book.isFiltering(t) ? '1' : '0');
|
||||
}
|
||||
out.println(kind + " " + count + " known=" + ids(packed.known()) + " highlight=" + ids(packed.highlight())
|
||||
+ " settings=" + settings + extra);
|
||||
}
|
||||
out.println("end");
|
||||
} catch (Throwable e) {
|
||||
out.println("error-case " + e.getClass().getSimpleName() + " " + e.getMessage());
|
||||
if (System.getenv("MENU_TRACE") != null) e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Compare the player's recipe book with vanilla's ServerRecipeBook.
|
||||
|
||||
Each case runs a sequence of operations on a fresh book: awarding recipes
|
||||
(advancement rewards, /recipe give, crafting; special recipes are never
|
||||
learnt, and the count is the displays added), taking them back, the client
|
||||
having seen a highlighted recipe, the open and filter settings of the four
|
||||
book types, and saving and loading the player's recipeBook compound (with
|
||||
unknown ids dropped, and a compound missing a list ignored). The Java oracle
|
||||
(VanillaRecipeBookOracle) drives ServerRecipeBook and its codec;
|
||||
examples/recipe_book_fixture drives horizon_client::recipe_book. After each
|
||||
operation the count, the known and highlighted recipes, the settings and
|
||||
the saved compound are compared.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import random
|
||||
try:
|
||||
from . import interaction_lab as lib
|
||||
except ImportError:
|
||||
import interaction_lab as lib
|
||||
|
||||
TYPES = ['CRAFTING', 'FURNACE', 'BLAST_FURNACE', 'SMOKER']
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--seed', type=int, default=5)
|
||||
parser.add_argument('--cases', type=int, default=1500)
|
||||
parser.add_argument('--limit', type=int, default=3)
|
||||
args = parser.parse_args()
|
||||
work = lib.work_dir('recipe-book-parity')
|
||||
vanilla = lib.Vanilla(work)
|
||||
vanilla.compile('ParityData', 'VanillaMenuOracle', 'VanillaRecipeBookOracle')
|
||||
ids = sorted('minecraft:' + p.stem for p in (lib.RESOURCES / 'data/minecraft/recipe').glob('*.json'))
|
||||
rng = random.Random(args.seed)
|
||||
cases = []
|
||||
for _ in range(args.cases):
|
||||
ops, known = [], set()
|
||||
for _ in range(rng.randrange(1, 12)):
|
||||
kind = rng.choices(['give', 'take', 'seen', 'set', 'save', 'load'], [10, 4, 4, 3, 3, 2])[0]
|
||||
if kind in ('give', 'take'):
|
||||
pool = list(known) if kind == 'take' and known and rng.random() < 0.7 else ids
|
||||
chosen = ids if rng.random() < 0.03 else rng.sample(pool, min(len(pool), rng.choice([1, 1, 2, 5, 20])))
|
||||
if rng.random() < 0.2:
|
||||
chosen = chosen + chosen[:1]
|
||||
ops.append({'op': kind, 'ids': chosen})
|
||||
if kind == 'give':
|
||||
known.update(chosen)
|
||||
elif kind == 'seen':
|
||||
ops.append({'op': kind, 'id': rng.choice(list(known) or ids)})
|
||||
elif kind == 'set':
|
||||
ops.append({'op': kind, 'type': rng.choice(TYPES), 'open': rng.random() < 0.5, 'filtering': rng.random() < 0.5})
|
||||
elif kind == 'save':
|
||||
ops.append({'op': kind})
|
||||
else:
|
||||
op = {'op': kind}
|
||||
if rng.random() < 0.2:
|
||||
op['drop'] = rng.choice(['recipes', 'toBeDisplayed'])
|
||||
ops.append(op)
|
||||
cases.append({'ops': ops})
|
||||
(work / 'cases.jsonl').write_text(''.join(json.dumps(c) + '\n' for c in cases))
|
||||
vanilla.run('VanillaRecipeBookOracle', work / 'cases.jsonl', work / 'native.txt')
|
||||
lib.cargo_example('horizon-client', 'recipe_book_fixture', lib.RESOURCES, work / 'cases.jsonl', work / 'rust.txt')
|
||||
|
||||
def by_case(path):
|
||||
out, cur = [], []
|
||||
for line in path.read_text().splitlines():
|
||||
cur.append(line)
|
||||
if line == 'end' or line.startswith('error-case'):
|
||||
out.append(cur)
|
||||
cur = []
|
||||
return out
|
||||
native, rust = by_case(work / 'native.txt'), by_case(work / 'rust.txt')
|
||||
bad = {}
|
||||
for case, a, b in zip(cases, native, rust):
|
||||
if a != b:
|
||||
step = next((i for i, (x, y) in enumerate(zip(a, b)) if x != y), min(len(a), len(b)))
|
||||
op = case['ops'][step]['op'] if step < len(case['ops']) else 'end'
|
||||
bad.setdefault(op, []).append((case, step, a, b))
|
||||
total = sum(len(v) for v in bad.values())
|
||||
for key, entries in sorted(bad.items(), key=lambda e: -len(e[1])):
|
||||
print(f'{key}: {len(entries)} differing')
|
||||
for case, step, a, b in entries[:args.limit]:
|
||||
print(f' ops {json.dumps(case["ops"][:step + 1])[:600]}')
|
||||
print(f' native {a[step] if step < len(a) else "-"}\n rust {b[step] if step < len(b) else "-"}')
|
||||
errors = sum(1 for c in native if c and c[-1].startswith('error-case'))
|
||||
print(f'{len(cases) - total}/{len(cases)} cases match ({errors} oracle errors)')
|
||||
raise SystemExit(1 if total or errors or len(native) != len(cases) else 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
Reference in New Issue
Block a user