diff --git a/crates/horizon-client/examples/hud_fixture.rs b/crates/horizon-client/examples/hud_fixture.rs index f02d7e1ff..46da5e0ad 100644 --- a/crates/horizon-client/examples/hud_fixture.rs +++ b/crates/horizon-client/examples/hud_fixture.rs @@ -7,6 +7,7 @@ use horizon_client::{ hud::{HudAtlas, HudBatch}, hud_layout::{self, GuiDraw, HealthHud, HealthInputs, HeartKind, HotbarInputs, IDENTITY, Pose}, + lang, text::Text, }; use serde_json::{Value, json}; @@ -25,6 +26,7 @@ fn main() -> Result<()> { return Err("usage: hud_fixture RESOURCES INPUTS OUTPUT".into()); }; let atlas = HudAtlas::build(root)?; + lang::set(lang::Language::load(&[root], lang::DEFAULT)); let mut out = BufWriter::new(fs::File::create(output)?); for line in fs::read_to_string(inputs)? .lines() @@ -53,7 +55,13 @@ fn runs(t: &Text) -> Option { _ => out.push((ch.to_string(), key.0, key.1, key.2)), } } - styled.then(|| json!(out.into_iter().map(|r| json!([r.0, r.1, r.2, r.3])).collect::>())) + styled.then(|| { + json!( + out.into_iter() + .map(|r| json!([r.0, r.1, r.2, r.3])) + .collect::>() + ) + }) } fn encode(draws: &[GuiDraw]) -> Vec { @@ -74,28 +82,80 @@ fn encode(draws: &[GuiDraw]) -> Vec { stack.pop(); continue; } - GuiDraw::Sprite { sprite, x, y, w, h, region, color } => { + GuiDraw::Sprite { + sprite, + x, + y, + w, + h, + region, + color, + } => { json!({"type": "sprite", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "region": region, "color": *color as i32}) } - GuiDraw::AtlasSprite { sprite, x, y, w, h, color } => { + GuiDraw::AtlasSprite { + sprite, + x, + y, + w, + h, + color, + } => { json!({"type": "atlas", "sprite": sprite, "x": x, "y": y, "w": w, "h": h, "color": *color as i32}) } - GuiDraw::Blit { texture, blend, x, y, w, h, uv, src, tex, color } => json!({ + GuiDraw::Blit { + texture, + blend, + x, + y, + w, + h, + uv, + src, + tex, + color, + } => json!({ "type": "blit", "texture": format!("textures/{texture}.png"), "pipeline": blend.pipeline(), "x": x, "y": y, "w": w, "h": h, "uv": uv, "src": src, "tex": tex, "color": *color as i32}), - GuiDraw::Fill { x0, y0, x1, y1, color } => { + GuiDraw::Fill { + x0, + y0, + x1, + y1, + color, + } => { json!({"type": "fill", "x0": x0, "y0": y0, "x1": x1, "y1": y1, "color": *color as i32}) } - GuiDraw::Text { text, x, y, color, shadow } => { + GuiDraw::Text { + text, + x, + y, + color, + shadow, + } => { let mut v = json!({"type": "text", "text": text.plain(), "x": x, "y": y, "color": *color as i32, "shadow": shadow}); if let Some(r) = runs(text) { v["runs"] = r; } v } - GuiDraw::Item { slot, x, y, seed, scale, pivot } => { + GuiDraw::Item { + slot, + x, + y, + seed, + scale, + pivot, + } => { // translate(pivot) * scale * translate(-pivot) as a 3x2 matrix. - let m = [scale[0], 0.0, 0.0, scale[1], pivot[0] - pivot[0] * scale[0], pivot[1] - pivot[1] * scale[1]]; + let m = [ + scale[0], + 0.0, + 0.0, + scale[1], + pivot[0] - pivot[0] * scale[0], + pivot[1] - pivot[1] * scale[1], + ]; out.push(json!({"type": "item", "slot": slot, "x": x, "y": y, "seed": seed, "matrix": m})); continue; } diff --git a/crates/horizon-client/examples/hud_fixture/kinds.rs b/crates/horizon-client/examples/hud_fixture/kinds.rs index fd8ea6ffe..52abd73a0 100644 --- a/crates/horizon-client/examples/hud_fixture/kinds.rs +++ b/crates/horizon-client/examples/hud_fixture/kinds.rs @@ -1,9 +1,117 @@ //! The overlay case kinds of the HUD parity fixture. -use horizon_client::{hud::HudAtlas, hud_layout::GuiDraw}; +use horizon_client::{ + brewing, component, + hud::HudAtlas, + hud_layout::{self, GuiDraw}, + hud_overlays::{self, EffectIcon, HeldName, Titles, ToolHighlight}, + text::{self, Text}, +}; use serde_json::Value; -pub fn run(kind: &str, _c: &Value, _atlas: &HudAtlas) -> Vec { +fn int(c: &Value, k: &str, d: i64) -> i32 { + c[k].as_i64().unwrap_or(d) as i32 +} +fn float(c: &Value, k: &str, d: f64) -> f32 { + c[k].as_f64().unwrap_or(d) as f32 +} +/// A text component in its JSON form. +fn comp(v: &Value) -> Text { + component::to_text(v, &mut |s| Text::literal(s)) +} +/// `Options.getBackgroundColor(0.0F)` from the case's text background options. +fn background(c: &Value) -> u32 { + hud_layout::background_color( + c["chatOnly"].as_bool().unwrap_or(true), + c["textOpacity"].as_f64().unwrap_or(0.5), + 0.0, + ) +} + +pub fn run(kind: &str, c: &Value, atlas: &HudAtlas) -> Vec { + let (w, h) = (int(c, "width", 0), int(c, "height", 0)); match kind { + "effects" => effects(c, w), + "title" => title(c, w, h, atlas), + "selected" => selected(c, w, h, atlas), _ => Vec::new(), } } + +fn effects(c: &Value, w: i32) -> Vec { + let icons: Vec = c["active"] + .as_array() + .into_iter() + .flatten() + .map(|e| { + let id = e["id"] + .as_str() + .unwrap_or("") + .trim_start_matches("minecraft:"); + let def = brewing::effect(id).expect("effect"); + EffectIcon { + id: id.to_owned(), + beneficial: def.category == brewing::Category::Beneficial, + color: def.color as i32, + ambient: e["ambient"].as_bool().unwrap_or(false), + duration: e["duration"].as_i64().unwrap_or(0) as i32, + show_icon: e["icon"].as_bool().unwrap_or(true), + } + }) + .collect(); + hud_overlays::effects(w, c["demo"].as_bool().unwrap_or(false), &icons) +} + +/// Replays `Hud.setTitle` / `setSubtitle` / `setTimes` / `clearTitles` / +/// `resetTitleTimes` / `setOverlayMessage` and ticks, then extracts the +/// action bar and the title. +fn title(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let mut t = Titles::default(); + for op in c["ops"].as_array().into_iter().flatten() { + let n = |i: usize| op[i].as_i64().unwrap_or(0) as i32; + match op[0].as_str().unwrap_or("") { + "title" => t.set_title(comp(&op[1])), + "subtitle" => t.set_subtitle(comp(&op[1])), + "times" => t.set_times(n(1), n(2), n(3)), + "clear" => t.clear(), + "reset" => t.reset_times(), + "overlay" => t.set_overlay(comp(&op[1]), op[2].as_bool().unwrap_or(false)), + "tick" => { + for _ in 0..n(1) { + t.tick(); + } + } + other => panic!("unknown title op {other}"), + } + } + let partial = float(c, "partial", 0.0); + let bg = background(c); + let mut out = t.overlay_message(w, h, partial, &atlas.font, bg); + out.extend(t.title(w, h, partial, &atlas.font, bg)); + out +} + +/// Ticks `toolHighlightTimer` through the selected stacks, then extracts the name. +fn selected(c: &Value, w: i32, h: i32, atlas: &HudAtlas) -> Vec { + let mut highlight = ToolHighlight::default(); + let time = c["displayTime"].as_f64().unwrap_or(1.0); + for step in c["steps"].as_array().into_iter().flatten() { + let held = (!step.is_null()).then(|| { + let custom = &step["custom"]; + HeldName { + item: step["item"].as_str().unwrap_or("").to_owned(), + hover_name: if custom.is_null() { + Text::translate(step["key"].as_str().unwrap_or(""), &[]) + } else { + comp(custom) + }, + rarity_color: text::named_color(step["rarity"].as_str().unwrap_or("white")) + .unwrap_or(0xFFFFFF), + custom_name: !custom.is_null(), + } + }); + highlight.tick(held, time); + } + let mode = c["gameMode"].as_str().unwrap_or("survival"); + let can_hurt = mode == "survival" || mode == "adventure"; + highlight.draw(w, h, can_hurt, &atlas.font, background(c)) +} diff --git a/crates/horizon-client/src/game.rs b/crates/horizon-client/src/game.rs index 667e7d911..5a1608282 100644 --- a/crates/horizon-client/src/game.rs +++ b/crates/horizon-client/src/game.rs @@ -634,6 +634,8 @@ struct Game<'a> { /// The source of a command run through /execute (the player otherwise). command_source: Option, titles: titles::Titles, + /// `Hud.toolHighlightTimer`: the selected item name. + tool_highlight: horizon_client::hud_overlays::ToolHighlight, applied_modifiers: Vec<(String, String)>, experience: Experience, orbs: Vec, @@ -2695,7 +2697,7 @@ impl Game<'_> { self.tick_effects(); self.tick_burning(); self.tick_using(); - self.titles.tick(); + self.tick_hud(); if running { self.tick_paintings(); self.tick_item_frames(); @@ -3000,6 +3002,9 @@ impl Game<'_> { let draws = self.health_hud.layout(&inputs, wi, hi); hud_layout::paint(&mut batch, atlas, &draws); } + if !spectator { + self.draw_selected_name(&mut batch, !self.creative); + } let atlas = &self.res.atlas; if self.debug { let p = self @@ -8036,6 +8041,7 @@ pub fn run() -> Result<()> { shield_cooldown: 0, command_source: None, titles: Default::default(), + tool_highlight: Default::default(), applied_modifiers: Vec::new(), experience: Experience::default(), orbs: Vec::new(), diff --git a/crates/horizon-client/src/game/commands.rs b/crates/horizon-client/src/game/commands.rs index 9dfed52ea..2b50bf260 100644 --- a/crates/horizon-client/src/game/commands.rs +++ b/crates/horizon-client/src/game/commands.rs @@ -687,7 +687,7 @@ impl Game<'_> { .append("]") .with_color(color) } - fn item_rarity(&self, item: &str) -> String { + pub(super) fn item_rarity(&self, item: &str) -> String { static RARITY: std::sync::OnceLock> = std::sync::OnceLock::new(); let map = RARITY.get_or_init(|| { diff --git a/crates/horizon-client/src/game/commands/text_commands.rs b/crates/horizon-client/src/game/commands/text_commands.rs index 12cb54603..e99e01e32 100644 --- a/crates/horizon-client/src/game/commands/text_commands.rs +++ b/crates/horizon-client/src/game/commands/text_commands.rs @@ -67,10 +67,10 @@ impl Game<'_> { } else { let text = self.component_arg(ctx, "title")?; if ctx.has("subtitle") { - self.titles.subtitle = Some(text); + self.titles.set_subtitle(text); "show.subtitle" } else if ctx.has("actionbar") { - self.titles.set_overlay(text); + self.titles.set_overlay(text, false); "show.actionbar" } else { self.titles.set_title(text); diff --git a/crates/horizon-client/src/game/jukebox.rs b/crates/horizon-client/src/game/jukebox.rs index f721e2352..c4f595a3a 100644 --- a/crates/horizon-client/src/game/jukebox.rs +++ b/crates/horizon-client/src/game/jukebox.rs @@ -104,8 +104,7 @@ impl Game<'_> { let description = horizon_client::component::to_text(&s.description, &mut |k| Text::literal(k)); self.titles - .set_overlay(Text::translate("record.nowPlaying", &[description])); - self.titles.overlay_animated = true; + .set_overlay(Text::translate("record.nowPlaying", &[description]), true); self.update_song_volumes(); } fn stop_song(&mut self, pos: [i32; 3]) { diff --git a/crates/horizon-client/src/game/potions.rs b/crates/horizon-client/src/game/potions.rs index fd5e30b34..ba7c10846 100644 --- a/crates/horizon-client/src/game/potions.rs +++ b/crates/horizon-client/src/game/potions.rs @@ -6,7 +6,8 @@ use super::{Game, Screen}; use horizon_client::{ brewing, effects::{EffectAction, EffectInstance, PlayerEffects}, - hud::{HudBatch, rgba}, + hud::HudBatch, + hud_layout, hud_overlays, items::ItemStack, }; use horizon_core::{geometry::Vec3, random::RandomSource}; @@ -542,52 +543,26 @@ impl Game<'_> { if self.screen != Screen::Playing || self.potions.effects.list.is_empty() { return; } - let mut list: Vec<&EffectInstance> = self.potions.effects.list.iter().collect(); - let color = |e: &EffectInstance| brewing::effect(e.id).map_or(0, |d| d.color); - list.sort_by(|a, b| { - (a.ambient, a.duration == -1, a.duration, color(a)) - .cmp(&(b.ambient, b.duration == -1, b.duration, color(b))) - .reverse() - }); - let (mut good, mut bad) = (0, 0); - let atlas = &self.res.atlas; - for e in list { - let beneficial = - brewing::effect(e.id).is_some_and(|d| d.category == brewing::Category::Beneficial); - let mut x = batch.width; - let mut y = 1.0; - if beneficial { - good += 1; - x -= 25.0 * good as f32; - } else { - bad += 1; - x -= 25.0 * bad as f32; - y += 26.0; - } - let mut alpha = 1.0f32; - if e.ambient { - batch.sprite(atlas, "gui/sprites/hud/effect_background_ambient", x, y); - } else { - batch.sprite(atlas, "gui/sprites/hud/effect_background", x, y); - if e.duration != -1 && e.duration <= 200 { - let d = e.duration as f32; - let used = 10.0 - (e.duration / 20) as f32; - alpha = ((d / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5) - + (d * std::f32::consts::PI / 5.0).cos() - * (used / 10.0 * 0.25).clamp(0.0, 0.25)) - .clamp(0.0, 1.0); + let icons: Vec = self + .potions + .effects + .list + .iter() + .map(|e| { + let def = brewing::effect(e.id); + hud_overlays::EffectIcon { + id: e.id.to_owned(), + beneficial: def.is_some_and(|d| d.category == brewing::Category::Beneficial), + color: def.map_or(0, |d| d.color as i32), + ambient: e.ambient, + duration: e.duration, + // Horizon keeps no showIcon flag: every effect shows its icon. + show_icon: true, } - } - batch.sprite_scaled( - atlas, - &format!("mob_effect/{}", e.id), - x + 3.0, - y + 3.0, - 18.0, - 18.0, - rgba(255, 255, 255, (alpha * 255.0) as u8), - ); - } + }) + .collect(); + let draws = hud_overlays::effects(batch.width as i32, false, &icons); + hud_layout::paint(batch, &self.res.atlas, &draws); } /// Effects saved in level.dat (`Player.active_effects`). pub(super) fn restore_effects(&mut self) { diff --git a/crates/horizon-client/src/game/titles.rs b/crates/horizon-client/src/game/titles.rs index 57fe9dbd5..89e50c0d0 100644 --- a/crates/horizon-client/src/game/titles.rs +++ b/crates/horizon-client/src/game/titles.rs @@ -1,169 +1,69 @@ -//! Titles, subtitles and the action bar (`Gui.setTitle`, `setSubtitle`, -//! `setTimes`, `setOverlayMessage`, `extractTitle`, `extractOverlayMessage`). +//! Titles, the action bar and the selected item name: the state and layout +//! live in `hud_overlays` (`Titles`, `ToolHighlight`); this feeds and draws them. use super::Game; +pub(super) use horizon_client::hud_overlays::Titles; use horizon_client::{ - hud::{HudBatch, rgba}, - text::Text, + hud::HudBatch, + hud_layout, + hud_overlays::HeldName, + text::{self, Text}, }; -pub(super) struct Titles { - pub title: Option, - pub subtitle: Option, - pub time: i32, - pub fade_in: i32, - pub stay: i32, - pub fade_out: i32, - pub overlay: Option, - pub overlay_time: i32, - /// `animateOverlayMessageColor`: the "Now Playing" rainbow. - pub overlay_animated: bool, -} -impl Default for Titles { - fn default() -> Self { - Self { - title: None, - subtitle: None, - time: 0, - fade_in: 10, - stay: 70, - fade_out: 20, - overlay: None, - overlay_time: 0, - overlay_animated: false, - } - } -} -impl Titles { - pub fn set_title(&mut self, title: Text) { - self.title = Some(title); - self.time = self.fade_in + self.stay + self.fade_out; - } - pub fn set_times(&mut self, fade_in: i32, stay: i32, fade_out: i32) { - if fade_in >= 0 { - self.fade_in = fade_in; - } - if stay >= 0 { - self.stay = stay; - } - if fade_out >= 0 { - self.fade_out = fade_out; - } - if self.time > 0 { - self.time = self.fade_in + self.stay + self.fade_out; - } - } - pub fn clear(&mut self) { - self.title = None; - self.subtitle = None; - self.time = 0; - } - pub fn reset_times(&mut self) { - (self.fade_in, self.stay, self.fade_out) = (10, 70, 20); - } - pub fn set_overlay(&mut self, text: Text) { - self.overlay = Some(text); - self.overlay_time = 60; - self.overlay_animated = false; - } - /// Gui.tick. - pub fn tick(&mut self) { - if self.overlay_time > 0 { - self.overlay_time -= 1; - } - if self.time > 0 { - self.time -= 1; - if self.time <= 0 { - self.title = None; - self.subtitle = None; - } - } - } -} impl Game<'_> { + /// `Hud.extractOverlayMessage` and `extractTitle`. pub(super) fn draw_titles(&self, batch: &mut HudBatch) { - let t = &self.titles; + let (w, h) = (batch.width as i32, batch.height as i32); let partial = self.clock.fraction() as f32; - let atlas = &self.res.atlas; - let (w, h) = (batch.width, batch.height); - if let Some(text) = &t.overlay - && t.overlay_time > 0 - { - let ticks = t.overlay_time as f32 - partial; - let alpha = ((ticks * 255.0 / 20.0) as i32).min(255); - if alpha > 0 { - let width = atlas.font.width_text(text); - let color = if t.overlay_animated { - let [r, g, b] = hsv_to_rgb(ticks / 50.0, 0.7, 0.6); - rgba(r, g, b, alpha as u8) - } else { - rgba(255, 255, 255, alpha as u8) - }; - batch.text_posed( - atlas, - text, - [-(width / 2.0).trunc(), -4.0], - color, - 1.0, - [(w / 2.0).trunc(), (h - 68.0).trunc()], - ); - } + let background = self.settings.text_background(0.0); + let font = &self.res.atlas.font; + let mut draws = self.titles.overlay_message(w, h, partial, font, background); + draws.extend(self.titles.title(w, h, partial, font, background)); + hud_layout::paint(batch, &self.res.atlas, &draws); + } + /// The selected stack as `Hud.tick` compares it for the name highlight. + fn held_name(&self) -> Option { + let stack = self.inventory.get(self.selected)?.as_ref()?; + let custom = stack.custom_name(); + // ItemStack.getRarity: enchanting raises common and uncommon to rare + // and rare to epic. + let mut rarity = self.item_rarity(&stack.item); + if !stack.enchantments().is_empty() { + rarity = match rarity.as_str() { + "common" | "uncommon" => "rare".into(), + "rare" => "epic".into(), + _ => rarity, + }; } - let Some(title) = &t.title else { return }; - if t.time <= 0 { - return; - } - let ticks = t.time as f32 - partial; - let mut alpha = 255; - if t.time > t.fade_out + t.stay { - let time = (t.fade_in + t.stay + t.fade_out) as f32 - ticks; - alpha = (time * 255.0 / t.fade_in.max(1) as f32) as i32; - } - if t.time <= t.fade_out { - alpha = (ticks * 255.0 / t.fade_out.max(1) as f32) as i32; - } - let alpha = alpha.clamp(0, 255); - if alpha == 0 { - return; - } - let color = rgba(255, 255, 255, alpha as u8); - let origin = [(w / 2.0).trunc(), (h / 2.0).trunc()]; - let width = atlas.font.width_text(title); - batch.text_posed( - atlas, - title, - [-(width / 2.0).trunc(), -10.0], - color, - 4.0, - origin, + Some(HeldName { + item: stack.item.to_string(), + hover_name: Text::literal( + custom.map_or_else(|| self.res.names.item(&stack.item), str::to_owned), + ), + rarity_color: match rarity.as_str() { + "uncommon" => text::YELLOW, + "rare" => text::AQUA, + "epic" => text::LIGHT_PURPLE, + _ => text::WHITE, + }, + custom_name: custom.is_some(), + }) + } + /// The title, action bar and selected-item parts of `Hud.tick`. + pub(super) fn tick_hud(&mut self) { + self.titles.tick(); + let held = self.held_name(); + self.tool_highlight + .tick(held, f64::from(self.settings.notification_display_time)); + } + /// `Hud.extractSelectedItemName`. + pub(super) fn draw_selected_name(&self, batch: &mut HudBatch, can_hurt: bool) { + let draws = self.tool_highlight.draw( + batch.width as i32, + batch.height as i32, + can_hurt, + &self.res.atlas.font, + self.settings.text_background(0.0), ); - if let Some(sub) = &t.subtitle { - let width = atlas.font.width_text(sub); - batch.text_posed( - atlas, - sub, - [-(width / 2.0).trunc(), 5.0], - color, - 2.0, - origin, - ); - } + hud_layout::paint(batch, &self.res.atlas, &draws); } } -/// `Mth.hsvToRgb`. -fn hsv_to_rgb(hue: f32, saturation: f32, value: f32) -> [u8; 3] { - let h = (hue * 6.0) as i32 % 6; - let f = hue * 6.0 - (hue * 6.0).floor(); - let p = value * (1.0 - saturation); - let q = value * (1.0 - f * saturation); - let t = value * (1.0 - (1.0 - f) * saturation); - let (r, g, b) = match h { - 0 => (value, t, p), - 1 => (q, value, p), - 2 => (p, value, t), - 3 => (p, q, value), - 4 => (t, p, value), - _ => (value, p, q), - }; - let c = |v: f32| (v * 255.0).clamp(0.0, 255.0) as u8; - [c(r), c(g), c(b)] -} diff --git a/crates/horizon-client/src/hud_layout.rs b/crates/horizon-client/src/hud_layout.rs index 32c2a0e86..8972eaa63 100644 --- a/crates/horizon-client/src/hud_layout.rs +++ b/crates/horizon-client/src/hud_layout.rs @@ -139,7 +139,14 @@ fn sprite(sprite: &'static str, x: i32, y: i32, w: i32, h: i32) -> GuiDraw { color: WHITE, } } -fn region(sprite: &'static str, size: [i32; 2], uv: [i32; 2], at: [i32; 2], w: i32, h: i32) -> GuiDraw { +fn region( + sprite: &'static str, + size: [i32; 2], + uv: [i32; 2], + at: [i32; 2], + w: i32, + h: i32, +) -> GuiDraw { GuiDraw::Sprite { sprite: Cow::Borrowed(sprite), x: at[0], @@ -172,14 +179,6 @@ fn text(out: &mut Vec, text: Text, x: i32, y: i32, color: u32, shadow: }); } } -/// `graphics.textWithBackdrop` under `background` = `Options.getBackgroundColor(0)`. -fn text_with_backdrop(out: &mut Vec, t: Text, x: i32, y: i32, w: i32, color: u32, background: u32) { - if background != 0 { - out.push(fill(x - 2, y - 2, x + w + 2, y + 9 + 2, multiply(background, color))); - } - text(out, t, x, y, color, true); -} - /// `Options.getBackgroundColor(float)`: `chat_only` = `backgroundForChatOnly`. pub fn background_color(chat_only: bool, opacity: f64, default: f32) -> u32 { let a = if chat_only { default } else { opacity as f32 }; @@ -424,7 +423,14 @@ pub fn experience( let x = (w - width(&text)) / 2; let y = h - 24 - 9 - 2; for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { - self::text(&mut out, Text::literal(&text), x + dx, y + dy, 0xFF00_0000, false); + self::text( + &mut out, + Text::literal(&text), + x + dx, + y + dy, + 0xFF00_0000, + false, + ); } self::text(&mut out, Text::literal(text), x, y, 0xFF80_FF20, false); } @@ -780,7 +786,15 @@ pub fn paint(batch: &mut crate::hud::HudBatch, atlas: &crate::hud::HudAtlas, dra h, color, } => { - batch.sprite_scaled(atlas, sprite, *x as f32, *y as f32, *w as f32, *h as f32, abgr(*color)); + batch.sprite_scaled( + atlas, + sprite, + *x as f32, + *y as f32, + *w as f32, + *h as f32, + abgr(*color), + ); } GuiDraw::Blit { texture, diff --git a/crates/horizon-client/src/hud_overlays.rs b/crates/horizon-client/src/hud_overlays.rs new file mode 100644 index 000000000..ec77a639b --- /dev/null +++ b/crates/horizon-client/src/hud_overlays.rs @@ -0,0 +1,437 @@ +//! The `Hud` overlays above the hotbar and decorations, laid out as +//! [`GuiDraw`] calls like [`crate::hud_layout`]: status effect icons +//! (`extractEffects`), titles and the action bar (`extractTitle`, +//! `extractOverlayMessage` and the title timers of `Hud.tick`), and the +//! selected item name (`extractSelectedItemName` and its `toolHighlightTimer`). +use crate::{ + font::Font, + hud_layout::{GuiDraw, PoseOp, fill, hsv_to_argb, multiply, white, width}, + text::{Style, Text}, +}; +use std::{borrow::Cow, cmp::Ordering}; + +/// `graphics.text`: dropped when fully transparent. +fn text(out: &mut Vec, text: Text, x: i32, y: i32, color: u32, shadow: bool) { + if color >> 24 != 0 { + out.push(GuiDraw::Text { + text, + x, + y, + color, + shadow, + }); + } +} + +/// `graphics.textWithBackdrop`; `background` is `Options.getBackgroundColor(0.0F)`. +pub fn text_with_backdrop( + out: &mut Vec, + t: Text, + x: i32, + y: i32, + w: i32, + color: u32, + background: u32, +) { + if background != 0 { + out.push(fill( + x - 2, + y - 2, + x + w + 2, + y + 9 + 2, + multiply(background, color), + )); + } + text(out, t, x, y, color, true); +} + +/// `Arrays.sort(T[], Comparator)` for the short arrays the HUD sorts: Java's +/// TimSort below `MIN_MERGE` (a natural run, then binary insertion), which +/// matters when the comparator is not a total order. Longer arrays fall back +/// to a stable sort. +pub fn java_sort(a: &mut [T], cmp: impl Fn(&T, &T) -> Ordering) { + let n = a.len(); + if n < 2 { + return; + } + if n >= 32 { + a.sort_by(cmp); + return; + } + // countRunAndMakeAscending. + let mut run = 2; + if cmp(&a[1], &a[0]) == Ordering::Less { + while run < n && cmp(&a[run], &a[run - 1]) == Ordering::Less { + run += 1; + } + a[..run].reverse(); + } else { + while run < n && cmp(&a[run], &a[run - 1]) != Ordering::Less { + run += 1; + } + } + // binarySort. + for start in run..n { + let (mut left, mut right) = (0, start); + while left < right { + let mid = (left + right) / 2; + if cmp(&a[start], &a[mid]) == Ordering::Less { + right = mid; + } else { + left = mid + 1; + } + } + a[left..=start].rotate_right(1); + } +} + +/// A `MobEffectInstance` as `extractEffects` sees it. +#[derive(Clone, Debug, PartialEq)] +pub struct EffectIcon { + /// The effect id without namespace (`speed`): the sprite is `mob_effect/`. + pub id: String, + /// `MobEffect.isBeneficial`. + pub beneficial: bool, + /// `MobEffect.getColor`. + pub color: i32, + pub ambient: bool, + /// Remaining ticks, -1 for infinite. + pub duration: i32, + pub show_icon: bool, +} + +/// `MobEffectInstance.compareTo`. +fn compare_effects(a: &EffectIcon, o: &EffectIcon) -> Ordering { + if (a.duration <= 32147 || o.duration <= 32147) && !(a.ambient && o.ambient) { + a.ambient + .cmp(&o.ambient) + .then((a.duration == -1).cmp(&(o.duration == -1))) + .then(a.duration.cmp(&o.duration)) + .then(a.color.cmp(&o.color)) + } else { + a.ambient.cmp(&o.ambient).then(a.color.cmp(&o.color)) + } +} + +/// `Hud.extractEffects`: `effects` in `getActiveEffects` order; `demo` moves +/// the icons below the demo timer. +pub fn effects(w: i32, demo: bool, effects: &[EffectIcon]) -> Vec { + let mut out = Vec::new(); + let mut sorted: Vec<&EffectIcon> = effects.iter().collect(); + // Ordering.natural().reverse().sortedCopy. + java_sort(&mut sorted, |a, b| compare_effects(b, a)); + let (mut beneficial, mut harmful) = (0, 0); + for e in sorted.into_iter().filter(|e| e.show_icon) { + let mut x = w; + let mut y = 1 + if demo { 15 } else { 0 }; + if e.beneficial { + beneficial += 1; + x -= 25 * beneficial; + } else { + harmful += 1; + x -= 25 * harmful; + y += 26; + } + let mut alpha = 1.0f32; + let background = if e.ambient { + "hud/effect_background_ambient" + } else { + if e.duration != -1 && e.duration <= 200 { + let remaining = e.duration; + let used = 10 - remaining / 20; + alpha = (remaining as f32 / 10.0 / 5.0 * 0.5).clamp(0.0, 0.5) + + horizon_core::geometry::trig::cos(f64::from( + remaining as f32 * std::f32::consts::PI / 5.0, + )) * (used as f32 / 10.0 * 0.25).clamp(0.0, 0.25); + alpha = alpha.clamp(0.0, 1.0); + } + "hud/effect_background" + }; + out.push(GuiDraw::Sprite { + sprite: Cow::Borrowed(background), + x, + y, + w: 24, + h: 24, + region: None, + color: crate::hud_layout::WHITE, + }); + out.push(GuiDraw::Sprite { + sprite: Cow::Owned(format!("mob_effect/{}", e.id)), + x: x + 3, + y: y + 3, + w: 18, + h: 18, + region: None, + color: white(alpha), + }); + } + out +} + +/// Titles and the action bar: `Hud.title`, `subtitle`, `titleTime`, the +/// fade times and `overlayMessageString` / `overlayMessageTime`. +#[derive(Clone, Debug, PartialEq)] +pub struct Titles { + pub title: Option, + pub subtitle: Option, + pub time: i32, + pub fade_in: i32, + pub stay: i32, + pub fade_out: i32, + pub overlay: Option, + pub overlay_time: i32, + /// `animateOverlayMessageColor`: the "Now Playing" rainbow. + pub overlay_animated: bool, +} +impl Default for Titles { + fn default() -> Self { + Self { + title: None, + subtitle: None, + time: 0, + fade_in: 10, + stay: 70, + fade_out: 20, + overlay: None, + overlay_time: 0, + overlay_animated: false, + } + } +} +impl Titles { + /// `setTitle`. + pub fn set_title(&mut self, title: Text) { + self.title = Some(title); + self.time = self.fade_in + self.stay + self.fade_out; + } + /// `setSubtitle`. + pub fn set_subtitle(&mut self, subtitle: Text) { + self.subtitle = Some(subtitle); + } + /// `setTimes`: negative values keep the current time. + pub fn set_times(&mut self, fade_in: i32, stay: i32, fade_out: i32) { + if fade_in >= 0 { + self.fade_in = fade_in; + } + if stay >= 0 { + self.stay = stay; + } + if fade_out >= 0 { + self.fade_out = fade_out; + } + if self.time > 0 { + self.time = self.fade_in + self.stay + self.fade_out; + } + } + /// `clearTitles`. + pub fn clear(&mut self) { + self.title = None; + self.subtitle = None; + self.time = 0; + } + /// `resetTitleTimes`. + pub fn reset_times(&mut self) { + (self.fade_in, self.stay, self.fade_out) = (10, 70, 20); + } + /// `setOverlayMessage`. + pub fn set_overlay(&mut self, text: Text, animate: bool) { + self.overlay = Some(text); + self.overlay_time = 60; + self.overlay_animated = animate; + } + /// The title and action bar part of `Hud.tick`. + pub fn tick(&mut self) { + if self.overlay_time > 0 { + self.overlay_time -= 1; + } + if self.time > 0 { + self.time -= 1; + if self.time <= 0 { + self.title = None; + self.subtitle = None; + } + } + } + /// `Hud.extractOverlayMessage`. + pub fn overlay_message( + &self, + w: i32, + h: i32, + partial: f32, + font: &Font, + background: u32, + ) -> Vec { + let mut out = Vec::new(); + let Some(message) = &self.overlay else { + return out; + }; + if self.overlay_time <= 0 { + return out; + } + let t = self.overlay_time as f32 - partial; + let alpha = ((t * 255.0 / 20.0) as i32).min(255); + if alpha > 0 { + out.push(GuiDraw::Push(vec![PoseOp::Translate( + (w / 2) as f32, + (h - 68) as f32, + )])); + let color = if self.overlay_animated { + hsv_to_argb(t / 50.0, 0.7, 0.6, alpha as u32) + } else { + crate::hud_layout::argb(alpha as u32, 255, 255, 255) + }; + let width = width(font, message); + text_with_backdrop( + &mut out, + message.clone(), + -width / 2, + -4, + width, + color, + background, + ); + out.push(GuiDraw::Pop); + } + out + } + /// `Hud.extractTitle`. + pub fn title( + &self, + w: i32, + h: i32, + partial: f32, + font: &Font, + background: u32, + ) -> Vec { + let mut out = Vec::new(); + let Some(title) = &self.title else { + return out; + }; + if self.time <= 0 { + return out; + } + let t = self.time as f32 - partial; + let mut alpha = 255; + if self.time > self.fade_out + self.stay { + let time = (self.fade_in + self.stay + self.fade_out) as f32 - t; + alpha = (time * 255.0 / self.fade_in as f32) as i32; + } + if self.time <= self.fade_out { + alpha = (t * 255.0 / self.fade_out as f32) as i32; + } + let alpha = alpha.clamp(0, 255); + if alpha > 0 { + out.push(GuiDraw::Push(vec![PoseOp::Translate( + (w / 2) as f32, + (h / 2) as f32, + )])); + out.push(GuiDraw::Push(vec![PoseOp::Scale(4.0, 4.0)])); + let title_width = width(font, title); + let color = crate::hud_layout::argb(alpha as u32, 255, 255, 255); + text_with_backdrop( + &mut out, + title.clone(), + -title_width / 2, + -10, + title_width, + color, + background, + ); + out.push(GuiDraw::Pop); + if let Some(subtitle) = &self.subtitle { + out.push(GuiDraw::Push(vec![PoseOp::Scale(2.0, 2.0)])); + let subtitle_width = width(font, subtitle); + text_with_backdrop( + &mut out, + subtitle.clone(), + -subtitle_width / 2, + 5, + subtitle_width, + color, + background, + ); + out.push(GuiDraw::Pop); + } + out.push(GuiDraw::Pop); + } + out + } +} + +/// The selected item as `Hud.tick` compares it: its item id and hover name. +#[derive(Clone, Debug, PartialEq)] +pub struct HeldName { + pub item: String, + /// `ItemStack.getHoverName`. + pub hover_name: Text, + /// `getRarity().color()`. + pub rarity_color: u32, + /// The stack has `CUSTOM_NAME`. + pub custom_name: bool, +} + +/// `Hud.toolHighlightTimer` and `lastToolHighlight`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct ToolHighlight { + pub timer: i32, + pub last: Option, +} +impl ToolHighlight { + /// The selected-item part of `Hud.tick`; `display_time` is the + /// `notificationDisplayTime` option. + pub fn tick(&mut self, selected: Option, display_time: f64) { + match &selected { + None => self.timer = 0, + Some(s) => { + let changed = self + .last + .as_ref() + .is_none_or(|l| l.item != s.item || l.hover_name != s.hover_name); + if changed { + self.timer = (40.0 * display_time) as i32; + } else if self.timer > 0 { + self.timer -= 1; + } + } + } + self.last = selected; + } + /// `Hud.extractSelectedItemName`; `can_hurt` is + /// `gameMode.canHurtPlayer()` (survival and adventure). + pub fn draw( + &self, + w: i32, + h: i32, + can_hurt: bool, + font: &Font, + background: u32, + ) -> Vec { + let mut out = Vec::new(); + let Some(last) = &self.last else { + return out; + }; + if self.timer <= 0 { + return out; + } + let mut name = last.hover_name.clone().with_color(last.rarity_color); + if last.custom_name { + name = name.with_style(&Style { + italic: Some(true), + ..Style::default() + }); + } + let str_width = width(font, &name); + let x = (w - str_width) / 2; + let mut y = h - 59; + if !can_hurt { + y += 14; + } + let alpha = ((self.timer as f32 * 256.0 / 10.0) as i32).min(255); + if alpha > 0 { + let color = crate::hud_layout::argb(alpha as u32, 255, 255, 255); + text_with_backdrop(&mut out, name, x, y, str_width, color, background); + } + out + } +} diff --git a/crates/horizon-client/src/lib.rs b/crates/horizon-client/src/lib.rs index 53685eeb2..ea6278878 100644 --- a/crates/horizon-client/src/lib.rs +++ b/crates/horizon-client/src/lib.rs @@ -45,6 +45,7 @@ pub mod gossip; pub mod health; pub mod hud; pub mod hud_layout; +pub mod hud_overlays; pub mod hunger; pub mod input; pub mod item_data; diff --git a/crates/horizon-client/src/settings.rs b/crates/horizon-client/src/settings.rs index 2d49feee4..3db17435a 100644 --- a/crates/horizon-client/src/settings.rs +++ b/crates/horizon-client/src/settings.rs @@ -475,6 +475,15 @@ impl Settings { } }) } + /// `Options.getBackgroundColor(float)`: the text backdrop colour, `default` + /// opacity unless `backgroundForChatOnly` is off. + pub fn text_background(&self, default: f32) -> u32 { + crate::hud_layout::background_color( + self.file.bool("backgroundForChatOnly"), + f64::from(self.text_background_opacity), + default, + ) + } pub fn chat_options(&self) -> crate::chat::ChatOptions { crate::chat::ChatOptions { opacity: self.chat_opacity, diff --git a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java index 01469ab40..65cc4cecf 100644 --- a/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java +++ b/mods/horizon/src/test/java/dev/horizonlab/parity/VanillaHudOracle.java @@ -88,6 +88,19 @@ public final class VanillaHudOracle { static float f(String k, float d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsFloat() : d; } static int i(String k, int d) { return c.has(k) && !c.get(k).isJsonNull() ? c.get(k).getAsInt() : d; } static boolean b(String k) { return c.has(k) && c.get(k).getAsBoolean(); } + static net.minecraft.network.chat.Component comp(JsonElement e) { + return net.minecraft.network.chat.ComponentSerialization.CODEC.parse(com.mojang.serialization.JsonOps.INSTANCE, e).getOrThrow(); + } + static OptionInstance option(T value) throws Exception { + @SuppressWarnings("unchecked") OptionInstance o = alloc(OptionInstance.class); + put(o, OptionInstance.class, "value", value); + return o; + } + static Method hudMethod(String name, Class... params) throws Exception { + Method m = Hud.class.getDeclaredMethod(name, params); + m.setAccessible(true); + return m; + } /** A player whose HUD-facing getters answer from the case. */ public static final class Actor extends LocalPlayer { @@ -95,6 +108,7 @@ public final class VanillaHudOracle { Entity vehicle; FoodData food; ItemStack offhand = ItemStack.EMPTY; + List active = new ArrayList<>(); private Actor() { super(null, null, null, null, null, null, false, null, null); } @Override public float getHealth() { return f("health", 20); } @Override public double getAttributeValue(Holder a) { return a == Attributes.MAX_HEALTH ? f("maxHealth", 20) : 0.0; } @@ -102,9 +116,10 @@ public final class VanillaHudOracle { @Override public int getArmorValue() { return i("armor", 0); } @Override public FoodData getFoodData() { return food; } @Override public boolean hasEffect(Holder effect) { - for (var e : c.getAsJsonArray("effects")) if (effect.is(Identifier.parse(e.getAsString()))) return true; + if (c.has("effects")) for (var e : c.getAsJsonArray("effects")) if (effect.is(Identifier.parse(e.getAsString()))) return true; return false; } + @Override public java.util.Collection getActiveEffects() { return active; } @Override public boolean isFullyFrozen() { return b("frozen"); } @Override public int getAirSupply() { return i("air", 300); } @Override public int getMaxAirSupply() { return i("maxAir", 300); } @@ -264,6 +279,11 @@ public final class VanillaHudOracle { Method crosshair = Hud.class.getDeclaredMethod("extractCrosshair", GuiGraphicsExtractor.class, DeltaTracker.class); crosshair.setAccessible(true); for (Method m : new Method[] {hotbar, health, vehicle}) m.setAccessible(true); + Method effects = hudMethod("extractEffects", GuiGraphicsExtractor.class, DeltaTracker.class); + Method title = hudMethod("extractTitle", GuiGraphicsExtractor.class, DeltaTracker.class); + Method overlayMessage = hudMethod("extractOverlayMessage", GuiGraphicsExtractor.class, DeltaTracker.class); + Method selectedName = hudMethod("extractSelectedItemName", GuiGraphicsExtractor.class); + Method tick = hudMethod("tick"); Method level = Class.forName("net.minecraft.client.gui.contextualbar.ContextualBar") .getDeclaredMethod("extractExperienceLevel", GuiGraphicsExtractor.class, Font.class, int.class); level.setAccessible(true); @@ -284,6 +304,7 @@ public final class VanillaHudOracle { put(clientLevel, ClientLevel.class, "clientLevelData", levelData); actor.level = clientLevel; actor.offhand = ItemStack.EMPTY; + actor.active = new ArrayList<>(); actor.food = new FoodData(); actor.food.setFoodLevel(i("food", 20)); actor.food.setSaturation(f("saturation", 5)); @@ -296,7 +317,7 @@ public final class VanillaHudOracle { var stacks = c.getAsJsonArray("slots"); var items = new net.minecraft.world.item.Item[] {Items.STONE, Items.DIAMOND_SWORD, Items.APPLE, Items.TORCH, Items.BOW, Items.OAK_LOG, Items.BREAD, Items.SHIELD, Items.COMPASS}; - for (int n = 0; n < 9; n++) { + for (int n = 0; stacks != null && n < 9; n++) { if (stacks.get(n).isJsonNull()) continue; var stack = new ItemStack(items[n]); stack.setPopTime(stacks.get(n).getAsInt()); @@ -317,17 +338,20 @@ public final class VanillaHudOracle { put(mc, Minecraft.class, "gameRenderer", renderer); put(mc, Minecraft.class, "font", font); var gameMode = alloc(MultiPlayerGameMode.class); - put(gameMode, MultiPlayerGameMode.class, "localPlayerMode", GameType.byName(c.get("gameMode").getAsString())); + put(gameMode, MultiPlayerGameMode.class, "localPlayerMode", GameType.byName(c.has("gameMode") ? c.get("gameMode").getAsString() : "survival")); put(mc, Minecraft.class, "gameMode", gameMode); var options = alloc(Options.class); - var indicator = alloc(OptionInstance.class); - put(indicator, OptionInstance.class, "value", AttackIndicatorStatus.valueOf(c.get("attackIndicator").getAsString())); - put(options, Options.class, "attackIndicator", indicator); + put(options, Options.class, "attackIndicator", option(AttackIndicatorStatus.valueOf(c.has("attackIndicator") ? c.get("attackIndicator").getAsString() : "OFF"))); + put(options, Options.class, "backgroundForChatOnly", option(c.has("chatOnly") ? b("chatOnly") : true)); + put(options, Options.class, "textBackgroundOpacity", option((double) f("textOpacity", 0.5F))); + put(options, Options.class, "notificationDisplayTime", option(c.has("displayTime") ? c.get("displayTime").getAsDouble() : 1.0)); put(mc, Minecraft.class, "options", options); var window = alloc(com.mojang.blaze3d.platform.Window.class); put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledWidth", i("width", 0)); put(window, com.mojang.blaze3d.platform.Window.class, "guiScaledHeight", i("height", 0)); put(mc, Minecraft.class, "window", window); + put(mc, Minecraft.class, "gui", alloc(net.minecraft.client.gui.Gui.class)); + put(mc, Minecraft.class, "demo", b("demo")); var hud = alloc(Hud.class); put(hud, Hud.class, "minecraft", mc); put(hud, Hud.class, "random", net.minecraft.util.RandomSource.create()); @@ -336,25 +360,79 @@ public final class VanillaHudOracle { put(hud, Hud.class, "displayHealth", i("displayHealth", 0)); put(hud, Hud.class, "lastHealthTime", Util.getMillis() - (long) i("lastHealthAgo", 0)); put(hud, Hud.class, "healthBlinkTime", (long) i("healthBlinkTime", 0)); + put(hud, Hud.class, "lastToolHighlight", ItemStack.EMPTY); + var chat = alloc(net.minecraft.client.gui.components.ChatComponent.class); + put(chat, net.minecraft.client.gui.components.ChatComponent.class, "messageDeletionQueue", new ArrayList<>()); + put(hud, Hud.class, "chat", chat); + hud.resetTitleTimes(); var capture = alloc(Capture.class); capture.draws = new JsonArray(); capture.stack = new Matrix3x2fStack(16); + put(capture, GuiGraphicsExtractor.class, "minecraft", mc); float partial = f("partial", 0); DeltaTracker delta = (DeltaTracker) Proxy.newProxyInstance(DeltaTracker.class.getClassLoader(), new Class[] {DeltaTracker.class}, (proxy, method, a) -> method.getReturnType() == float.class ? partial : null); - var mode = GameType.byName(c.get("gameMode").getAsString()); - if (c.has("crosshair") && c.get("crosshair").getAsBoolean()) { - put(options, Options.class, "cameraType", net.minecraft.client.CameraType.FIRST_PERSON); - var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class); - put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList()); - put(mc, Minecraft.class, "debugEntries", debug); - crosshair.invoke(hud, capture, delta); + var mode = GameType.byName(c.has("gameMode") ? c.get("gameMode").getAsString() : "survival"); + // Hud.tick's vignette brightness reads the camera entity's level: tick without one. + if (Set.of("title", "selected").contains(c.get("kind").getAsString())) + put(camera, net.minecraft.client.Camera.class, "entity", null); + switch (c.get("kind").getAsString()) { + case "decorations" -> { + if (c.has("crosshair") && c.get("crosshair").getAsBoolean()) { + put(options, Options.class, "cameraType", net.minecraft.client.CameraType.FIRST_PERSON); + var debug = alloc(net.minecraft.client.gui.components.debug.DebugScreenEntryList.class); + put(debug, net.minecraft.client.gui.components.debug.DebugScreenEntryList.class, "currentlyEnabled", new ArrayList()); + put(mc, Minecraft.class, "debugEntries", debug); + crosshair.invoke(hud, capture, delta); + } + if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta); + if (mode.isSurvival()) health.invoke(hud, capture); + vehicle.invoke(hud, capture); + if (c.has("experienceBar") && c.get("experienceBar").getAsBoolean()) new ExperienceBar(mc).extractBackground(capture, delta); + if (mode.isSurvival() && actor.experienceLevel > 0) level.invoke(null, capture, font, actor.experienceLevel); + } + case "effects" -> { + for (var e : c.getAsJsonArray("active")) { + var o = e.getAsJsonObject(); + var effect = BuiltInRegistries.MOB_EFFECT.get(Identifier.parse(o.get("id").getAsString())).orElseThrow(); + actor.active.add(new net.minecraft.world.effect.MobEffectInstance(effect, o.get("duration").getAsInt(), 0, + o.get("ambient").getAsBoolean(), true, o.get("icon").getAsBoolean())); + } + effects.invoke(hud, capture, delta); + } + case "title" -> { + for (var e : c.getAsJsonArray("ops")) { + var op = e.getAsJsonArray(); + switch (op.get(0).getAsString()) { + case "title" -> hud.setTitle(comp(op.get(1))); + case "subtitle" -> hud.setSubtitle(comp(op.get(1))); + case "times" -> hud.setTimes(op.get(1).getAsInt(), op.get(2).getAsInt(), op.get(3).getAsInt()); + case "clear" -> hud.clearTitles(); + case "reset" -> hud.resetTitleTimes(); + case "overlay" -> hud.setOverlayMessage(comp(op.get(1)), op.get(2).getAsBoolean()); + case "tick" -> { for (int n = op.get(1).getAsInt(); n > 0; n--) tick.invoke(hud); } + default -> throw new IllegalArgumentException(op.toString()); + } + } + overlayMessage.invoke(hud, capture, delta); + title.invoke(hud, capture, delta); + } + case "selected" -> { + int slot = i("selected", 0); + for (var e : c.getAsJsonArray("steps")) { + ItemStack stack = ItemStack.EMPTY; + if (!e.isJsonNull()) { + var o = e.getAsJsonObject(); + stack = new ItemStack(BuiltInRegistries.ITEM.getValue(Identifier.withDefaultNamespace(o.get("item").getAsString()))); + if (!o.get("custom").isJsonNull()) stack.set(net.minecraft.core.component.DataComponents.CUSTOM_NAME, comp(o.get("custom"))); + } + inventory.setItem(slot, stack); + tick.invoke(hud); + } + selectedName.invoke(hud, capture); + } + default -> throw new IllegalArgumentException(c.get("kind").getAsString()); } - if (mode != GameType.SPECTATOR) hotbar.invoke(hud, capture, delta); - if (mode.isSurvival()) health.invoke(hud, capture); - vehicle.invoke(hud, capture); - if (c.has("experienceBar") && c.get("experienceBar").getAsBoolean()) new ExperienceBar(mc).extractBackground(capture, delta); - if (mode.isSurvival() && actor.experienceLevel > 0) level.invoke(null, capture, font, actor.experienceLevel); result.add("draws", capture.draws); } catch (Throwable error) { var cause = error instanceof InvocationTargetException && error.getCause() != null ? error.getCause() : error; diff --git a/tools/hud_parity_cases.py b/tools/hud_parity_cases.py index df70e80e3..b3ebebdb7 100644 --- a/tools/hud_parity_cases.py +++ b/tools/hud_parity_cases.py @@ -35,12 +35,90 @@ def decorations(rng, n): if rng.random() < 0.15: case['vehicleMaxHealth'] = rng.choice([15.0, 30.0, 53.0, 100.0]) case['vehicleHealth'] = round(rng.uniform(0, case['vehicleMaxHealth']), 1) - - return case +ALL_EFFECTS = ['speed', 'slowness', 'haste', 'mining_fatigue', 'strength', 'instant_health', 'instant_damage', 'jump_boost', + 'nausea', 'regeneration', 'resistance', 'fire_resistance', 'water_breathing', 'invisibility', 'blindness', + 'night_vision', 'hunger', 'weakness', 'poison', 'wither', 'health_boost', 'absorption', 'saturation', 'glowing', + 'levitation', 'luck', 'unluck', 'slow_falling', 'conduit_power', 'dolphins_grace', 'bad_omen', + 'hero_of_the_village', 'darkness', 'trial_omen', 'raid_omen', 'wind_charged', 'weaving', 'oozing', 'infested', + 'breath_of_the_nautilus'] +SIZES = dict(width=[427, 320, 480, 640, 961], height=[240, 255, 270, 360, 501]) + + +def screen(rng): + return {'width': rng.choice(SIZES['width']), 'height': rng.choice(SIZES['height'])} + + +def backdrop(rng): + """The text background options behind textWithBackdrop.""" + return {'chatOnly': rng.random() < 0.5, 'textOpacity': rng.choice([0.0, 0.5, 0.25, 1.0, round(rng.random(), 3)])} + + +def effects(rng, n): + count = rng.choice([1, 2, 3, 5, 8, 12, 20]) + active = [] + for e in rng.sample(ALL_EFFECTS, count): + duration = rng.choice([-1, 1, 7, 19, 20, 99, 150, 199, 200, 201, 600, 32147, 32148, 40000, rng.randint(0, 220)]) + active.append({'id': 'minecraft:' + e, 'duration': duration, 'ambient': rng.random() < 0.25, 'icon': rng.random() < 0.9}) + return {**screen(rng), 'demo': rng.random() < 0.15, 'active': active} + + +TITLES = [{'text': 'Hello'}, {'text': 'Boss fight!', 'color': 'red', 'bold': True}, {'text': 'Wave 3', 'italic': True}, + {'text': 'A long title over the whole screen'}, {'text': ''}, ['Mixed ', {'text': 'parts', 'color': 'gold'}], + {'text': 'Ünïcödé ★'}] + + +def title(rng, n): + """Title, subtitle and action bar events between ticks (fades, setTimes mid-title, clears).""" + ops = [] + for _ in range(rng.randint(1, 6)): + r = rng.random() + if r < 0.3: + ops.append(['title', rng.choice(TITLES)]) + elif r < 0.45: + ops.append(['subtitle', rng.choice(TITLES)]) + elif r < 0.6: + ops.append(['times', rng.choice([-1, 0, 1, 5, 10, 20]), rng.choice([-1, 0, 3, 40, 70]), rng.choice([-1, 0, 1, 7, 20])]) + elif r < 0.65: + ops.append(['clear']) + elif r < 0.7: + ops.append(['reset']) + elif r < 0.85: + ops.append(['overlay', rng.choice(TITLES), rng.random() < 0.3]) + ops.append(['tick', rng.choice([0, 0, 1, 2, 5, 9, 10, 11, 30, 50, 59, 60, 79, 80, 81, 99, 100, rng.randint(0, 120)])]) + return {**screen(rng), **backdrop(rng), 'partial': round(rng.random(), 3), 'ops': ops} + + +# Items for the selected item name: id, translation key and rarity colour (checked by the oracle's own stacks). +HELD = [('stone', 'block.minecraft.stone', 'white'), ('diamond_sword', 'item.minecraft.diamond_sword', 'white'), + ('totem_of_undying', 'item.minecraft.totem_of_undying', 'yellow'), ('beacon', 'block.minecraft.beacon', 'aqua'), + ('dragon_egg', 'block.minecraft.dragon_egg', 'light_purple'), ('apple', 'item.minecraft.apple', 'white')] +CUSTOM = [None, None, None, {'text': 'Excalibur'}, {'text': 'Red', 'color': 'red'}, {'text': 'Plain', 'italic': False}] + + +def selected(rng, n): + """Selected-slot changes tick by tick, then the name with its fade.""" + def stack(): + item, key, rarity = rng.choice(HELD) + return {'item': item, 'key': key, 'rarity': rarity, 'custom': rng.choice(CUSTOM)} + steps, held = [], stack() + for _ in range(rng.randint(1, 60)): + if rng.random() < 0.1: + if rng.random() < 0.2: + held = None + else: + held = stack() + steps.append(held) + return {**screen(rng), **backdrop(rng), 'gameMode': rng.choice(['survival', 'adventure', 'creative']), + 'displayTime': rng.choice([1.0, 1.0, 0.5, 2.0, 0.123]), 'steps': steps} + + # Generators by kind: (rng, index) -> case. Cases are drawn round-robin. KINDS = { 'decorations': decorations, + 'effects': effects, + 'title': title, + 'selected': selected, }