Keep container names and saddle components, order and search the recipe book like vanilla

Containers now remember a custom name: it is read and saved as CustomName, taken from the item when placed (including by dispensers), shown as the screen title of chests, furnaces, the brewing stand, hoppers, dispensers and the crafter, and given back to the dropped item when the block is broken. Saddles on pigs, striders and horses are kept as full item stacks instead of a flag, so their components survive taming, the horse menu, dispensers, saving and death drops. The recipe book lists dye, transmute (shulker box, bundle, map cloning) and tipped arrow recipes, searches the tooltip lines and ids of a collection's results the way the vanilla search tree does, and squeezes new recipes' tabs and buttons once, saving the pending recipes as toBeDisplayed.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-09 14:17:24 +02:00
parent 69c7fd925e
commit 513004936d
19 changed files with 376 additions and 64 deletions
+3
View File
@@ -100,6 +100,8 @@ pub struct Chunk {
pub fresh: bool,
/// Block entities read from a save, moved into the world on arrival.
pub block_entities: Vec<((i32, i32, i32), crate::containers::BlockEntity)>,
/// `CustomName` of the container block entities (shown as the screen title).
pub block_names: Vec<((i32, i32, i32), String)>,
/// Generation postprocessing marks (ProtoChunk.postProcessing) as world
/// positions, applied once by LevelChunk.postProcessGeneration.
pub postprocess: Vec<[i32; 3]>,
@@ -125,6 +127,7 @@ impl Chunk {
light_loaded: false,
fresh: false,
block_entities: Vec::new(),
block_names: Vec::new(),
structure_refs: Vec::new(),
postprocess: Vec::new(),
saved: None,
+59
View File
@@ -253,6 +253,65 @@ pub enum Special {
/// `RepairItemRecipe`: two damaged items of one kind.
RepairItem,
}
impl Special {
/// 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)> {
use crate::recipe_book::Display;
match self {
Self::Transmute {
input,
material,
min,
max,
add_count,
result,
} => (*min..=*max)
.map(|n| {
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)
})
.collect(),
Self::Dye {
target,
dye,
result,
} => vec![(
Display::Shapeless(vec![target.clone(), dye.clone()]),
result.create(),
)],
Self::Imbue {
source,
material,
result,
} => {
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(),
)]
}
_ => Vec::new(),
}
}
}
/// `CraftingInput`: the occupied bounding box of the grid.
pub struct Input<'a> {
pub width: usize,
+17 -13
View File
@@ -211,11 +211,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
map.remove(&"Items".into());
}
let mut equipment = Vec::new();
if m.extra.saddled {
equipment.push((
"saddle",
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
));
if let Some(saddle) = m.saddle_item() {
equipment.push(("saddle", crate::save::item_to_nbt(&saddle)));
}
if let Some(armor) = &m.extra.head {
equipment.push((
@@ -241,11 +238,8 @@ pub fn mob_to_nbt(m: &Mob, uuid: [i32; 4], raw: Option<&Tag>) -> Tag {
Some(Tag::Compound(c)) => c.clone(),
_ => Compound::new(),
};
if m.extra.saddled {
equipment.insert(
"saddle".into(),
Tag::compound([("id", string("minecraft:saddle")), ("count", Tag::Int(1))]),
);
if let Some(saddle) = m.saddle_item() {
equipment.insert("saddle".into(), crate::save::item_to_nbt(&saddle));
} else {
equipment.remove(&"saddle".into());
}
@@ -499,8 +493,15 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.species(),
crate::mobs::Species::Pig | crate::mobs::Species::Strider
) {
m.extra.saddled =
tag.get("equipment").and_then(|e| e.get("saddle")).is_some() || flag(tag, "Saddle");
let saddle = tag
.get("equipment")
.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt);
if saddle.is_some() || flag(tag, "Saddle") {
m.set_saddle(Some(saddle.unwrap_or_else(|| {
crate::items::ItemStack::new("minecraft:saddle", 1)
})));
}
}
if crate::mobs::equine::is_equine(m.species()) {
m.extra.tame = flag(tag, "Tame");
@@ -514,7 +515,10 @@ pub fn mob_from_nbt(tag: &Tag, types: &HashMap<String, Arc<MobType>>, id: u32) -
m.extra.items = crate::save::decode_items(tag.get("Items"), 15);
}
let eq = tag.get("equipment");
m.extra.saddled = eq.and_then(|e| e.get("saddle")).is_some();
m.set_saddle(
eq.and_then(|e| e.get("saddle"))
.and_then(crate::save::item_from_nbt),
);
m.extra.head = eq
.and_then(|e| e.get("body"))
.and_then(|b| text(b.get("id")))
+16
View File
@@ -630,6 +630,8 @@ struct Game<'a> {
pending_shulker: HashMap<[i32; 3], Vec<(u8, ItemStack)>>,
/// Layers of broken banners waiting for their dropped item.
pending_banner: HashMap<[i32; 3], horizon_client::containers::Banner>,
/// Custom names of broken containers, for the dropped item (`copy_components`).
pending_names: HashMap<[i32; 3], (String, String)>,
/// The recipe book of the open screen (game/recipe_book.rs).
recipe_ui: recipe_book::RecipeUi,
/// The horse inventory (game/mount_menu.rs).
@@ -1005,6 +1007,7 @@ impl Game<'_> {
/// Block.popResource
fn pop_resource(&mut self, pos: [i32; 3], mut stack: ItemStack) {
self.attach_shulker_contents(pos, &mut stack);
self.attach_container_name(pos, &mut stack);
self.attach_banner_layers(pos, &mut stack);
let r = &mut self.world.random;
let mut offset = || f64::from(r.next_float()) * 0.5 - 0.25;
@@ -1838,6 +1841,7 @@ impl Game<'_> {
.block_entities
.insert((target[0], target[1], target[2]), entity);
self.fill_placed_box(target, &stack);
self.name_placed_container(target, &stack);
self.fill_placed_banner(target, &stack);
if sign {
self.open_sign_editor((target[0], target[1], target[2]), true);
@@ -3249,6 +3253,7 @@ impl Game<'_> {
}
};
part(batch, tex, 0.0, 0.0, 176.0, 166.0, ox, oy);
let title = &self.container_title(title.to_owned());
let tw = HudBatch::text_width(atlas, title);
batch.text(atlas, title, ox + (176.0 - tw) / 2.0, oy + 6.0, grey, false);
batch.text(atlas, "Inventory", ox + 8.0, oy + 72.0, grey, false);
@@ -4416,6 +4421,13 @@ impl Game<'_> {
.filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z)
.map(|(p, e)| (*p, e.clone()))
.collect();
c.block_names = self
.world
.block_names
.iter()
.filter(|(p, _)| p.0 >> 4 == c.x && p.2 >> 4 == c.z)
.map(|(p, n)| (*p, n.clone()))
.collect();
self.attach_save_data(&mut c);
Arc::new(c)
}
@@ -6999,6 +7011,9 @@ impl Game<'_> {
self.world
.block_entities
.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
self.world
.block_names
.retain(|p, _| !(p.0 >> 4 == c.x && p.2 >> 4 == c.z));
}
if !modified.is_empty()
&& let Err(e) = self
@@ -7751,6 +7766,7 @@ pub fn run() -> Result<()> {
ender_open: None,
pending_shulker: HashMap::new(),
pending_banner: HashMap::new(),
pending_names: HashMap::new(),
recipe_ui: Default::default(),
mount_menu: Default::default(),
hook: None,
+2 -2
View File
@@ -727,8 +727,8 @@ impl Game<'_> {
}
// Saddles, horse armour and chests always drop.
let mut gear: Vec<&str> = Vec::new();
if m.extra.saddled {
gear.push("minecraft:saddle");
if let Some(saddle) = m.saddle_item() {
self.spawn_item(saddle, pos, [0.0, 0.2, 0.0], 10);
}
// WitherBoss.dropCustomDeathLoot.
if m.species() == Species::Wither {
+2 -1
View File
@@ -578,7 +578,7 @@ impl Game<'_> {
(_, Some(1)) => m.extra.chest = Some(item.clone()),
(_, Some(2)) => m.extra.legs = Some(item.clone()),
(_, Some(3)) => m.extra.feet = Some(item.clone()),
("saddle", _) => m.extra.saddled = true,
("saddle", _) => m.set_saddle(Some(one.clone())),
_ => m.extra.head = Some(item.clone()),
}
// setGuaranteedDrop / setPersistenceRequired.
@@ -1155,6 +1155,7 @@ impl Game<'_> {
if let Some(entity) = BlockEntity::for_block(&self.res.facts.get(state).name) {
self.world.block_entities.insert(target, entity);
self.fill_placed_box([target.0, target.1, target.2], &stack);
self.name_placed_container([target.0, target.1, target.2], &stack);
}
let sounds = self.res.facts.get(state).sounds.clone();
self.audio.play(
@@ -746,6 +746,7 @@ impl Game<'_> {
batch.rect_uv(ox, oy, 176.0, height, r, u32::MAX);
}
let grey = horizon_client::hud::rgba(64, 64, 64, 255);
let title = &self.container_title(title.to_owned());
let title_x = if screen == Screen::Hopper {
8.0
} else {
@@ -270,7 +270,7 @@ impl Game<'_> {
256.0,
);
let grey = rgba(64, 64, 64, 255);
let title = self.translate("container.crafter", "Crafter");
let title = self.container_title(self.translate("container.crafter", "Crafter"));
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+4 -7
View File
@@ -67,10 +67,7 @@ impl Game<'_> {
mob: m.id,
species,
columns,
saddle: m
.extra
.saddled
.then(|| ItemStack::new("minecraft:saddle", 1)),
saddle: m.saddle_item(),
armor: m
.extra
.head
@@ -137,18 +134,18 @@ impl Game<'_> {
let Some(index) = self.mount_mob_index(open.mob) else {
return;
};
let (saddle, armor) = (open.saddle.is_some(), open.armor.clone());
let (saddle, armor) = (open.saddle.clone(), open.armor.clone());
let items = open.items.clone();
let m = &mut self.mobs[index];
let at = m.center();
let sound = if saddle && !m.extra.saddled {
let sound = if saddle.is_some() && !m.extra.saddled {
Some("minecraft:entity.horse.saddle")
} else if armor.is_some() && m.extra.head.is_none() {
Some("minecraft:entity.horse.armor")
} else {
None
};
m.extra.saddled = saddle;
m.set_saddle(saddle);
if open.show_armor {
m.extra.head = armor.map(|a| a.item);
}
+4 -2
View File
@@ -38,13 +38,14 @@ impl Game<'_> {
}
/// `Pig` / `Strider.mobInteract`: saddle an adult, or ride a saddled one.
fn interact_steerable(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &mut self.mobs[index];
if m.is_baby() || !m.alive() || Some(m.id) == self.riding {
return false;
}
let at = m.center();
if item == "minecraft:saddle" && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
let sound = if m.species() == Species::Strider {
"minecraft:entity.strider.saddle"
} else {
@@ -91,6 +92,7 @@ impl Game<'_> {
}
/// `AbstractHorse.mobInteract`. Returns whether the click was used.
pub(super) fn interact_mount(&mut self, index: usize, item: &str) -> bool {
let held = self.inventory[self.selected].clone();
let m = &self.mobs[index];
let species = m.species();
if matches!(species, Species::Pig | Species::Strider) {
@@ -118,7 +120,7 @@ impl Game<'_> {
let at = m.center();
let tamed = m.extra.tame;
let sound = if item == "minecraft:saddle" && tamed && !m.extra.saddled {
m.extra.saddled = true;
m.set_saddle(held);
Some("minecraft:entity.horse.saddle")
} else if item.ends_with("_horse_armor")
&& species == Species::Horse
+98 -10
View File
@@ -68,6 +68,9 @@ pub(super) struct RecipeUi {
overlay: Option<Overlay>,
view: View,
view_key: u64,
/// Squeeze animations of new recipes: ticks left per button index and tab.
button_anim: Vec<(usize, f32)>,
tab_anim: Vec<(Tab, f32)>,
}
impl RecipeUi {
@@ -179,6 +182,11 @@ 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
@@ -291,6 +299,71 @@ impl Game<'_> {
if self.recipe_ui.page >= pages.max(1) {
self.recipe_ui.page = 0;
}
self.start_new_recipe_animations(book_type);
}
/// `RecipeBookTabButton.startAnimation` and `RecipeButton.init`: tabs
/// holding a recipe still to be displayed squeeze, and the buttons of the
/// shown page squeeze once and clear their recipes' highlight.
fn start_new_recipe_animations(&mut self, book_type: BookType) {
if self.level.recipe_book.to_be_displayed.is_empty() {
return;
}
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);
let shown = |e: &Entry| {
(book_type != BookType::Crafting || e.fits(gw, gh))
&& (!filtering || available.can_craft(&e.requirements()))
};
let new = |level: &Self, e: &Entry| level.level.recipe_book.to_be_displayed.contains(&e.id);
let mut tabs = Vec::new();
for tab in self.recipe_ui.view.tabs.clone() {
if tab == Tab::Search {
continue;
}
let hit = book
.collections(&unlocked, book_type, tab)
.iter()
.flat_map(|c| c.entries.iter())
.any(|&i| shown(&book.entries[i]) && new(self, &book.entries[i]));
if hit {
tabs.push((tab, 15.0));
}
}
self.recipe_ui.tab_anim = tabs;
let first = self.recipe_ui.page * 20;
let mut buttons = Vec::new();
let mut cleared = Vec::new();
for (n, button) in self
.recipe_ui
.view
.buttons
.iter()
.skip(first)
.take(20)
.enumerate()
{
let ids: Vec<&String> = button
.entries
.iter()
.map(|e| &book.entries[e.0].id)
.filter(|id| self.level.recipe_book.to_be_displayed.contains(*id))
.collect();
if !ids.is_empty() {
buttons.push((first + n, 15.0));
cleared.extend(ids.into_iter().cloned());
}
}
self.level
.recipe_book
.to_be_displayed
.retain(|id| !cleared.contains(id));
self.recipe_ui.button_anim = buttons;
self.recipe_ui.book = Some(book);
}
fn build_view(&mut self, ui: &RecipeUi, book_type: BookType) -> View {
let Some(book) = ui.book.as_ref() else {
@@ -329,9 +402,8 @@ impl Game<'_> {
continue;
}
if !query.is_empty()
&& !c.entries.iter().any(|&i| {
let e = &book.entries[i];
book.matches_search(e, &query, &self.res.names.item(&e.result.item))
&& !book.collection_matches(&c.entries, &query, &|stack| {
self.stack_tooltip(stack).into_iter().map(|l| l.0).collect()
})
{
continue;
@@ -972,26 +1044,30 @@ impl Game<'_> {
.tab
.filter(|t| tabs.contains(t))
.unwrap_or(Tab::Search);
let mut tab_icons = Vec::new();
let frame = self.frame_ticks;
for (n, tab) in tabs.iter().enumerate() {
let (x, y) = self.tab_pos(xo, yo, n);
let selected = *tab == current;
let name = if selected { "tab_selected" } else { "tab" };
let sx = if selected { x - 2.0 } else { x };
let start = batch.vertices.len();
batch.sprite(&self.res.atlas, &sprite(name), sx, y);
let (a, b) = tab.icons();
let shift = if selected { -2.0 } else { 0.0 };
match b {
Some(b) => {
tab_icons.push((a, x + 3.0 + shift, y + 5.0));
tab_icons.push((b, x + 14.0 + shift, y + 5.0));
self.draw_item(batch, &ItemStack::new(a, 1), x + 3.0 + shift, y + 5.0);
self.draw_item(batch, &ItemStack::new(b, 1), x + 14.0 + shift, y + 5.0);
}
None => tab_icons.push((a, x + 9.0 + shift, y + 5.0)),
None => self.draw_item(batch, &ItemStack::new(a, 1), x + 9.0 + shift, y + 5.0),
}
if let Some(entry) = self.recipe_ui.tab_anim.iter_mut().find(|e| e.0 == *tab) {
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(start, x + 8.0, y + 12.0, 1.0, squeeze);
entry.1 -= frame;
}
}
for (item, x, y) in tab_icons {
self.draw_item(batch, &ItemStack::new(item, 1), x, y);
}
self.recipe_ui.tab_anim.retain(|e| e.1 > 0.0);
// Craftable filter.
let filtering = self.book_filtering(book_type);
let hover = inside(cursor, xo + 110.0, yo + 12.0, 26.0, 16.0);
@@ -1019,6 +1095,7 @@ impl Game<'_> {
break;
};
let (x, y) = Self::button_pos(xo, yo, n);
let anim_start = batch.vertices.len();
let many = button.entries.len() > 1;
let name = match (button.craftable(), many) {
(true, true) => "slot_many_craftable",
@@ -1048,6 +1125,16 @@ impl Game<'_> {
offset -= 1.0;
}
self.draw_item_plain(batch, &stack, x + offset, y + offset);
if let Some(entry) = self
.recipe_ui
.button_anim
.iter_mut()
.find(|e| e.0 == first + n)
{
let squeeze = 1.0 + 0.1 * (entry.1 / 15.0 * std::f32::consts::PI).sin();
batch.scale_since(anim_start, x + 8.0, y + 12.0, squeeze, squeeze);
entry.1 -= self.frame_ticks;
}
if inside(cursor, x, y, 25.0, 25.0) && !overlay_open {
let mut lines = self.stack_tooltip(&stack);
if many {
@@ -1059,6 +1146,7 @@ impl Game<'_> {
tooltip = Some(lines);
}
}
self.recipe_ui.button_anim.retain(|e| e.1 > 0.0);
// Page arrows and number.
if pages > 1 {
let page_text = self
+7 -1
View File
@@ -1305,7 +1305,13 @@ impl Game<'_> {
);
}
}
let title = self.translate("container.brewing", "Brewing Stand");
let default = self.translate("container.brewing", "Brewing Stand");
let title = self
.station
.as_ref()
.and_then(|s| self.world.block_names.get(&(s.pos[0], s.pos[1], s.pos[2])))
.cloned()
.unwrap_or(default);
let tw = HudBatch::text_width(atlas, &title);
batch.text(
atlas,
+41 -1
View File
@@ -11,6 +11,14 @@ impl Game<'_> {
/// Block-entity contents on removal: shulker boxes keep theirs for the
/// dropped box (`copy_components`), other containers spill them.
pub(super) fn release_contents(&mut self, pos: [i32; 3], entity: BlockEntity, block: &str) {
if let Some(name) = self
.world
.block_names
.remove(&(pos[0], pos[1], pos[2]))
.filter(|_| !matches!(entity, BlockEntity::Banner(_)))
{
self.pending_names.insert(pos, (block.to_owned(), name));
}
if let BlockEntity::Banner(banner) = entity {
self.pending_banner.insert(pos, banner);
return;
@@ -41,6 +49,38 @@ impl Game<'_> {
stack.data_mut().container = contents;
}
}
/// The custom name a broken container drops with (`copy_components`).
pub(super) fn attach_container_name(&mut self, pos: [i32; 3], stack: &mut ItemStack) {
if self
.pending_names
.get(&pos)
.is_some_and(|(item, _)| **item == *stack.item)
&& let Some((_, name)) = self.pending_names.remove(&pos)
{
stack.data_mut().custom_name = Some(name);
}
}
/// A placed container takes the item's custom name.
pub(super) fn name_placed_container(&mut self, pos: [i32; 3], stack: &ItemStack) {
let key = (pos[0], pos[1], pos[2]);
if let Some(name) = stack.custom_name()
&& !matches!(
self.world.block_entities.get(&key),
Some(BlockEntity::Banner(_) | BlockEntity::Sign(_))
)
{
self.world.block_names.insert(key, name.to_owned());
}
}
/// The custom name of the open container, or its default title
/// (a double chest is named by whichever half has a name).
pub(super) fn container_title(&self, default: String) -> String {
self.container_parts()
.iter()
.find_map(|(key, _)| self.world.block_names.get(key))
.cloned()
.unwrap_or(default)
}
/// A placed shulker box takes the item's contents.
pub(super) fn fill_placed_box(&mut self, pos: [i32; 3], stack: &ItemStack) {
let Some(data) = stack.data() else { return };
@@ -234,7 +274,7 @@ impl Game<'_> {
_ if rows > 3 => ("container.chestDouble", "Large Chest"),
_ => ("container.chest", "Chest"),
};
self.translate(key, fallback)
self.container_title(self.translate(key, fallback))
}
/// `ContainerScreen` / `ShulkerBoxScreen`: the background with its
/// container rows, the title and the inventory label.
+8
View File
@@ -278,6 +278,14 @@ impl HudBatch {
/// Clip the quads drawn since `start` to `[x0, x1) x [y0, y1)` (the
/// GUI scissor): axis-aligned quads are cut with their UVs, others are
/// kept or dropped by their centre.
/// Scale the vertices pushed since `start` about `(cx, cy)` (a GUI pose
/// matrix of translate, scale, translate back).
pub fn scale_since(&mut self, start: usize, cx: f32, cy: f32, sx: f32, sy: f32) {
for v in &mut self.vertices[start..] {
v.pos[0] = cx + (v.pos[0] - cx) * sx;
v.pos[1] = cy + (v.pos[1] - cy) * sy;
}
}
pub fn clip_since(&mut self, start: usize, x0: f32, y0: f32, x1: f32, y1: f32) {
let quads: Vec<[HudVertex; 6]> = self.vertices[start..].as_chunks::<6>().0.to_vec();
self.vertices.truncate(start);
+22
View File
@@ -438,6 +438,9 @@ pub struct Extra {
/// `Mob.canPickUpLoot` (also lets dispensers equip it).
pub pick_up_loot: bool,
pub saddled: bool,
/// The saddle's components (name, enchantments...) when it is not a bare
/// one; `saddled` stays the gameplay flag.
pub saddle_stack: Option<crate::items::ItemStack>,
pub chested: bool,
/// The chest contents of a donkey or mule (15 slots).
pub items: Vec<Option<crate::items::ItemStack>>,
@@ -1136,3 +1139,22 @@ pub fn render_model(
}
}
}
impl Mob {
/// The saddle worn, with its components.
pub fn saddle_item(&self) -> Option<crate::items::ItemStack> {
self.extra.saddled.then(|| {
self.extra
.saddle_stack
.clone()
.unwrap_or_else(|| crate::items::ItemStack::new("minecraft:saddle", 1))
})
}
/// Wear (or take off) a saddle stack, keeping its components.
pub fn set_saddle(&mut self, saddle: Option<crate::items::ItemStack>) {
self.extra.saddled = saddle.is_some();
self.extra.saddle_stack = saddle
.map(|s| crate::items::ItemStack { count: 1, ..s })
.filter(|s| s.damage != 0 || s.extra.is_some());
}
}
+70 -24
View File
@@ -280,7 +280,20 @@ impl Book {
ingredients,
result,
} => (Display::Shapeless(ingredients.clone()), result),
Recipe::Special(_) => continue,
// Custom recipes are never learnable; the others show one
// display per material count (TransmuteRecipe.display).
Recipe::Special(special) => {
for (display, result) in special.book_displays() {
entries.push(Entry {
id: format!("minecraft:{name}"),
category: crafting_category(&category),
group: group(&grp),
display,
result,
});
}
continue;
}
};
entries.push(Entry {
id: format!("minecraft:{name}"),
@@ -376,24 +389,33 @@ impl Book {
items.sort_by_key(|i| (self.order.get(i).copied().unwrap_or(usize::MAX), i.clone()));
items
}
/// `RecipeCollection` search: the result's name or registry path, or
/// `@namespace`.
pub fn matches_search(&self, entry: &Entry, query: &str, name: &str) -> bool {
/// 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`
/// needs the namespace in a result id and the path in an id or a line.
pub fn collection_matches(
&self,
entries: &[usize],
query: &str,
tooltip: &dyn Fn(&ItemStack) -> Vec<String>,
) -> bool {
let query = query.to_lowercase();
if let Some(ns) = query.strip_prefix('@') {
return entry
.result
.item
.split(':')
.next()
.is_some_and(|n| n.starts_with(ns));
}
name.to_lowercase().contains(&query)
|| entry
.result
.item
.trim_start_matches("minecraft:")
.contains(&query)
let results: Vec<&ItemStack> = entries.iter().map(|&i| &self.entries[i].result).collect();
let in_lines = |text: &str| {
results
.iter()
.any(|r| tooltip(r).iter().any(|l| l.to_lowercase().contains(text)))
};
let Some((namespace, path)) = query.split_once(':') else {
return in_lines(&query);
};
let (namespace, path) = (namespace.trim(), path.trim());
let id = |r: &&ItemStack| {
let (ns, p) = r.item.split_once(':').unwrap_or(("minecraft", &r.item));
(ns.to_lowercase(), p.to_lowercase())
};
results.iter().any(|r| id(r).0.contains(namespace))
&& (results.iter().any(|r| id(r).1.contains(path)) || in_lines(path))
}
}
@@ -524,6 +546,8 @@ pub struct Settings {
pub filtering: [bool; 4],
/// Unlocked recipe ids (`recipes`).
pub recipes: Vec<String>,
/// Recipes not yet shown in the book (`toBeDisplayed`): they animate once.
pub to_be_displayed: Vec<String>,
}
impl Settings {
pub fn read(tag: Option<&Tag>) -> Self {
@@ -535,18 +559,21 @@ impl Settings {
s.open[b.index()] = flag(open);
s.filtering[b.index()] = flag(filter);
}
if let Some(Tag::List(list)) = tag.get("recipes") {
s.recipes = list
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();
}
.collect(),
_ => Vec::new(),
};
s.recipes = ids("recipes");
s.to_be_displayed = ids("toBeDisplayed");
s
}
/// The compound written to the player file; `toBeDisplayed` stays empty.
/// The compound written to the player file.
pub fn write(&self) -> Tag {
let mut entries: Vec<(&str, Tag)> = Vec::new();
for b in BookType::ALL {
@@ -558,7 +585,7 @@ impl Settings {
Tag::List(ids.iter().map(|i| Tag::String(i.as_str().into())).collect())
};
entries.push(("recipes", list(&self.recipes)));
entries.push(("toBeDisplayed", Tag::List(Vec::new())));
entries.push(("toBeDisplayed", list(&self.to_be_displayed)));
Tag::compound(entries)
}
}
@@ -672,6 +699,25 @@ mod tests {
assert_eq!(book.collections(&some, BookType::Crafting, tab).len(), 1);
}
#[test]
fn search_reads_tooltip_lines_and_ids() {
let book = Book {
entries: vec![Entry {
id: "minecraft:stick".into(),
category: Category::CraftingMisc,
group: None,
display: Display::Shapeless(Vec::new()),
result: ItemStack::new("minecraft:stick", 4),
}],
order: HashMap::new(),
};
let lines = |s: &ItemStack| vec![format!("Item {}", s.item), "Stick".to_owned()];
assert!(book.collection_matches(&[0], "STI", &lines));
// Plain text searches tooltips only, not the registry path.
assert!(!book.collection_matches(&[0], "stick:", &lines));
assert!(book.collection_matches(&[0], "minecraft:stic", &lines));
assert!(!book.collection_matches(&[0], "other:stick", &lines));
}
#[test]
fn settings_round_trip() {
let mut s = Settings::default();
s.open[BookType::Furnace.index()] = true;
+15 -2
View File
@@ -730,7 +730,15 @@ pub fn encode_with(
let mut block_entities: Vec<Tag> = chunk
.block_entities
.iter()
.map(|(p, e)| encode_block_entity(*p, e, &block_name(p)))
.map(|(p, e)| {
let mut tag = encode_block_entity(*p, e, &block_name(p));
if let Some((_, name)) = chunk.block_names.iter().find(|(q, _)| q == p)
&& let Tag::Compound(map) = &mut tag
{
map.insert("CustomName".into(), string(name));
}
tag
})
.collect();
if let Some(extras) = extras {
for raw in &extras.block_entities {
@@ -940,7 +948,12 @@ pub fn decode_with(
if let Some(Tag::List(entities)) = tag.get("block_entities") {
for e in entities {
match decode_block_entity(e) {
Some(be) => chunk.block_entities.push(be),
Some(be) => {
if let Some(name) = text(e.get("CustomName")) {
chunk.block_names.push((be.0, name));
}
chunk.block_entities.push(be);
}
None => extras.block_entities.push(e.clone()),
}
}
+3
View File
@@ -320,6 +320,9 @@ impl Streaming {
world
.block_entities
.extend(std::mem::take(&mut chunk.block_entities));
world
.block_names
.extend(std::mem::take(&mut chunk.block_names));
let entities = std::mem::take(&mut chunk.entities);
if !entities.is_empty() {
world.loaded_entities.push(((chunk.x, chunk.z), entities));
+3
View File
@@ -26,6 +26,8 @@ pub struct World {
/// Chunks changed since the last save.
pub modified: HashSet<(i32, i32)>,
pub block_entities: HashMap<(i32, i32, i32), crate::containers::BlockEntity>,
/// `BaseContainerBlockEntity.name`: custom names of container block entities.
pub block_names: HashMap<(i32, i32, i32), String>,
/// `ChunkAccess.inhabitedTime` of resident chunks: ticks a player spent
/// within spawning range (local difficulty).
pub inhabited: HashMap<(i32, i32), i64>,
@@ -106,6 +108,7 @@ impl World {
loaded_entities: Vec::new(),
modified: HashSet::new(),
block_entities: HashMap::new(),
block_names: HashMap::new(),
inhabited: HashMap::new(),
game_time: 0,
day_time: 1000,