From f88bfc66f82096347a4cb55883d931d4e1fd5d38 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 08:55:36 +0200 Subject: [PATCH 01/16] 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 --- .../horizon-client/src/game/advancements.rs | 253 +++++++++++++++--- crates/horizon-client/src/game/recipe_book.rs | 63 +++-- crates/horizon-client/src/recipe_book.rs | 116 +++++++- crates/horizon-client/src/stations.rs | 63 ++++- 4 files changed, 421 insertions(+), 74 deletions(-) diff --git a/crates/horizon-client/src/game/advancements.rs b/crates/horizon-client/src/game/advancements.rs index 02638f64f..4c5c0fbbe 100644 --- a/crates/horizon-client/src/game/advancements.rs +++ b/crates/horizon-client/src/game/advancements.rs @@ -19,27 +19,99 @@ pub(super) struct Toast { icon: String, frame: Frame, title: Text, - shown: Option, - /// 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, + 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) { + 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, Option) { + 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 = [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:?}" + ); + } +} diff --git a/crates/horizon-client/src/game/recipe_book.rs b/crates/horizon-client/src/game/recipe_book.rs index 67e79eb6a..ef4caa988 100644 --- a/crates/horizon-client/src/game/recipe_book.rs +++ b/crates/horizon-client/src/game/recipe_book.rs @@ -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)), } } diff --git a/crates/horizon-client/src/recipe_book.rs b/crates/horizon-client/src/recipe_book.rs index 6de6416c2..2caa68cac 100644 --- a/crates/horizon-client/src/recipe_book.rs +++ b/crates/horizon-client/src/recipe_book.rs @@ -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, + recipes: std::collections::BTreeMap, +} +#[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, +} +/// `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 { @@ -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 { - 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 { - 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)]); diff --git a/crates/horizon-client/src/stations.rs b/crates/horizon-client/src/stations.rs index d1582a6b8..35b02c12e 100644 --- a/crates/horizon-client/src/stations.rs +++ b/crates/horizon-client/src/stations.rs @@ -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 { + 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 { + 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)] From 6953710c74fccbde4c7d928c3a577d11e3501610 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 09:32:16 +0200 Subject: [PATCH 02/16] Blur the panorama behind the title menus' screens, as vanilla does (#282) Screen.extractBlurredBackground: every classic screen reached from the title (world selection and creation, multiplayer, options) blurs the panorama with vanilla's minecraft:blur post chain, three horizontal and vertical box blur passes of menuBackgroundBlurriness pixels, then draws menu_background over it instead of a flat dark fill. The title screen itself stays sharp. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/game.rs | 13 ++ crates/horizon-client/src/gfx.rs | 23 +++ crates/horizon-client/src/lib.rs | 1 + crates/horizon-client/src/menu_blur.rs | 249 +++++++++++++++++++++++ crates/horizon-client/src/menu_blur.wgsl | 32 +++ crates/horizon-client/src/multiplayer.rs | 2 +- crates/horizon-client/src/title.rs | 12 +- 7 files changed, 325 insertions(+), 7 deletions(-) create mode 100644 crates/horizon-client/src/menu_blur.rs create mode 100644 crates/horizon-client/src/menu_blur.wgsl diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 45068c9d6..fd4557137 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8226,6 +8226,7 @@ impl Game<'_> { } else { None }, + menu_blur: self.menu_blur(), }; let result = match self.renderer.as_mut() { Some(renderer) => horizon_client::spans::time("renderer", || renderer.render(&frame)), @@ -8235,6 +8236,18 @@ impl Game<'_> { self.entity_vertices = entities; result } + /// `Screen.extractBlurredBackground` over the panorama: every classic + /// screen of the title menus but the title itself (`TitleScreen` + /// doesn't blur), when `menuBackgroundBlurriness` is at least 1. + fn menu_blur(&self) -> Option { + let blurred = !horizon_client::ui_theme::horizon() + && self.title.as_ref().is_some_and(|t| { + self.screen == Screen::Options + || !matches!(t.mode, horizon_client::title::Mode::Main) + }); + let radius = self.settings.menu_blur as f32; + (blurred && radius >= 1.0).then_some(radius) + } /// `LevelExtractor` / `LevelRenderer`: the world border wall this frame. fn border_draw( &mut self, diff --git a/crates/horizon-client/src/gfx.rs b/crates/horizon-client/src/gfx.rs index f68ba554b..b419cbcd1 100644 --- a/crates/horizon-client/src/gfx.rs +++ b/crates/horizon-client/src/gfx.rs @@ -169,6 +169,9 @@ pub struct Frame<'a> { pub block_flicker: f32, /// Blur and grade the frame under a Horizon-style menu (`post`). pub post: Option, + /// `Screen.extractBlurredBackground`: blur the frame by this radius + /// (`menuBackgroundBlurriness`) before the screen is drawn over it. + pub menu_blur: Option, } /// One frame of the world border wall (`WorldBorderRenderer.render`). #[derive(Clone, Debug)] @@ -287,6 +290,8 @@ pub struct Renderer { pub hud: HudRenderer, /// The menus' backdrop blur, made on first use. post: Option, + /// Vanilla's menu background blur, made on first use. + menu_blur: Option, pub info: wgpu::AdapterInfo, pub suspended: bool, pub drawn_sections: usize, @@ -1432,6 +1437,7 @@ impl Renderer { world_post, hud, post: None, + menu_blur: None, info, suspended: size.width == 0 || size.height == 0, drawn_sections: 0, @@ -2397,6 +2403,23 @@ impl Renderer { pass.draw_indexed(0..6, (i * 4) as i32, 0..1); } } + if let Some(radius) = frame.menu_blur + && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) + { + let format = self.config.format; + let device = &self.device; + self.menu_blur + .get_or_insert_with(|| crate::menu_blur::MenuBlur::new(device, format)) + .apply( + &self.device, + &self.queue, + &mut encoder, + &target_texture, + &view_target, + [self.config.width, self.config.height], + radius, + ); + } if let Some(grade) = &frame.post && self.config.usage.contains(wgpu::TextureUsages::COPY_SRC) { diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index f8dd9d503..8d5d91f87 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -92,6 +92,7 @@ pub mod lang; pub mod light; pub mod logging; pub mod menu; +pub mod menu_blur; pub mod merchant; pub mod mesher; pub mod minimap; diff --git a/crates/horizon-client/src/menu_blur.rs b/crates/horizon-client/src/menu_blur.rs new file mode 100644 index 000000000..65251f678 --- /dev/null +++ b/crates/horizon-client/src/menu_blur.rs @@ -0,0 +1,249 @@ +//! Vanilla's menu background blur (`GameRenderer.processBlurEffect`, the +//! `minecraft:blur` post chain): three rounds of a horizontal then a vertical +//! `post/box_blur` pass over the frame drawn so far, `menuBackgroundBlurriness` +//! framebuffer pixels wide, before the screen is drawn over it. Works in the +//! frame's own (gamma) values, as vanilla's main target does, and needs a +//! swapchain that can be copied from. + +/// `blur.json`: the passes' directions, ping-ponging between the copied +/// frame and a swap texture; the last one writes the frame. +const PASSES: [[f32; 2]; 6] = [ + [1.0, 0.0], + [0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], + [1.0, 0.0], + [0.0, 1.0], +]; + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct Uniform { + size_dir: [f32; 4], + radius: [f32; 4], +} + +pub struct MenuBlur { + layout: wgpu::BindGroupLayout, + pipeline: wgpu::RenderPipeline, + sampler: wgpu::Sampler, + uniforms: Vec, + /// The copied frame (`minecraft:main`) and `swap`. + targets: Vec<(wgpu::Texture, wgpu::TextureView)>, + size: [u32; 2], + format: wgpu::TextureFormat, +} +impl MenuBlur { + /// `format` is the swapchain's; the blur works in its non-sRGB view. + pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> Self { + let format = format.remove_srgb_suffix(); + let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("Menu blur"), + source: wgpu::ShaderSource::Wgsl(include_str!("menu_blur.wgsl").into()), + }); + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("Menu blur bindings"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { + sample_type: wgpu::TextureSampleType::Float { filterable: true }, + view_dimension: wgpu::TextureViewDimension::D2, + multisampled: false, + }, + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 1, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering), + count: None, + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { + ty: wgpu::BufferBindingType::Uniform, + has_dynamic_offset: false, + min_binding_size: None, + }, + count: None, + }, + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("Menu blur"), + bind_group_layouts: &[Some(&layout)], + ..Default::default() + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("Menu blur pass"), + layout: Some(&pipeline_layout), + vertex: wgpu::VertexState { + module: &shader, + entry_point: Some("vs_main"), + buffers: &[], + compilation_options: Default::default(), + }, + fragment: Some(wgpu::FragmentState { + module: &shader, + entry_point: Some("fs_main"), + targets: &[Some(wgpu::ColorTargetState { + format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + compilation_options: Default::default(), + }), + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + multiview_mask: None, + cache: None, + }); + // The post chain's "bilinear": true inputs, clamped like render targets. + let sampler = device.create_sampler(&wgpu::SamplerDescriptor { + label: Some("Menu blur"), + mag_filter: wgpu::FilterMode::Linear, + min_filter: wgpu::FilterMode::Linear, + address_mode_u: wgpu::AddressMode::ClampToEdge, + address_mode_v: wgpu::AddressMode::ClampToEdge, + ..Default::default() + }); + let uniforms = PASSES + .iter() + .map(|_| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some("Menu blur pass"), + size: std::mem::size_of::() as u64, + usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }) + }) + .collect(); + Self { + layout, + pipeline, + sampler, + uniforms, + targets: Vec::new(), + size: [0, 0], + format, + } + } + fn ensure(&mut self, device: &wgpu::Device, size: [u32; 2]) { + if self.size == size && !self.targets.is_empty() { + return; + } + self.size = size; + self.targets = (0..2) + .map(|_| { + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("Menu blur target"), + size: wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: self.format, + usage: wgpu::TextureUsages::TEXTURE_BINDING + | wgpu::TextureUsages::RENDER_ATTACHMENT + | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + let view = texture.create_view(&Default::default()); + (texture, view) + }) + .collect(); + } + /// Blur `frame` (the swapchain texture) in place through `target`, its + /// non-sRGB view, by `radius` pixels (`menuBackgroundBlurriness`). + #[allow(clippy::too_many_arguments)] + pub fn apply( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + encoder: &mut wgpu::CommandEncoder, + frame: &wgpu::Texture, + target: &wgpu::TextureView, + size: [u32; 2], + radius: f32, + ) { + self.ensure(device, size); + encoder.copy_texture_to_texture( + frame.as_image_copy(), + self.targets[0].0.as_image_copy(), + wgpu::Extent3d { + width: size[0], + height: size[1], + depth_or_array_layers: 1, + }, + ); + for (i, dir) in PASSES.iter().enumerate() { + let data = Uniform { + size_dir: [size[0] as f32, size[1] as f32, dir[0], dir[1]], + radius: [radius, 0.0, 0.0, 0.0], + }; + queue.write_buffer(&self.uniforms[i], 0, bytemuck::bytes_of(&data)); + let source = &self.targets[i % 2].1; + let output = if i + 1 == PASSES.len() { + target + } else { + &self.targets[(i + 1) % 2].1 + }; + let group = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("Menu blur pass"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: wgpu::BindingResource::TextureView(source), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: wgpu::BindingResource::Sampler(&self.sampler), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.uniforms[i].as_entire_binding(), + }, + ], + }); + let attachments = [Some(wgpu::RenderPassColorAttachment { + view: output, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { + load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), + store: wgpu::StoreOp::Store, + }, + })]; + let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("Menu blur pass"), + color_attachments: &attachments, + ..Default::default() + }); + pass.set_pipeline(&self.pipeline); + pass.set_bind_group(0, &group, &[]); + pass.draw(0..3, 0..1); + } + } +} + +#[cfg(test)] +mod tests { + #[test] + fn box_blur_shader_validates() { + let module = naga::front::wgsl::parse_str(include_str!("menu_blur.wgsl")).unwrap(); + naga::valid::Validator::new( + naga::valid::ValidationFlags::all(), + naga::valid::Capabilities::all(), + ) + .validate(&module) + .unwrap(); + } +} diff --git a/crates/horizon-client/src/menu_blur.wgsl b/crates/horizon-client/src/menu_blur.wgsl new file mode 100644 index 000000000..d8b15fa94 --- /dev/null +++ b/crates/horizon-client/src/menu_blur.wgsl @@ -0,0 +1,32 @@ +// Vanilla's post/box_blur.fsh: one direction of a box blur of 2·Radius + 1 +// pixels, reading two pixels per linear sample. +struct Blur { + // InSize (pixels), BlurDir. + size_dir: vec4, + // Radius, unused, unused, unused. + radius: vec4, +} +@group(0) @binding(0) var src: texture_2d; +@group(0) @binding(1) var samp: sampler; +@group(0) @binding(2) var blur: Blur; +struct Out { + @builtin(position) clip: vec4, + @location(0) uv: vec2, +} +@vertex fn vs_main(@builtin(vertex_index) i: u32) -> Out { + let p = vec2(f32((i << 1u) & 2u), f32(i & 2u)); + var out: Out; + out.clip = vec4(p * 2.0 - 1.0, 0.0, 1.0); + out.uv = vec2(p.x, 1.0 - p.y); + return out; +} +@fragment fn fs_main(in: Out) -> @location(0) vec4 { + let step = blur.size_dir.zw / blur.size_dir.xy; + let radius = round(blur.radius.x); + var blurred = vec4(0.0); + for (var a = -radius + 0.5; a <= radius; a += 2.0) { + blurred += textureSampleLevel(src, samp, in.uv + step * a, 0.0); + } + blurred += textureSampleLevel(src, samp, in.uv + step * radius, 0.0) / 2.0; + return blurred / (radius + 0.5); +} diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 9e7023391..1936c8ace 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -314,7 +314,7 @@ impl Screen { } pub fn draw(&self, atlas: &HudAtlas, batch: &mut HudBatch, blink: bool) { let (w, h) = (batch.width, batch.height); - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let centered = |batch: &mut HudBatch, text: &str, y: f32, color: u32| { let tw = HudBatch::text_width(atlas, text); batch.text(atlas, text, (w - tw) / 2.0, y, color, true); diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index d680b32ab..1cd57f00d 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -765,7 +765,7 @@ impl Title { batch.text(atlas, notice, w - tw - 2.0, h - 10.0, u32::MAX, true); } Mode::Select { worlds, selected } => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); centered(atlas, batch, "Select World", 8.0, u32::MAX); text_field( atlas, @@ -908,7 +908,7 @@ impl Title { Mode::Create { name, seed, focus, .. } => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let title = "Create New World"; let tw = HudBatch::text_width(atlas, title); batch.text(atlas, title, (w - tw) / 2.0, 8.0, u32::MAX, true); @@ -972,7 +972,7 @@ impl Title { } } Mode::Edit { name, focused, .. } => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); centered( atlas, batch, @@ -999,7 +999,7 @@ impl Title { ); } Mode::Delete { world } => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let message = translate( "selectWorld.deleteWarning", "'%s' will be lost forever! (A long time!)", @@ -1024,7 +1024,7 @@ impl Title { } Mode::Backup { .. } => { self.backup_shown.set(true); - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); centered( atlas, batch, @@ -1050,7 +1050,7 @@ impl Title { } } Mode::Error { message, .. } => { - batch.fill(atlas, 0.0, 0.0, w, h, rgba(0, 0, 0, 120)); + crate::ui::menu_background(batch, atlas, 0.0, 0.0, w, h, false); let lines = wrapped(atlas, message, w - 50.0); self.message_lines.set(lines.len()); let top = confirm_top(h, lines.len()); From 587695e108d4fc21f5922ef7518613552a6649ea Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 09:48:14 +0200 Subject: [PATCH 03/16] Multiplayer: vanilla's server list, with the LAN scanning header and its dots (#282) JoinMultiplayerScreen's layout: the title centred in the 33-pixel header, the ServerSelectionList between the separators (list background, 305-wide rows, white selection outline, scissored rows, the scroller sprites), the footer buttons centred in 60 pixels. The list always ends with the LAN header, "Scanning for games on your local network" over LoadingDotsText's dots, then the LAN games. Saved servers show two MOTD lines, the player count and the ping, pinging or unreachable icon; Edit and Delete need a saved server. The list scrolls with the wheel and a draggable scrollbar (ui::Scroll, after AbstractScrollArea). Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/front.rs | 1 + crates/horizon-client/src/game.rs | 14 + crates/horizon-client/src/multiplayer.rs | 573 +++++++++++++++++------ crates/horizon-client/src/title.rs | 18 +- crates/horizon-client/src/ui.rs | 83 ++++ 5 files changed, 538 insertions(+), 151 deletions(-) diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 72b70a56b..828402944 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -814,6 +814,7 @@ fn multiplayer_page(ui: &mut Ui, x: f32, w: f32, screen: &Screen, caret: bool) { selected, pings, lan, + .. } => { let games = lan.games(); let sub = match servers.len() { diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index fd4557137..6c456a71f 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -8673,6 +8673,11 @@ impl ApplicationHandler for Game<'_> { if self.screen == Screen::Inventory || self.creative_inventory_open() { self.inventory_drag_move(); } + if let Some(title) = &mut self.title + && !horizon_client::ui_theme::horizon() + { + title.drag(self.cursor, (b.width, b.height)); + } if self.dragging && self.screen == Screen::Options { let _ = b; self.options_drag()?; @@ -8748,6 +8753,15 @@ impl ApplicationHandler for Game<'_> { )?; } } + WindowEvent::MouseInput { + state: ElementState::Released, + button: MouseButton::Left, + .. + } if self.title.is_some() && self.screen != Screen::Options => { + if let Some(title) = &mut self.title { + title.release(); + } + } WindowEvent::MouseInput { state, button: MouseButton::Left, diff --git a/crates/horizon-client/src/multiplayer.rs b/crates/horizon-client/src/multiplayer.rs index 1936c8ace..a13bc7063 100644 --- a/crates/horizon-client/src/multiplayer.rs +++ b/crates/horizon-client/src/multiplayer.rs @@ -34,6 +34,7 @@ pub enum Screen { pings: Pings, /// Worlds announced on the local network, listed after the servers. lan: Scanner, + scroll: crate::ui::Scroll, }, /// Add (index None) or edit a server entry. Edit { @@ -117,6 +118,60 @@ fn entry_address(servers: &[ServerEntry], lan: &Scanner, index: usize) -> Option } } +/// JoinMultiplayerScreen's `HeaderAndFooterLayout(33, 60)`. +const HEADER: f32 = 33.0; +const FOOTER: f32 = 60.0; +/// ServerSelectionList: rows 305 wide and 36 high. +const ROW_WIDTH: f32 = 305.0; +const ROW_HEIGHT: f32 = 36.0; +/// One row of the list: the saved servers, the LAN header, the LAN games. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Row { + Server(usize), + LanHeader, + Lan(usize), +} +/// The list's top and bottom and its rows' left edge (`getRowLeft`). +fn list_area(w: f32, h: f32) -> (f32, f32, f32) { + ( + HEADER, + h - FOOTER, + (w / 2.0).floor() - (ROW_WIDTH / 2.0).floor(), + ) +} +fn rows(servers: usize, lan: usize) -> impl Iterator { + (0..servers) + .map(Row::Server) + .chain(std::iter::once(Row::LanHeader)) + .chain((0..lan).map(Row::Lan)) +} +/// `contentHeight`: the rows and 4 pixels of padding. +fn content_height(servers: usize, lan: usize) -> f32 { + (servers + 1 + lan) as f32 * ROW_HEIGHT + 4.0 +} +/// The row under `(x, y)` (`getEntryAtPosition`), scrolled by `scroll`. +fn row_at( + servers: usize, + lan: usize, + (x, y): (f32, f32), + size: (f32, f32), + scroll: f32, +) -> Option { + let (top, bottom, left) = list_area(size.0, size.1); + if y < top || y >= bottom || x < left || x >= left + ROW_WIDTH { + return None; + } + let index = ((y - top - 2.0 + scroll.trunc()) / ROW_HEIGHT).floor(); + if index < 0.0 { + return None; + } + rows(servers, lan).nth(index as usize) +} +/// `LoadingDotsText.get`. +fn loading_dots(millis: u128) -> &'static str { + ["O o o", "o O o", "o o O", "o O o"][(millis / 300 % 4) as usize] +} + impl Screen { /// The address of list row `row` (saved servers, then LAN games). pub fn address_of(&self, row: usize) -> Option { @@ -134,6 +189,7 @@ impl Screen { selected: None, pings, lan: Scanner::start(), + scroll: crate::ui::Scroll::default(), } } pub fn buttons(&self, w: f32, h: f32) -> Vec { @@ -141,44 +197,75 @@ impl Screen { (x, y, bw, label.to_owned(), enabled, id) }; match self { - // JoinMultiplayerScreen's two button rows. - Self::List { selected, .. } => vec![ - b( - w / 2.0 - 154.0, - h - 52.0, - 100.0, - "Join Server", - selected.is_some(), - 40, - ), - b( - w / 2.0 - 50.0, - h - 52.0, - 100.0, - "Direct Connection", - true, - 41, - ), - b(w / 2.0 + 54.0, h - 52.0, 100.0, "Add Server", true, 42), - b( - w / 2.0 - 154.0, - h - 28.0, - 74.0, - "Edit", - selected.is_some(), - 43, - ), - b( - w / 2.0 - 76.0, - h - 28.0, - 74.0, - "Delete", - selected.is_some(), - 44, - ), - b(w / 2.0 + 2.0, h - 28.0, 74.0, "Refresh", true, 45), - b(w / 2.0 + 80.0, h - 28.0, 74.0, "Back", true, 46), - ], + // JoinMultiplayerScreen's footer: two rows of buttons, 4 apart, + // centred in the 60-pixel footer. Join needs a server or LAN game + // selected (onSelectedChange), Edit and Delete a saved server. + Self::List { + servers, selected, .. + } => { + let (w, h) = (w.ceil(), h.ceil()); + let x = ((w - 308.0) / 2.0).floor(); + let saved = selected.is_some_and(|i| i < servers.len()); + let label = |key: &str, fallback: &str| crate::lang::get_or(key, fallback); + vec![ + b( + x, + h - 52.0, + 100.0, + &label("selectServer.select", "Join Server"), + selected.is_some(), + 40, + ), + b( + x + 104.0, + h - 52.0, + 100.0, + &label("selectServer.direct", "Direct Connection"), + true, + 41, + ), + b( + x + 208.0, + h - 52.0, + 100.0, + &label("selectServer.add", "Add Server"), + true, + 42, + ), + b( + x, + h - 28.0, + 74.0, + &label("selectServer.edit", "Edit"), + saved, + 43, + ), + b( + x + 78.0, + h - 28.0, + 74.0, + &label("selectServer.delete", "Delete"), + saved, + 44, + ), + b( + x + 156.0, + h - 28.0, + 74.0, + &label("selectServer.refresh", "Refresh"), + true, + 45, + ), + b( + x + 234.0, + h - 28.0, + 74.0, + &label("gui.back", "Back"), + true, + 46, + ), + ] + } Self::Edit { address, .. } => vec![ b( w / 2.0 - 100.0, @@ -325,121 +412,205 @@ impl Screen { selected, pings, lan, + scroll, } => { - centered(batch, "Play Multiplayer", 8.0, u32::MAX); - batch.fill(atlas, 0.0, 32.0, w, h - 32.0 - 64.0, rgba(0, 0, 0, 100)); + let (w, h) = (w.ceil(), h.ceil()); + let title = crate::lang::get_or("multiplayer.title", "Play Multiplayer"); + // The header's StringWidget, centred in its 33 pixels. + let tw = HudBatch::text_width(atlas, &title); + let tx = ((w - tw.ceil()) / 2.0).floor(); + batch.text( + atlas, + &title, + tx, + ((HEADER - 9.0) / 2.0).floor(), + u32::MAX, + true, + ); + let games = lan.games(); + let (top, bottom, left) = list_area(w, h); + let content = content_height(servers.len(), games.len()); + let mut scroll = *scroll; + scroll.clamp(top, bottom, content); + // AbstractSelectionList.extractWidgetRenderState: background, + // the rows clipped to the list, separators, scrollbar. + crate::ui::list_background(batch, atlas, top, bottom, false); + let first = batch.vertices.len(); let pings = pings.lock().unwrap(); - for (i, server) in servers.iter().enumerate() { - let y = 36.0 + i as f32 * 36.0; - if y + 36.0 > h - 64.0 { - break; + let millis = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map_or(0, |d| d.as_millis()); + let gray = rgba(128, 128, 128, 255); + for (i, row) in rows(servers.len(), games.len()).enumerate() { + let y = top + 2.0 - scroll.amount.trunc() + i as f32 * ROW_HEIGHT; + if y + ROW_HEIGHT < top || y > bottom { + continue; } - let x = w / 2.0 - 152.0; - crate::widgets::target_as( - [x - 2.0, y - 2.0, 306.0, 36.0], - crate::widgets::Kind::Row, - ); - if *selected == Some(i) { - batch.fill( - atlas, - x - 2.0, - y - 2.0, - 306.0, - 36.0, - rgba(128, 128, 128, 255), - ); - batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); - } - batch.sprite_scaled(atlas, "misc/unknown_server", x, y, 32.0, 32.0, u32::MAX); - batch.text(atlas, &server.name, x + 35.0, y + 1.0, u32::MAX, false); - let (line, right, color) = match pings.get(&server.ip) { - Some(Ping::Ok { - motd, players, ms, .. - }) => ( - motd.lines().next().unwrap_or("").to_owned(), - format!("{players} {ms} ms"), - rgba(128, 128, 128, 255), - ), - Some(Ping::Failed(_)) => ( - "Can't connect to server".to_owned(), - String::new(), - rgba(170, 0, 0, 255), - ), - _ => ( - "Pinging...".to_owned(), - String::new(), - rgba(128, 128, 128, 255), - ), + let index = match row { + Row::Server(k) => Some(k), + Row::Lan(k) => Some(servers.len() + k), + Row::LanHeader => None, }; - batch.text(atlas, &line, x + 35.0, y + 12.0, color, false); - batch.text( - atlas, - &server.ip, - x + 35.0, - y + 22.0, - rgba(96, 96, 96, 255), - false, - ); - if !right.is_empty() { - let tw = HudBatch::text_width(atlas, &right); - batch.text( - atlas, - &right, - x + 300.0 - tw, - y + 1.0, - rgba(128, 128, 128, 255), - false, + if index.is_some() + && y + ROW_HEIGHT / 2.0 > top + && y + ROW_HEIGHT / 2.0 < bottom + { + crate::widgets::target_as( + [left, y, ROW_WIDTH, ROW_HEIGHT], + crate::widgets::Kind::Row, ); } - } - for (k, game) in lan.games().iter().enumerate() { - let i = servers.len() + k; - let y = 36.0 + i as f32 * 36.0; - if y + 36.0 > h - 64.0 { - break; - } - let x = w / 2.0 - 152.0; - crate::widgets::target_as( - [x - 2.0, y - 2.0, 306.0, 36.0], - crate::widgets::Kind::Row, - ); - if *selected == Some(i) { + // extractSelection: a white outline round black (the list + // has focus once a row is clicked). + if index.is_some() && *selected == index { + batch.fill(atlas, left, y, ROW_WIDTH, ROW_HEIGHT, u32::MAX); batch.fill( atlas, - x - 2.0, - y - 2.0, - 306.0, - 36.0, - rgba(128, 128, 128, 255), + left + 1.0, + y + 1.0, + ROW_WIDTH - 2.0, + ROW_HEIGHT - 2.0, + rgba(0, 0, 0, 255), ); - batch.fill(atlas, x - 1.0, y - 1.0, 304.0, 34.0, rgba(0, 0, 0, 255)); } - batch.text(atlas, "LAN World", x + 35.0, y + 1.0, u32::MAX, false); - batch.text( - atlas, - &game.motd, - x + 35.0, - y + 12.0, - rgba(128, 128, 128, 255), - false, - ); - batch.text( - atlas, - &game.address, - x + 35.0, - y + 22.0, - rgba(96, 96, 96, 255), - false, - ); - } - if servers.is_empty() { - centered( - batch, - "No servers yet: add one or use Direct Connection", - h / 2.0 - 20.0, - rgba(160, 160, 160, 255), - ); + // Entry content: 2 pixels in from the row. + let (cx, cy) = (left + 2.0, y + 2.0); + match row { + Row::Server(k) => { + let server = &servers[k]; + batch.sprite_scaled( + atlas, + "misc/unknown_server", + cx, + cy, + 32.0, + 32.0, + u32::MAX, + ); + batch.text(atlas, &server.name, cx + 35.0, cy + 1.0, u32::MAX, false); + // OnlineServerEntry: up to two lines of MOTD, the + // player count left of the status icon. + let (motd, status, motd_color, icon) = match pings.get(&server.ip) { + Some(Ping::Ok { + motd, players, ms, .. + }) => ( + motd.clone(), + players.clone(), + gray, + format!( + "server_list/ping_{}", + match ms { + 0..150 => 5, + 150..300 => 4, + 300..600 => 3, + 600..1000 => 2, + _ => 1, + } + ), + ), + Some(Ping::Failed(_)) => ( + crate::lang::get_or( + "multiplayer.status.cannot_connect", + "Can't connect to server", + ), + String::new(), + rgba(255, 0, 0, 255), + "server_list/unreachable".to_owned(), + ), + _ => { + // The pinging bars bounce, offset by the row. + let frame = (millis / 100 + i as u128 * 2) & 7; + let frame = if frame > 4 { 8 - frame } else { frame }; + ( + crate::lang::get_or( + "multiplayer.status.pinging", + "Pinging...", + ), + String::new(), + gray, + format!("server_list/pinging_{}", frame + 1), + ) + } + }; + for (n, line) in wrap(&motd, ROW_WIDTH - 4.0 - 34.0, atlas) + .iter() + .take(2) + .enumerate() + { + batch.text( + atlas, + line, + cx + 35.0, + cy + 12.0 + 9.0 * n as f32, + motd_color, + false, + ); + } + let icon_x = cx + ROW_WIDTH - 4.0 - 15.0; + batch.sprite_scaled( + atlas, + &format!("gui/sprites/{icon}"), + icon_x, + cy, + 10.0, + 8.0, + u32::MAX, + ); + if !status.is_empty() { + let sw = HudBatch::text_width(atlas, &status).ceil(); + batch.text( + atlas, + &status, + icon_x - sw - 5.0, + cy + 1.0, + gray, + false, + ); + } + } + Row::LanHeader => { + // LANHeader's LoadingDotsWidget: the label, then + // the dots on its last line, both centred. + let label = crate::lang::get_or( + "lanServer.scanning", + "Scanning for games on your local network", + ); + let middle = cx + ((ROW_WIDTH - 4.0) / 2.0).floor(); + let lw = HudBatch::text_width(atlas, &label).ceil(); + let lx = middle - (lw / 2.0).floor(); + let centre = lx + (lw / 2.0).floor(); + batch.text(atlas, &label, lx, cy + 2.0, u32::MAX, false); + let dots = loading_dots(millis); + let dw = HudBatch::text_width(atlas, dots).ceil(); + batch.text( + atlas, + dots, + centre - (dw / 2.0).floor(), + cy + 28.0 - 9.0 - 2.0, + gray, + false, + ); + } + Row::Lan(k) => { + let game = &games[k]; + let header = crate::lang::get_or("lanServer.title", "LAN World"); + batch.text(atlas, &header, cx + 35.0, cy + 1.0, u32::MAX, false); + batch.text(atlas, &game.motd, cx + 35.0, cy + 12.0, gray, false); + batch.text(atlas, &game.address, cx + 35.0, cy + 23.0, gray, false); + } + } } + batch.clip_since(first, 0.0, top, w, bottom); + crate::ui::separators(batch, atlas, top, bottom, false); + crate::ui::scrollbar( + batch, + atlas, + left + ROW_WIDTH + 8.0, + top, + bottom, + content, + scroll.amount, + ); } Self::Edit { index, @@ -583,19 +754,36 @@ impl Screen { servers, selected, lan, + scroll, .. }, None, ) => { - let index = ((y - 36.0) / 36.0).floor(); - if y >= 36.0 && y < h - 64.0 && (x - w / 2.0).abs() < 154.0 { - let index = index as usize; - if let Some(address) = entry_address(servers, lan, index) { - if *selected == Some(index) { - return Outcome::Connect(address); - } - *selected = Some(index); + let (w, h) = (w.ceil(), h.ceil()); + let games = lan.games().len(); + let (top, bottom, left) = list_area(w, h); + let content = content_height(servers.len(), games); + if scroll.press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) { + return Outcome::None; + } + // Clicking a selected row again joins it; the LAN header + // takes the click without anything to join. + let index = match row_at(servers.len(), games, (x, y), (w, h), scroll.amount) { + Some(Row::Server(k)) => Some(k), + Some(Row::Lan(k)) => Some(servers.len() + k), + Some(Row::LanHeader) => { + *selected = None; + None } + None => None, + }; + if let Some(index) = index + && let Some(address) = entry_address(servers, lan, index) + { + if *selected == Some(index) { + return Outcome::Connect(address); + } + *selected = Some(index); } } ( @@ -648,6 +836,45 @@ impl Screen { } Outcome::None } + /// The mouse wheel over the server list (`scrollRate`: half a row). + pub fn wheel(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Self::List { + servers, + lan, + scroll, + .. + } = self + { + let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil()); + if cursor.1 >= top && cursor.1 < bottom { + let content = content_height(servers.len(), lan.games().len()); + scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content); + } + } + } + /// The pointer moved: a held scrollbar follows it. + pub fn drag(&mut self, y: f32, size: (f32, f32)) { + if let Self::List { + servers, + lan, + scroll, + .. + } = self + { + let (top, bottom, _) = list_area(size.0.ceil(), size.1.ceil()); + scroll.drag( + y, + top, + bottom, + content_height(servers.len(), lan.games().len()), + ); + } + } + pub fn release(&mut self) { + if let Self::List { scroll, .. } = self { + scroll.release(); + } + } fn focused_field(&mut self) -> Option<&mut String> { match self { Self::Edit { @@ -756,3 +983,49 @@ pub fn wrap(text: &str, width: f32, atlas: &HudAtlas) -> Vec { } lines } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_lan_header_follows_the_saved_servers() { + let all: Vec = rows(2, 1).collect(); + assert_eq!( + all, + [Row::Server(0), Row::Server(1), Row::LanHeader, Row::Lan(0)] + ); + // No saved servers: the list is the scanning header alone. + assert_eq!(rows(0, 0).collect::>(), [Row::LanHeader]); + assert_eq!(content_height(0, 0), 40.0); + } + + #[test] + fn rows_sit_two_pixels_under_the_header_and_scroll_with_the_list() { + // 427x240 GUI: the list spans 33..180, rows 305 wide from x 61. + let size = (427.0, 240.0); + assert_eq!(list_area(size.0, size.1), (33.0, 180.0, 61.0)); + assert_eq!(row_at(3, 0, (100.0, 35.0), size, 0.0), Some(Row::Server(0))); + assert_eq!(row_at(3, 0, (100.0, 70.9), size, 0.0), Some(Row::Server(0))); + assert_eq!(row_at(3, 0, (100.0, 71.0), size, 0.0), Some(Row::Server(1))); + assert_eq!( + row_at(3, 0, (100.0, 35.0), size, 36.0), + Some(Row::Server(1)) + ); + assert_eq!( + row_at(3, 0, (100.0, 143.0), size, 0.0), + Some(Row::LanHeader) + ); + assert_eq!(row_at(3, 0, (60.0, 40.0), size, 0.0), None); + assert_eq!(row_at(3, 0, (100.0, 32.0), size, 0.0), None); + } + + #[test] + fn loading_dots_step_every_300_ms() { + let frames: Vec<&str> = [0, 299, 300, 600, 900, 1200].map(loading_dots).to_vec(); + assert_eq!( + frames, + ["O o o", "O o o", "o O o", "o o O", "o O o", "O o o"] + ); + } +} diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 1cd57f00d..97f460fba 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -324,8 +324,24 @@ impl Title { .collect::>() .into_iter() } - /// Mouse wheel over the classic world list. + /// The pointer moved with the button held (`mouseDragged`). + pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.drag(cursor.1, size); + } + } + /// The button was released (`onRelease`). + pub fn release(&mut self) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.release(); + } + } + /// Mouse wheel over the classic world and server lists. pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { + if let Mode::Multiplayer(screen) = &mut self.mode { + screen.wheel(delta, cursor, size); + return; + } let Mode::Select { worlds, .. } = &self.mode else { return; }; diff --git a/crates/horizon-client/src/ui.rs b/crates/horizon-client/src/ui.rs index e5740616e..44d208a69 100644 --- a/crates/horizon-client/src/ui.rs +++ b/crates/horizon-client/src/ui.rs @@ -430,6 +430,67 @@ pub(crate) fn scrollbar_thumb( Some((y, bar)) } +/// `AbstractScrollArea`'s scrolling of a list `top..bottom` holding `content` +/// pixels: the amount, the mouse wheel and the held scrollbar. +#[derive(Clone, Copy, Debug, Default)] +pub struct Scroll { + pub amount: f32, + /// The pointer's last y while the scrollbar is held (`scrolling`). + held: Option, +} +impl Scroll { + fn max(top: f32, bottom: f32, content: f32) -> f32 { + (content - (bottom - top)).max(0.0) + } + /// `setScrollAmount`: kept within the content. + pub fn clamp(&mut self, top: f32, bottom: f32, content: f32) { + self.amount = self.amount.clamp(0.0, Self::max(top, bottom, content)); + } + /// `mouseScrolled`: `rate` pixels per wheel step. + pub fn wheel(&mut self, delta: f32, rate: f32, top: f32, bottom: f32, content: f32) { + self.amount -= delta * rate; + self.clamp(top, bottom, content); + } + /// `updateScrolling`: a press on the scrollbar column at `bar_x` (when + /// there is something to scroll) holds it. + pub fn press( + &mut self, + (x, y): (f32, f32), + bar_x: f32, + top: f32, + bottom: f32, + content: f32, + ) -> bool { + let over = x >= bar_x && x <= bar_x + 6.0 && y >= top && y < bottom; + self.held = (over && Self::max(top, bottom, content) > 0.0).then_some(y); + self.held.is_some() + } + pub fn held(&self) -> bool { + self.held.is_some() + } + /// `mouseDragged` while held: above or below the list jumps to an end, + /// otherwise the thumb follows the pointer. + pub fn drag(&mut self, y: f32, top: f32, bottom: f32, content: f32) { + let Some(last) = self.held else { return }; + let max = Self::max(top, bottom, content); + if y < top { + self.amount = 0.0; + } else if y > bottom { + self.amount = max; + } else { + let height = bottom - top; + let bar = ((height * height / content).trunc()).clamp(32.0, height - 8.0); + self.amount += (y - last) * (max.max(1.0) / (height - bar)).max(1.0); + } + self.clamp(top, bottom, content); + self.held = Some(y); + } + /// `onRelease`. + pub fn release(&mut self) { + self.held = None; + } +} + /// Vertical scroll bar (AbstractScrollArea): background and scroller sprites. pub fn scrollbar( batch: &mut HudBatch, @@ -874,6 +935,28 @@ impl EditBox { mod tests { use super::*; #[test] + fn held_scrollbars_follow_the_pointer_and_stop_at_the_ends() { + // A 100-pixel list holding 400: the thumb is 25 -> 32 high, so a + // pixel of drag scrolls 300 / 68 pixels (AbstractScrollArea.mouseDragged). + let (top, bottom, content) = (0.0, 100.0, 400.0); + let mut s = Scroll::default(); + assert!(!s.press((50.0, 10.0), 100.0, top, bottom, content)); + assert!(s.press((103.0, 10.0), 100.0, top, bottom, content)); + s.drag(20.0, top, bottom, content); + assert!((s.amount - 10.0 * 300.0 / 68.0).abs() < 1e-3); + s.drag(150.0, top, bottom, content); + assert_eq!(s.amount, 300.0); + s.drag(-5.0, top, bottom, content); + assert_eq!(s.amount, 0.0); + s.release(); + s.drag(50.0, top, bottom, content); + assert_eq!(s.amount, 0.0); + // Nothing to scroll: the column doesn't take the press. + assert!(!s.press((103.0, 10.0), 100.0, top, bottom, 90.0)); + s.wheel(-2.0, 18.0, top, bottom, content); + assert_eq!(s.amount, 36.0); + } + #[test] fn edit_box_editing() { let mut e = EditBox::new(0.0, 0.0, 100.0, 20.0); e.max_length = 10; From a8bd497132388f045874beb4486fbb8f07c83791 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:04:37 +0200 Subject: [PATCH 04/16] World list and pack lists: vanilla scroller, dragged with the pointer SelectWorldScreen's list now sits at vanilla's 49..h-60 with the list background, header and footer separators, white selection outline and the widget/scroller sprites at the row's right + 8. The scroller follows the pointer while held (AbstractScrollArea.mouseDragged), the wheel moves half a row, and the pack screen's lists can be dragged the same way. Part of #282 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/options_ui.rs | 9 +- crates/horizon-client/src/pack_screen.rs | 39 ++++++- crates/horizon-client/src/title.rs | 133 ++++++++++++----------- crates/horizon-client/src/title/tests.rs | 25 ++++- 4 files changed, 140 insertions(+), 66 deletions(-) diff --git a/crates/horizon-client/src/options_ui.rs b/crates/horizon-client/src/options_ui.rs index 4b447663a..8d67dcc04 100644 --- a/crates/horizon-client/src/options_ui.rs +++ b/crates/horizon-client/src/options_ui.rs @@ -1699,7 +1699,11 @@ impl OptionsUi { } if self.page() == Page::Packs { let mut events = Vec::new(); - if drag || right { + if drag { + self.packs(atlas, size).drag(y as f64); + return events; + } + if right { return events; } let m = crate::screen_draw::Measure(&atlas.font); @@ -1862,6 +1866,9 @@ impl OptionsUi { } pub fn release(&mut self) -> Vec { self.scrollbar_drag_y = None; + if let Some(p) = &mut self.pack_screen { + p.release(); + } // AbstractSliderButton suppresses the press sound and plays once on // release, even if the pointer has left the widget or its value stayed. let slider = self.dragging.take().is_some(); diff --git a/crates/horizon-client/src/pack_screen.rs b/crates/horizon-client/src/pack_screen.rs index a96ea3072..934ecaf95 100644 --- a/crates/horizon-client/src/pack_screen.rs +++ b/crates/horizon-client/src/pack_screen.rs @@ -136,6 +136,8 @@ struct List { selected: Option, /// The list has a focused child (possibly an entry it no longer holds). focused: bool, + /// The pointer's last y while the scrollbar is held (`scrolling`). + held: Option, } impl List { fn new(selected_side: bool, height: i32) -> Self { @@ -149,6 +151,7 @@ impl List { entries: Vec::new(), selected: None, focused: false, + held: None, } } fn bottom(&self) -> i32 { @@ -244,6 +247,21 @@ impl List { fn scroller_height(&self) -> i32 { ((self.height * self.height) as f32 / self.content_height() as f32) as i32 } + /// `AbstractScrollArea.mouseDragged` while the scrollbar is held. + fn drag(&mut self, y: f64) { + let Some(last) = self.held else { return }; + if y < self.y as f64 { + self.set_scroll(0.0); + } else if y > self.bottom() as f64 { + self.set_scroll(self.max_scroll() as f64); + } else { + let max = self.max_scroll().max(1) as f64; + let bar = self.scroller_height().clamp(32, self.height - 8); + let scale = (max / (self.height - bar) as f64).max(1.0); + self.set_scroll(self.scroll + (y - last) * scale); + } + self.held = Some(y); + } } #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -490,6 +508,13 @@ impl PackScreen { && x <= (l.scroll_bar_x() + 6) as f64 && y >= l.y as f64 && y < l.bottom() as f64; + // updateScrolling: a press on the scroller holds it. + if scrolling { + self.lists[side].held = Some(y); + self.set_focus(Focus::List(side)); + return Action::None; + } + let l = &self.lists[side]; let hit = l.entry_at(x as i32, y as i32); let mut took = false; if let Some(i) = hit { @@ -516,7 +541,7 @@ impl PackScreen { } } } - if took || scrolling { + if took { self.set_focus(Focus::List(side)); } return Action::None; @@ -669,6 +694,18 @@ impl PackScreen { false } /// The mouse wheel (`AbstractScrollArea.mouseScrolled`). + /// The pointer moved with the button held: a held scrollbar follows it. + pub fn drag(&mut self, y: f64) { + for l in &mut self.lists { + l.drag(y); + } + } + /// `onRelease`. + pub fn release(&mut self) { + for l in &mut self.lists { + l.held = None; + } + } pub fn scroll(&mut self, x: f64, y: f64, amount: f64) { if self.confirm.is_some() || self.search.contains(x, y) { return; diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 97f460fba..52dfba28a 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -16,8 +16,9 @@ use std::{ mod tests; mod world_management; -const LIST_TOP: f32 = 48.0; -const LIST_BOTTOM: f32 = 58.0; +/// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`. +const LIST_TOP: f32 = 49.0; +const LIST_BOTTOM: f32 = 60.0; const ROW_HEIGHT: f32 = 36.0; const ROW_WIDTH: f32 = 270.0; @@ -124,7 +125,7 @@ pub struct Title { pub started: std::time::Instant, search: String, search_focused: bool, - scroll: Cell, + scroll: Cell, create_return_to_main: bool, message_lines: Cell, backup: Option>>, @@ -228,7 +229,7 @@ impl Title { started: now, search: String::new(), search_focused: false, - scroll: Cell::new(0.0), + scroll: Cell::default(), create_return_to_main: false, message_lines: Cell::new(1), backup: None, @@ -252,7 +253,7 @@ impl Title { pub fn enter_singleplayer(&mut self) { self.search.clear(); self.search_focused = true; - self.scroll.set(0.0); + self.scroll.set(crate::ui::Scroll::default()); let worlds = list_worlds(&self.saves); self.create_return_to_main = worlds.is_empty(); self.mode = if worlds.is_empty() { @@ -324,10 +325,23 @@ impl Title { .collect::>() .into_iter() } + /// The world list's top, bottom, rows' left edge and content height. + fn world_list(&self, worlds: &[WorldEntry], (w, h): (f32, f32)) -> (f32, f32, f32, f32) { + let (w, h) = (w.ceil(), h.ceil()); + let content = self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0; + let left = (w / 2.0).floor() - ROW_WIDTH / 2.0; + (LIST_TOP, h - LIST_BOTTOM, left, content) + } /// The pointer moved with the button held (`mouseDragged`). pub fn drag(&mut self, cursor: (f32, f32), size: (f32, f32)) { if let Mode::Multiplayer(screen) = &mut self.mode { - screen.drag(cursor.1, size); + return screen.drag(cursor.1, size); + } + if let Mode::Select { worlds, .. } = &self.mode { + let (top, bottom, _, content) = self.world_list(worlds, size); + let mut scroll = self.scroll.get(); + scroll.drag(cursor.1, top, bottom, content); + self.scroll.set(scroll); } } /// The button was released (`onRelease`). @@ -335,6 +349,7 @@ impl Title { if let Mode::Multiplayer(screen) = &mut self.mode { screen.release(); } + self.scroll.get_mut().release(); } /// Mouse wheel over the classic world and server lists. pub fn scroll_worlds(&mut self, delta: f32, cursor: (f32, f32), size: (f32, f32)) { @@ -345,14 +360,13 @@ impl Title { let Mode::Select { worlds, .. } = &self.mode else { return; }; - if cursor.1 < LIST_TOP || cursor.1 >= size.1 - LIST_BOTTOM { + let (top, bottom, _, content) = self.world_list(worlds, size); + if cursor.1 < top || cursor.1 >= bottom { return; } - let max = (self.visible_worlds(worlds).count() as f32 * ROW_HEIGHT + 4.0 - - (size.1 - LIST_TOP - LIST_BOTTOM)) - .max(0.0); - self.scroll - .set((self.scroll.get() - delta * ROW_HEIGHT / 2.0).clamp(0.0, max)); + let mut scroll = self.scroll.get(); + scroll.wheel(delta, ROW_HEIGHT / 2.0, top, bottom, content); + self.scroll.set(scroll); } fn failed(&mut self, error: impl std::fmt::Display) { let return_to = Box::new(self.mode.clone()); @@ -802,44 +816,33 @@ impl Title { true, ); } - let bottom = h - LIST_BOTTOM; - batch.fill( - atlas, - 0.0, - LIST_TOP, - w, - bottom - LIST_TOP, - rgba(0, 0, 0, 100), - ); - batch.fill(atlas, 0.0, LIST_TOP - 1.0, w, 1.0, rgba(160, 160, 160, 255)); - batch.fill(atlas, 0.0, bottom, w, 1.0, rgba(160, 160, 160, 255)); - let count = self.visible_worlds(worlds).count(); - let max = (count as f32 * ROW_HEIGHT + 4.0 - (bottom - LIST_TOP)).max(0.0); - self.scroll.set(self.scroll.get().clamp(0.0, max)); + let (top, bottom, left, content) = self.world_list(worlds, (w, h)); + let mut scroll = self.scroll.get(); + scroll.clamp(top, bottom, content); + self.scroll.set(scroll); + let offset = scroll.amount.trunc(); + // AbstractSelectionList: background, rows clipped to the + // list, separators, scrollbar. + crate::ui::list_background(batch, atlas, top, bottom, false); let first = batch.vertices.len(); - let x = ((w - ROW_WIDTH) / 2.0).floor() + 2.0; + // Entry content sits 2 pixels inside its row. + let x = left + 2.0; let mut slot = 0; for (row, (i, world)) in self.visible_worlds(worlds).enumerate() { - let y = LIST_TOP + 5.0 + row as f32 * ROW_HEIGHT - self.scroll.get(); - if y + 32.0 <= LIST_TOP || y >= bottom { + let y = top + 4.0 + row as f32 * ROW_HEIGHT - offset; + if y + 32.0 <= top || y >= bottom { continue; } let mid = y - 2.0 + ROW_HEIGHT / 2.0; - if mid > LIST_TOP && mid < bottom { + if mid > top && mid < bottom { crate::widgets::target_as( [x - 2.0, y - 2.0, ROW_WIDTH, ROW_HEIGHT], crate::widgets::Kind::Row, ); } + // extractSelection: white once the list has focus. if *selected == Some(i) { - batch.fill( - atlas, - x - 2.0, - y - 2.0, - ROW_WIDTH, - ROW_HEIGHT, - rgba(128, 128, 128, 255), - ); + batch.fill(atlas, x - 2.0, y - 2.0, ROW_WIDTH, ROW_HEIGHT, u32::MAX); batch.fill( atlas, x - 1.0, @@ -888,8 +891,8 @@ impl Title { } // Clip list quads, including their UVs, to the content area. for quad in batch.vertices[first..].as_chunks_mut::<6>().0 { - let top = quad.iter().map(|v| v.pos[1]).fold(f32::INFINITY, f32::min); - let bot = quad + let low = quad.iter().map(|v| v.pos[1]).fold(f32::INFINITY, f32::min); + let high = quad .iter() .map(|v| v.pos[1]) .fold(f32::NEG_INFINITY, f32::max); @@ -899,27 +902,22 @@ impl Title { .map(|v| v.uv[1]) .fold(f32::NEG_INFINITY, f32::max); for v in quad { - v.pos[1] = v.pos[1].clamp(LIST_TOP, bottom); - if bot > top { - v.uv[1] = uv_top + (uv_bot - uv_top) * (v.pos[1] - top) / (bot - top); + v.pos[1] = v.pos[1].clamp(top, bottom); + if high > low { + v.uv[1] = uv_top + (uv_bot - uv_top) * (v.pos[1] - low) / (high - low); } } } - if max > 0.0 { - let track = bottom - LIST_TOP; - let thumb = - (track * track / (count as f32 * ROW_HEIGHT + 4.0)).clamp(32.0, track); - let sx = (w / 2.0).floor() + ROW_WIDTH / 2.0 + 6.0; - batch.fill(atlas, sx, LIST_TOP, 6.0, track, rgba(0, 0, 0, 255)); - batch.fill( - atlas, - sx, - LIST_TOP + self.scroll.get() / max * (track - thumb), - 6.0, - thumb, - rgba(128, 128, 128, 255), - ); - } + crate::ui::separators(batch, atlas, top, bottom, false); + crate::ui::scrollbar( + batch, + atlas, + left + ROW_WIDTH + 8.0, + top, + bottom, + content, + scroll.amount, + ); } Mode::Create { name, seed, focus, .. @@ -1246,11 +1244,20 @@ impl Title { (Mode::Select { .. }, None) => { self.search_focused = (21.0..41.0).contains(&y) && (x - (w / 2.0).floor()).abs() < 100.0; - if y >= LIST_TOP - && y < h - LIST_BOTTOM - && (x - (w / 2.0).floor()).abs() < ROW_WIDTH / 2.0 + let Mode::Select { worlds, .. } = &self.mode else { + unreachable!() + }; + let (top, bottom, left, content) = self.world_list(worlds, (w, h)); + if self + .scroll + .get_mut() + .press((x, y), left + ROW_WIDTH + 8.0, top, bottom, content) { - let row = ((y - LIST_TOP - 5.0 + self.scroll.get()) / ROW_HEIGHT).floor(); + return Action::None; + } + if y >= top && y < bottom && x >= left && x < left + ROW_WIDTH { + let offset = self.scroll.get().amount.trunc(); + let row = ((y - top - 2.0 + offset) / ROW_HEIGHT).floor(); if row >= 0.0 { let Mode::Select { worlds, selected } = &self.mode else { unreachable!() @@ -1383,7 +1390,7 @@ impl Title { && let Mode::Select { selected, .. } = &mut self.mode { *selected = None; - self.scroll.set(0.0); + self.scroll.set(crate::ui::Scroll::default()); } } pub fn confirm_edit(&mut self) { diff --git a/crates/horizon-client/src/title/tests.rs b/crates/horizon-client/src/title/tests.rs index f1148a7b7..d8583c813 100644 --- a/crates/horizon-client/src/title/tests.rs +++ b/crates/horizon-client/src/title/tests.rs @@ -414,7 +414,7 @@ fn recreate_uses_existing_name_seed_and_mode_and_scroll_reaches_later_rows() { f.click("Cancel"); f.title .scroll_worlds(-100.0, (240.0, 100.0), (480.0, 262.0)); - assert!(f.title.scroll.get() > 0.0); + assert!(f.title.scroll.get().amount > 0.0); let Mode::Select { worlds, .. } = &f.title.mode else { panic!() }; @@ -561,3 +561,26 @@ fn delete_removes_links_without_following_them() { assert!(!f.title.saves.join("World").exists()); assert!(outside.join("keep.txt").is_file()); } + +#[test] +fn scrolled_world_list_draws_inside_the_list_and_drags_its_scroller() { + let mut f = Fixture::new(); + for i in 0..10 { + f.world(&format!("World{i}"), &format!("World {i}")); + } + f.select(); + let size = (480.0, 262.0); + // SelectWorldScreen's list: 49 to h - 60, scroller at the row's right + 8. + let bar = (480.0 / 2.0 - ROW_WIDTH / 2.0 + ROW_WIDTH + 8.0 + 3.0, 60.0); + f.title.click(bar.0, bar.1, size); + f.title.drag((bar.0, 120.0), size); + let moved = f.title.scroll.get().amount; + assert!(moved > 0.0); + f.title.release(); + f.title.drag((bar.0, 60.0), size); + assert_eq!(f.title.scroll.get().amount, moved); + let atlas = crate::hud::HudAtlas::build(Path::new("/nonexistent/horizon-test-assets")).unwrap(); + let mut batch = HudBatch::new([480, 262]); + f.title.draw(&atlas, &mut batch, (0.0, 0.0), true); + assert!(!batch.vertices.is_empty()); +} From 6ae018055da280b7d7b7b3cb5643fecbca2c7ddb Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:16:02 +0200 Subject: [PATCH 05/16] Debug charts: F3+2 frame and tick times, F3+3 ping and bandwidth DebugScreenOverlay's FpsDebugChart, TpsDebugChart, PingDebugChart and BandwidthDebugChart with vanilla's scales, colours and places: 240 samples (LocalSampleLogger), F3+2 and F3+3 toggles that show the overlay and exclude each other, the overlay's "Debug charts" lines, and the play-state ping request and pong response packets the ping chart uses on servers. Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/debug_chart.rs | 536 +++++++++++++++++++ crates/horizon-client/src/game.rs | 20 +- crates/horizon-client/src/game/debug_keys.rs | 87 ++- crates/horizon-client/src/game/remote.rs | 6 + crates/horizon-client/src/lib.rs | 1 + crates/horizon-protocol/src/packets/play.rs | 4 + 6 files changed, 649 insertions(+), 5 deletions(-) create mode 100644 crates/horizon-client/src/debug_chart.rs diff --git a/crates/horizon-client/src/debug_chart.rs b/crates/horizon-client/src/debug_chart.rs new file mode 100644 index 000000000..43d30d349 --- /dev/null +++ b/crates/horizon-client/src/debug_chart.rs @@ -0,0 +1,536 @@ +//! The debug charts (26.3 `debugchart`): F3+2 shows the frame times and, in +//! single player, the integrated server's tick times; F3+3 the ping and, on a +//! remote server, the bandwidth. Each chart keeps the last 240 samples +//! (`LocalSampleLogger`) and draws one bar per sample over a 60 pixel high +//! box (`AbstractDebugChart`). +use crate::{ + font::Font, + hud_layout::{GuiDraw, argb, fill}, + text::Text, +}; +use std::{ + collections::VecDeque, + time::{Duration, Instant}, +}; + +/// `LocalSampleLogger.CAPACITY`. +pub const CAPACITY: usize = 240; +/// `AbstractDebugChart.CHART_HEIGHT`. +pub const CHART_HEIGHT: i32 = 60; +/// `TpsDebugDimensions`: a tick sample's values. +pub const FULL_TICK: usize = 0; +pub const TICK_SERVER_METHOD: usize = 1; +pub const SCHEDULED_TASKS: usize = 2; +pub const IDLE: usize = 3; + +/// `LocalSampleLogger`: the last [`CAPACITY`] samples, oldest first; a +/// sample has up to four values (`TpsDebugDimensions`), the first the main. +#[derive(Clone, Debug, Default)] +pub struct SampleLogger { + samples: VecDeque<[i64; 4]>, +} +impl SampleLogger { + /// `logSample`. + pub fn log(&mut self, value: i64) { + self.log_full([value, 0, 0, 0]); + } + /// `logFullSample`. + pub fn log_full(&mut self, sample: [i64; 4]) { + if self.samples.len() == CAPACITY { + self.samples.pop_front(); + } + self.samples.push_back(sample); + } + pub fn len(&self) -> usize { + self.samples.len() + } + pub fn is_empty(&self) -> bool { + self.samples.is_empty() + } + pub fn reset(&mut self) { + self.samples.clear(); + } + fn get(&self, index: usize, dimension: usize) -> i64 { + self.samples[index][dimension] + } +} + +/// `DebugScreenOverlay`'s chart switches and the samples behind them. +#[derive(Clone, Debug, Default)] +pub struct DebugCharts { + /// `renderFpsCharts` (F3+2). + pub fps: bool, + /// `renderNetworkCharts` (F3+3). + pub network: bool, + /// `frameTimeLogger`: nanoseconds between frames. + pub frame_times: SampleLogger, + /// `tickTimeLogger`: the integrated server's ticks. + pub tick_times: SampleLogger, + /// `pingLogger`: milliseconds. + pub ping: SampleLogger, + /// `bandwidthLogger`: bytes received per tick. + pub bandwidth: SampleLogger, + previous_tick: Option, + bytes_seen: Option, +} +impl DebugCharts { + /// `toggleFpsCharts`; `overlay` is the debug overlay's visibility. + pub fn toggle_fps(&mut self, overlay: &mut bool) { + self.fps = !*overlay || !self.fps; + if self.fps { + *overlay = true; + self.network = false; + } + } + /// `toggleNetworkCharts`. + pub fn toggle_network(&mut self, overlay: &mut bool) { + self.network = !*overlay || !self.network; + if self.network { + *overlay = true; + self.fps = false; + } + } + /// `reset`: leaving a world. + pub fn reset(&mut self) { + self.tick_times.reset(); + self.ping.reset(); + self.bandwidth.reset(); + self.previous_tick = None; + self.bytes_seen = None; + } + /// One integrated server tick that started at `started` and ran its + /// tick method for `method` (`MinecraftServer.logFullTickTime` and + /// `logTickMethodTime`): the full tick runs from one start to the next, + /// and what the tick method leaves of it is idle. + pub fn log_tick(&mut self, started: Instant, method: Duration) { + let method = method.as_nanos() as i64; + let full = self + .previous_tick + .map_or(method, |p| (started - p).as_nanos() as i64) + .max(method); + self.previous_tick = Some(started); + self.tick_times.log_full([full, method, 0, full - method]); + } + /// `BandwidthDebugMonitor.tick`: the bytes received since the last + /// tick, from the connection's running total. + pub fn log_bandwidth(&mut self, total: i64) { + if let Some(seen) = self.bytes_seen { + self.bandwidth.log(total - seen); + } + self.bytes_seen = Some(total); + } + /// The charts along the bottom of the screen (`extractRenderState`): + /// frame times left and tick times right, or bandwidth left (remote + /// servers only) and ping right. `mspt` is the level's milliseconds + /// per tick. + pub fn draw( + &self, + font: &Font, + width: i32, + height: i32, + framerate_limit: u32, + mspt: f32, + remote: bool, + ) -> Vec { + let mut out = Vec::new(); + let max_width = width / 2; + let chart_width = Chart::width(max_width); + if self.fps { + let fps = Chart::Fps { framerate_limit }; + out.extend(fps.draw(font, &self.frame_times, 0, chart_width, height)); + if !self.tick_times.is_empty() { + let tps = Chart::Tps { mspt }; + out.extend(tps.draw( + font, + &self.tick_times, + width - chart_width, + chart_width, + height, + )); + } + } + if self.network { + if remote { + out.extend(Chart::Bandwidth.draw(font, &self.bandwidth, 0, chart_width, height)); + } + out.extend(Chart::Ping.draw( + font, + &self.ping, + width - chart_width, + chart_width, + height, + )); + } + out + } +} + +/// The four charts and what each needs to scale its bars. +#[derive(Clone, Copy, Debug, PartialEq)] +pub enum Chart { + /// `FpsDebugChart`: frame durations in nanoseconds; the frame rate limit + /// option (`maxFps`). + Fps { framerate_limit: u32 }, + /// `TpsDebugChart`: tick samples in nanoseconds; the level's + /// milliseconds per tick. + Tps { mspt: f32 }, + /// `PingDebugChart`: round trips in milliseconds. + Ping, + /// `BandwidthDebugChart`: bytes received per tick. + Bandwidth, +} + +/// The labels' colour and the backdrop of the box and shaded labels. +const LABEL: u32 = 0xFFE0_E0E0; +const BACKDROP: u32 = 0x9050_5050; +const WHITE: u32 = 0xFFFF_FFFF; +const GREEN: u32 = 0xFF00_FF00; +const YELLOW: u32 = 0xFFFF_FF00; +const RED: u32 = 0xFFFF_0000; +const CYAN: u32 = 0xFF00_FFFF; +/// `BandwidthDebugChart.MID_COLOR`. +const LAVENDER: u32 = 0xFFA0_A0FF; +/// `TpsDebugChart`'s bar parts. +const TICK_METHOD_COLOR: u32 = 0xFF99_1111; +const TASK_COLOR: u32 = 0xFFBA_995F; +const OTHER_COLOR: u32 = 0xFF5F_0E8C; +const MEGABYTE: f64 = 1_048_576.0; + +impl Chart { + /// `AbstractDebugChart.getWidth`. + pub fn width(max_width: i32) -> i32 { + (CAPACITY as i32 + 2).min(max_width) + } + /// `getFullHeight`: the box and the min/avg/max line above it. + pub fn full_height() -> i32 { + CHART_HEIGHT + 9 + } + /// `AbstractDebugChart.extractRenderState`. + pub fn draw( + self, + font: &Font, + samples: &SampleLogger, + left: i32, + width: i32, + bottom: i32, + ) -> Vec { + let mut out = vec![fill( + left, + bottom - CHART_HEIGHT, + left + width, + bottom, + BACKDROP, + )]; + let (mut sum, mut min, mut max) = (0i64, i64::from(i32::MAX), i64::from(i32::MIN)); + let start = CAPACITY.saturating_sub((width - 2).max(0) as usize); + let count = samples.len().saturating_sub(start); + for i in 0..count { + let x = left + i as i32 + 1; + let index = start + i; + let value = self.aggregated(samples, index); + min = min.min(value); + max = max.max(value); + sum += value; + self.bars(&mut out, samples, bottom, x, index); + } + horizontal_line( + &mut out, + left, + left + width - 1, + bottom - CHART_HEIGHT, + WHITE, + ); + horizontal_line(&mut out, left, left + width - 1, bottom - 1, WHITE); + vertical_line(&mut out, left, bottom - CHART_HEIGHT, bottom, WHITE); + vertical_line( + &mut out, + left + width - 1, + bottom - CHART_HEIGHT, + bottom, + WHITE, + ); + if count > 0 { + let y = bottom - CHART_HEIGHT - 9; + let min_text = format!("{} min", self.display(min as f64)); + let avg_text = format!("{} avg", self.display(sum as f64 / count as f64)); + let max_text = format!("{} max", self.display(max as f64)); + text(&mut out, min_text, left + 2, y, LABEL, true); + let avg_x = left + width / 2 - font.width(&avg_text) as i32 / 2; + text(&mut out, avg_text, avg_x, y, LABEL, true); + let max_x = left + width - font.width(&max_text) as i32 - 2; + text(&mut out, max_text, max_x, y, LABEL, true); + } + self.lines_and_labels(&mut out, font, left, width, bottom); + out + } + fn bars( + self, + out: &mut Vec, + samples: &SampleLogger, + bottom: i32, + x: i32, + index: usize, + ) { + let value = samples.get(index, 0); + let height = self.height(value as f64); + out.push(fill(x, bottom - height, x + 1, bottom, self.color(value))); + if let Chart::Tps { .. } = self { + let method = samples.get(index, TICK_SERVER_METHOD); + let method_h = self.height(method as f64); + out.push(fill(x, bottom - method_h, x + 1, bottom, TICK_METHOD_COLOR)); + let tasks = samples.get(index, SCHEDULED_TASKS); + let tasks_h = self.height(tasks as f64); + out.push(fill( + x, + bottom - method_h - tasks_h, + x + 1, + bottom - method_h, + TASK_COLOR, + )); + let other = value - samples.get(index, IDLE) - method - tasks; + let other_h = self.height(other as f64); + out.push(fill( + x, + bottom - other_h - tasks_h - method_h, + x + 1, + bottom - tasks_h - method_h, + OTHER_COLOR, + )); + } + } + /// `getValueForAggregation`: a tick's time without its idle part. + fn aggregated(self, samples: &SampleLogger, index: usize) -> i64 { + match self { + Chart::Tps { .. } => samples.get(index, 0) - samples.get(index, IDLE), + _ => samples.get(index, 0), + } + } + /// `extractAdditionalLinesAndLabels`. + fn lines_and_labels( + self, + out: &mut Vec, + font: &Font, + left: i32, + width: i32, + bottom: i32, + ) { + match self { + Chart::Fps { framerate_limit } => { + shaded(out, font, "30 fps", left + 1, bottom - CHART_HEIGHT + 1); + shaded(out, font, "60 fps", left + 1, bottom - 30 + 1); + horizontal_line(out, left, left + width - 1, bottom - 30, WHITE); + if framerate_limit > 0 && framerate_limit <= 250 { + let y = bottom - self.height(1.0e9 / f64::from(framerate_limit)) - 1; + horizontal_line(out, left, left + width - 1, y, CYAN); + } + } + Chart::Tps { mspt } => { + let tps = 1000.0 / mspt; + shaded( + out, + font, + &format!("{tps:.1} tps"), + left + 1, + bottom - CHART_HEIGHT + 1, + ); + } + Chart::Ping => shaded(out, font, "500 ms", left + 1, bottom - CHART_HEIGHT + 1), + Chart::Bandwidth => { + for bytes in [64.0, 1024.0, 16384.0] { + let y = bottom - bandwidth_height(bytes); + shaded(out, font, &bandwidth_display(bytes), left + 1, y + 1); + horizontal_line(out, left, left + width - 1, y, WHITE); + } + let y = bottom - bandwidth_height(MEGABYTE) + 1; + shaded(out, font, &bandwidth_display(MEGABYTE), left + 1, y); + } + } + } + /// `toDisplayString`. + fn display(self, sample: f64) -> String { + match self { + Chart::Fps { .. } | Chart::Tps { .. } => format!("{} ms", java_round(sample / 1.0e6)), + Chart::Ping => format!("{} ms", java_round(sample)), + Chart::Bandwidth => bandwidth_display(sample * 20.0), + } + } + /// `getSampleHeight`. + fn height(self, sample: f64) -> i32 { + match self { + Chart::Fps { .. } => java_round(sample / 1.0e6 * 60.0 / 33.333333333333336) as i32, + Chart::Tps { mspt } => java_round(sample / 1.0e6 * 60.0 / f64::from(mspt)) as i32, + Chart::Ping => java_round(sample * 60.0 / 500.0) as i32, + Chart::Bandwidth => bandwidth_height(sample * 20.0), + } + } + /// `getSampleColor`. + fn color(self, sample: i64) -> u32 { + let s = sample as f64; + match self { + Chart::Fps { .. } => gradient(s / 1.0e6, 0.0, GREEN, 28.0, YELLOW, 56.0, RED), + Chart::Tps { mspt } => { + let m = f64::from(mspt); + gradient(s / 1.0e6, m, GREEN, m * 1.125, YELLOW, m * 1.25, RED) + } + Chart::Ping => gradient(s, 0.0, GREEN, 250.0, YELLOW, 500.0, RED), + Chart::Bandwidth => gradient(s * 20.0, 0.0, CYAN, 8192.0, LAVENDER, 1.048576e7, RED), + } + } +} + +/// `BandwidthDebugChart.toDisplayStringInternal`. +fn bandwidth_display(bytes_per_second: f64) -> String { + if bytes_per_second >= MEGABYTE { + format!("{:.1} MiB/s", bytes_per_second / MEGABYTE) + } else if bytes_per_second >= 1024.0 { + format!("{:.1} KiB/s", bytes_per_second / 1024.0) + } else { + format!("{} B/s", bytes_per_second.floor() as i64) + } +} +/// `BandwidthDebugChart.getSampleHeightInternal`: logarithmic, 1 MiB/s at +/// the top. +fn bandwidth_height(bytes_per_second: f64) -> i32 { + java_round((bytes_per_second + 1.0).ln() * 60.0 / MEGABYTE.ln()) as i32 +} +/// `Math.round(double)`: halves round up. +fn java_round(v: f64) -> i64 { + (v + 0.5).floor() as i64 +} +/// `AbstractDebugChart.getSampleColor(sample, min, minColor, mid, ...)`. +fn gradient( + sample: f64, + min: f64, + min_color: u32, + mid: f64, + mid_color: u32, + max: f64, + max_color: u32, +) -> u32 { + let sample = sample.clamp(min, max); + if sample < mid { + srgb_lerp(((sample - min) / (mid - min)) as f32, min_color, mid_color) + } else { + srgb_lerp(((sample - mid) / (max - mid)) as f32, mid_color, max_color) + } +} +/// `ARGB.srgbLerp`: each channel by `Mth.lerpInt`. +fn srgb_lerp(alpha: f32, p0: u32, p1: u32) -> u32 { + let channel = |shift: u32| { + let (a, b) = (((p0 >> shift) & 255) as i32, ((p1 >> shift) & 255) as i32); + (a + (alpha * (b - a) as f32).floor() as i32) as u32 + }; + argb(channel(24), channel(16), channel(8), channel(0)) +} +/// `GuiGraphicsExtractor.horizontalLine`. +fn horizontal_line(out: &mut Vec, x0: i32, x1: i32, y: i32, color: u32) { + out.push(fill(x0.min(x1), y, x0.max(x1) + 1, y + 1, color)); +} +/// `GuiGraphicsExtractor.verticalLine`. +fn vertical_line(out: &mut Vec, x: i32, y0: i32, y1: i32, color: u32) { + out.push(fill(x, y0.min(y1) + 1, x + 1, y0.max(y1), color)); +} +fn text(out: &mut Vec, s: String, x: i32, y: i32, color: u32, shadow: bool) { + out.push(GuiDraw::Text { + text: Text::literal(s), + x, + y, + color, + shadow, + }); +} +/// `extractStringWithShade`: a label on a dark backdrop, without shadow. +fn shaded(out: &mut Vec, font: &Font, s: &str, x: i32, y: i32) { + out.push(fill(x, y, x + font.width(s) as i32 + 1, y + 9, BACKDROP)); + text(out, s.to_owned(), x + 1, y + 1, LABEL, false); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_logger_keeps_the_last_240_samples() { + let mut l = SampleLogger::default(); + for i in 0..300 { + l.log(i); + } + assert_eq!(l.len(), CAPACITY); + assert_eq!(l.get(0, 0), 60); + assert_eq!(l.get(CAPACITY - 1, 0), 299); + } + + #[test] + fn chart_toggles_show_the_overlay_and_exclude_each_other() { + let mut c = DebugCharts::default(); + let mut overlay = false; + c.toggle_fps(&mut overlay); + assert!(overlay && c.fps); + c.toggle_network(&mut overlay); + assert!(c.network && !c.fps); + c.toggle_network(&mut overlay); + assert!(!c.network && overlay); + // With the overlay hidden, the key shows it again with the chart on. + c.toggle_fps(&mut overlay); + overlay = false; + c.toggle_fps(&mut overlay); + assert!(overlay && c.fps); + } + + #[test] + fn ticks_and_bandwidth_log_their_differences() { + let mut c = DebugCharts::default(); + let t0 = Instant::now(); + c.log_tick(t0, Duration::from_millis(5)); + c.log_tick(t0 + Duration::from_millis(50), Duration::from_millis(7)); + assert_eq!( + c.tick_times.samples[1], + [50_000_000, 7_000_000, 0, 43_000_000] + ); + c.log_bandwidth(1000); + c.log_bandwidth(1600); + assert_eq!(c.bandwidth.len(), 1); + assert_eq!(c.bandwidth.get(0, 0), 600); + } + + #[test] + fn heights_match_vanilla_scales() { + let fps = Chart::Fps { + framerate_limit: 260, + }; + // 33.3 ms (30 fps) fills the chart; 16.7 ms half of it. + assert_eq!(fps.height(33_333_333.0), 60); + assert_eq!(fps.height(16_666_667.0), 30); + let tps = Chart::Tps { mspt: 50.0 }; + assert_eq!(tps.height(25e6), 30); + assert_eq!(Chart::Ping.height(250.0), 30); + // 1 MiB/s at the top; 52 bytes per tick is 1 KiB/s. + assert_eq!(bandwidth_height(MEGABYTE), 60); + assert_eq!(Chart::Bandwidth.height(51.2), 30); + } + + #[test] + fn labels_match_vanilla_formats() { + assert_eq!( + Chart::Fps { framerate_limit: 0 }.display(16_500_000.0), + "17 ms" + ); + assert_eq!(Chart::Ping.display(12.4), "12 ms"); + assert_eq!(Chart::Bandwidth.display(3.0), "60 B/s"); + assert_eq!(Chart::Bandwidth.display(100.0), "2.0 KiB/s"); + assert_eq!(bandwidth_display(MEGABYTE), "1.0 MiB/s"); + } + + #[test] + fn colours_go_green_yellow_red() { + let fps = Chart::Fps { framerate_limit: 0 }; + assert_eq!(fps.color(0), GREEN); + assert_eq!(fps.color(28_000_000), YELLOW); + assert_eq!(fps.color(100_000_000), RED); + // Halfway between green and yellow: Mth.lerpInt floors. + assert_eq!(fps.color(14_000_000), 0xFF7F_FF00); + let tps = Chart::Tps { mspt: 50.0 }; + assert_eq!(tps.color(10_000_000), GREEN); + assert_eq!(Chart::Bandwidth.color(0), CYAN); + } +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index b406c5766..9d7c24cda 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -948,6 +948,8 @@ struct Game<'a> { /// KeyboardHandler's debug key state (game/debug_keys.rs), the physical /// keys held, and the debug renderers F3+B and F3+G switch on. debug_keys: horizon_client::debug_keys::DebugKeys, + /// The F3 overlay's charts (F3+2, F3+3). + debug_charts: horizon_client::debug_chart::DebugCharts, show_hitboxes: bool, show_chunk_borders: bool, /// PauseScreen.showPauseMenu (false after F3+Escape). @@ -2855,6 +2857,7 @@ impl Game<'_> { } fn tick(&mut self) -> Result<()> { self.tick_debug_keys()?; + self.tick_debug_charts(); if self.remote.is_some() { return self.tick_remote(); } @@ -3645,7 +3648,7 @@ impl Game<'_> { 2 => "north (Towards negative Z)", _ => "east (Towards positive X)", }; - let lines = [ + let mut lines = vec![ format!("Horizon 26.3 (Rust) {:.0} fps", self.fps), format!( "C: {} chunks, {} sections drawn / {}", @@ -3688,7 +3691,9 @@ impl Game<'_> { self.world.day_time / 24000, self.world.day_time % 24000 ), + String::new(), ]; + lines.extend(self.debug_chart_lines()); for (i, line) in lines.iter().enumerate() { if line.is_empty() { continue; @@ -3711,6 +3716,15 @@ impl Game<'_> { false, ); } + let charts = self.debug_charts.draw( + &atlas.font, + w as i32, + h as i32, + self.settings.max_fps, + 1000.0 / self.clock.rate(), + self.remote.is_some(), + ); + hud_layout::paint(&mut batch, atlas, &charts); } if !self.ui.hide_gui && let Some((text, at)) = &self.message @@ -6287,6 +6301,7 @@ impl Game<'_> { self.save.flush(); self.session_lock = None; horizon_client::crash::clear_detail("World"); + self.debug_charts.reset(); self.streaming.paused = true; self.world = World::new(self.res.facts.air, 0); self.player = None; @@ -9056,6 +9071,7 @@ impl ApplicationHandler for Game<'_> { // In single player the tick is the integrated server's. if self.remote.is_none() { self.perf.tick(tick.elapsed().as_secs_f32() * 1000.0); + self.debug_charts.log_tick(tick, tick.elapsed()); } self.tick_ambience(); self.tick_fov(); @@ -9142,6 +9158,7 @@ impl ApplicationHandler for Game<'_> { } if rendered { self.frame_stats.record(elapsed.as_secs_f32() * 1000.0); + self.debug_charts.frame_times.log(elapsed.as_nanos() as i64); if self.frames == 0 { // The launcher times Play to this line (launcher/src/perf.rs). log::info!( @@ -9620,6 +9637,7 @@ pub fn run() -> Result<()> { world_options: None, friends: None, debug_keys: Default::default(), + debug_charts: Default::default(), show_hitboxes: false, show_chunk_borders: false, pause_menu: true, diff --git a/crates/horizon-client/src/game/debug_keys.rs b/crates/horizon-client/src/game/debug_keys.rs index 0f49cd459..bc3bb82c4 100644 --- a/crates/horizon-client/src/game/debug_keys.rs +++ b/crates/horizon-client/src/game/debug_keys.rs @@ -151,7 +151,7 @@ impl Game<'_> { } } /// `Util.getMillis` (positive: KeyboardHandler treats 0 as unset). - fn debug_millis(&self) -> i64 { + pub(super) fn debug_millis(&self) -> i64 { self.started.elapsed().as_millis() as i64 + 1_000_000 } /// `KeyboardHandler.tick`: the debug crash countdown. @@ -180,6 +180,79 @@ impl Game<'_> { } Ok(()) } + /// The network charts' samples each tick: `PingDebugMonitor.tick` while + /// they show, `BandwidthDebugMonitor.tick` always. + pub(super) fn tick_debug_charts(&mut self) { + let shown = self.debug && self.debug_charts.network; + let Some(r) = &self.remote else { + // The integrated server answers within the tick. + if shown { + self.debug_charts.ping.log(0); + } + return; + }; + let received = r + .session + .counters + .lock() + .unwrap() + .as_ref() + .map(|c| c.bytes_in.load(std::sync::atomic::Ordering::Relaxed)); + if let Some(total) = received { + self.debug_charts.log_bandwidth(total); + } + if shown { + use horizon_protocol::packets::{play::Serverbound, status::Ping}; + let time = self.debug_millis(); + self.send(Serverbound::PingRequest(Ping { time })); + } + } + /// The overlay's chart lines (`DebugScreenOverlay`'s "Debug charts"). + pub(super) fn debug_chart_lines(&self) -> [String; 3] { + let keys = &self.settings.keys; + let modifier = keys.get("key.debug.modifier"); + let key = |mapping: &str| { + let prefix = if modifier == "key.keyboard.unknown" { + String::new() + } else { + format!("{}+", keybinds::display_name(modifier).plain()) + }; + format!( + "[{prefix}{}]", + keybinds::display_name(keys.get(mapping)).plain() + ) + }; + let chart = |mapping: &str, name: &str, on: bool| { + format!( + "{} {name} {}", + key(mapping), + if on { "visible" } else { "hidden" } + ) + }; + let remote = self.remote.is_some(); + let c = &self.debug_charts; + [ + format!( + "Debug charts: {}; {};", + chart("key.debug.profilingChart", "Profiler", false), + chart( + "key.debug.fpsCharts", + if remote { "fps" } else { "fps + tps" }, + c.fps + ), + ), + format!( + "{}; {}", + chart( + "key.debug.networkCharts", + if remote { "Bandwidth + Ping" } else { "Ping" }, + c.network + ), + chart("key.debug.lightmapTexture", "Lightmap", false), + ), + format!("To edit: press {}", key("key.debug.debugOptions")), + ] + } /// `KeyMapping.getTranslatedKeyMessage`. fn key_text(&self, mapping: &str) -> Text { keybinds::display_name(self.settings.keys.get(mapping)) @@ -339,15 +412,21 @@ impl Game<'_> { }); true } + DebugAction::FpsCharts => { + self.debug_charts.toggle_fps(&mut self.debug); + true + } + DebugAction::NetworkCharts => { + self.debug_charts.toggle_network(&mut self.debug); + true + } // Screens and overlays Horizon does not draw yet (the debug - // options screen, the profiler and its charts, the lightmap, the + // options screen, the profiler and its chart, the lightmap, the // texture dump): the keys are used up as in vanilla. DebugAction::DebugOptions | DebugAction::DumpDynamicTextures | DebugAction::Profiling | DebugAction::ProfilingChart - | DebugAction::FpsCharts - | DebugAction::NetworkCharts | DebugAction::LightmapTexture => true, DebugAction::ShowHitboxes | DebugAction::ShowChunkBorders diff --git a/crates/horizon-client/src/game/remote.rs b/crates/horizon-client/src/game/remote.rs index 3ec2b9924..6ad981151 100644 --- a/crates/horizon-client/src/game/remote.rs +++ b/crates/horizon-client/src/game/remote.rs @@ -272,6 +272,7 @@ impl Game<'_> { r.session.disconnect(); } horizon_client::crash::clear_detail("Server"); + self.debug_charts.reset(); self.tab_list.reset(); self.score.board = Default::default(); self.streaming = Streaming::new(Arc::new(NoTerrain), self.res.context.clone(), 1); @@ -736,6 +737,11 @@ impl Game<'_> { fn handle_packet(&mut self, packet: C) -> Result<()> { match packet { + // PingDebugMonitor.onPongReceived. + C::PongResponse(p) => { + let delay = self.debug_millis() - p.time; + self.debug_charts.ping.log(delay); + } C::Login(p) => { if let Some(r) = self.remote.as_mut() { r.online_mode = p.online_mode; diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index f8dd9d503..ebcdc47b2 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -44,6 +44,7 @@ pub mod crash; pub mod creative; pub mod data_cmd; pub mod datapack; +pub mod debug_chart; pub mod debug_keys; pub mod effects; pub mod enchant; diff --git a/crates/horizon-protocol/src/packets/play.rs b/crates/horizon-protocol/src/packets/play.rs index 49f75f7f3..1459f7d9f 100644 --- a/crates/horizon-protocol/src/packets/play.rs +++ b/crates/horizon-protocol/src/packets/play.rs @@ -1012,6 +1012,7 @@ packet_enum!(Clientbound, crate::ids::play::clientbound { MerchantOffers(MerchantOffers) = MERCHANT_OFFERS, OpenScreen(OpenScreen) = OPEN_SCREEN, Ping(Ping) = PING, + PongResponse(crate::packets::status::Ping) = PONG_RESPONSE, PlayerAbilities(PlayerAbilities) = PLAYER_ABILITIES, PlayerChat(PlayerChat) = PLAYER_CHAT, PlayerCombatKill(PlayerCombatKill) = PLAYER_COMBAT_KILL, @@ -1199,6 +1200,7 @@ packet_enum!(Serverbound, crate::ids::play::serverbound { MovePlayerRot(MovePlayerRot) = MOVE_PLAYER_ROT, MovePlayerStatus(MovePlayerStatus) = MOVE_PLAYER_STATUS_ONLY, PickItemFromBlock(PickItemFromBlock) = PICK_ITEM_FROM_BLOCK, + PingRequest(crate::packets::status::Ping) = PING_REQUEST, PlayerAction(PlayerAction) = PLAYER_ACTION, PlayerCommand(PlayerCommand) = PLAYER_COMMAND, PlayerInput(PlayerInput) = PLAYER_INPUT, @@ -1240,6 +1242,7 @@ mod tests { fn clientbound_round_trips() { let packets = vec![ Clientbound::BundleDelimiter(Empty), + Clientbound::PongResponse(crate::packets::status::Ping { time: 1_234_567 }), Clientbound::SetBorderCenter(SetBorderCenter { x: 1.5, z: -2.0 }), Clientbound::SetBorderLerpSize(SetBorderLerpSize { old_size: 10.0, @@ -1529,6 +1532,7 @@ mod tests { #[test] fn serverbound_round_trips() { let packets = vec![ + Serverbound::PingRequest(crate::packets::status::Ping { time: -7 }), Serverbound::AcceptTeleportation(AcceptTeleportation { id: 1, x: 0.5, From dc863a66a45643b2d6142ef6d462161e01b46b12 Mon Sep 17 00:00:00 2001 From: Ludovic Marie <136255825+ludovic111@users.noreply.github.com> Date: Thu, 15 Oct 2026 10:24:52 +0200 Subject: [PATCH 06/16] Create New World: vanilla's Game, World and More tabs CreateWorldScreen as in 26.3: a MenuTabBar (tab sprites, header separators, underline) over the transparent tab header, each tab's GridLayout aligned at (0.5, 1/6) between it and a 33-pixel footer with Create New World and Cancel. Game: the world name box with its save-folder tooltip, Game Mode (Survival, Hardcore, Creative), Difficulty and Allow Commands, locked in Hardcore. World: World Type (Default, Superflat), Customize, the seed box with its hint, and the Generate Structures / Bonus Chest switches. More: Game Rules, Experiments and Data Packs. Tooltips follow vanilla's. The choices reach the new world: hardcore, difficulty and allowCommands in level.dat, and world_gen_settings with the flat preset, structures and bonus chest written before streaming starts. Re-Create reads them back. Fixes #281 Co-Authored-By: Claude Opus 5.5 --- crates/horizon-client/src/front.rs | 10 +- crates/horizon-client/src/game.rs | 23 +- crates/horizon-client/src/game/agent.rs | 21 +- crates/horizon-client/src/game/control.rs | 2 +- crates/horizon-client/src/game/dedicated.rs | 8 +- crates/horizon-client/src/save.rs | 203 +++++-- crates/horizon-client/src/title.rs | 178 +++---- .../horizon-client/src/title/create_world.rs | 498 ++++++++++++++++++ crates/horizon-client/src/title/tests.rs | 98 +++- crates/horizon-client/src/ui.rs | 4 + 10 files changed, 863 insertions(+), 182 deletions(-) create mode 100644 crates/horizon-client/src/title/create_world.rs diff --git a/crates/horizon-client/src/front.rs b/crates/horizon-client/src/front.rs index 828402944..e6224683f 100644 --- a/crates/horizon-client/src/front.rs +++ b/crates/horizon-client/src/front.rs @@ -154,6 +154,7 @@ impl Title { seed, creative, focus, + .. } => { let caret = (self.started.elapsed().as_millis() / 500).is_multiple_of(2); create_page(ui, x, w, name, seed, *creative, *focus, caret); @@ -379,14 +380,7 @@ impl Title { }; } } - CREATE => { - self.mode = Mode::Create { - name: "New World".into(), - seed: String::new(), - creative: false, - focus: 0, - } - } + CREATE => self.mode = Title::new_world(), DELETE_WORLD => { if let Some(world) = selected.and_then(|i| worlds.get(i)).cloned() { self.mode = Mode::Delete { world }; diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 6c456a71f..d4988a6ee 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -5805,6 +5805,7 @@ impl Game<'_> { name: Option<&str>, seed: Option, creative: bool, + create: Option<&horizon_client::title::WorldOptions>, ) -> Result<()> { self.perf.world_opening(); let save_root = std::env::current_dir()?.join("saves").join(folder); @@ -5825,7 +5826,9 @@ impl Game<'_> { .map(|d| horizon_client::random_sequences::RandomSequences::from_nbt(&d)) .unwrap_or_default(); self.border = Default::default(); - let level = Level::read(&save_root).unwrap_or_else(|| Level { + let existing = Level::read(&save_root); + let created = existing.is_none(); + let level = existing.unwrap_or_else(|| Level { name: name.unwrap_or(folder).to_owned(), // WorldOptions.randomSeed when no seed was given. seed: seed.unwrap_or_else(|| { @@ -5842,6 +5845,13 @@ impl Game<'_> { ..Level::default() }); let mut level = level; + // CreateWorldScreen's choices, before streaming reads the generator. + if created && let Some(o) = create { + level.hardcore = o.hardcore; + level.difficulty = horizon_client::title::DIFFICULTIES[o.difficulty()].into(); + level.allow_commands = Some(o.commands(creative)); + horizon_client::save::write_world_gen_settings(&save_root, level.seed, o.world_gen())?; + } horizon_client::crash::set_detail("World", format!("{} (saves/{folder})", level.name)); if let Some(d) = &self.options.dimension { level.dimension = d.clone(); @@ -8795,13 +8805,18 @@ impl ApplicationHandler for Game<'_> { Action::Language => { self.open_options_at(true, horizon_client::options_ui::Page::Language) } - Action::Play { folder } => self.open_world(&folder, None, None, false)?, + Action::Play { folder } => { + self.open_world(&folder, None, None, false, None)? + } Action::Create { folder, name, seed, creative, - } => self.open_world(&folder, Some(&name), seed, creative)?, + options, + } => { + self.open_world(&folder, Some(&name), seed, creative, Some(&options))? + } Action::Connect { address } => { self.connect_server(&address, &self.options.player_name())? } @@ -9726,7 +9741,7 @@ pub fn run() -> Result<()> { } Some(folder) => { let (seed, creative) = (game.options.seed, game.options.creative); - game.open_world(&folder, None, Some(seed), creative)?; + game.open_world(&folder, None, Some(seed), creative, None)?; } None => { let title = Title::new( diff --git a/crates/horizon-client/src/game/agent.rs b/crates/horizon-client/src/game/agent.rs index af70b738a..243351af6 100644 --- a/crates/horizon-client/src/game/agent.rs +++ b/crates/horizon-client/src/game/agent.rs @@ -485,11 +485,19 @@ impl Game<'_> { seed, creative, focus, + options, } => json!({ "mode": "create-world", + "tab": (["game", "world", "more"][options.tab.min(2)]), "fields": { "name": name, "seed": seed }, "focus": match focus { 0 => "name", 1 => "seed", _ => "none" }, "creative": creative, + "hardcore": options.hardcore, + "difficulty": horizon_client::title::DIFFICULTIES[options.difficulty()], + "allow_commands": options.commands(*creative), + "superflat": options.flat, + "generate_structures": options.structures, + "bonus_chest": options.bonus_chest(), }), Mode::Edit { world, @@ -1322,10 +1330,17 @@ impl Game<'_> { let title = self.title.as_mut().ok_or("no title screen")?; if let Some(field) = &field { match &mut title.mode { - horizon_client::title::Mode::Create { focus, .. } => { + horizon_client::title::Mode::Create { focus, options, .. } => { + // Each box is on its own tab. *focus = match field.as_str() { - "name" => 0, - "seed" => 1, + "name" => { + options.tab = 0; + 0 + } + "seed" => { + options.tab = 1; + 1 + } other => { return Err(format!( "the create-world fields are name and seed, not {other}" diff --git a/crates/horizon-client/src/game/control.rs b/crates/horizon-client/src/game/control.rs index affa8d464..adaefacc5 100644 --- a/crates/horizon-client/src/game/control.rs +++ b/crates/horizon-client/src/game/control.rs @@ -488,7 +488,7 @@ impl Game<'_> { let folder = arg(1)?; let seed = words.get(2).map(|s| s.parse::()).transpose()?; let creative = words.get(3) == Some(&"creative"); - self.open_world(folder, Some(folder), seed, creative)?; + self.open_world(folder, Some(folder), seed, creative, None)?; ok() } "connect" => { diff --git a/crates/horizon-client/src/game/dedicated.rs b/crates/horizon-client/src/game/dedicated.rs index f4e410e2f..e73de6988 100644 --- a/crates/horizon-client/src/game/dedicated.rs +++ b/crates/horizon-client/src/game/dedicated.rs @@ -372,7 +372,13 @@ impl Game<'_> { let world_dir = std::env::current_dir()?.join(&universe).join(&level_name); let folder = world_dir.to_string_lossy().into_owned(); let new_world = !world_dir.join("level.dat").exists(); - self.open_world(&folder, Some(&level_name), Some(props.seed), game_mode == 1)?; + self.open_world( + &folder, + Some(&level_name), + Some(props.seed), + game_mode == 1, + None, + )?; if new_world { self.level.hardcore = props.hardcore; } diff --git a/crates/horizon-client/src/save.rs b/crates/horizon-client/src/save.rs index 294b788b6..8bd8a6aa9 100644 --- a/crates/horizon-client/src/save.rs +++ b/crates/horizon-client/src/save.rs @@ -1922,6 +1922,145 @@ const INT_RULES: [&str; 11] = [ /// World and player state stored in `level.dat`, the saved-data files and /// the player file. +/// The world options CreateWorldScreen sets (`WorldOptions` and the world +/// preset) that `world_gen_settings` keeps. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct WorldGen { + /// The `minecraft:flat` preset (Superflat) instead of `normal`. + pub flat: bool, + pub structures: bool, + pub bonus_chest: bool, +} +impl WorldGen { + /// A saved world's choices, from its `world_gen_settings`. + pub fn read(world: &Path) -> Option { + let settings = world_gen_settings(world)?; + let flag = |key: &str, default: bool| number(settings.get(key)).map_or(default, |v| v != 0); + let generator = settings + .get("dimensions") + .and_then(|d| d.get("minecraft:overworld")) + .and_then(|o| o.get("generator")); + Some(Self { + flat: text(generator.and_then(|g| g.get("type"))) + .is_some_and(|t| t.trim_start_matches("minecraft:") == "flat"), + structures: flag("generate_structures", true), + bonus_chest: flag("bonus_chest", false), + }) + } +} +impl Default for WorldGen { + fn default() -> Self { + Self { + flat: false, + structures: true, + bonus_chest: false, + } + } +} +/// Writes a new world's `world_gen_settings` (seed, options and dimensions). +pub fn write_world_gen_settings(dir: &Path, seed: i64, options: WorldGen) -> Result<()> { + fs::create_dir_all(dir)?; + // worldgen/world_preset/flat.json's overworld: the classic flat layers. + let layer = |block: &str, height: i32| { + Tag::compound([("block", string(block)), ("height", Tag::Int(height))]) + }; + let flat = Tag::compound([ + ("type", string("minecraft:overworld")), + ( + "generator", + Tag::compound([ + ("type", string("minecraft:flat")), + ( + "settings", + Tag::compound([ + ("biome", string("minecraft:plains")), + ("features", Tag::Byte(0)), + ("lakes", Tag::Byte(0)), + ( + "layers", + Tag::List(vec![ + layer("minecraft:bedrock", 1), + layer("minecraft:dirt", 2), + layer("minecraft:grass_block", 1), + ]), + ), + ( + "structure_overrides", + Tag::List(vec![ + string("minecraft:strongholds"), + string("minecraft:villages"), + ]), + ), + ]), + ), + ]), + ), + ]); + let dimension = |kind: &str, settings: &str, source: Tag| { + Tag::compound([ + ("type", string(kind)), + ( + "generator", + Tag::compound([ + ("type", string("minecraft:noise")), + ("settings", string(settings)), + ("biome_source", source), + ]), + ), + ]) + }; + let preset = |p: &str| { + Tag::compound([ + ("type", string("minecraft:multi_noise")), + ("preset", string(p)), + ]) + }; + write_saved_data( + dir, + "world_gen_settings", + Tag::compound([ + ("seed", Tag::Long(seed)), + ( + "generate_structures", + Tag::Byte(i8::from(options.structures)), + ), + ("bonus_chest", Tag::Byte(i8::from(options.bonus_chest))), + ( + "dimensions", + Tag::compound([ + ( + "minecraft:overworld", + if options.flat { + flat + } else { + dimension( + "minecraft:overworld", + "minecraft:overworld", + preset("minecraft:overworld"), + ) + }, + ), + ( + "minecraft:the_nether", + dimension( + "minecraft:the_nether", + "minecraft:nether", + preset("minecraft:nether"), + ), + ), + ( + "minecraft:the_end", + dimension( + "minecraft:the_end", + "minecraft:end", + Tag::compound([("type", string("minecraft:the_end"))]), + ), + ), + ]), + ), + ]), + ) +} #[derive(Clone, Debug, Default)] pub struct Level { pub name: String, @@ -1964,6 +2103,9 @@ pub struct Level { pub world_spawn: Option<[i32; 3]>, pub difficulty: String, pub hardcore: bool, + /// `allowCommands` chosen on the Create New World screen; unset keeps + /// the saved value (off for a new world). + pub allow_commands: Option, /// Game rule values by name without namespace (`keep_inventory`, ...). pub game_rules: BTreeMap, pub player_uuid: Option<[i32; 4]>, @@ -2524,6 +2666,9 @@ impl Level { } if let Tag::Compound(map) = &mut data { map.entry("allowCommands".into()).or_insert(Tag::Byte(0)); + if let Some(allow) = self.allow_commands { + map.insert("allowCommands".into(), Tag::Byte(i8::from(allow))); + } map.entry("WasModded".into()).or_insert(Tag::Byte(0)); map.entry("DataPacks".into()).or_insert_with(|| { Tag::compound([ @@ -2567,63 +2712,7 @@ impl Level { } write_saved_data(dir, "world_clocks", clocks)?; if legacy || !saved_data_path(dir, "world_gen_settings").exists() { - let dimension = |kind: &str, settings: &str, source: Tag| { - Tag::compound([ - ("type", string(kind)), - ( - "generator", - Tag::compound([ - ("type", string("minecraft:noise")), - ("settings", string(settings)), - ("biome_source", source), - ]), - ), - ]) - }; - let preset = |p: &str| { - Tag::compound([ - ("type", string("minecraft:multi_noise")), - ("preset", string(p)), - ]) - }; - write_saved_data( - dir, - "world_gen_settings", - Tag::compound([ - ("seed", Tag::Long(self.seed)), - ("generate_structures", Tag::Byte(1)), - ("bonus_chest", Tag::Byte(0)), - ( - "dimensions", - Tag::compound([ - ( - "minecraft:overworld", - dimension( - "minecraft:overworld", - "minecraft:overworld", - preset("minecraft:overworld"), - ), - ), - ( - "minecraft:the_nether", - dimension( - "minecraft:the_nether", - "minecraft:nether", - preset("minecraft:nether"), - ), - ), - ( - "minecraft:the_end", - dimension( - "minecraft:the_end", - "minecraft:end", - Tag::compound([("type", string("minecraft:the_end"))]), - ), - ), - ]), - ), - ]), - )?; + write_world_gen_settings(dir, self.seed, WorldGen::default())?; } if !saved_data_path(dir, "game_rules").exists() || !self.game_rules.is_empty() { // Only rules vanilla knows: an unknown key makes it reject the file. diff --git a/crates/horizon-client/src/title.rs b/crates/horizon-client/src/title.rs index 52dfba28a..c4e568df5 100644 --- a/crates/horizon-client/src/title.rs +++ b/crates/horizon-client/src/title.rs @@ -12,9 +12,11 @@ use std::{ sync::mpsc, }; +mod create_world; #[cfg(test)] mod tests; mod world_management; +pub use create_world::{DIFFICULTIES, WorldOptions}; /// SelectWorldScreen's `HeaderAndFooterLayout(8 + 9 + 8 + 20 + 4, 60)`. const LIST_TOP: f32 = 49.0; @@ -81,6 +83,7 @@ pub enum Mode { seed: String, creative: bool, focus: u8, + options: WorldOptions, }, Edit { world: WorldEntry, @@ -114,6 +117,7 @@ pub enum Action { name: String, seed: Option, creative: bool, + options: WorldOptions, }, Connect { address: String, @@ -140,7 +144,7 @@ pub struct Title { /// The saves listed for Home, re-read every couple of seconds. recent: std::cell::RefCell)>>, } -struct Button { +pub(crate) struct Button { x: f32, y: f32, w: f32, @@ -265,12 +269,13 @@ impl Title { } }; } - fn new_world() -> Mode { + pub(crate) fn new_world() -> Mode { Mode::Create { name: "New World".into(), seed: String::new(), creative: false, focus: 0, + options: WorldOptions::default(), } } fn return_to_list(&mut self, folder: Option<&str>) { @@ -483,11 +488,22 @@ impl Title { name, seed, creative, + options, .. } = &self.mode else { return Action::None; }; + Action::Create { + folder: self.target_folder(name), + name: name.clone(), + seed: parse_seed(seed), + creative: *creative, + options: options.clone(), + } + } + /// The folder a new world named `name` gets (`findResultFolder`). + fn target_folder(&self, name: &str) -> String { let base: String = name .chars() .map(|c| { @@ -510,12 +526,7 @@ impl Title { folder = format!("{base} ({n})"); n += 1; } - Action::Create { - folder, - name: name.clone(), - seed: parse_seed(seed), - creative: *creative, - } + folder } fn buttons(&self, w: f32, h: f32) -> Vec