Recipe toasts show the crafting station and cycle through every unlocked recipe (#283)

RecipeToast keeps the station and result of each display unlocked while it
is up, draws the station at 0.6 scale in the plaque's corner over the result,
takes turns through them over the display time and stays up five more seconds
after each unlock. Toasts slide in and out on ToastInstance's squared curve,
honour notificationDisplayTime and play ui.toast.in / ui.toast.out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ludovic Marie
2026-10-15 08:55:36 +02:00
parent b5a2afb71e
commit f88bfc66f8
4 changed files with 421 additions and 74 deletions
+215 -38
View File
@@ -19,27 +19,99 @@ pub(super) struct Toast {
icon: String,
frame: Frame,
title: Text,
shown: Option<Instant>,
/// A `RecipeToast`: the icon is a recipe result.
recipe: bool,
slide: Slide,
/// A `RecipeToast`: the crafting station and result of each display
/// unlocked while it lasts (`recipeItems`); empty for an advancement.
recipes: Vec<(String, ItemStack)>,
/// `RecipeToast.changed` and `lastChanged`.
changed: bool,
last_changed: i64,
}
impl Toast {
pub(super) fn is_recipe(&self) -> bool {
self.recipe
}
pub(super) fn was_shown(&self) -> bool {
self.shown.is_some()
}
/// `RecipeToast`: "New Recipe(s) Unlocked!" with the recipe's result.
pub(super) fn recipe(icon: &str) -> Self {
/// `RecipeToast.addOrUpdate` on a new toast.
pub(super) fn recipe(items: Vec<(String, ItemStack)>) -> Self {
Self {
icon: icon.to_owned(),
icon: String::new(),
frame: Frame::Task,
title: Text::literal(""),
shown: None,
recipe: true,
slide: Slide::default(),
recipes: items,
changed: true,
last_changed: 0,
}
}
pub(super) fn is_recipe(&self) -> bool {
!self.recipes.is_empty()
}
/// `RecipeToast.addItem`: more displays on a toast still queued or shown.
pub(super) fn add_recipes(&mut self, items: Vec<(String, ItemStack)>) {
self.recipes.extend(items);
self.changed = true;
}
/// `Toast.update` with `fullyVisibleForMs`: whether it wants to be shown.
fn wants_show(&mut self, fully_for: i64, multiplier: f64) -> bool {
let time = 5000.0 * multiplier;
if self.recipes.is_empty() {
// AdvancementToast.
return (fully_for as f64) < time;
}
if self.changed {
self.last_changed = fully_for;
self.changed = false;
}
((fully_for - self.last_changed) as f64) < time
}
/// `RecipeToast.displayedRecipeIndex`: the displays take turns over the
/// toast's display time.
fn displayed_recipe(&self, fully_for: i64, multiplier: f64) -> usize {
let n = self.recipes.len() as f64;
(fully_for as f64 / (5000.0 * multiplier / n).max(1.0) % n) as usize
}
}
/// `ToastManager.ToastInstance`: slides a toast in and out over 600 ms,
/// eased by the square, and counts how long it has been fully shown.
#[derive(Default)]
struct Slide {
/// When it first updated; the times below are milliseconds since.
origin: Option<Instant>,
begun: bool,
/// `animationStartTime`.
start: i64,
/// `becameFullyVisibleAt`.
fully_at: i64,
show: bool,
/// `visiblePortion`: 0 off screen, 1 fully in.
portion: f32,
/// `fullyVisibleFor`.
fully_for: i64,
}
impl Slide {
const MS: i64 = 600;
/// `ToastInstance.update` at `now`; `wants_show` is the toast's own
/// update. The visibility it switched to (the sound to play), and whether
/// it has finished sliding out.
fn update(&mut self, now: i64, wants_show: impl FnOnce(i64) -> bool) -> (Option<bool>, bool) {
let was = self.show;
if !self.begun {
self.begun = true;
self.start = now;
self.show = true;
}
if self.show && now - self.start <= Self::MS {
self.fully_at = now;
}
self.fully_for = now - self.fully_at;
let progress = ((now - self.start) as f32 / Self::MS as f32).clamp(0.0, 1.0);
let progress = progress * progress;
self.portion = if self.show { progress } else { 1.0 - progress };
let wanted = wants_show(self.fully_for);
if wanted != self.show {
self.start = now - ((1.0 - self.portion) * Self::MS as f32) as i64;
self.show = wanted;
}
let finished = !self.show && now - self.start > Self::MS;
((self.show != was).then_some(self.show), finished)
}
}
#[derive(Default)]
pub(super) struct AdvState {
@@ -430,8 +502,10 @@ impl Game<'_> {
icon: d.icon.clone(),
frame: d.frame,
title: text_of(&d.title),
shown: None,
recipe: false,
slide: Slide::default(),
recipes: Vec::new(),
changed: false,
last_changed: 0,
});
}
if d.announce && self.ui.rules.bool("show_advancement_messages") {
@@ -679,45 +753,57 @@ impl Game<'_> {
c["from"].as_str().is_none_or(|f| f == from) && c["to"].as_str().is_none_or(|t| t == to)
});
}
/// `ToastManager` with the `AdvancementToast`.
/// `ToastManager` with the `AdvancementToast` and the `RecipeToast`,
/// one at a time.
pub(super) fn draw_toasts(&mut self, batch: &mut HudBatch) {
let multiplier = f64::from(self.settings.notification_display_time);
let Some(t) = self.adv.toasts.front_mut() else {
return;
};
let shown = *t.shown.get_or_insert_with(Instant::now);
let ms = shown.elapsed().as_millis() as f32;
// AdvancementToast.DISPLAY_TIME: 5 s, sliding 600 ms in and out.
if ms > 5600.0 {
let first = t.slide.origin.is_none();
let origin = *t.slide.origin.get_or_insert_with(Instant::now);
let now = origin.elapsed().as_millis() as i64;
let mut slide = std::mem::take(&mut t.slide);
let (sound, finished) = slide.update(now, |fully| t.wants_show(fully, multiplier));
t.slide = slide;
if finished {
self.adv.toasts.pop_front();
return;
}
let slide = if ms < 600.0 {
ms / 600.0
} else if ms > 5000.0 {
1.0 - (ms - 5000.0) / 600.0
} else {
1.0
};
let (title, frame, icon, recipe) = (t.title.clone(), t.frame, t.icon.clone(), t.recipe);
if recipe {
// RecipeToast: black description under a purple title.
let x = batch.width - 160.0 * t.slide.portion;
let fully_for = t.slide.fully_for;
let (title, frame, icon) = (t.title.clone(), t.frame, t.icon.clone());
let recipe = t
.is_recipe()
.then(|| t.recipes[t.displayed_recipe(fully_for, multiplier)].clone());
// ToastManager.update: the sound of the new visibility, and a
// challenge's own sound as it leaves the queue.
if let Some(show) = sound {
let event = if show { "ui.toast.in" } else { "ui.toast.out" };
self.audio
.play(&format!("minecraft:{event}"), None, 1.0, 1.0);
}
if first && recipe.is_none() && frame == Frame::Challenge {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
}
if let Some((station, item)) = recipe {
// RecipeToast: black description under a purple title, the
// station at 0.6 scale in the corner over the cycling result.
let atlas = &self.res.atlas;
let x = batch.width - 160.0 * slide;
batch.sprite(atlas, "gui/sprites/toast/recipe", x, 0.0);
let title = self.translate("recipe.toast.title", "New Recipe(s) Unlocked!");
let description = self.translate("recipe.toast.description", "Check your recipe book");
let atlas = &self.res.atlas;
batch.text(atlas, &title, x + 30.0, 7.0, 0xFF50_0050, false);
batch.text(atlas, &description, x + 30.0, 18.0, 0xFF00_0000, false);
self.draw_item(batch, &ItemStack::new(&icon, 1), x + 8.0, 8.0);
let start = batch.vertices.len();
self.draw_item_model(batch, &ItemStack::new(&station, 1), x + 3.0, 3.0);
batch.scale_since(start, x, 0.0, 0.6, 0.6);
self.draw_item_model(batch, &item, x + 8.0, 8.0);
return;
}
if frame == Frame::Challenge && ms < 50.0 {
self.audio
.play("minecraft:ui.toast.challenge_complete", None, 1.0, 1.0);
}
let atlas = &self.res.atlas;
let x = batch.width - 160.0 * slide;
batch.sprite(atlas, "gui/sprites/toast/advancement", x, 0.0);
let (key, color) = match frame {
Frame::Task => ("advancements.toast.task", 0xFF00_FFFF),
@@ -813,3 +899,94 @@ pub(super) fn text_of(v: &Value) -> Text {
Text::empty()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn recipes(n: usize) -> Toast {
Toast::recipe(
(0..n)
.map(|i| {
let item = ItemStack::new(&format!("minecraft:item_{i}"), 1);
("minecraft:crafting_table".to_owned(), item)
})
.collect(),
)
}
/// Drives a toast frame by frame (every `step` ms) and returns the slide
/// portions at the given times and when it finished.
fn run(toast: &mut Toast, step: i64, until: i64, at: &[i64]) -> (Vec<f32>, Option<i64>) {
let mut slide = Slide::default();
let mut seen = Vec::new();
for now in (0..=until).step_by(step as usize) {
let (_, finished) = slide.update(now, |f| toast.wants_show(f, 1.0));
if finished {
return (seen, Some(now));
}
if at.contains(&now) {
seen.push(slide.portion);
}
}
(seen, None)
}
#[test]
fn toasts_slide_in_squared_and_out_after_five_seconds() {
let mut toast = recipes(1);
let (portions, finished) = run(&mut toast, 10, 10_000, &[0, 300, 600, 3000]);
// (300 / 600)² = 0.25: ToastInstance.calculateVisiblePortion.
assert_eq!(portions, [0.0, 0.25, 1.0, 1.0]);
// Fully in at 600, shown 5000 ms, out over 600 more.
assert!(
finished.is_some_and(|t| (6200..=6220).contains(&t)),
"{finished:?}"
);
}
#[test]
fn the_first_update_plays_the_show_sound_and_the_hide_sound_follows() {
let mut toast = recipes(1);
let mut slide = Slide::default();
assert_eq!(slide.update(0, |f| toast.wants_show(f, 1.0)).0, Some(true));
assert_eq!(slide.update(100, |f| toast.wants_show(f, 1.0)).0, None);
assert_eq!(
slide.update(5600, |f| toast.wants_show(f, 1.0)).0,
Some(false)
);
}
#[test]
fn recipe_toasts_cycle_through_their_displays_over_the_display_time() {
let toast = recipes(4);
let shown: Vec<usize> = [0, 1249, 1250, 2500, 3750, 4999, 5000]
.iter()
.map(|&t| toast.displayed_recipe(t, 1.0))
.collect();
assert_eq!(shown, [0, 0, 1, 2, 3, 3, 0]);
// notificationDisplayTime doubles each turn.
assert_eq!(toast.displayed_recipe(2500, 2.0), 1);
}
#[test]
fn unlocking_more_recipes_keeps_the_toast_up_five_more_seconds() {
let mut toast = recipes(1);
let mut slide = Slide::default();
let mut finished = None;
for now in (0..=20_000).step_by(10) {
if now == 4000 {
toast.add_recipes(recipes(1).recipes);
}
if slide.update(now, |f| toast.wants_show(f, 1.0)).1 {
finished = Some(now);
break;
}
}
assert_eq!(toast.recipes.len(), 2);
// lastChanged moved to 3400 ms fully shown: hidden at 8400 + 600.
assert!(
finished.is_some_and(|t| (9600..=9620).contains(&t)),
"{finished:?}"
);
}
}
+47 -16
View File
@@ -197,28 +197,59 @@ impl Game<'_> {
search.reset_blink();
}
/// The toast for newly unlocked recipes: one for a burst of unlocks.
/// `RecipeToast.addOrUpdate` for each display of the recipes just
/// unlocked: its crafting station and result join the toast still
/// queued or shown, or a new one.
pub(super) fn recipe_toast(&mut self, recipes: &[String]) {
if recipes.is_empty() || self.adv.quiet {
return;
}
self.ensure_book();
let icon = self
.recipe_ui
.book
.as_ref()
.and_then(|b| recipes.iter().find_map(|id| b.entry(id)))
.map(|e| e.result.item.to_string());
let Some(icon) = icon else { return };
let fresh = self
.adv
.toasts
.back()
.is_some_and(|t| t.is_recipe() && !t.was_shown());
if !fresh {
self.adv
let index = &self.res.stations.recipe_index;
let book = self.recipe_ui.book.as_ref();
// SmithingTrimDemoSlotDisplay draws from a random of its own.
let mut random = super::dispenser::entity_random();
let mut items = Vec::new();
for id in recipes {
let Some(station) = index.toast_station(id) else {
continue;
};
for display in index.display_ids(id) {
// The book's displays carry their resolved results; the
// other recipe types name theirs, and trims are demos.
let result = book
.and_then(|b| {
b.entry_of_display(display)
.map(|i| b.entries[i].result.clone())
})
.or_else(|| index.result(id).map(|r| ItemStack::new(r, 1)))
.or_else(|| {
self.res.stations.recipes.trim_demo(
&self.res.stations.enchantments,
id,
&mut |n| {
horizon_core::random::RandomSource::next_int_bound(
&mut random,
n as i32,
)
.unwrap_or(0) as usize
},
)
});
if let Some(result) = result {
items.push((station.to_owned(), result));
}
}
}
if items.is_empty() {
return;
}
match self.adv.toasts.iter_mut().find(|t| t.is_recipe()) {
Some(toast) => toast.add_recipes(items),
None => self
.adv
.toasts
.push_back(super::advancements::Toast::recipe(&icon));
.push_back(super::advancements::Toast::recipe(items)),
}
}
+107 -9
View File
@@ -646,8 +646,31 @@ impl ClientBook {
/// displays it has (`RecipeManager.listDisplaysForRecipe`).
#[derive(Clone, Debug, Default)]
pub struct RecipeIndex {
/// Recipe id -> (special, display count, first display id).
recipes: std::collections::BTreeMap<String, (bool, usize, i32)>,
recipes: std::collections::BTreeMap<String, Known>,
}
#[derive(Clone, Debug)]
struct Known {
special: bool,
displays: usize,
first_display: i32,
/// `RecipeDisplay.craftingStation`: the workstation item of its displays.
station: &'static str,
/// `Recipe.showNotification`: unlocking it shows the `RecipeToast`.
notify: bool,
/// `result.id`, for the recipes the book doesn't list.
result: Option<String>,
}
/// `RecipeDisplay.craftingStation` of a recipe type.
fn crafting_station(kind: &str) -> &'static str {
match kind {
"minecraft:smelting" => "minecraft:furnace",
"minecraft:blasting" => "minecraft:blast_furnace",
"minecraft:smoking" => "minecraft:smoker",
"minecraft:campfire_cooking" => "minecraft:campfire",
"minecraft:stonecutting" => "minecraft:stonecutter",
"minecraft:smithing_transform" | "minecraft:smithing_trim" => "minecraft:smithing_table",
_ => "minecraft:crafting_table",
}
}
impl RecipeIndex {
/// Reads `data/minecraft/recipe/*.json` under `root`.
@@ -685,13 +708,23 @@ impl RecipeIndex {
} else {
1
};
recipes.insert(format!("minecraft:{stem}"), (special, displays, 0));
recipes.insert(
format!("minecraft:{stem}"),
Known {
special,
displays,
first_display: 0,
station: crafting_station(kind),
notify: v["show_notification"].as_bool().unwrap_or(true),
result: v["result"]["id"].as_str().map(str::to_owned),
},
);
}
// 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;
r.first_display = next;
next += r.displays as i32;
}
Self { recipes }
}
@@ -699,10 +732,19 @@ impl RecipeIndex {
self.recipes.contains_key(id)
}
pub fn special(&self, id: &str) -> bool {
self.recipes.get(id).is_some_and(|r| r.0)
self.recipes.get(id).is_some_and(|r| r.special)
}
pub fn displays(&self, id: &str) -> usize {
self.recipes.get(id).map_or(0, |r| r.1)
self.recipes.get(id).map_or(0, |r| r.displays)
}
/// The crafting station shown on its displays' toast, when unlocking it
/// shows one (`Recipe.showNotification`).
pub fn toast_station(&self, id: &str) -> Option<&'static str> {
self.recipes.get(id).filter(|r| r.notify).map(|r| r.station)
}
/// The result item id its file names (none for trims).
pub fn result(&self, id: &str) -> Option<&str> {
self.recipes.get(id).and_then(|r| r.result.as_deref())
}
/// Every recipe id, in id order.
pub fn ids(&self) -> impl Iterator<Item = &String> {
@@ -710,10 +752,15 @@ impl RecipeIndex {
}
/// 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)
self.recipes.get(id).map_or(0..0, |r| {
r.first_display..r.first_display + r.displays as i32
})
}
pub fn first_display(&self, id: &str) -> Option<i32> {
self.recipes.get(id).filter(|r| r.1 > 0).map(|r| r.2)
self.recipes
.get(id)
.filter(|r| r.displays > 0)
.map(|r| r.first_display)
}
}
@@ -836,6 +883,57 @@ mod tests {
Ingredient::of(items.iter().map(|s| (*s).to_owned()).collect())
}
#[test]
fn the_index_knows_each_recipes_toast_station_and_result() {
let root = std::env::temp_dir().join(format!("horizon-toast-index-{}", std::process::id()));
let dir = root.join("data/minecraft/recipe");
std::fs::create_dir_all(&dir).unwrap();
for (name, json) in [
(
"stick",
r#"{"type":"minecraft:crafting_shaped","result":{"id":"minecraft:stick"}}"#,
),
(
"crafting_table",
r#"{"type":"minecraft:crafting_shaped","show_notification":false,"result":{"id":"minecraft:crafting_table"}}"#,
),
(
"cooked_beef_from_campfire_cooking",
r#"{"type":"minecraft:campfire_cooking","result":{"id":"minecraft:cooked_beef"}}"#,
),
(
"stone_slab_from_stonecutting",
r#"{"type":"minecraft:stonecutting","result":{"id":"minecraft:stone_slab"}}"#,
),
(
"coast_trim",
r#"{"type":"minecraft:smithing_trim","pattern":"minecraft:coast"}"#,
),
] {
std::fs::write(dir.join(format!("{name}.json")), json).unwrap();
}
let index = RecipeIndex::load(&root);
std::fs::remove_dir_all(&root).unwrap();
let toast = |id: &str| (index.toast_station(id), index.result(id));
assert_eq!(
toast("minecraft:stick"),
(Some("minecraft:crafting_table"), Some("minecraft:stick"))
);
// show_notification: false unlocks silently.
assert_eq!(toast("minecraft:crafting_table").0, None);
assert_eq!(
toast("minecraft:cooked_beef_from_campfire_cooking"),
(Some("minecraft:campfire"), Some("minecraft:cooked_beef"))
);
assert_eq!(
toast("minecraft:stone_slab_from_stonecutting").0,
Some("minecraft:stonecutter")
);
assert_eq!(
toast("minecraft:coast_trim"),
(Some("minecraft:smithing_table"), None)
);
}
#[test]
fn small_recipes_are_centred_in_the_grid() {
// One ingredient in a 3x3 grid goes to the middle cell.
assert_eq!(place_cells(3, 3, 1, 1, &['a']), vec![('a', 4)]);
+52 -11
View File
@@ -437,6 +437,7 @@ pub enum Smithing {
result: String,
},
Trim {
id: String,
template: Ingredient,
base: Ingredient,
addition: Ingredient,
@@ -510,6 +511,7 @@ impl StationRecipes {
.to_owned(),
}),
"minecraft:smithing_trim" => smithing.push(Smithing::Trim {
id,
template: ingredient(&v["template"], items),
base: ingredient(&v["base"], items),
addition: ingredient(&v["addition"], items),
@@ -614,25 +616,64 @@ impl StationRecipes {
base: b,
addition: a,
pattern,
..
} => {
if t.test(template) && b.test(base) && a.test(addition) {
let material = e.props(&addition.item)?.trim_material.clone()?;
let trim = (Arc::from(material.as_str()), Arc::from(pattern.as_str()));
if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) {
return None;
}
let mut out = ItemStack {
count: 1,
..base.clone()
};
out.data_mut().trim = Some(trim);
return Some(out);
return apply_trim(e, base, addition, pattern);
}
}
}
}
None
}
/// `SmithingTrimDemoSlotDisplay.resolveForFirstStack` of a trim recipe:
/// a random base trimmed with a random material (`pick(n)` draws below n).
pub fn trim_demo(
&self,
e: &Enchantments,
id: &str,
pick: &mut dyn FnMut(usize) -> usize,
) -> Option<ItemStack> {
let (base, addition, pattern) = self.smithing.iter().find_map(|r| match r {
Smithing::Trim {
id: i,
base,
addition,
pattern,
..
} if i == id => Some((&base.1, &addition.1, pattern)),
_ => None,
})?;
if base.is_empty() || addition.is_empty() {
return None;
}
// applyDemoTransformation: up to 256 draws, the first that isn't empty.
(0..256).find_map(|_| {
let base = ItemStack::new(&base[pick(base.len())], 1);
let material = ItemStack::new(&addition[pick(addition.len())], 1);
apply_trim(e, &base, &material, pattern)
})
}
}
/// `SmithingTrimRecipe.applyTrim`: none when the material provides no trim
/// or the base already has this one.
fn apply_trim(
e: &Enchantments,
base: &ItemStack,
material: &ItemStack,
pattern: &str,
) -> Option<ItemStack> {
let material = e.props(&material.item)?.trim_material.clone()?;
let trim = (Arc::from(material.as_str()), Arc::from(pattern));
if base.data().and_then(|d| d.trim.as_ref()) == Some(&trim) {
return None;
}
let mut out = ItemStack {
count: 1,
..base.clone()
};
out.data_mut().trim = Some(trim);
Some(out)
}
#[cfg(test)]