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 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-13 05:35:49 +02:00
parent 2756b55b5b
commit 23d7ebdfaa
8 changed files with 454 additions and 5 deletions
@@ -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 {
+31
View File
@@ -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<ItemStack> {
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)> {
@@ -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;
+297
View File
@@ -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<String>,
attribute: &str,
amount: f64,
operation: usize,
) -> Option<String> {
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<String>) -> Vec<String> {
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>) -> 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<String>,
) -> Vec<String> {
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<String> = 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<String>,
) -> Vec<String> {
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);
}
}
+1
View File
@@ -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;
+21 -1
View File
@@ -157,6 +157,10 @@ pub struct Entry {
pub group: Option<String>,
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<ItemStack>,
}
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<String>,
) -> 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(),
@@ -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<RecipeCollection> found = null;
if (!query.isEmpty()) {
// SessionSearchTrees.updateRecipes.
List<RecipeCollection> all = book.getCollections();
Registry<Item> 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<RecipeCollection> 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<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 (found != null) {
Set<RecipeCollection> 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) {
+51 -2
View File
@@ -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)